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
48daaa44516aa669a2f9ea6ecce182c70501ab6f
C++
YessicaCh/Computacion-Bioinspirada
/bioinspirada-master/Agentes/Agente.h
UTF-8
6,977
3.078125
3
[]
no_license
#ifndef AGENTE_H_INCLUDED #define AGENTE_H_INCLUDED #include <stdlib.h> #include <stdio.h> #include <time.h> #include <iostream> #include <math.h> #include "Nido.h" using namespace std; int Contener(vector <vector<int>> aux, int x, int y) //funcion para saber si una cordenada esta contenido en un vector de vectores { if (aux.empty()) return -1; int tam=aux.size(),i; for (i=0;i<tam;i++) { if (aux[i][0]==x && aux [i][1]==y) return i; } return -1; } struct Agente { int posx,posy; //posicion en la grilla del agente char name; //nombre del agente bool cargandoComida; // si esta cargando comida o no Agente(int x, int y, char nombre) { posx=x; posy=y; name=nombre; cargandoComida=0; } void Print() { cout<<endl<<"Agente :"<<name<<" carga "<<cargandoComida<<" de comida"<<endl; } void PonerFeromona (char **&tab,vector< vector<int>> &fero,vector <char> &fer, int x , int y) //Funcion para poner la feromona al lugar al que va { int Iterador=Contener(fero,x,y); if (Iterador==-1) { vector<int>aux={x,y}; fero.push_back(aux); fer.push_back('1'); tab[y][x]=' '; return; } fer[Iterador]+=1; return; } //funcion para percibir si existe el nido o la comida cerca bool Percibir (char **&tab,int Size,vector< vector<int>> &fero, vector<char> &fer) { if (posx+1<Size && (tab[posy][posx+1]=='C' || tab[posy][posx+1]=='N')) //a la derecha { PonerFeromona(tab,fero,fer,posx,posy); posx+=1; return 1; } if (posx-1>-1 && (tab[posy][posx-1]=='C' || tab[posy][posx-1]=='N')) //a la izquierda { PonerFeromona(tab,fero,fer,posx,posy); posx-=1; return 1; } if (posy+1<Size && (tab[posy+1][posx]=='C' || tab[posy+1][posx]=='N')) // arriba { PonerFeromona(tab,fero,fer,posx,posy); posy+=1; return 1; } if (posy-1>-1 && (tab[posy-1][posx]=='C' || tab[posy-1][posx]=='N')) //abajo { PonerFeromona(tab,fero,fer,posx,posy); posy-=1; return 1; } return 0; } //Funcion probabilistica para moverse en base a las feromonas bool Pferomonas(char ** &tab,int Size,vector< vector<int>> &fero, vector<char> &fer) { bool moverse=0; int auxX=posx,auxY=posy; double Max=-1.0; double t=0.5; int derecha=(tab[auxY][auxX+1]-'0'); int izquierda=(tab[auxY][auxX-1]-'0'); int abajo=(tab[auxY+1][auxX]-'0'); int arriba=(tab[auxY-1][auxX]-'0'); double total =exp(derecha/t)+exp(izquierda/t)+exp(abajo/t)+exp(arriba/t); if (auxX+1<Size && (exp(derecha/t)/total)>Max) //a la derecha { Max=exp(derecha/t)/total; moverse=1; posx=auxX; posx+=1; if (tab[auxY][auxX+1]!=' ') moverse=0; } if (auxX-1>-1 && (exp(izquierda/t)/total)>Max) //a la izquierda { Max=exp(izquierda/t)/total; moverse=1; posx=auxX; posx-=1; if (tab[auxY][auxX-1]!=' ') moverse=0; } if (auxY+1<Size && (exp(abajo/t)/total)>Max) // arriba { Max=exp(abajo/t)/total; moverse=1; posy=auxY; posy+=1; if (tab[auxY+1][auxX]!=' ') moverse=0; } if (auxY-1>-1 && (exp(arriba/t)/total)>Max) //abajo { Max=exp(arriba/t)/total; moverse=1; posy-=1; if (tab[auxY-1][auxX]!=' ') moverse=0; } if (moverse) { PonerFeromona(tab,fero,fer,posx,posy); return moverse; } posx=auxX; posy=auxY; return moverse; } // bool Pferomonas(char ** &tab,int Size,vector< vector<int>> &fero, vector<char> &fer) // { // bool moverse=0; // int mayor=0, auxX=posx,auxY=posy; // if (posx+1<Size && tab[auxY][auxX+1]!=' ' && (tab[auxY][auxX+1]-'0')>mayor) //a la derecha // { // moverse=1; // mayor=tab[auxY][auxX+1]-'0'; // posx=auxX; // posx+=1; // } // if (posx-1>-1 && tab[auxY][auxX-1]!=' ' && (tab[auxY][auxX-1]-'0')>mayor) //a la izquierda // { // moverse=1; // mayor=tab[auxY][auxX-1]-'0'; // posx=auxX; // posx-=1; // } // if (posy+1<Size && tab[auxY+1][auxX]!=' ' && (tab[auxY+1][auxX]-'0')>mayor) // arriba // { // moverse=1; // mayor=tab[auxY+1][auxX]-'0'; // posy=auxY; // posy+=1; // } // if (posy-1>-1 && tab[auxY-1][auxX]!=' ' && (tab[auxY-1][auxX]-'0')>mayor) //abajo // { // moverse=1; // mayor=tab[auxY-1][auxX]; // posy-=1; // } // if (moverse) // { // PonerFeromona(tab,fero,fer,posx,posy); // return moverse; // } // return moverse; // } //Funcion para moverse void Move(char **& tab, int Size, Nido *&nido, vector< vector <int>> &comida,vector< vector <int>> &feromona, vector<char> &fer) { int auxX=posx, auxY=posy; if (Percibir(tab,Size,feromona,fer)) //movimiento en base al nido y la comida { if (tab[posy][posx]=='N'&& cargandoComida==1) { nido->comida+=1; cargandoComida=0; return; } if (tab[posy][posx]=='C'&& cargandoComida==0) { cargandoComida=1; int aux = Contener(comida,auxX,auxY); comida.erase (comida.begin()+(aux+1)); return; //si retorna 1 se borra la posicion de la comida del vector } return; } else if (Pferomonas(tab,Size,feromona,fer)) return; //movimiento en base a la feromona else //movimiento aleatorio { PonerFeromona (tab,feromona,fer,auxX,auxY); int accion=rand() % 5; // accion=0; if (accion==0 && posx+1<Size)//derecha { posx+=1; //cout<<endl<<"here"<<posx<<endl; return; } if (accion==1 && posx-1>-1)//izquierda { posx-=1; return; } if (accion==2 && posy+1<Size)//arriba { posy+=1; return; } if (accion==3 && posy-1>-1)//abajo { posy-=1; return; } return; } } }; #endif // AGENTE_H_INCLUDED
true
f812e06ad3e6ff17c646d83ccf71149e813517e0
C++
kmichalk/xlib
/xlib/xlib/thread_safe.h
UTF-8
7,777
3.125
3
[]
no_license
#ifndef _X_THREAD_SAFE_H_ #define _X_THREAD_SAFE_H_ #include "result.h" #include "xrnd.h" #include "byte.h" namespace x { class lock { private: public: static byte* disabler_; void* volatile user_; bool volatile locked_; __forceinline void set_lock_(void* user) { locked_ = true; user_ = user; } __forceinline void unlock_() { user_ = nullptr; locked_ = false; } __forceinline void wait_() { while (locked_) { } } template<class _Func> __forceinline void wait_(_Func&& whileWait) { while (locked_) { whileWait(); } } /*void wait_(double timeout) { x::timer<std::chrono::microseconds> waitTimer; waitTimer.tic(); while (locked_ && waitTimer.toc() < timeout) { } }*/ __forceinline bool used_by_(void* user) { return user_ == user; } public: lock(): user_{nullptr}, locked_{false} { } lock(void* user): user_{user}, locked_{false} { } lock(lock const& other): user_{nullptr}, locked_{false} { } lock(lock&& other): user_{other.user_}, locked_{other.locked_} { } __forceinline bool is_locked() const { return locked_; } void use(void* user) { //if (!used_by_(user)){ wait_(); set_lock_(user); //} } template<class _Func> void use(void* user, _Func&& whileWait) { wait_(whileWait); set_lock_(user); } bool try_use(void* user) { if (!is_locked()) set_lock_(user); } void unlock(void* user) { if (used_by_(user)) unlock_(); } void disable() { wait_(); set_lock_(++disabler_); } virtual ~lock() { disable(); } }; byte* x::lock::disabler_ = (byte*)x::random<unsigned>(); /////////////////////////////////////////////////////////////////////////////// /// <summary> /// Provides thread-safe access to data of type specified in template parameter /// by preventing multiple objects to access the data at the same time. /// It also prevents the deletion of data while it is being used. /// The usage is to create a variable or class field wrapping it in thread_safe object. /// </summary> /// <typeparam name="_Type">Type of stored data.</typeparam> template<class _Type> class thread_safe { private: protected: void* volatile user_; _Type value_; /*__forceinline void wait_(thread_safe<_Type> const& other) { while (other.user_) { } }*/ __forceinline void lock_(void* user) { user_ = user; } __forceinline void unlock_() { user_ = nullptr; } __forceinline void wait_() { while (user_) { } } void wait_(double timeout) { x::timer<std::chrono::microseconds> waitTimer; waitTimer.tic(); while (user_ && waitTimer.toc() < timeout) { } } __forceinline bool used_by_(void* user) { return user_ == user; } public: /// <summary> /// Default constructor. /// Calls default condtructor of the contained value object. /// Sets user to nullptr. /// </summary> /// <example><code>thread_safe<x::string> safeStr;</code></example> thread_safe(): user_{nullptr}, value_{} { } /// <summary> /// Constructor initializing the value and user which is nullptr by default if not specified. /// </summary> /// <param name="value">Value to be initialized with.</param> /// <param name="user">User to be set.</param> /// <example><code>x::thread_safe<x::string> safeStr{""};</code></example> thread_safe(_Type const& value, void* user = nullptr): value_{value}, user_{user} { } thread_safe(_Type&& value, void* user = nullptr): value_{std::forward<_Type>(value)}, user_{user} { } thread_safe(thread_safe<_Type> const& other): value_{other.value()}, user_{nullptr} { } thread_safe(thread_safe<_Type>&& other): value_{other.value_}, user_{other.user_} { } /// <summary> /// Checks whether data is being currently used by any object. /// </summary> /// <returns>True if user is set, otherwise false.</returns> bool is_used() const { return (bool)user_; } /// <summary> /// Forces object to wait until call of release method from current user. /// Sets user to specified and returns accesed data on success. /// </summary> /// <param name="user">User requested.</param> /// <returns>Reference to accessed data.</returns> /// <example><code>thread_safe<x::string> safeStr{"114.0098"}; /// auto dot = safeStr.use(this).find('.');</code></example> _Type& use(void* user) { wait_(); user_ = user; return value_; } /// <summary> /// Forces object to wait until call of release method from current user. /// While access is being permitted, executes function \a whileWait with \a user as caller. /// Sets user to specified and returns accesed data on success. /// </summary> /// <param name="user"> - user requested.</param> /// <param name="whileWait"> - function to be executed repeatedly while waiting for the access </param> /// <returns>Reference to accessed data.</returns> /// <example><code>thread_safe<x::string> safeStr{"114.0098"}; /// auto dot = safeStr.use(this, ).find('.');</code></example> template<class _User, class _Ret> _Type& use(_User* user, _Ret(_User::*whileWait)()) { while (user_) { (user->*whileWait)(); } user_ = user; return value_; } /// <summary> /// Forces object to wait until call of release method from current user. /// While access is being permitted, executes function \a whileWait. /// Sets user to specified and returns accesed data on success. /// </summary> /// <param name="user"> - user requested.</param> /// <param name="whileWait"> - function to be executed repeatedly while waiting for the access </param> /// <returns>Reference to accessed data.</returns> /// <example><code>thread_safe<x::string> safeStr{"114.0098"}; /// auto dot = safeStr.use(this, ).find('.');</code></example> template<class _Func> _Type& use(void* user, _Func&& whileWait) { while (user_) { whileWait(); } lock_(user); return value_; } /// <summary> /// Validates specified user and releases unlocks the data on success. /// Sets user to nullptr. /// </summary> /// <param name="user">User to be validated.</param> void release(void* user) { if (used_by_(user)) unlock_(); } /// <summary> /// Tries to access data by specified user without waiting for release. /// </summary> /// <param name="user">User to be validated.</param> /// <returns>Reference to data wrapped in x::result object if validation succeeded, /// otherwise invalid x::result not containing desired information.</returns> /// <example><code>x::thread_safe&lt;int&gt;safeInt{1}; /// if (auto val = safeInt.access(this)){ /// ++val; /// }</code></example> result<_Type&> access(void* user) { if (used_by_(user)) return value_; else return result<_Type&>::INVALID; } template<_capture(_Type)> std::enable_if_t<!std::is_fundamental<_Type>::value, _Type> value() const { wait_(); lock_(this); _Type copy = value_; unlock_(); return copy; } template<_capture(_Type)> std::enable_if_t<std::is_fundamental<_Type>::value, _Type> value() const { wait_(); return value_; } /// <summary> /// Destructor providing wait until release from current user will have been called. /// </summary> virtual ~thread_safe() { wait_(); lock_(this); } }; //class _Synchronized: public thread_safe<int> //{ //public: // // template<class _Func> // void operator=(_Func&& func) // { // while(user_){ // //displn ""; // } // user_ = this; // func(); // user_ = nullptr; // } //}; } #endif //_X_THREAD_SAFE_H_
true
08648d30ddfa9358e50de75001f62fab37692140
C++
murar8/self-balancing-car
/src/Encoder.cpp
UTF-8
1,664
2.65625
3
[]
no_license
#include "Encoder.h" #include <PinChangeInterrupt.h> #include <util/atomic.h> #define ISR_HANDLER(n) [] { instances[n]->_onPulse(); } typedef void (*Handler)(void); static Encoder *instances[2]; static Handler handlers[2] = {ISR_HANDLER(0), ISR_HANDLER(1)}; Encoder::Encoder(float sample_time, uint8_t pin_phase_a, uint8_t pin_phase_b, uint8_t fw_level) : sample_time_(sample_time), pin_phase_a_(pin_phase_a), pin_phase_b_(pin_phase_b), fw_level_(fw_level) { port_phase_b_ = digitalPinToPort(pin_phase_b_); bit_phase_b_ = digitalPinToBitMask(pin_phase_b_); last_sample_ = millis(); }; void Encoder::begin() { pinMode(pin_phase_a_, INPUT_PULLUP); pinMode(pin_phase_b_, INPUT_PULLUP); uint8_t int_vect = digitalPinToInterrupt(pin_phase_a_); instances[int_vect] = this; attachInterrupt(int_vect, handlers[int_vect], RISING); } inline void Encoder::_onPulse() { uint8_t level = (*portInputRegister(port_phase_b_) & bit_phase_b_) != 0; Direction next_direction = level ^ fw_level_ ? Direction::CW : Direction::CCW; if (next_direction == direction_) { pulse_count_++; } else { pulse_count_ = 1; } direction_ = next_direction; } bool Encoder::tick() { uint32_t now = millis(); if (now - last_sample_ < sample_time_) { return false; } frequency_ = (static_cast<float>(pulse_count_) * (1000.0 / ENCODER_PULSES_PER_REVOLUTION)) / sample_time_; pulse_count_ = 0; last_sample_ = now; if (direction_ == Direction::CCW) { frequency_ *= -1; } return true; } float Encoder::getFrequency() { return frequency_; }
true
47ce535d94f9ae0ecde76a5ecda0fff42041af69
C++
bdorhan/Sheet-3
/Vehicle.cpp
UTF-8
1,138
3.546875
4
[]
no_license
#include "Vehicle.h" // WARNING: this file is only function definition of the class declared in Vehicle.h Vehicle :: Vehicle() { company = " "; enginePower = "0"; YearOfProduction = "0"; maxSpeed = "0"; } Vehicle :: Vehicle(string c, string e, string y, string m) { company = c; enginePower = e; YearOfProduction = y; maxSpeed = m ; } void Vehicle :: setCompany(string a) { company = a; } string Vehicle :: getCompany() { return company; } void Vehicle :: setYearOfProduction(string a) { YearOfProduction = a; } string Vehicle :: getYearOfProduction() { return YearOfProduction; } string Vehicle :: getEnginePower() { return enginePower; } void Vehicle :: setEnginePower(string a) { enginePower = a; } string Vehicle :: getMaxSpeed() { return maxSpeed; } void Vehicle :: setMaxSpeed(string a) { maxSpeed = a; } string Vehicle :: display() { cout << "Company Name: " << company << endl; cout << "Engine Power: " << enginePower << endl; cout << "Year of Production: " << YearOfProduction << endl; cout << "Maximum Speed: " << maxSpeed << endl; }
true
45030118a1ddfaac29bedce6b24e7a20e26c3c32
C++
yogendrarp/udemyc-
/files/parsing.cpp
UTF-8
607
3.046875
3
[]
no_license
#include <iostream> #include <fstream> #include <sstream> int main() { std::string in_file_path = "population.txt"; std::ifstream in_file; in_file.open(in_file_path); if (!in_file.is_open()) { return 1; } while (in_file) { std::string line; getline(in_file, line, ':'); int population; in_file >> population; in_file.get(); if (!in_file) { continue; } std::cout << "'" << line << "'" << " -- '" << population << "'" << std::endl; } in_file.close(); }
true
6938fe6309767c338d8d2e4d672a6d5eebb040d0
C++
SpaceCat-Chan/OpenGL_SDL
/OpenGL_SDL/ECS/Components/Transform/Transform.cpp
UTF-8
760
2.578125
3
[]
no_license
#include "Transform.hpp" #include "ECS/ECS.hpp" glm::dmat4x4 Transform::CalculateFull(const World &GameWorld, size_t id, bool UseBackup) const { glm::dmat4x4 Result(1); for (auto &Matrix : Tranformations) { if (Matrix.first == Type::AutoPosition) { if (GameWorld[id].Position() && !UseBackup) { Result = glm::translate( glm::dmat4{1}, *GameWorld[id].Position()) * Result; } else if(GameWorld[id].BasicBackup()->Position && UseBackup) { Result = glm::translate( glm::dmat4{1}, *GameWorld[id].BasicBackup()->Position) * Result; } } else { Result = Matrix.second * Result; } } return Result; }
true
1548f6c2997acefe60978c79e36cf44fc82c06c1
C++
Shin-jun/Network
/Lecture5_Server/Lecture_Server/TCPServer_Fix.cpp
UHC
3,875
2.859375
3
[]
no_license
#pragma comment(lib, "ws2_32") #include <WinSock2.h> #include <Windows.h> #include <stdio.h> #include <stdlib.h> #define _WINSOCK_DEPRECATED_NO_WARNINGS #define _CRT_SECURE_NO_WARNINGS #define SERVERPORT 9000 #define BUFSIZE 50 // Լ --> void err_quit(const char* msg) { exit(1); } // Լ void err_display(const char* msg) { printf(" ޽"); } // --> recvn int recvn(SOCKET s, char* buf, int len, int flags) { int received; // char* ptr = buf; // ġ int left = len; // while (left > 0) { received = recv(s, ptr, left, flags); if (received == SOCKET_ERROR) { return SOCKET_ERROR; } else if (received == 0) { break; } left -= received; ptr += received; } return(len - left); } int main() { int retval; // Ͽ // ʱȭ WSADATA wsa; if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0) return 1; // --> SOCKET listen_sock = socket(AF_INET, SOCK_STREAM, 0); // AF_INET : IPv4, SOCK_STREAM : TCP if (listen_sock == INVALID_SOCKET) err_quit("socket()"); // 2ܰ : bind() : ip, Ʈ SOCKADDR_IN serveraddr; // ּ ü ZeroMemory(&serveraddr, sizeof(serveraddr)); // ּ 0 ʱȭ serveraddr.sin_family = AF_INET; // ּ ü serveraddr.sin_addr.s_addr = htonl(INADDR_ANY); // ipּ , hton --> host -> network, INADDR_ANY : Ŭ̾Ʈ ipּҸ ̵ serveraddr.sin_port = htons(SERVERPORT); retval = bind(listen_sock, (SOCKADDR*)&serveraddr, sizeof(serveraddr)); if (retval == SOCKET_ERROR) err_quit("bind()"); // 3ܰ : listen() : ¸ ""· ȯ retval = listen(listen_sock, SOMAXCONN); // SOMAXCONN : ִ밪 if (retval == SOCKET_ERROR) err_quit("listen()"); // غ ۾ SOCKET client_sock; // ɶ SOCKADDR_IN clientaddr; // Ŭ̾Ʈ ip, Ʈ () int addrlen; // ּ char buf[BUFSIZE + 1]; // α׷ ۽, ۿ ִ ؼ while (1) { // 4ܰ : accept()Լ --> Ŭ̾Ʈ connectԼ addrlen = sizeof(clientaddr); client_sock = accept(listen_sock, (SOCKADDR*)&clientaddr, &addrlen); if (client_sock == INVALID_SOCKET) { err_display("accept()"); break; } // Ŭ̾Ʈ printf("\n[TCP] Ŭ̾Ʈ : IPּ=%s, Ʈȣ=%d\n", inet_ntoa(clientaddr.sin_addr), ntohs(clientaddr.sin_port)); // Ŭ̾Ʈ while (1) { // 5ܰ : retval = recvn(client_sock, buf, BUFSIZE, 0); // , Źۿ ִ ؼ α׷ , ũ, (0) if (retval == SOCKET_ERROR) { err_display("recv()"); break; } else if (retval == 0) break; // buf[retval] = '\0'; printf("[TCP/%s:%d] %s\n", inet_ntoa(clientaddr.sin_addr), ntohs(clientaddr.sin_port), buf); // 6ܰ : (۽) retval = send(client_sock, buf, retval, 0); // α׷ȿ buf ۽ ۿ ؼ if (retval == SOCKET_ERROR) { err_display("send()"); break; } }// // closesocket 7ܰ : closesocket(client_sock); printf("[TCP] Ŭ̾Ʈ :IPּ =%s, Ʈȣ = %d\n", inet_ntoa(clientaddr.sin_addr), ntohs(clientaddr.sin_port)); } // closesocket() closesocket(listen_sock); // WSACleanup(); getchar(); return 0; }
true
2549e9c29cea438dbc858b2385cfb09af710e435
C++
tristanred/MicroEngine
/projects/tester/DinoCharacter.cpp
UTF-8
1,599
2.78125
3
[ "MIT" ]
permissive
#include "DinoCharacter.h" DinoCharacter::DinoCharacter(GameEngine* engine) : GameObject(engine) { this->DinoSprite = NULL; } DinoCharacter::~DinoCharacter() { // this->GetEngine()->DestroyObject(this->DinoSprite); } void DinoCharacter::Setup(GameModule* currentModule) { this->DinoSprite = currentModule->CreateSprite(); this->DinoSprite->SetPosition(600, 0); this->DinoSprite->SetScale(6); /** * Current implementation needs : * We have 1 long strip of sprites * We need to split that strip and take some textures and generate * animations from them. * */ auto textureStrip = currentModule->CreateTexture("assets/engine/dino/doux.png"); // SplitTexture(int numberOfSplits) Only horizontal split // SplitTexture(int rows, int columns) Grid splitting // SplitTexture(FRectangle) Piece by piece splitting ArrayList<ATexture*>* splitted = textureStrip->SplitTexture(24); SpriteAnimation* idleAnim = SpriteAnimation::FromTextures(splitted, "0..6"); idleAnim->SetName("Idle"); SpriteAnimation* moveAnim = SpriteAnimation::FromTextures(splitted, "6..12"); moveAnim->SetName("Move"); SpriteAnimation* hurtAnim = SpriteAnimation::FromTextures(splitted, "12..24"); hurtAnim->SetName("Hurt"); this->DinoSprite->AddAnimation(idleAnim); this->DinoSprite->AddAnimation(moveAnim); this->DinoSprite->AddAnimation(hurtAnim); this->DinoSprite->Play("Idle", true, 10); } void DinoCharacter::Update(unsigned int deltaTime) { this->DinoSprite->Update(deltaTime); }
true
9de715880d82ec02689d9bd9e74879ae229a7403
C++
huanghongxun/ACM
/vijos/p1391.cpp
UTF-8
804
2.75
3
[ "Unlicense" ]
permissive
#include <iostream> #include <vector> #include <queue> #include <cstring> #define N 2005 using namespace std; struct Edge { int to, rp; Edge(int t, int r) { to = t; rp = r; } }; typedef vector<Edge>::iterator iter; vector<Edge> graph[N]; int main() { int a, b, r, n; cin.sync_with_stdio(false); cin>>n; while(cin>>a>>b>>r && a != 0 && b != 0 && r != 0) { graph[a].push_back(Edge(b, r)); } int dist[N]; memset(dist, 0, sizeof(dist)); queue<int> q; q.push(1); dist[1] = 0x7ffffff; while(!q.empty()) { int u = q.front(); q.pop(); for(iter i = graph[u].begin(); i != graph[u].end(); i++) { if(dist[i->to] < min(i->rp, dist[u])) { dist[i->to] = min(i->rp, dist[u]); q.push(i->to); } } } for(int i = 2; i <= n; i++) cout<<dist[i]<<endl; return 0; }
true
24e556848d3ac6f929c152f013a4085d905b5ff0
C++
Montia/nest
/code/nest/lab1/l1e3_diff_tid_kernel.cc
UTF-8
759
2.609375
3
[ "MIT-Modern-Variant" ]
permissive
#include <cstring> #include "system.h" #ifndef THREAD_NUM #define THREAD_NUM 3 #endif #ifndef PRINT_NUM #define PRINT_NUM 2 #endif void PrintTid(void *p) { int which = (int)p; for (int i = 0; i < PRINT_NUM; i++) { DEBUG('e', "*** thread %d's tid is %d ***\n", which, GetTid()); currentThread->Yield(); } } int Nest(void *arg) { DEBUG('e', "Entering Nest()\n"); char* threadNames[THREAD_NUM+1]; threadNames[0] = "main"; PrintTid(0); for (int i = 1; i <= THREAD_NUM; i++) { threadNames[i] = new char[10]; sprintf(threadNames[i], "thread%d", i); Thread *t = new Thread(threadNames[i]); t->Fork(PrintTid, (void*)i); } return 0; }
true
af98b4445c8edece75666b592245d934f1c8d27d
C++
glebzhut/lab1
/Demo.cpp
UTF-8
2,468
3.546875
4
[]
no_license
#include "Graph.h" void Demo() { cout << "Hello user. Now I show you what can this program." << endl; cout << "Let's start from Dishones Dice. This default dice: "; DishonestDice d; cout << d << endl; cout << "This is a dice with 10 edges: "; d = DishonestDice(10); cout << d << endl; try { cout << "This is a dice with 9 edges: "; d = DishonestDice(9); cout << d << endl; } catch (logic_error e) { cout << e.what() << endl; } cout << "This a dice with 4 edges and chances 1-0.1, 2-0.2, 3-0.3, 4-0.4: "; d = DishonestDice(4, { 1,2,3,4 }); cout << d << endl; cout << "This is autogenerated dice: "; d.AutoGenerate(); cout << d << endl; system("pause"); system("cls"); cout << "Now i autogenerate two dices and count sum and chances." << endl; d.AutoGenerate(); cout << "This is first dice: " << d << endl; DishonestDice d2; d2.AutoGenerate(); cout << "This is second dice: " << d2 << endl; vector<DishonestDice> dices; dices.push_back(d); dices.push_back(d2); cout << "This sums and chances:" << endl; cout << GetStatistic(dices) << endl; system("pause"); system("cls"); cout << "This is all for dices."; cout << "Now Graph. I show you work with graph. For example I choose integer." << endl; cout << "Now I create empty undirected graph with 5 tops and zero element is 0." << endl; Graph<int> g(0, 5, 0); cout << g.GraphMatrix() << endl;; cout << "This information about tops:" << endl; g.InfoAboutTops(); system("pause"); cout << "Now I autogenerate undirected graph with 5 tops, 5 edges, zero element 0." << endl; for (int i = 0; i < 5; i++) g.ChangeTop(AutoGenerateInt(), i); for (int i = 0; i < 5; i++) g.AddEdge(rand() % 5, rand() % 5, AutoGenerateInt()); cout << g.GraphMatrix() << endl;; cout << "This information about tops:" << endl; g.InfoAboutTops(); system("pause"); if (g.Check_Connected()) cout << "Graph connected." << endl; else cout << "Graph not connected" << endl; cout << "This is minimal way table:" << endl; cout << g.Minimal_way_table() << endl; cout << "This list of edges:" << endl; g.PrintList(); system("pause"); cout << "Now I add edge between 1 and 3 with value 6." << endl; g.AddEdge(1, 3, 6); g.PrintList(); cout << "Now I dell edge between 1 and 3." << endl; g.DelEdge(1, 3); g.PrintList(); cout << "Now I delete 0 top." << endl; g.DelTop(1); cout << g.GraphMatrix() << endl; system("pause"); cout << "This is all. Goodbye." << endl; system("pause"); }
true
107cf24d726280d16ab8d1fb798037cbfd9518b3
C++
mjssw/NetworkConnect
/src/Thread.h
UTF-8
764
2.96875
3
[]
no_license
#ifndef THREAD_H #define THREAD_H #include <stdint.h> #ifdef WIN32 #include <windows.h> #else #include <pthread.h> #endif /** * 线程基类,实现类仅需实现Run函数,调用Start启动线程 */ class Thread { private: #ifdef WIN32 static DWORD __stdcall StartRoutine(LPVOID lpParameter); #else static void * StartRoutine(void * lpParameter); #endif public: // 开启线程 void Start(); // 等待线程结束 void WaitForShutdown(); // 子类实现操作 virtual void Run() = 0; // 停止,默认杀线程,子类可更为优雅的实现 virtual void Stop(); virtual ~Thread() {} private: // 线程句柄 #ifdef WIN32 HANDLE m_Thread; #else pthread_t m_Thread; #endif }; #endif // THREAD_H
true
e4486cbc185af83d9e791e845f1a1dde6f4483db
C++
rajeev921/Algorithms
/LeetCode/All_Problem/Tree/426.cpp
UTF-8
2,411
4.15625
4
[]
no_license
/* Convert Binary Search Tree to Sorted Doubly Linked List Convert a Binary Search Tree to a sorted Circular Doubly-Linked List in place. You can think of the left and right pointers as synonymous to the predecessor and successor pointers in a doubly-linked list. For a circular doubly linked list, the predecessor of the first element is the last element, and the successor of the last element is the first element. We want to do the transformation in place. After the transformation, the left pointer of the tree node should point to its predecessor, and the right pointer should point to its successor. You should return the pointer to the smallest element of the linked list. Example 1: Input: root = [4,2,5,1,3] Output: [1,2,3,4,5] Explanation: The figure below shows the transformed BST. The solid line indicates the successor relationship, while the dashed line means the predecessor relationship. Example 2: Input: root = [2,1,3] Output: [1,2,3] Example 3: Input: root = [] Output: [] Explanation: Input is an empty tree. Output is also an empty Linked List. Example 4: Input: root = [1] Output: [1] Constraints: -1000 <= Node.val <= 1000 Node.left.val < Node.val < Node.right.val All values of Node.val are unique. 0 <= Number of Nodes <= 2000 // Definition for a Node. class Node { public: int val; Node* left; Node* right; Node() {} Node(int _val) { val = _val; left = NULL; right = NULL; } Node(int _val, Node* _left, Node* _right) { val = _val; left = _left; right = _right; } }; */ class Solution { private: Node* createNode(int val) { return new Node(val); } void inorder(Node* root, Node*& prev) { if(root==nullptr) return; inorder(root->left, prev); prev->right = root; root->left = prev; prev = root; inorder(root->right, prev); return; } public: Node* treeToDoublyList(Node* root) { if(root==nullptr) return root; Node* dummy = createNode(0); Node* prev = dummy; inorder(root, prev); dummy->right->left = prev; prev->right = dummy->right; return dummy->right; } }; //================================ [4,2,5,1,3] 4 / \ 2 5 / \ 1 3 //================================
true
77c0830a51d74ff141913bc9028ecf914d6140ec
C++
gav1n-cheung/PCL_Study
/Segmentation/NoteOfSegmentation/NoteOfRegionGrowingRGB.cpp
UTF-8
3,013
2.609375
3
[]
no_license
//// //// Created by cheung on 2021/6/12. //// ///*基于颜色的区域生长分割算法 // * 在本教程中,我们将学习如何使用pcl::RegionGrowingRGB类中的实现的基于颜色的区域增长算法。 // * 基于颜色的算法和基于曲率的算法主要有两个主要区别。第一个是它使用颜色而非法线。第二个是它使用合并算法进行过分割和欠分割控制。 // * 分割后,尝试合并颜色相近的簇。两个相邻的平均颜色差异很小的簇被合并在一起。然后进行第二个合并步骤。在此步骤中,每个集群都通过 // * 其包含的点数进行验证。如果这个值小于用户定义的阈值,则当前集群将与最近的相邻集群合并。 // */ //#include <iostream> //#include <thread> //#include <vector> // //#include <pcl/point_types.h> //#include <pcl/io/pcd_io.h> //#include <pcl/search/search.h> //#include <pcl/search/kdtree.h> //#include <pcl/visualization/cloud_viewer.h> //#include <pcl/filters/passthrough.h> //#include <pcl/segmentation/region_growing_rgb.h> // //using namespace std::chrono_literals; // //int //main (int argc, char** argv) //{ // pcl::search::Search <pcl::PointXYZRGB>::Ptr tree (new pcl::search::KdTree<pcl::PointXYZRGB>); // // pcl::PointCloud <pcl::PointXYZRGB>::Ptr cloud (new pcl::PointCloud <pcl::PointXYZRGB>); // if ( pcl::io::loadPCDFile <pcl::PointXYZRGB> ("region_growing_rgb_tutorial.pcd", *cloud) == -1 ) // { // std::cout << "Cloud reading failed." << std::endl; // return (-1); // } // // pcl::IndicesPtr indices (new std::vector <int>); // pcl::PassThrough<pcl::PointXYZRGB> pass; // pass.setInputCloud (cloud); // pass.setFilterFieldName ("z"); // pass.setFilterLimits (0.0, 1.0); // pass.filter (*indices); // //pcl::RegionGrowingRGB实例化,这里我们不使用第二个法线参数,也就是说,我们在这个实例中,并没哟使用法线来分割点云 // pcl::RegionGrowingRGB<pcl::PointXYZRGB> reg; // //设定输入、索引和搜索方法 // reg.setInputCloud (cloud); // reg.setIndices (indices); // reg.setSearchMethod (tree); // //设定距离阈值,用于确定点是否相邻。如果该点位于小于给定阈值的距离处,则认为他是相邻的。该值用于集群邻居搜索。 // reg.setDistanceThreshold (10); // //设定颜色阈值,用于划分集群 // reg.setPointColorThreshold (6); // //设定区域颜色阈值,用于集群合并 // reg.setRegionColorThreshold (5); // //设定最小的集群数 // reg.setMinClusterSize (600); // // std::vector <pcl::PointIndices> clusters; // reg.extract (clusters); // // pcl::PointCloud <pcl::PointXYZRGB>::Ptr colored_cloud = reg.getColoredCloud (); // pcl::visualization::CloudViewer viewer ("Cluster viewer"); // viewer.showCloud (colored_cloud); // while (!viewer.wasStopped ()) // { // std::this_thread::sleep_for(100us); // } // // return (0); //}
true
e69c6390506be9f368994cc8d621c3029434a8cd
C++
ymladeno/OOPaint
/plugins/BasicShapes/BasicShapes.cpp
UTF-8
637
2.515625
3
[]
no_license
/* * BasicShapes.cpp * * Created on: 22 Mar 2018 * Author: osboxes */ #include <iostream> #include <memory> #include "Circle.hpp" #include "Rectangle.hpp" #include "../../inc/ShapeRegistry.hpp" extern "C" void registerMakers(ShapeRegistry& registry ) { std::cout << __PRETTY_FUNCTION__ << std::endl; registry.registerShapes("Circle", [](const Coord2D& coordinates, const std::string& params) { return std::make_shared<Circle>(coordinates, params); }); registry.registerShapes("Rectangle", [](const Coord2D& coordinates, const std::string& params) { return std::make_shared<Rectangle>(coordinates, params); }); }
true
1301f5d65d433e5a0fd04742ba753e96067cdb0e
C++
KiMC2/SelfStudyCpp
/2일차/default_param_with_declare.cpp
UTF-8
321
2.984375
3
[]
no_license
#include <iostream> using namespace std; // 함수 원형에 디폴트 선언 가능. 하지만 독특하다. int TestFunc(int = 10); int TestFunc(int nParam){ return nParam; } int main(int argc, char *argv[]){ std::cout << TestFunc() << std::endl; std::cout << TestFunc(20) << std::endl; return 0; }
true
47b303b255627d61258f9f473b0ce5ba2855a5f9
C++
emreercelebi/Advent-of-Code
/Day 2/checkSumCalculator.cpp
UTF-8
1,912
3.9375
4
[]
no_license
/************************************************************* Advent of Code: Day 2 Challenge 1 Take an input file where each line is a string of lowercase letters. The task is to count how many lines have exactly two of any character, and how many lines have exactly three of any character, then calculate the product of those two values. *************************************************************/ #include <fstream> #include <iostream> #include <string> using std::ifstream; using std::string; using std::cout; using std::endl; void resetCharFreq(int *); int main() { //get input file ifstream inputFile; inputFile.open("input.txt"); if (inputFile) { int *charFreq = new int[26]; //array to store character frequencies for each line //these two results will be incremented as we traverse the file and be multiplies //together to produce the final result. int twoCount = 0; int threeCount = 0; string line; while (inputFile >> line) { resetCharFreq(charFreq); //reset frequency array to all 0's (see function below) //increment frequency table at each letter for (int i = 0; i < line.size(); i++) { charFreq[line.at(i) - 'a']++; } //determine whether current line has exactly two or exactly three //of any character (if both, then it counts for both) bool twoFound = false; bool threeFound = false; for (int i = 0; i < 26; i++) { if (charFreq[i] == 2 && !twoFound) { twoCount++; twoFound = true; } if (charFreq[i] == 3 && !threeFound) { threeCount++; threeFound = true; } } } delete [] charFreq; //delete dynamically allocated array cout << twoCount << " * " << threeCount << " = " <<twoCount * threeCount << endl; //print result } } void resetCharFreq(int *charFreq) { for (int i = 0; i < 26; i++) { charFreq[i] = 0; } }
true
561fe5d395f9d4e483689c6ad737fcd19b88a7a7
C++
nihk/Cap-Man
/Cap-Man/Sprite.cpp
UTF-8
514
3.046875
3
[]
no_license
#include "Sprite.h" #include "Renderer.h" Sprite::Sprite(Texture& texture, Rect source) : mTexture(texture) , mSource(source) { } Sprite::Sprite(const Sprite& other) : mTexture(other.mTexture) , mSource(other.mSource) { } Sprite::~Sprite() { } Sprite& Sprite::operator=(const Sprite& other) { mTexture = other.mTexture; mSource = other.mSource; return *this; } void Sprite::draw(const Renderer& renderer, const Rect& dest) { renderer.copyTexture(mTexture, mSource, dest); }
true
8201bb3cc906a221488ceb97b60bc836f6e0e53f
C++
en30/online-judge
/aoj/ALDS1_3_D.cpp
UTF-8
799
2.765625
3
[]
no_license
#include <bits/stdc++.h> using namespace std; typedef long long ll; #define rep(i, N) for (int i = 0; i < (int)N; i++) struct puddle { int area; int x; }; int main () { stack<int> down; stack<puddle> s; char c; int x = 0; while(cin >> c) { x++; if(c == '\\') { down.push(x); } else if(c == '/' && !down.empty()) { int px = down.top(); down.pop(); int a = x - px; while(!s.empty() && s.top().x > px) { a += s.top().area; s.pop(); } s.push(puddle{a, x}); } } int A = 0; vector<int> L(s.size()); rep(i,L.size()) { int a = s.top().area; L[L.size() - 1 - i] = a; A += a; s.pop(); } cout << A << endl; cout << L.size(); rep(i,L.size()) cout << " " << L[i]; cout << endl; return 0; }
true
1c607d887a9334a5b8f32c8ee446c81a8188639b
C++
likunjk/Algorithm
/sub_structure_of _tree.cpp
UTF-8
1,314
2.796875
3
[]
no_license
#include<iostream> #include<cstdio> #include<cstring> using namespace std; typedef unsigned long long ull; const int N = 1009; int A[N][2]; //因为是二叉树,因此不必使用数组 int B[N][2]; int valueA[N]; int valueB[N]; bool dfs(int a, int b) { if(b==0) //为0表示不存在该节点 return true; //若要是子树, 则必须左右子树一一对应 if(a==0 || valueA[a]!=valueB[b] || dfs(A[a][0], B[b][0])==false || dfs(A[a][1], B[b][1])==false) return false; return true; } bool is_Sub(int n) { for(int i=1; i<=n; ++i) { if(valueA[i]==valueB[1]) //默认1为B树的根节点 { if(dfs(i,1)) return true; } } return false; } //测试链接:http://ac.jobdu.com/problem.php?pid=1520 int main(void) { int i,j,n,m,k; int tt; while(scanf("%d %d", &n, &m)!=EOF) { memset(A, 0, sizeof(A)); memset(B, 0, sizeof(B)); for(i=1; i<=n; ++i) scanf("%d", &valueA[i]); for(i=1; i<=n; ++i) { scanf("%d", &k); for(j=0; j<k; ++j) { scanf("%d", &tt); A[i][j] = tt; } } for(i=1; i<=m; ++i) scanf("%d", &valueB[i]); for(i=1; i<=m; ++i) { scanf("%d", &k); for(j=0; j<k; ++j) { scanf("%d", &tt); B[i][j] = tt; } } if(n!=0 && m!=0 && is_Sub(n)==true) printf("YES\n"); else printf("NO\n"); } return 0; }
true
bfd2977edc475f78b075abe8d490bee08994bdc7
C++
Jyrgal/eggPickup
/pickup___dropoff/pickup___dropoff.ino
UTF-8
3,916
2.984375
3
[]
no_license
#include <Servo.h> Servo servo1; // create servo object to control a servo // twelve servo objects can be created on most boards int pickup_open_servo = 0; int pickup_close_servo = 0; int initial_distance = 0; int picked_up = 0; int dropoff = 1; int servo_dropoff = 0; int complete = 0; int dropoff_start = 0; int trigPin = 11 ; // Trigger int echoPin = 12; // Echo float duration, cm; //Pulley motor int IN1 = 5; //control pin for first motor int IN2 = 7; //control pin for first motor int EN_A = 6; //Enable pin for first motor //Vertical motor int IN3 = 2; int IN4 = 4; int EN_B = 3; int warning = 13; void setup() { Serial.begin (9600); servo1.attach(A5); // attaches the servo on pin 9 to the servo object pinMode (warning, OUTPUT); pinMode(trigPin, OUTPUT); pinMode(echoPin, INPUT); } void loop() { //audioVal_total = 0.0; //audioSense(); if (picked_up == 0) { digitalWrite(warning, HIGH); delay(500); digitalWrite(warning, LOW); pickup_function(); } else { digitalWrite(warning, HIGH); delay(500); digitalWrite(warning, LOW); dropoff_function(); } } void dropoff_function() { ultrasonic_sense(); //servo1.write(0); if (dropoff_start == 0) { initial_distance = cm; Serial.println(initial_distance); dropoff_start = 1; } if (servo_dropoff == 1 && cm >= initial_distance) { wind_stop(); complete = 1; } if (dropoff == 1 && complete == 0) { if (cm > 12 && servo_dropoff == 0) { wind_down(); } else if (cm <= 12 && servo_dropoff == 0) { wind_stop(); delay(2000); servo1.write(0); servo_dropoff = 1; } else if (complete == 0) { wind_up(); servo1.detach(); } } } void pickup_function() { ultrasonic_sense(); if (pickup_close_servo == 1 && cm >= initial_distance) { Serial.println("initiate movement"); wind_stop(); picked_up = 1; } //opening servo at top if (pickup_open_servo == 0) { servo1.write(0); initial_distance = cm; pickup_open_servo = 1; Serial.println(); Serial.println(" INTIAL DISTANCE:"); Serial.println(initial_distance); } if (picked_up == 0) { if (cm > 12 && pickup_close_servo == 0) { wind_down(); } else if (cm <= 12 && pickup_close_servo == 0) { wind_stop(); delay(2000); for (int angle = 0; angle < 130; angle++) { servo1.write(angle); delay(10); } pickup_close_servo = 1; } else if (picked_up == 0) { wind_up(); //servo1.detach(); } } } void ultrasonic_sense(){ // The sensor is triggered by a HIGH pulse of 10 or more microseconds. // Give a short LOW pulse beforehando //to ensure a clean HIGH pulse: digitalWrite(trigPin, LOW); delayMicroseconds(5); digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, LOW); // Read the signal from the sensor: a HIGH pulse whose // duration is the time (in microseconds) from the sending // of the ping to the reception of its echo off of an object. //pinMode(echoPin, INPUT) duration = pulseIn(echoPin, HIGH); // Convert the time into a distance cm = (duration/2) / 29.1; // Divide by 29.1 or multiply by 0.0343 Serial.print(cm); Serial.println(" cm"); delay(250); } void wind_down() { Serial.println(initial_distance); Serial.print("wind down"); analogWrite(EN_B, 50); digitalWrite(IN3, HIGH); digitalWrite(IN4, LOW); } void wind_stop() { Serial.println(initial_distance); digitalWrite(IN3, LOW); digitalWrite(IN4, LOW); analogWrite(EN_B, 0); Serial.print(cm); Serial.println(" cm"); Serial.println("WIND STOP"); } void wind_up() { Serial.println(initial_distance); digitalWrite(IN3, LOW); digitalWrite(IN4, HIGH); analogWrite(EN_B, 150); Serial.print("WIND UP"); Serial.println(); }
true
f66c4dbf30c38fe1195ac4fd201f1ceec06dc227
C++
wolfdan666/WolfEat3moreMeatEveryday
/history_practice/2019.4/2019.4.24/D_zoj3822_概率dp.cpp
UTF-8
4,185
3.109375
3
[]
no_license
// 2019年4月24日16:20:52再次看题,希望20mins后就完成 // 2019年4月24日16:59:44 由于没有学这部分,所以只看懂了第二种解法,然后就用第二种解法 // 2019年4月24日17:02:36 发现ZOJ只是单独地不能交B题... // 概率dp(暂时还没有补这部分) // 首先求出 放置到前i行 前j列时刻,棋盘中 放置 k棋子个数的 概率。 // 然后递推。 // 我们发现,总共四种状态。 // 1 当前行当前列有,我们可以在之前已经合法的地方在加一个。 // 2当前列没有 n-j+1 *i // 3 当前行没有 // 4 当前行 当前列都没有 /*#include <queue> #include <vector> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <iostream> #include <algorithm> using namespace std; double dp[55][55][3005]; int main(){ int t; int m,n; scanf("%d",&t); while(t--) { scanf("%d%d",&m,&n); memset(dp,0,sizeof(dp)); dp[0][0][0]=1; for(int k=1;k<=m*n;k++) for(int i=1;i<=m;i++){ for(int j=1;j<=n;j++){ dp[i][j][k]+=dp[i-1][j-1][k-1]*1.0*(m-i+1)*(n-j+1)/(1.0*(m*n-k+1));// 此行此列的左上角部分,所以就是m-(i-1)=m-i+1,其他同理 dp[i][j][k]+=dp[i-1][j][k-1]*1.0*(m-i+1)*j/(1.0*(m*n-k+1)); dp[i][j][k]+=dp[i][j-1][k-1]*1.0*i*(n-j+1)/(1.0*(m*n-k+1)); if(i==m&&j==n) continue; dp[i][j][k]+=dp[i][j][k-1]*1.0*(i*j-k+1)/(1.0*(m*n-k+1)); } } double ans=0; for(int i=0;i<=n*m;i++) ans+=dp[m][n][i]*i; printf("%.8f\n",ans); } return 0; }*/ // 大佬:http://www.voidcn.com/article/p-hrvhlcgl-bqp.html /* 题目大意:有一个n行n列的棋盘,每次可以放一个棋子,问把每行每列都至少有一个棋子的期望。 题目思路:概率dp,dp[i][j][k]。i表示放了i行,j表示放了j列,k代表用了k个棋子。 dp[i][j][k] = 原始状态的概率 * 选到当前这样状态的概率。 我们可以知道,每放一个棋子会出现4种情况, 一、没有增加一行一列,dp[i][j][k] += dp[i][j][k - 1] * (i * j - k + 1) / (sum - k + 1); 二、增加了一行,dp[i][j][k] += dp[i - 1][j][k - 1] * (n- i + 1) * j / (sum - k + 1); 三、增加了一列,dp[i][j][k] += dp[i][j - 1][k - 1] * (m - j + 1) * i / (sum - k + 1); 四、增加了一行一列 dp[i][j][k] += dp[i - 1][j - 1][k - 1] * (n - i + 1) * (m - j + 1) / (sum - k + 1); 例外需要注意,由于题目要求第k个棋子刚好填满n行m列,故概率为dp[n][m][k] - dp[n][m][k - 1]; // 自己理解:所以到了后面的时候,d[n][m][n*m量级的时候],两个相减几乎就是0.因为两者的值都接近于1吧 --------------------- 作者:宣之于口 原文:https://blog.csdn.net/loy_184548/article/details/46849367 */ #include <vector> #include <map> #include <set> #include <algorithm> #include <iostream> #include <cstdio> #include <cmath> #include <cstdlib> #include <string> #include <cstring> using namespace std; double dp[60][60][3600] = {0}; int main(){ int t; cin >> t; while(t--) { int n,m; cin >> n >> m; int sum = n * m; for (int k = 0; k <= sum; k++) for (int i = 0; i <= n; i++) for (int j = 0; j <= m; j++) dp[i][j][k] = 0; dp[0][0][0] = 1; for (int k = 1; k <= sum; k++) { for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { double ret = sum - k + 1; dp[i][j][k] += dp[i][j][k - 1] * (i * j - k + 1) / ret; dp[i][j][k] += dp[i][j - 1][k - 1] * (m - j + 1) * i / ret; dp[i][j][k] += dp[i - 1][j][k - 1] * (n- i + 1) * j / ret; dp[i][j][k] += dp[i - 1][j - 1][k - 1] * (n - i + 1) * (m - j + 1) / ret; } } } double ans = 0; for (int k = 1; k <= sum; k++) ans += (dp[n][m][k] - dp[n][m][k - 1]) * k; printf("%.10f\n",ans); } return 0; }
true
3e8e0c4b09275d433ae5edc6ecb5782b9bc79205
C++
LionCoder4ever/algorithm
/cpp/121.买卖股票的最佳时机.cpp
UTF-8
427
3
3
[]
no_license
/* * @lc app=leetcode.cn id=121 lang=cpp * * [121] 买卖股票的最佳时机 */ // @lc code=start class Solution { public: int maxProfit(vector<int>& prices) { int n = prices.size(); int ans = INT_MIN; int buy = INT_MAX; for(int i =0;i<n;i++) { buy = min(buy, prices[i]); ans = max(prices[i]- buy, ans); } return ans; } }; // @lc code=end
true
05a14c19429d9ead85e18f5e01b19c95946e8410
C++
gaolu/Leetcode
/distinctSubsequences.cpp
UTF-8
465
2.578125
3
[]
no_license
class Solution { public: int numDistinct(string S, string T) { // Start typing your C/C++ solution below // DO NOT write int main() function vector<int> dp(T.size() + 1); dp[T.size()] = 1; // choose nothing for(int i = S.size() - 1; i >= 0; i--){ for(int j = 0; j < T.size(); j++){ if(T[j] == S[i]) dp[j] += dp[j + 1]; } } return dp[0]; } };
true
2b9ff858cabf2e3ebb611343dcdb7548d37dbb44
C++
niekbouman/ctbignum
/include/ctbignum/utility.hpp
UTF-8
2,071
2.828125
3
[ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ]
permissive
// // This file is part of // // CTBignum // // C++ Library for Compile-Time and Run-Time Multi-Precision and Modular Arithmetic // // // This file is distributed under the Apache License, Version 2.0. See the LICENSE // file for details. #ifndef CT_UTILITY_HPP #define CT_UTILITY_HPP #include <ctbignum/bigint.hpp> #include <array> #include <cstddef> #include <limits> namespace cbn { namespace detail { template <size_t N, typename T> constexpr auto tight_length(big_int<N, T> num) { // count the effective number of limbs // (ignoring zero-limbs at the most-significant-limb side) size_t L = N; while (L > 0 && num[L - 1] == 0) --L; return L; } template <typename T, T... Is> constexpr auto tight_length(std::integer_sequence<T, Is...>) { // count the effective number of limbs // (ignoring zero-limbs at the most-significant-limb side) size_t L = sizeof...(Is); std::array<T, sizeof...(Is)> num{Is...}; while (L > 0 && num[L - 1] == 0) --L; return L; } template <std::size_t N, typename T> constexpr auto bit_length(big_int<N, T> num) { // we define bit_length(0) := 1 auto L = tight_length(num); L += (L == 0U); // ensure L > 0 size_t bitlen = L * std::numeric_limits<T>::digits; T msb = num[L - 1]; while (bitlen > 1 && (msb & (static_cast<T>(1) << (std::numeric_limits<T>::digits - 1))) == 0) { msb <<= 1; --bitlen; } return bitlen; } template <std::size_t N1, std::size_t N2, typename T> constexpr void assign(big_int<N1, T>& dst, big_int<N2, T> src) { // assignment for the scenario where N1 >= N2 static_assert(N1 >= N2, "cannot assign: destination has smaller size than source"); for (std::size_t i = 0; i < N1; ++i) dst[i] = src[i]; for (auto i = N1; i < N2; ++i) dst[i] = 0; } } // end of detail namespace template <size_t ExplicitLength = 0, typename T, T... Limbs> constexpr auto to_big_int(std::integer_sequence<T, Limbs...>) { return big_int<ExplicitLength ? ExplicitLength : sizeof...(Limbs),T>{ Limbs... }; } } // end of cbn namespace #endif
true
e026278afe32cd068b08b3824accd87d4c5caecb
C++
nya3jp/icpc
/uva/solved/104/10424-nya.cc
UTF-8
1,161
3.40625
3
[]
no_license
/* * UVA 10424 Love Calculator * 2005-07-16 * by nya */ #include <iostream> #include <string> #include <cstdio> #include <algorithm> int value_of_name(const std::string& name) { int n = name.size(); int value = 0; for(int i=0; i<n; i++) { char c = name[i]; if ('A' <= c && c <= 'Z') { value += (int)(c-'A') + 1; } else if ('a' <= c && c <= 'z') { value += (int)(c-'a') + 1; } } return value; } inline int compact(int n) { while(n >= 10) { int t = 0; while(n > 0) { t += n%10; n /= 10; } n = t; } return n; } int main() { while(true) { std::string girl, boy; std::getline(std::cin, girl); std::getline(std::cin, boy); if (! std::cin) break; int girl_n, boy_n; girl_n = compact( value_of_name(girl) ); boy_n = compact( value_of_name(boy) ); std::printf("%.2f %%\n", ((double)std::min(girl_n, boy_n) / std::max(girl_n, boy_n) * 100.0) ); } return 0; }
true
5fb5d65f4be18e038d8597affb273e778c3fda75
C++
KeyMaker13/C-plus-plus
/Pearson Books/Data Abstraction And Problem Solving With C++ 5e/src/ByName/c11/PQ.cpp
UTF-8
824
3.296875
3
[]
no_license
/** @file PQ.cpp * ADT priority queue. * A heap represents the priority queue. */ #include "PQ.h" // header file for priority queue bool PriorityQueue::pqIsEmpty() const { return h.heapIsEmpty(); } // end pqIsEmpty void PriorityQueue::pqInsert(const PQueueItemType& newItem) throw(PQueueException) { try { h.heapInsert(newItem); } // end try catch (HeapException e) { throw PQueueException("PQueueException: Priority queue full"); } // end catch } // end pqInsert void PriorityQueue::pqDelete(PQueueItemType& priorityItem) throw(PQueueException) { try { h.heapDelete(priorityItem); } // end try catch (HeapException e) { throw PQueueException("PQueueException: Priority queue empty"); } // end catch } // end pqDelete // End of implementation file.
true
888d32a27846909a98f4196c4ec13917b5c4551a
C++
Aaron-Cai/brainfuck
/branfuck/Source.cpp
UTF-8
3,670
3.3125
3
[]
no_license
#include <iostream> #include <string> #include <fstream> #include <stdio.h> using namespace std; const unsigned byteSize = 30000; class Interpreter { public: enum InterpretingState { NORMAL, LOOP_END, ERROR }; Interpreter(bool de = false) { byte = new char[byteSize]; memset(byte, 0, byteSize*sizeof(char)); pointer = byte; debug = de; } ~Interpreter() { delete[]byte; } InterpretingState interpreter(char opr) { InterpretingState state = NORMAL; try { switch (opr) { case '>': if (pointer < byte + byteSize) { pointer++; } break; case '<': if (pointer > byte) { pointer--; } else { throw("error"); } break; case '+': (*pointer)++; break; case '-': (*pointer)--; break; case '.': cout << (*pointer); break; case ',': cout << "Please input a value... "; cin >> (*pointer); break; default: throw exception("Invalid operator"); } } catch (const std::exception& e) { cerr << e.what() << endl; cout << "$ "; } return state; } void ScanCode(string code) { size_t i = 0; try { while (i < code.size()) { if (code[i] != '[' && code[i] != ']') { interpreter(code[i]); i++; } else { if (*pointer == 0) { if (code[i] == ']') i++; else { while (code[i] != ']')i++; i++; } } else { if (code[i] == ']') while (code[i] != '[') { i--; if (i < 0) throw exception("Syntax error"); } else i++; } } } if (debug) { display(); } } catch (const std::exception& e) { cerr << e.what() << endl; } } void display() // { cout << "\n\n"; for (size_t i = 0; i < 20; i++) { cout << (int)byte[i] << " "; } cout << "\n"; int pos = pointer - byte; for (int i = 0; i < pos-1; i++) { cout << " "; } cout << "^\n$ "; } void SwitchDebugState() { debug = !debug; } private: char* byte; char* pointer; bool debug = false; }; int main(int argc, char** argv) { const string version = "0.9.0"; if (argc == 1) //interactor mode { cout << "Brainfuck " << version << ". "; cout << "Type \"help\", \"copyright\" for more information.\n"; cout << "To quit, press CTRL+Z\n"; cout << "$ "; Interpreter in(true); string code; while (cin >> code) { if (code == "help") { string info = "> increment the data pointer (to point to the next cell to the right).\n< decrement the data pointer(to point to the next cell to the left).\n+ increment(increase by one) the byte at the data pointer.\n- decrement(decrease by one) the byte at the data pointer.\n. output the byte at the data pointer.\n, accept one byte of input, storing its value in the byte at the data pointer.\n[ if the byte at the data pointer is zero, then instead of moving the instruction pointer forward to the next command, jump it forward to the command after the matching] command.\n] if the byte at the data pointer is nonzero, then instead of moving the instruction pointer forward to the next command, jump it back to the command after the matching [ command.\n"; cout << info << "$ "; continue; } cout << "$ "; in.ScanCode(code); } } else if (argc == 2) { string arg = argv[1]; if (arg == "-v") { cout << "Brainfuck version: " << version << "\n"; } else { ifstream fin(arg); string code; Interpreter in; while (fin >> code)//todo some bug when exec file { cout << code << endl; in.ScanCode(code); } } } return 0; }
true
81ab01c2af86e65d81c11534de9d0431235151a6
C++
yeoneei/algorithm
/backjoon/17281.cpp
UTF-8
1,657
2.59375
3
[]
no_license
// // 17281.cpp // backjoon // // Created by 조연희 on 29/03/2020. // Copyright © 2020 조연희. All rights reserved. // #include <iostream> #include <vector> #include <deque> using namespace std; int n; vector<vector<int>> vc; int play[9]; bool check[9]; int answer=0; void getScore(){ int ening=0,j=0,scroe=0; while(ening<n){ int out=0; deque<int> de; while(out<3){ int now = vc[ening][play[j]]; if(now==0){ out++; } else if(now==1 ||now==2 || now==3){ for(int s=0; s<de.size();s++){ de[s]+=now; } while(!de.empty() && de[0]>3){ scroe++; de.pop_front(); } de.push_back(now); }else if(now==4){ scroe+=(de.size()+1); de.clear(); } j++; if(j==9){ j=0; } } ening++; } answer = max(scroe,answer); } void getPlayer(int cnt){ if(cnt==9){ getScore(); return; } for(int i=1; i<9;i++){ if(check[i])continue; check[i]=1; play[cnt]=i; if(cnt+1==3){ getPlayer(cnt+2); }else getPlayer(cnt+1); check[i]=0; } } int main(){ ios_base::sync_with_stdio(0); cin.tie(0); cin>>n; vc.resize(n); for(int i=0; i<n;i++){ vc[i].resize(9); for(int j=0; j<9;j++){ cin>>vc[i][j]; } } play[3]=0; check[0]=1; getPlayer(0); cout<<answer; }
true
e182dfab60909e0e5582b53ddb6ae78a454b3044
C++
Lancelot0902/LeetCode
/leetcode/17.LetterCombination/solution.cpp
UTF-8
949
3.359375
3
[]
no_license
#include <iostream> #include <vector> #include <map> #include <string> void dfs(std::map<char, std::string> &m, std::vector<std::string> &res, std::string &str, int pos) { if (pos == str.size()) return; std::string s = m[str[pos]]; int n = res.size(); for (int i = 0; i != n; ++i) { for (int j = 0; j != s.size(); ++j) { std::string temp = res[i]; temp += s[j]; res.push_back(temp); } } res.erase(res.begin(), res.begin() + n); dfs(m, res, str, pos + 1); } std::vector<std::string> letterCombinations(std::string digits) { std::map<char, std::string> m; std::vector<std::string> res; m['2'] = "abc"; m['3'] = "def"; m['4'] = "ghi"; m['5'] = "jkl"; m['6'] = "mno"; m['7'] = "pqrs"; m['8'] = "tuv"; m['9'] = "wxyz"; std::string temp; res.push_back(temp); dfs(m, res, digits, 0); return res; }
true
5bd8bbd386b19d0fd6fe5756a21e4b5b69e1494f
C++
yashika66011/Daily-DSA-Coding
/Arrays/MaxMinInArray.cpp
UTF-8
958
3.921875
4
[ "MIT" ]
permissive
/* Find Max and Min elements in an Array Time Complexity: O(N) */ #include<iostream> using namespace std; struct Pair { int min; int max; }; struct Pair getMinMax(int arr[], int n) { struct Pair P; if(n==1) { P.min = P.max = arr[0]; return P; } if(arr[0] > arr[1]) { P.min = arr[1]; P.max = arr[0]; } else { P.min = arr[0]; P.max = arr[1]; } for(int i=2; i<n; ++i) if(arr[i] < P.min) P.min = arr[i]; else if(arr[i] > P.max) P.max = arr[i]; return P; } void printArray(int arr[], int n) { for(int i=0; i<n; i++) cout<<arr[i]<<" "; } int main() { int arr[5] = {21, 5, 9, 2, 20}; int n = sizeof(arr)/sizeof(arr[0]); cout<<"Original Array: "; printArray(arr, n); struct Pair P = getMinMax(arr, n); cout<<"\nMin Value: "<<P.min; cout<<"\nMax Value: "<<P.max; return 0; }
true
888dcc8b25b7530036cc8466f061c9c7092ef162
C++
sogapalag/problems
/codejam/2019_1a_b.cpp
UTF-8
2,346
2.59375
3
[ "MIT" ]
permissive
#include <bits/stdc++.h> using namespace std; template <typename T=int> T exgcd(T a, T b, T& x, T& y) { if (!a) { x = 0; y = 1; return b; } T d = exgcd(b%a, a, y, x); x -= b/a * y; return d; } // watch out potential overflow! template <typename T> T crt(T a1, T a2, T n1, T n2) { T m1, m2; assert(exgcd<T>(n1,n2,m1,m2) == 1); T z = n1*n2; T res = (__int128)a1*m2%z*n2 %z + (__int128)a2*m1%z*n1 %z; ((res%=z)+=z)%=z; assert(res%n1 == a1%n1); assert(res%n2 == a2%n2); return res; } template <typename T> T excrt(T a1, T a2, T n1, T n2) { T m1, m2; T g = exgcd<T>(n1,n2,m1,m2); assert(abs(a1-a2) % g == 0); T z = n1*n2/g; T res = a1 - (__int128)n1*m1%z*((a1-a2)/g)%z; ((res%=z)+=z)%=z; assert(res%n1 == a1%n1); assert(res%n2 == a2%n2); return res; } using ll=long long; using vl = vector<ll>; ll dummy(vl& a, vl& p){ const int N = 1e6+10; vector<int> cnt(N, 0); for (int i = 0; i < 7; i++) { for (int x = a[i]; x < N; x+=p[i]) { cnt[x]++; } } for (int x = 1; x < N; x++) { if (cnt[x] == 7) return x; } } // 7, 18, cycle, obvious hint crt. // 2*3*5*7*11*13*17 ~ 5e5. since crt require pair-coprime, 2->4, already sat.1e6. // even though 3->9, 2->16. we can get larger bound. void solve() { int n = 7; vector<ll> p = {3, 4, 5, 7, 11, 13, 17}; vector<ll> a(n); auto query = [](ll x){ for (int _ = 0; _ < 18; _++) { cout << x << ' '; }cout << endl;//'\n' << flush; ll sum = 0; for (int _ = 0; _ < 18; _++) { ll r; cin >> r; sum += r; } return sum % x; }; for (int i = 0; i < n; i++) { a[i] = query(p[i]); } ll r = a[0], m = p[0]; for (int i = 1; i < n; i++) { r = crt<ll>(r, a[i], m, p[i]); m *= p[i]; } for (int i = 0; i < n; i++) { assert(r % p[i] == a[i]); } assert(dummy(a,p) == r); cout << r << endl;// << '\n' << flush; int verdict; cin >> verdict; assert(verdict == 1); if (verdict == -1) exit(-1); } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int t,_n,_m; cin >> t >> _n >> _m; while(t--)solve(); return 0; // ...additional endl, result WA. //cout << endl; }
true
eef9b1a8c7d8934bd3e2c33974b8965d7c1497ec
C++
heisai/Buffer
/Buffer.h
UTF-8
1,253
3.234375
3
[]
no_license
#ifndef BUFFER_H #define BUFFER_H #include<iostream> #include<cstring> #include<assert.h> using namespace std; class Buffer { public: explicit Buffer(); virtual ~Buffer(); public: void PutUint8(uint8_t value); void PutUint16(uint16_t value); void PutUint32(uint32_t value); void PutUint64(uint64_t value); void PutString(const string &str); uint8_t ReadUint8(); uint16_t ReadUint16(); uint32_t ReadUint32(); uint64_t ReadUint64(); string ReadString(size_t len); void Reset(); void Truncate(size_t index); void Skip(size_t index); size_t Length(); size_t size(); void Reserve(size_t size); size_t WriteableBytes(); unsigned char *begin(); unsigned char *end(); private: uint8_t PeekUint8(); uint16_t PeekUint16(); uint32_t PeekUint32(); uint64_t PeekUint64(); string PeekString(size_t len); void Write(const void* d, int len); void Read(); unsigned char* WriteBegin(); const unsigned char * ReadBegin(); int Capacity()const {return capacity_;} void grow(size_t size); private: unsigned char *buffer_; size_t write_index_ = 0; size_t read_index = 0; size_t capacity_ = 2048; }; #endif // BUFFER_H
true
ff6477862ff273e1f646ad1a55b796a937fe226c
C++
kangsanguk/C_study
/hw32.cpp
UHC
1,693
3.5625
4
[]
no_license
#include<stdio.h> #pragma warning(disable:4996) int inputUInt(const char *msg); double inputDouble(const char *msg); int ipow(int aVal1,int aVal2); double fpow(double aVal1, int aVal2); void myflush(); int main() { int num1, pNum,result1; double num2,result2; num1 = inputUInt(" * ԷϽÿ:"); pNum = inputUInt(" * ԷϽÿ:"); result1 = ipow(num1, pNum); printf("%d %d %d Դϴ.\n", num1, pNum, result1); num2 = inputDouble(" * Ǽ ԷϽÿ:"); pNum = inputUInt(" * ԷϽÿ:"); result2 = fpow(num2, pNum); printf("%.2lf %d %.3lf Դϴ.", num2, pNum, result2); } int inputUInt(const char *msg) { int value; printf("%s", msg); scanf("%d", &value); while (getchar() != '\n') { myflush(); printf("%s", msg); scanf("%d", &value); } return value; } void myflush() { while (getchar() != '\n'); { ; } } double inputDouble(const char *msg) { double value; printf("%s", msg); scanf("%lf", &value); while (getchar() != '\n') { myflush(); printf("%s", msg); scanf("%lf", &value); } return value; } int ipow(int aVal1, int aVal2) { int value; if (aVal1 == 0) { return 0; } for (int i = 0; i <= aVal2; i++) { if (i == 0) { value = 1; } else { value *= aVal1; } } return value; } double fpow(double aVal1, int aVal2) { double value; if (aVal1 == 0) { return 0.0; } for (int i = 0; i <= aVal2; i++) { if (i == 0) { value = 1.0; } else { value *= aVal1; } } return value; }
true
cdc4df7f387235114981ba4bf926b1cf9788e5b9
C++
krpraveen0/cpp-resource
/oops/class-10/mem-func-overriding.cpp
UTF-8
599
3.515625
4
[]
no_license
//overiding of member function-- //overriding is the proces in which we try to redefine the base class functions // in its child/derived class //note: a function can be overriden only if both the child class and parent class //function have the same name as well as same number of arguments. #include<iostream> using namespace std; class Animal{ public: void msg(){ cout<<"I am animal"<<endl; } }; class Dog:public Animal{ public: void msg(){ cout<<"bhow!! bhow I am dog here!!"<<endl; } }; int main(){ Animal a; a.msg(); Dog d; d.msg(); }
true
4beb9a33371a2f96aa9700bbd3a0a30c604a637c
C++
necokeine/eos
/plugins/sql_db_plugin/fifo.h
UTF-8
1,735
3.203125
3
[ "MIT", "BSD-3-Clause", "Apache-2.0" ]
permissive
/** * @file * @copyright defined in eos/LICENSE.txt */ #pragma once #include <mutex> #include <condition_variable> #include <atomic> #include <utility> #include <vector> #include <boost/noncopyable.hpp> namespace eosio { template<typename T> class fifo : public boost::noncopyable { public: enum class behavior {blocking, not_blocking}; fifo(behavior value); void push(const unsigned int& block_num); std::pair<unsigned int, unsigned int> pop_all(); void set_behavior(behavior value); private: std::condition_variable m_cond; std::atomic<behavior> m_behavior; std::mutex m_mux; unsigned int current_biggest_block; unsigned int last_fetched_block; }; template<typename T> fifo<T>::fifo(behavior value) { m_behavior = value; current_biggest_block = 0; last_fetched_block = 2; } template<typename T> void fifo<T>::push(const unsigned int& block_num) { std::lock_guard<std::mutex> lock(m_mux); current_biggest_block = std::max(current_biggest_block, block_num); m_cond.notify_one(); } template<typename T> std::pair<unsigned int, unsigned int> fifo<T>::pop_all() { const unsigned int size_per_pick = 1000; unsigned int left = 0, right = 0; { std::unique_lock<std::mutex> lock(m_mux); m_cond.wait(lock, [&]{return m_behavior == behavior::not_blocking || (current_biggest_block >= last_fetched_block);}); left = last_fetched_block; right = std::min(left + size_per_pick, current_biggest_block); last_fetched_block = right + 1; } return std::make_pair(left, right); } template<typename T> void fifo<T>::set_behavior(behavior value) { m_behavior = value; m_cond.notify_all(); } } // namespace
true
59302c1f70fad4d7f266ac6ef0f6758b542cad1d
C++
andreiburov/db
/database/slotted/TID.h
UTF-8
1,245
2.96875
3
[]
no_license
#ifndef DB_TID_H #define DB_TID_H #include <cstdint> #include <functional> struct TID { // sizeof 64 bits uint16_t slot_id; uint64_t page_offset : 48; static const uint64_t SLOT_MASK = 0xFFFF000000000000; static const uint64_t PAGE_MASK = 0xFFFFFFFFFFFF; TID(uint16_t slot_id, uint64_t page_offset) : slot_id(slot_id), page_offset(page_offset) {} TID(uint64_t tid) : slot_id((uint16_t)(((tid & SLOT_MASK))>>48)), page_offset(tid & PAGE_MASK) {} TID() : slot_id(0), page_offset(0) { } uint64_t uint64() { return ((uint64_t)slot_id<<48)|page_offset; } bool operator==(const TID& other) const { return slot_id == other.slot_id && page_offset == other.page_offset; } bool operator!=(const TID& other) const { return slot_id != other.slot_id || page_offset != other.page_offset; } TID& operator++() // prefix increment { slot_id++; return *this; } }; namespace std { template<> struct hash<TID> { size_t operator()(const TID &tid) const { return (hash<uint64_t>()(tid.page_offset) ^ (hash<uint16_t>()(tid.slot_id) << 1)) >> 1; } }; } #endif //DB_TID_H
true
00aaec23dde935779e72a1707f6a88e1cd1e7575
C++
sofi-moshkovskaya/C-plus-labs
/lab_16/2.cpp
WINDOWS-1251
686
3.15625
3
[]
no_license
/* 2. , , , . Moshkovskaya Sophia 18.03.2019*/ #include <iostream> #include <conio.h> using namespace std; void main() { char surname[50]; char name[50]; char patronymic[50]; cout << "Input your Surname, Name, Patronymic by space." << endl; cin >> surname >> name >> patronymic; cout << "\n\nStrudent:\nSurname: " << surname << "\nName: " << name << "\nPatronymic: " << patronymic << endl; _getch(); }
true
71398e19da0123f5df76c964b6b748196954d591
C++
TatTangpirul/h3
/Donut.cpp
UTF-8
432
2.515625
3
[ "MIT" ]
permissive
#include<bits/stdc++.h> using namespace std; int main() { int n,song; cin>>n; deque<int> dq; for (int i=0;i<n;i++){ cin>>song; dq.push_back(song); } cin>>n; for (int i=0;i<n;i++){ char c; cin>>c>>song; if (c=='B') dq.push_back(song); else dq.push_front(song); } while (!(dq.empty())){ cout<<dq.front()<<" "; dq.pop_front(); } }
true
9da646e3cc5644f30f981759ca66c20a6196034a
C++
SpencerMichaels/evdevw
/include/evdevw/Event/Event.hpp
UTF-8
3,525
2.796875
3
[ "MIT" ]
permissive
#ifndef EVDEVW_EVENT_HPP #define EVDEVW_EVENT_HPP #include <libevdev/libevdev.h> #include "../Enum.hpp" #include "../Utility.hpp" #define DECLARE_EVENT_TYPE(_raw_type, _type, _code_type, _value_type) \ namespace event { \ struct _type : public Event<_raw_type, _code_type, _value_type> { \ _type(_code_type code, _value_type value) \ : Event<_raw_type, _code_type, _value_type>(code, value) \ { \ } \ _type(struct input_event event) \ : Event<_raw_type, _code_type, _value_type>(event) \ { \ } \ }; \ template <> \ struct event_from_event_code<_code_type> { \ using type = _type; \ }; \ } namespace evdevw::event { template <typename Code> struct event_from_event_code { }; template <uint16_t _type, typename _Code, typename _Value> struct Event { public: using Code = _Code; using Value = _Value; static const int type = _type; public: static Value raw_to_value(int raw) { if constexpr (std::is_enum<Value>::value) return raw_to_enum<Value>(raw); else return raw; } static int value_to_raw(Value value) { if constexpr (std::is_enum<Value>::value) return enum_to_raw<Value>(value); else return value; } Event(Code code, Value value) : _code(code), _value(value) { } Event(struct input_event event) : _code(raw_to_enum<Code>(event.code)), _value(raw_to_value(event.value)) { if (event.type != type) throw std::runtime_error( std::string("Raw type mismatch for event type ") + typeid(decltype(*this)).name() + ": got " + std::to_string(event.type) + ", expected " + std::to_string(type)); } Event(uint16_t raw_code, Value value) : _code(raw_to_enum<Code>(raw_code)), _value(raw_to_value(value)) { } bool operator==(const Event &other) const { return is_code(other._code); } bool is_code(Code code) const { return code == _code; } uint16_t get_raw_code() const { return enum_to_raw<Code>(_code); } int get_raw_value() const { return value_to_raw(_value); } Code get_code() const { return _code; } Value get_value() const { return _value; } std::string get_type_name() const { return libevdev_event_type_get_name(type); } std::string get_code_name() const { return libevdev_event_code_get_name(type, enum_to_raw(_code)); } private: Code _code; Value _value; }; template <typename E> std::string get_type_name() { return libevdev_event_type_get_name(E::type); } template <typename E> std::string get_code_name(typename E::Code code) { return libevdev_event_code_get_name(E::type, enum_to_raw(code)); } } #endif //EVDEVW_EVENT_HPP
true
440d54f63872ecdaa8d8010413c2ac31ac18dda0
C++
Starnett/TouchEvolved
/TouchEvolved/GLUT Apparatus/Mouse.cpp
UTF-8
2,931
3.015625
3
[]
no_license
/* * mouse.c * ------- * Mouse callbacks for the canvas. Currently a little clunky, because * all rotations are in terms of the original axes of the model, rather * than the transformed axes of the current viewpoint. * * You shouldn't have to modify anything in this file. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "common.h" #include "mouse.h" /* The frustum and zoom factor variables from canvas.c */ extern GLfloat fleft; extern GLfloat fright; extern GLfloat ftop; extern GLfloat fbottom; extern GLfloat zNear; extern GLfloat zFar; extern GLfloat zoomFactor; extern int win_width; extern int win_height; /* The current mode the mouse is in, based on what button(s) is pressed */ int mouse_mode; /* The last position of the mouse since the last callback */ int m_last_x, m_last_y; //this breaks the window into 4 quadrants which go from -1 to 1 in x and y directions void convert_coordinate(GLfloat *results, GLfloat x, GLfloat y) { GLfloat realX = x / (GLfloat)win_width * (fright - fleft) + fleft; GLfloat realY = (1 - y / (GLfloat)win_height) * (ftop - fbottom) + fbottom; printf("after convert: ( %f , %f ) \n", realX, realY); results[0] = realX; results[1] = realY; } void myMouseButton(int button, int state, int x, int y) { GLfloat proper_coordinates[2]; if (state == GLUT_DOWN) { m_last_x = x; m_last_y = y; if (button == GLUT_LEFT_BUTTON) { printf("before convert: ( %d , %d ) \n", x, y); convert_coordinate(proper_coordinates, x, y); mouse_mode = MOUSE_ROTATE_YX; } else if (button == GLUT_MIDDLE_BUTTON) { mouse_mode = MOUSE_ROTATE_YZ; } else if (button == GLUT_RIGHT_BUTTON) { mouse_mode = MOUSE_ZOOM; } } } //will need to modify this so that only and individual object is moved at a time. void myMouseMotion(int x, int y) { double d_x, d_y; /* The change in x and y since the last callback */ d_x = x - m_last_x; d_y = y - m_last_y; m_last_x = x; m_last_y = y; if (mouse_mode == MOUSE_ROTATE_YX) { /* scaling factors */ d_x /= 2.0; d_y /= 2.0; glRotatef(d_x, 0.0, 1.0, 0.0); /* y-axis rotation */ glRotatef(-d_y, 1.0, 0.0, 0.0); /* x-axis rotation */ } else if (mouse_mode == MOUSE_ROTATE_YZ) { /* scaling factors */ d_x /= 2.0; d_y /= 2.0; glRotatef(d_x, 0.0, 1.0, 0.0); /* y-axis rotation */ glRotatef(-d_y, 0.0, 0.0, 1.0); /* z-axis rotation */ } else if (mouse_mode == MOUSE_ZOOM) { d_y /= 100.0; zoomFactor += d_y; if (zoomFactor <= 0.0) { /* The zoom factor should be positive */ zoomFactor = 0.001; } glMatrixMode(GL_PROJECTION); glLoadIdentity(); /* * glFrustum must receive positive values for the near and far * clip planes ( arguments 5 and 6 ). */ glFrustum(fleft*zoomFactor, fright*zoomFactor, fbottom*zoomFactor, ftop*zoomFactor, -zNear, -zFar); } /* Redraw the screen */ glutPostRedisplay(); } /* end of mouse.c */
true
b5c5616c86c61dd3970d771231ca688fad007378
C++
skl7028320/Udemy_Advanced_Cpp
/OverloadingTheDereferenceOperator/src/overloading_the_dereference_operator.cpp
UTF-8
271
2.671875
3
[]
no_license
/* * overloading_the_dereference_operator.cpp * * Created on: 14 Mar 2021 * Author: Bowen Li */ #include <iostream> #include "Complex.h" using namespace std; using namespace advanced_cpp; int main() { Complex c1(2, 4); cout << *c1 << endl; return 0; }
true
17c594655f18c8807736c898d629f8453db1295a
C++
xnyuq/CompetitiveProgramming
/atcoder/abc218/C.cpp
UTF-8
2,369
2.578125
3
[]
no_license
#include <bits/stdc++.h> using namespace std; template<typename A, typename B> ostream& operator<<(ostream &os, const pair<A, B> &p) { return os << '(' << p.first << ", " << p.second << ')'; } template<typename T_container, typename T = typename enable_if<!is_same<T_container, string>::value, typename T_container::value_type>::type> ostream& operator<<(ostream &os, const T_container &v) { os << '{'; string sep; for (const T &x : v) os << sep << x, sep = ", "; return os << '}'; } void dbg_out() { cerr << endl; } template<typename Head, typename... Tail> void dbg_out(Head H, Tail... T) { cerr << ' ' << H; dbg_out(T...); } #ifdef QUYNX_DEBUG #define dbg(...) cerr << "(" << #__VA_ARGS__ << "):", dbg_out(__VA_ARGS__) #else #define dbg(...) #endif using mat = vector<vector<bool>>; void strip(mat &a) { int mini = (int)a.size() - 1, maxi = 0; int minj = (int)a.size() - 1, maxj = 0; for (int i = 0; i < (int)a.size(); ++i) { for (int j = 0; j < (int)a[0].size(); ++j) { if (a[i][j]) { mini = min(mini, i); maxi = max(maxi, i); minj = min(minj, j); maxj = max(maxj, j); } } } mat b; for (int i = mini; i <= maxi; ++i) { vector<bool> tmp; for (int j = minj; j <= maxj; ++j) tmp.push_back(a[i][j]); b.push_back(tmp); } a.swap(b); } void rotate(mat &a) { int n = a.size(), m = a[0].size(); mat b(m, vector<bool>(n)); for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { b[i][j] = a[j][m-i-1]; } } a.swap(b); } int main() { ios_base::sync_with_stdio(false); #ifndef QUYNX_DEBUG cin.tie(nullptr); #endif int n; cin >> n; mat a(n, vector<bool>(n)), b(n, vector<bool>(n)); for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { char tmp; cin >> tmp; a[i][j] = tmp == '#'; } } for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { char tmp; cin >> tmp; b[i][j] = tmp == '#'; } } strip(a); strip(b); bool ans = a == b; for (int i = 0; i < 3; ++i) { rotate(a); if (a == b) ans = true; } cout << (ans ? "Yes" : "No"); }
true
bd11547a15ca77fc2e5916cafc8e9d6bea414eae
C++
pan-dan/intro
/Inheritance/Academy/Student.cpp
WINDOWS-1251
1,286
3.171875
3
[]
no_license
#include "Distributed.h" const string& Student::get_university()const { return university; } const string& Student::get_speciality()const { return speciality; } const string& Student::get_group()const { return group; } const double Student::get_rating()const { return rating; } void Student::set_university(const string& university) { this->university = university; } void Student::set_speciality(const string& speciality) { this->speciality = speciality; } void Student::set_group(const string& group) { this->group = group; } void Student::set_rating(double rating) { this->rating = rating; } // Constructors Student::Student ( HUMAN_TAKE_PARAMETERS, // STUDENT_TAKE_PARAMETERS // ) :Human(HUMAN_GIVE_PARAMETERS) { set_university(university); set_speciality(speciality); set_group(group); set_rating(rating); cout << "SConstructor:\t" << this << endl; } Student::~Student() { cout << "SDestructor:\t" << this << endl; } // Methods void Student::info()const { Human::info(); cout << university << ", " << speciality << ", " << group << ", : " << rating << ", " << endl; }
true
c4b66202f54a246c729d731c385c560417c9456c
C++
Tifloz/Tek2
/Piscine_CPP/cpp_d14m_2018/ex00/main.cpp
UTF-8
478
2.515625
3
[]
no_license
#include "Lemon.hpp" #include "Banana.hpp" /* ** EPITECH PROJECT, 2022 ** cpp_d14m_2018 ** File description: ** Created by Florian Louvet, */ int main() { Lemon l; Banana b; std::cout << l.getVitamins() << std::endl; std::cout << b.getVitamins() << std::endl; std::cout << l.getName() << std::endl; std::cout << b.getName() << std::endl; Fruit &f = l; std::cout << f.getVitamins() << std::endl; std::cout << f.getName() << std::endl; return 0; }
true
689be05142b2f0f78f2495e614bb4fa416a1e8f6
C++
ChadFunckes/CU_Denver_CSCI2312
/Project2/quadratic.cpp
UTF-8
2,771
3.46875
3
[]
no_license
// Chad S Funckes // CSCI 2312 // QUADRATIC CLASS IMPLEMENTATION // // See Quadratic.h for documentation #include <iostream> #include "Quadratic.h" #include <cmath> #include <cassert> using namespace std; namespace Funckes_PA2{ /// Constructors quadratic::quadratic(){ a = 0; b = 0; c = 0; }; quadratic::quadratic(double A, double B, double C){ assert(A != 0); a = A; b = B; c = C; } /// Mutator Functions void quadratic::Set_Coefficient(double A, double B, double C){ assert(A != 0); a = A; b = B; c = C; }; /// Accessor Functions double quadratic::Find_X(const double& X) const { double ans; ans = (a * (X * X)) + (b*X) + c; return ans; }; void quadratic::Root_X(const double& X) const { double discriminant; discriminant = (b * b) - (4*a*c); // if discriminant is less than 0, there is no real root if (discriminant < 0) cout << "There are no real roots for the quadratic "<< a <<"X^2 + " << b << "X + " << c << endl; // if dicriminant is = 0 there is one answer else if (discriminant == 0) cout << "The root for the quadratic " << a << "X^2 + " << b << "X + " << c << " is: " << (-b) / (2 * a) << endl; // if discriminant is greater than 0, there are two answers else if (discriminant > 0) cout << "The roots for the quadratic " << a << "X^2 + " << b << "X + " << c << " are: " << ((-b) + sqrt((b * b) - (4 * a*c))) / (2 * a) << " and " << ((-b) - sqrt((b * b) - (4 * a*c))) / (2 * a) << endl; }; double quadratic::Get_A()const { return a; }; double quadratic::Get_B()const { return b; }; double quadratic::Get_C()const { return c; }; /// operator overloads quadratic operator+(const quadratic& q1, const quadratic& q2){ quadratic quad; quad.Set_Coefficient((q1.Get_A() + q2.Get_A()), (q1.Get_B() + q2.Get_B()), (q1.Get_C() + q2.Get_C())); return quad; }; quadratic operator-(const quadratic& q1, const quadratic& q2){ quadratic quad; quad.Set_Coefficient((q1.Get_A() - q2.Get_A()), (q1.Get_B() - q2.Get_B()), (q1.Get_C() - q2.Get_C())); return quad; }; void operator*(const quadratic& q1, const quadratic& q2){ double a,b,c,d,e; a = q1.Get_A() * q2.Get_A(); b = (q1.Get_A() * q2.Get_B()) + (q1.Get_B()*q2.Get_A()); c = (q1.Get_A() * q2.Get_C()) + (q1.Get_B()*q2.Get_B()) + (q1.Get_C()*q2.Get_A()); d = (q1.Get_B()*q2.Get_C()) + (q1.Get_C()*q2.Get_B()); e = (q1.Get_C()*q2.Get_C()); cout << "The results of multiplication of quadratics is: (" << a << ", " << b << ", " << c << ", " << d << ", " << e << ")\n"; }; quadratic operator*(double r, const quadratic& q){ quadratic quad; quad.Set_Coefficient((r*q.Get_A()), (r*q.Get_B()), (r*q.Get_C())); return quad; }; ostream& operator <<(ostream& output, const quadratic& Q){ output << "(" << Q.Get_A() << ", " << Q.Get_B() << ", " << Q.Get_C() << ")"; return output; } }
true
7b0913ef56926646700d0305da90ac2e9bc7f5c8
C++
TechStuffBoy/ArduinoDev
/Sketch Files/MQTT_4_SENSOR/MQTT_4_SENSOR.ino
UTF-8
3,459
2.578125
3
[]
no_license
//Including necessary libraries. #include<SPI.h> #include<Ethernet.h> #include<PubSubClient.h> // Assigning analog input pins int proximity_1=2; int proximity_2=3; int temp_sensor=A0; int moisture_sensor=A1; //assigning output pins int proximity_1_trigger=4; int proximity_2_trigger=5; int temp_sensor_trigger=6; int moisture_sensor_trigger=7; //assigning variables to store values int proximity_1_val=0; int proximity_2_val=0; int Temp_Sense=0; float volts=0; float tempF=0; float tempC=0; int moisture_sensor_val=0; int moisture_percent=0; byte mac[] = { 0xDE, 0xAD, 0xBE, 0xFF, 0x06, 0xED }; byte server[]={192,168,1,14}; //My Arduino's IP address byte ip[]={192,168,1,34}; byte subnet[]={255,255,255,0}; byte gateway[]={192,168,1,1}; EthernetClient ethClient; PubSubClient client(server,1883,callback,ethClient); void setup() { Ethernet.begin(mac,ip,gateway,subnet); Serial.begin(9600); Serial.println("Ethernet Begin "); pinMode(proximity_1,INPUT); pinMode(proximity_2,INPUT); pinMode(proximity_1_trigger,OUTPUT); pinMode(proximity_2_trigger,OUTPUT); pinMode(temp_sensor_trigger,OUTPUT); pinMode(moisture_sensor_trigger,OUTPUT); } void loop(){ readTempSen(); readProximity_1(); readProximity_2(); readMoistureSen(); while(!client.connected()){ Serial.println("Trying to connect client with server"); client.connect("My_arduino_Temp_sensor"); if(client.connected()){ Serial.println("Success!!,Client Connected!"); } } if(client.connected()){ String json=buildJson(); char jsonStr[300]; json.toCharArray(jsonStr,300); // We hav to convert string to char array,then only we can pass this value to client.publish() boolean resultSend= client.publish("/arduino/4Sensors", jsonStr); if(resultSend) Serial.println("Successfully Sent"); else Serial.println("Warning!!,Sent Unsuccessfull"); delay(3000); } client.loop(); } } void readTempSen(){ Temp_Sense=analogRead(temp_sensor); volts=Temp_Sense/205.0; tempC=100*volts-50; tempF=tempC*(9.0/5.0)+32.0; Serial.print("tempC :"); Serial.print(tempC); Serial.print(" , "); Serial.print("tempF :"); Serial.println(tempF); } void readProximity_1(){ proximity_1_val=digitalRead(proximity_1); Serial.print("proximity_1 :"); Serial.println(proximity_1_val); } void readProximity_2(){ proximity_1_val=digitalRead(proximity_2); Serial.print("proximity_2 :"); Serial.println(proximity_2_val); } void readMoistureSen(){ moisture_sensor_val=analogRead(moisture_sensor); moisture_percent=map(moisture_percent,1023,465,0,100); Serial.print("moisture_sensor_percent :"); Serial.print(moisture_percent); Serial.println("%"); } String buildJson() { String data = "{"; data+="\n"; data+= "\"TilesUnit\": {"; data+="\n"; data+="\"myName\": \"Arduino TMP36\","; data+="\n"; data+="\"temperature (F)\": "; data+=(int)tempF; data+= ","; data+="\n"; data+="\"temperature (C)\": "; data+=(int)tempC; data+="\n"; data+="\"Proximity_1\": "; data+= TRUE; data+= ","; data+="\n"; data+="\"Proximity_2\": "; data+=(int)proximity_2_val; data+= ","; data+="\n"; data+="\"MyName\": \"Moisture_sen\","; data+="\n"; data+="\"Moisture_%\": "; data+=(int)moisture_percent; data+= ","; data+="\n"; data+="}"; data+="\n"; data+="}"; return data; } void callback(char* topic,byte* payload,unsigned int length){ }
true
c32ea01df8115d3693153ac723881b177cbe7083
C++
munib10mufc/Banking-System
/ChequeBook.h
UTF-8
560
2.546875
3
[]
no_license
#ifndef ChequeBook_H #define ChequeBook_H #include "Cheque.h" #include "CurrentAccount.h" #include <vector> using namespace std; class Cheque; class ChequeBook { int chequeBookId; int accountID; vector < Cheque *> cheques; public: ChequeBook(int c = 0 , int accID = 0); void setChequeBookId(int ); void setAccountId(int); int getAccountId(); int getChequeBookId(); bool recieveCheck( int id ); bool cancelCheck( int id ); bool isChequeRecieved(int id); bool isChequeCanceled(int id); ~ChequeBook(); private: Cheque * find( int id); }; #endif
true
af782152d312840680bec9efb55ee9d16a091c9f
C++
ase09/Project-Assignment
/socket/EchoServer/EchoServer.cc
UTF-8
1,228
3.1875
3
[]
no_license
/* * File: main.cpp * Author: sanath * * Created on July 20, 2009, 3:17 PM */ #include <stdlib.h> #include <iostream> #include <string> #include "ServerSocket.hh" #include "SocketException.hh" using namespace std; int main(int argc, char* argv[]) { cout << "EchoServer is Running...." << endl; try { // Create the socket ServerSocket server(30000); while (true) { cout << "Waiting for a client connection..." << endl; Socket sock; server.accept(sock); try { while (true) { string data; sock >> data; cout << "Received <" << data << ">... echoing back to client." << endl; sock << data; } } catch (SocketException& e) { cout << "Error in data stream:" << e.description() << endl; cout << "Terminating current connection." << endl; } } } catch (SocketException& e) { cout << "Error creating server or accepting client connection" << e.description() << endl; cout << "Terminating the application" << endl; } return (EXIT_SUCCESS); }
true
583b334b1682ca5fd5739644689699276dc627d9
C++
itroot/university-tasks
/old/sources/kurs4/tviz/tmath/Vector3D.h
UTF-8
2,768
3.59375
4
[]
no_license
#ifndef VECTOR3D_H_ #define VECTOR3D_H_ template<class T> class Vector3D { public: Vector3D(); Vector3D(const T& in_x, const T& in_y, const T& in_z); ~Vector3D(); // minus Vector3D& operator-=(const Vector3D& rhs); Vector3D operator-(const Vector3D& rhs); // plus Vector3D& operator+=(const Vector3D& rhs); Vector3D operator+(const Vector3D& rhs)const; // / Vector3D& operator/=(const T& rhs); Vector3D operator/(const T& rhs); // cross product; Vector3D operator&(const Vector3D& rhs); T& operator[](int index); const T& operator[](int index) const; T x()const; T y()const; T z()const; T norm_2()const; private: T X; T Y; T Z; }; template<class T> Vector3D<T>::Vector3D() { X=0; Y=0; Z=0; } template<class T> Vector3D<T>::Vector3D(const T& in_x, const T& in_y, const T& in_z) { X=in_x; Y=in_y; Z=in_z; } template<class T> Vector3D<T>& Vector3D<T>::operator-=(const Vector3D<T>& rhs) { this->X-=rhs.X; this->Y-=rhs.Y; this->Z-=rhs.Z; return *this; } template<class T> Vector3D<T> Vector3D<T>::operator-(const Vector3D<T>& rhs) { Vector3D<T> that=*this; that-=rhs; return that; } template<class T> Vector3D<T>& Vector3D<T>::operator+=(const Vector3D<T>& rhs) { this->X+=rhs.X; this->Y+=rhs.Y; this->Z+=rhs.Z; return *this; } template<class T> Vector3D<T> Vector3D<T>::operator+(const Vector3D<T>& rhs) const { Vector3D<T> that=*this; that+=rhs; return that; } template<class T> Vector3D<T>& Vector3D<T>::operator/=(const T& rhs) { this->X/=rhs; this->Y/=rhs; this->Z/=rhs; return *this; } template<class T> Vector3D<T> Vector3D<T>::operator/(const T& rhs) { Vector3D<T> that=*this; that/=rhs; return that; } template<class T> Vector3D<T> Vector3D<T>::operator&(const Vector3D<T>& rhs) { Vector3D<T>& lhs=*this; //synonim return Vector3D<T>( lhs.y()*rhs.z()-rhs.y()*lhs.z(), rhs.x()*lhs.z()-lhs.x()*rhs.z(), lhs.x()*rhs.y()-rhs.x()*lhs.y() ); } template<class T> T Vector3D<T>::x() const {return X;} template<class T> T Vector3D<T>::y() const {return Y;} template<class T> T Vector3D<T>::z() const {return Z;} template<class T> T Vector3D<T>::norm_2() const { return sqrt(X*X+Y*Y+Z*Z); } template<class T> T& Vector3D<T>::operator[](int index) { if (index==0) return X; if (index==1) return Y; if (index==2) return Z; // throw (out_of_range) return Z; } template<class T> const T& Vector3D<T>::operator[](int index) const { if (index==0) return X; if (index==1) return Y; if (index==2) return Z; // throw (out_of_range) return Z; } template<class T> Vector3D<T>::~Vector3D() {} #endif /*VECTOR3D_H_*/
true
b2e4ef63c1745387fc2842327a7e04a2f4ff8690
C++
rishirv/competitive-programming
/USACO Training/4/4.3/buylow/buylow.cpp
UTF-8
2,334
2.828125
3
[]
no_license
/* ID: verma.r1 PROG: buylow LANG: C++11 */ //Repl.it BlindEnormousPony #include <iostream> #include <fstream> #include <string> #include <algorithm> using namespace std; //Begin bigint class (needs string and algorithm) char get(string a, int b){ if(b<a.length()) return a[b]; else return '0'; } string addInt(string a, string b){ string s(max(a.length(), b.length()), '0'); int c=0; for(int i=0; i<max(a.length(), b.length()); i++){ s[i]=((get(a,i)-'0')+(get(b,i)-'0')+c)%10 + '0'; c=((get(a,i)-'0')+(get(b,i)-'0')+c)/10; } if(c) s+= c+'0'; return s; } string subInt(string a, string b){ string s(max(a.length(), b.length()), '0'); int borrow=0, size=0; for(int i=0; i<max(a.length(), b.length()); i++){ s[i]=get(a,i)-get(b,i)-borrow; borrow = (s[i]<0); if(borrow) s[i]+=10; s[i]+='0'; if(s[i]!='0') size=i; } return s.substr(0, size+1); } bool isLess(string a, string b){ if(a.length()!=b.length()){ return a.length()<b.length(); } for(int i=max(a.length(), b.length())-1; i>=0; i--){ if(get(a,i)!=get(b,i)){ return get(a,i)<get(b,i); } } return false; } string rev(string s){ reverse(s.begin(), s.end()); return s; } //End bigint class int main(){ ifstream cin ("buylow.in"); ofstream cout ("buylow.out"); int n; cin>>n; string prices[n], len[n], num[n], longestLength="0", numSols="0", prev; for(int i=0; i<n; i++){ cin>>prices[i]; prices[i]=rev(prices[i]); len[i]="1"; num[i]="0"; for(int j=0; j<i; j++){ if(isLess(prices[i], prices[j]) && isLess(len[i], addInt(len[j], "1"))){ len[i]=addInt(len[j], "1"); } } prev=""; if(len[i]=="1"){ num[i]="1"; } else{ for(int j=i-1; j>=0; j--){ if(isLess(prices[i], prices[j]) && addInt(len[j], "1") == len[i] && prices[j]!=prev){ num[i] = addInt(num[i], num[j]); prev = prices[j]; } } } if(!isLess(len[i], longestLength)){ longestLength = len[i]; } } prev=""; for(int i=n-1; i>=0; i--){ if(len[i]==longestLength && prices[i]!=prev){ numSols = addInt(numSols, num[i]); prev = prices[i]; } } cout<<rev(longestLength)<<" "<<rev(numSols)<<endl; }
true
56d89ba7027378900463424b6c11f4fddf72e511
C++
Nikhil-Dingane/codechef
/easymath.cpp
UTF-8
822
3.4375
3
[]
no_license
#include<iostream> using namespace std; int sumOfDigit(int no){ int sum = 0; while(no != 0){ sum = sum + (no%10); no = no / 10; } return sum; } int prodOfMaxSum(int *arr, int n){ int productWithMaxSum = 0; for(int i = 0; i < n; i++){ for(int j = (i + 1); j < n; j++){ if(sumOfDigit(arr[i] * arr[j]) > productWithMaxSum){ productWithMaxSum = sumOfDigit(arr[i] * arr[j]); } } } return productWithMaxSum; } int main(){ int testCases = 0; cin>>testCases; for(int test = 1 ; test <= testCases ; test++){ int n = 0; cin>>n; int *arr = new int[n]; for(int i = 0; i < n; i++){ cin>>arr[i]; } cout<<prodOfMaxSum(arr,n)<<endl; } return 0; }
true
8ef6d5ce5e00e68b5d0e939c53c5c05b8362b04c
C++
portaloffreedom/tol-controllers
/RoombotController/RLPower/include/Values.h
UTF-8
4,958
3.03125
3
[]
no_license
#ifndef VALUES_H #define VALUES_H #include <tinyxmlplus.h> #include <cstddef> #include <iostream> #include <valarray> namespace POWER { class Values { public: /** * Class name for XML */ static const std::string XML_NAME; // <editor-fold defaultstate="collapsed" desc="Constructors"> /** * Creates a matrix of values with n rows and m columns initialized to 0 * or to a specified value. * * Example: n = 2, m = 2. * (a,a; * a,a) * @param Number of rows * @param Number of columns * @param Default value */ Values(std::size_t = 1, std::size_t = 1, double = 0.0); /** * Creates a matrix of values with n rows and values.size() columns * * Example: n = 2, m = 2. * (a,b; * a,b) * @param Number of rows * @param Init value array for each column */ Values(std::size_t, const std::valarray<double> &); /** * Creates a matrix of values with values.size() rows and m columns * * Example: n = 2, m = 2. * (a,a; * b,b) * @param Init value array for each row * @param Number of columns */ Values(const std::valarray<double> &, std::size_t); /** * Create a matrix of values with n rows and m columns where each element * is initialized by some value * * Example: n = 2, m = 2. * (a,b; * c,d) * @param Number of rows * @param Number of columns * @param Init value array for each element of the matrix */ Values(std::size_t, std::size_t, const std::valarray<double> &); Values(const TiXmlElement &); // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Accessors"> /** * Returns the matrix number of rows * @return Number of rows */ std::size_t rows() const; /** * Returns the matrix number of columns * @return Number of columns */ std::size_t columns() const; /** * Returns the matrix number of elements * @return Number of elements */ std::size_t size() const; /** * Returns the contents of the i-th row * @param Row index * @return Row contents */ std::valarray<double> row(std::size_t) const; /** * Returns the contents of the j-th column * @param Column index * @return Column contents */ std::valarray<double> column(std::size_t) const; // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Mutators"> void row(std::size_t, const std::valarray<double> &); void column(std::size_t, const std::valarray<double> &); // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Operators"> /** * Returns a reference to the k-th mtrix element * @param Element index * @return Matrix element reference */ double & operator[](std::size_t); /** * Returns a constant reference to the k-th mtrix element * @param Element index * @return Constant matrix element reference */ const double & operator[](std::size_t) const; /** * Returns a reference to the matix element in i-th row and j-th column * @param Row index * @param Column index * @return Matrix element reference */ double & operator()(std::size_t, std::size_t); /** * Returns a constant reference to the matix element in i-th row and j-th column * @param Row index * @param Column index * @return Constant matrix element reference */ const double & operator()(std::size_t, std::size_t) const; inline Values operator +() const { return Values(_rows, _columns, _values); } inline Values operator -() const { return Values(_rows, _columns, -_values); } Values & operator +=(double); Values & operator -=(double); Values & operator *=(double); Values & operator /=(double); Values & operator +=(const Values &); Values & operator -=(const Values &); Values & operator *=(const Values &); Values & operator /=(const Values &); friend std::ostream & operator <<(std::ostream &, const Values &); //friend std::istream & operator >> (std::istream &, Values &); // </editor-fold> /** * Save class internal data in XML format * @return XML Element representing class */ TiXmlElement save_xml() const; private: std::size_t _rows; std::size_t _columns; std::valarray<double> _values; std::valarray<double> _init_rows(const std::valarray<double> &); std::valarray<double> _init_columns(const std::valarray<double> &); }; Values operator+(double, const Values &); Values operator-(double, const Values &); Values operator*(double, const Values &); Values operator/(double, const Values &); Values operator+(const Values &, double); Values operator-(const Values &, double); Values operator*(const Values &, double); Values operator/(const Values &, double); Values operator+(const Values &, const Values &); Values operator-(const Values &, const Values &); Values operator*(const Values &, const Values &); Values operator/(const Values &, const Values &); } #endif /* VALUES_H */
true
7e278960df6b02211182f8965bbdde5f25c2c63d
C++
HoldenGao/oops
/src/application/MatExpTest.cpp
UTF-8
3,085
2.65625
3
[]
no_license
#include "include/app/app.h" #include "include/math/MatExp.h" #include <complex> #include "include/math/krylov_expv.h" cx_mat MAT; cx_vec VEC; vec TIME_LIST; SumKronProd SKP; cx_double PREFACTOR; void prepare_data(string filename); void test_small_mat(); cx_mat test_large_mat(); cx_mat test_large_mat_sparse(); cx_mat test_very_large_mat_CPU(); cx_mat test_very_large_mat_GPU(); int main(int argc, char* argv[]) { string filename = "./dat/input/RoyCoord.xyz8"; prepare_data(filename); test_small_mat(); cx_mat res_large = test_large_mat(); cx_mat res_large_sp = test_large_mat_sparse(); cx_mat res_very_large_CPU = test_very_large_mat_CPU(); cx_mat res_very_large_GPU = test_very_large_mat_GPU(); cout << "diff 1 = " << norm(res_large_sp - res_large) << endl; cout << "diff 2 = " << norm(res_very_large_CPU - res_large) << endl; cout << "diff 3 = " << norm(res_very_large_GPU - res_large) << endl; cout << "diff 4 = " << norm(res_very_large_GPU - res_very_large_CPU) << endl; return 0; } void prepare_data(string filename) {/*{{{*/ cSpinSourceFromFile spin_file(filename); cSpinCollection spins(&spin_file); spins.make(); vector<cSPIN> sl = spins.getSpinList(); SpinDipolarInteraction dip(sl); Hamiltonian hami(sl); hami.addInteraction(dip); hami.make(); PREFACTOR = cx_double(0.0, -1.0); MAT = hami.getMatrix(); cout << "hamiltonian mat generated." <<endl; SKP = hami.getKronProdForm(); int dim = MAT.n_cols; PureState psi(dim); psi.setComponent(0, 1.0); VEC = psi.getVector(); cout << "vector generated." <<endl; TIME_LIST = linspace<vec>(0.01, 0.1, 10); }/*}}}*/ void test_small_mat() {/*{{{*/ for(int i=0; i<TIME_LIST.size(); ++i) { MatExp expM(MAT, PREFACTOR*TIME_LIST(i), MatExp::ArmadilloExpMat); expM.run(); MatExp expM2(MAT, PREFACTOR*TIME_LIST(i), MatExp::PadeApproximation); expM2.run(); cx_mat resArma = expM.getResultMatrix(); cx_mat resPade = expM2.getResultMatrix(); cout << "t = " << TIME_LIST(i) << "; diff = " ; cout << norm(resArma-resPade) << endl; } }/*}}}*/ cx_mat test_large_mat() {/*{{{*/ cout << endl; cout << "begin LARGE DENSE MAT" << endl; MatExpVector expM(MAT, VEC, PREFACTOR, TIME_LIST); return expM.run(); }/*}}}*/ cx_mat test_large_mat_sparse() {/*{{{*/ cout << endl; cout << "begin LARGE SPARSE MAT" << endl; sp_cx_mat mat_sparse = sp_cx_mat(MAT); MatExpVector expM(mat_sparse, VEC, PREFACTOR, TIME_LIST); return expM.run(); }/*}}}*/ cx_mat test_very_large_mat_CPU() {/*{{{*/ cout << endl; cout << "Begin VERY_LARGE_MAT on CPU " << endl; MatExpVector expM(SKP, VEC, TIME_LIST, MatExpVector::Inexplicit); return expM.run(); }/*}}}*/ cx_mat test_very_large_mat_GPU() {/*{{{*/ cout << endl; cout << "Begin VERY_LARGE_MAT on GPU " << endl; MatExpVector expM(SKP, VEC, TIME_LIST, MatExpVector::InexplicitGPU); return expM.run(); }/*}}}*/
true
150610b6be9ea80c3a0dec9c359b3434882bbcfd
C++
GitJoeBentley/SpaceInvaders
/include/Invader.h
UTF-8
962
3.125
3
[]
no_license
#ifndef INVADER_H #define INVADER_H #include <SFML/Graphics.hpp> #include <SFML/System.hpp> class Invader : public sf::RectangleShape { public: enum Status {Visible,Hit,Invisible}; Invader(); virtual ~Invader(); Status getStatus() const { return status; } void setStatus(Status stat) { this->status = stat; explosionCount = 1;} bool isVisible() const { return status == Visible; } void setVisible() { status = Visible; } void setHitStatus() { status = Hit; } void setExplosionCount() { explosionCount = 1; } void resetExplosionCount() { explosionCount = 0u; } unsigned getExplosionCount() const { return explosionCount; } void incrementExplosionCount() { ++explosionCount; if (explosionCount > 100) status = Invisible; } protected: private: Status status; unsigned explosionCount; }; #endif // INVADER_H
true
7bf1125c1a96ad05a5e9aeb723593838f0c633fb
C++
AnanyaKumar/competition-programs
/stackingnumbers.cpp
UTF-8
1,941
2.5625
3
[]
no_license
/** * Australian Informatics Olympiad Senior 2003, Q2 * Ananya Kumar, 2011 * NUS High School */ #include <cstdio> #include <algorithm> using namespace std; #define MAXN 32 #define MAXB 35000 int best[MAXB]; bool done[MAXN] = {false}; int cur[6]; int choice[MAXN]; int bestChoice[MAXN]; int s, b; int highs = 0; void recur ( int num ) { if ( num == 5 ) { int t1 = (4*choice[cur[1]]+6*choice[cur[2]]+4*choice[cur[3]]+choice[cur[4]])%b; int t2 = (choice[cur[1]]+4*choice[cur[2]]+6*choice[cur[3]]+4*choice[cur[4]])%b; int maxt = max(t1,t2); int mint = min(t1,t2); //printf("%d %d %d %d\n",choice[cur[1]],choice[cur[2]],choice[cur[3]],choice[cur[4]]); int i, j; i = best[mint]; while ( done[i] ) i = (i+s-1)%s; done[i] = true; j = best[maxt]; while ( done[j] ) j = (j+s-1)%s; int curh = ((choice[i]+mint)%b) * ((choice[j]+maxt)%b); if ( curh >= highs ) { highs = curh; copy(cur+1,cur+5,bestChoice+1); if ( t1 == mint ) { bestChoice[0] = i; bestChoice[5] = j; } else { bestChoice[0] = j; bestChoice[5] = i; } } done[i] = false; } else { int maxs = s; if ( num == 3 ) maxs = cur[2]; for ( int i = 0; i < maxs; i++ ) { if ( done[i] ) continue; done[i] = true; cur[num] = i; recur(num+1); done[i] = false; } } } int main () { FILE *in = fopen("stackin.txt","r"); FILE *out = fopen("stackout.txt","w"); fscanf(in,"%d",&b); fscanf(in,"%d",&s); int i, j, k; for ( i = 0; i < s; i++ ) fscanf(in,"%d",&choice[i]); sort(choice,choice+s); //Precompute best array for ( i = 0; i < b; i++ ) { k = 0; for ( j = 0; j < s; j++ ) { if ( (i+choice[j])%b >= k ) { k = (i+choice[j])%b; best[i] = j; } } //printf("%d %d\n",i,choice[best[i]]); } recur(1); fprintf(out,"%d\n",highs); for ( i = 0; i < 6; i++ ) fprintf(out,"%d ",choice[bestChoice[i]]); fprintf(out,"\n"); }
true
134692162f5bfe379954f04393b60991f33aa30c
C++
Nebul5/CS372Final
/monsterArm.cpp
UTF-8
455
2.640625
3
[]
no_license
// ************************** // // monsterArm.cpp // // by Jake Conner // // ************************** // #include "monsterArm.h" // hit void monsterArm::hit(attackEvent e) { if (e.blunt() && _strength > 0) { if (e.damage() >= _strength) { _monster->injure("nursing a broken arm."); _strength = 0; } } else { _monster->hit(e); } } // injure void monsterArm::injure(std::string injury) { _monster->injure(injury); }
true
d6483eccb224536e6f17421dc3ca5fab23de64f5
C++
myqcxy/Sophomore
/c++/coordinate.cpp
UTF-8
332
2.734375
3
[]
no_license
#include"coordinate.h" #include<math.h> coordinate::coordinate(double a,double b) { setdate(a,b); } void coordinate::setdate(double a, double b) { x = a; y = b; } double coordinate::distanceToOrigin() { return sqrt(x*x+y*y); } double coordinate::coordinate_x() { return x; } double coordinate::coordinate_y() { return y; }
true
cd49806cc74ec2e0b84c1a50f85c76bd732452e9
C++
ejawe/cpp
/CPP08/ex00/main.cpp
UTF-8
1,770
2.546875
3
[]
no_license
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* main.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ejawe <ejawe@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/03/21 21:46:32 by ejawe #+# #+# */ /* Updated: 2021/03/21 21:46:33 by ejawe ### ########.fr */ /* */ /* ************************************************************************** */ #include "easyfind.hpp" int main(void) { std::vector<int> tab1(20, 0); Remplir f(0); generate(tab1.begin(), tab1.end(), f); try { int result = easyfind(tab1, 5); std::cout << result << std::endl; } catch(std::string const &errorMessage) { std::cerr << errorMessage << std::endl; } try { int result = easyfind(tab1, 21); std::cout << result << std::endl; } catch(std::string const &errorMessage) { std::cerr << errorMessage << std::endl; } std::deque<int> tab2(4, 0); generate(tab2.begin(), tab2.end(), f); try { int result = easyfind(tab2, 5); std::cout << result << std::endl; } catch(std::string const &errorMessage) { std::cerr << errorMessage << std::endl; } try { int result = easyfind(tab2, 3); std::cout << result << std::endl; } catch(std::string const &errorMessage) { std::cerr << errorMessage << std::endl; } return 0; }
true
20f5482668f8b08aa13e590a9fbd693b17b8f614
C++
millanlaboratory/cnbiros_wheelchair
/examples/example_sonars_setaddress.cpp
UTF-8
1,882
2.921875
3
[]
no_license
#include "cnbiros_wheelchair/Sonar.hpp" #include <iostream> void usage( char *x ) { printf( "usage: %s /dev/ttyUSB0\n", x ); } int main(int argc, char *argv[]) { std::string s; int retval, revision, err; unsigned char current_addr, new_addr; char msg[256]; cnbiros::wheelchair::Sonar *sr; if ( argc == 2 ) { try { sr = new cnbiros::wheelchair::Sonar(argv[1]); } catch (std::runtime_error& e) { fprintf(stderr, "%s\n", e.what()); exit(EXIT_FAILURE); } } else { try { sr = new cnbiros::wheelchair::Sonar(); } catch (std::runtime_error& e) { fprintf(stderr, "%s\n", e.what()); exit(EXIT_FAILURE); } } std::cout << "\nYou must only have ONE sonar connected to the I2C bus.\nEnter its current address: 0x"; std::cin >> s; current_addr = strtoul( s.c_str(), NULL, 16); sprintf(msg, "%#x", current_addr); //std::cout << msg << std::endl; err = sr->requestRangeCm(current_addr); usleep( 75000 ); err += sr->requestRegisterValues(current_addr, true); revision = sr->getRevision(); //std::cout << revision << std::endl; if (revision == 255 || err != 0){ std::cout << "ERROR: Could not connect to SRF02 at address 0x" << s << std::endl; exit(-1); } std::cout << "Connected to SRF02 at address 0x" << s << ", revision = " << revision << std::endl; std::cout << "Enter new address : 0x"; s.clear(); std::cin >> s; new_addr = strtoul( s.c_str(), NULL, 16); sprintf(msg, "%#x", new_addr); sr->changeAddress(current_addr, new_addr); err = sr->requestRangeCm(new_addr); usleep( 75000 ); err += sr->requestRegisterValues(new_addr, true); retval = sr->getRevision(); if (retval == revision && err == 0){ std::cout << "Successfully changed address of SRF02 to 0x" << s << std::endl; } else { std::cout << "ERROR: could not change address of SRF02 to 0x" << s << std::endl; } delete sr; return 0; }
true
a727174a91bfa32f73471cb1df7f8d7994cf7350
C++
Camicam311/Educational-Projects
/3D Computer Graphics/SceneGraphs and Culling/window.cpp
UTF-8
2,079
2.5625
3
[]
no_license
#include <iostream> #include <GL/glut.h> #include "Window.h" #include "Matrix4.h" #include "main.h" #include "Vector3.h" #include "Robot.h" #include "FrustumG.h" using namespace std; int Window::width = 512; // set window width in pixels here int Window::height = 512; // set window height in pixels here int frame=0,time,timebase=0; char s[50]; //---------------------------------------------------------------------------- // Callback method called when system is idle. void Window::idleCallback() { displayCallback(); // call display routine to show the cube frame++; time=glutGet(GLUT_ELAPSED_TIME); if (time - timebase > 1000) { sprintf(s,"FPS:%4.2f",frame*1000.0/(time-timebase)); timebase = time; frame = 0; printf("%s\n",s); } } //---------------------------------------------------------------------------- // Callback method called by GLUT when graphics window is resized by the user void Window::reshapeCallback(int w, int h) { cerr << "Window::reshapeCallback called" << endl; width = w; height = h; glViewport(0, 0, w, h); // set new viewport size glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(60.0, double(width)/(double)height, 1.0, 1000.0); // set perspective projection viewing frustum Globals::frustum.setCamInternals(60.0, double(width)/(double)height, 1.0, 1000.0); glMatrixMode(GL_MODELVIEW); } //---------------------------------------------------------------------------- // Callback method called by GLUT when window readraw is necessary or when glutPostRedisplay() was called. void Window::displayCallback() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // clear color and depth buffers glMatrixMode(GL_MODELVIEW); // make sure we're in Modelview mode Matrix4 temp = Globals::Camera; Globals::frustum.setCamDef(Globals::e, Globals::d, Globals::up); Globals::world.setFrustum(&Globals::frustum, Globals::has_culling); Globals::world.root->draw(temp); glEnd(); glFlush(); glutSwapBuffers(); }
true
39aa582c7c6bb94ee6db16cf1b8eb5eb8ef6b480
C++
lukytto/SFML-console
/console.cpp
UTF-8
6,157
3.125
3
[]
no_license
#include "pch.h" #include "console.h" Menu::Menu(float width, float height) { if (!font.loadFromFile("RAVIE.ttf")) { std::cerr << "Error! Failed to open the font file!" << std::endl; } menu[0].setFont(font); menu[0].setFillColor(sf::Color::Green); menu[0].setString("Window"); menu[0].setPosition(sf::Vector2f(width / 2, height / (MENU_ITEMS + 1) * 1)); menu[1].setFont(font); menu[1].setFillColor(sf::Color::White); menu[1].setString("Text Window"); menu[1].setPosition(sf::Vector2f(width / 2, height / (MENU_ITEMS + 1) * 2)); selectedItemIndex = 0; } void Menu::draw(sf::RenderWindow & window) { for (auto i = 0; i < MENU_ITEMS; i++) { window.draw(menu[i]); } } void Menu::moveUp() { if (selectedItemIndex - 1 >= 0) { menu[selectedItemIndex].setFillColor(sf::Color::White); selectedItemIndex--; menu[selectedItemIndex].setFillColor(sf::Color::Green); } } void Menu::moveDown() { if (selectedItemIndex + 1 < MENU_ITEMS) { menu[selectedItemIndex].setFillColor(sf::Color::White); selectedItemIndex++; menu[selectedItemIndex].setFillColor(sf::Color::Green); } } int Menu::getPressedItem() { return selectedItemIndex; } void TextWindows::drawTextWindows() { std::cout << std::endl << "Enter width and height for your Text Window!" << std::endl; std::cin >> width >> height; sf::RenderWindow window(sf::VideoMode(width, height), "Text Window", sf::Style::None); sf::Font font; if (!font.loadFromFile("RAVIE.ttf")) { std::cerr << "Error! Failed to read the font file!" << std::endl; } sf::Text text; text.setFont(font); text.setString(chosenText); text.setCharacterSize(fontSize); text.setPosition(Xcoord, Ycoord); text.setFillColor(sf::Color(r_text, g_text, b_text)); text.setStyle(sf::Text::Style::Bold | sf::Text::Style::Italic); while (window.isOpen()) { sf::Event Event; while (window.pollEvent(Event)) { switch (Event.type) { case sf::Event::Closed: window.close(); break; case sf::Event::Resized: std::cout << "New Text Window width: " << Event.size.width << " and height: " << Event.size.height << std::endl; break; case sf::Event::TextEntered: if (Event.text.unicode < 128) { /*std::cout << Event.text.unicode;*/ printf("%c", Event.text.unicode); } break; } } window.clear(sf::Color(r, g, b)); window.draw(text); window.display(); } } void TextWindows::getWindowColor() { std::cout << "What color do you wish your Window to be?" << std::endl << std::endl; std::cout << "1.) Black" << std::endl; std::cout << "2.) Gray" << std::endl; std::cout << "3.) Red" << std::endl; std::cout << "4.) Green" << std::endl; std::cout << "5.) Blue" << std::endl; std::cout << "6.) Yellow" << std::endl; std::cout << "7.) Magenta" << std::endl; std::cout << "8.) Cyan" << std::endl; std::cout << "9.) Purple" << std::endl << std::endl; int myColor; std::cin >> myColor; switch (myColor) { case 1: r = 0; g = 0; b = 0; break; case 2: r = 128; g = 128; b = 128; break; case 3: r = 255; g = 0; b = 0; break; case 4: r = 0; g = 255; b = 0; break; case 5: r = 0; g = 0; b = 255; break; case 6: r = 255; g = 255; b = 0; break; case 7: r = 255; g = 0; b = 255; break; case 8: r = 0; g = 255; b = 255; break; case 9: r = 128; g = 0; b = 128; break; } system("CLS"); } std::string TextWindows::chooseText() { std::cout << std::endl << "Enter the text that you wish to display on your Text Window!" << std::endl; std::cin.ignore(); getline(std::cin, chosenText); return chosenText; } void TextWindows::getFontColor() { std::cout << "What color do you wish your text to be?" << std::endl << std::endl; std::cout << "1.) Black" << std::endl; std::cout << "2.) Gray" << std::endl; std::cout << "3.) Red" << std::endl; std::cout << "4.) Green" << std::endl; std::cout << "5.) Blue" << std::endl; std::cout << "6.) Yellow" << std::endl; std::cout << "7.) Magenta" << std::endl; std::cout << "8.) Cyan" << std::endl; std::cout << "9.) Purple" << std::endl << std::endl; int myColor; std::cin >> myColor; switch (myColor) { case 1: r_text = 0; g_text = 0; b_text = 0; break; case 2: r_text = 128; g_text = 128; b_text = 128; break; case 3: r_text = 255; g_text = 0; b_text = 0; break; case 4: r_text = 0; g_text = 255; b_text = 0; break; case 5: r_text = 0; g_text = 0; b_text = 255; break; case 6: r_text = 255; g_text = 255; b_text = 0; break; case 7: r_text = 255; g_text = 0; b_text = 255; break; case 8: r_text = 0; g_text = 255; b = 255; break; case 9: r_text = 128; g_text = 0; b = 128; break; } system("CLS"); } unsigned int TextWindows::getFontSize() { std::cout << std::endl << "What size do you wish your text to be?" << std::endl; std::cin >> fontSize; return fontSize; } void TextWindows::getFontCoordinates() { std::cout << std::endl << "Enter the X and Y coordinates for your Text on a Window!" << std::endl; std::cin >> Xcoord >> Ycoord; } void Windows::drawWindows() { int width, height; std::cout << std::endl << "Enter width and height for your Window!" << std::endl; std::cin >> width >> height; sf::RenderWindow window(sf::VideoMode(width, height), "Window", sf::Style::Default); while (window.isOpen()) { sf::Event Event; while (window.pollEvent(Event)) { switch (Event.type) { case sf::Event::Closed: window.close(); break; case sf::Event::Resized: std::cout << "New Window width: " << Event.size.width << " and height: " << Event.size.height << std::endl; break; case sf::Event::TextEntered: if (Event.text.unicode < 128) { /*std::cout << Event.text.unicode;*/ printf("%c", Event.text.unicode); } break; } } window.clear(sf::Color(r, g, b)); window.display(); } }
true
9305cdf6d67ddf80f78504afca1bb0ce1876d854
C++
LEX0RE/PI2020
/Sources/Scenes/MainMenu.hpp
UTF-8
3,829
2.65625
3
[]
no_license
/// \file MainMenu.hpp #ifndef MAINMENU_HPP #define MAINMENU_HPP #include "../Scene.hpp" #include "../Event.hpp" #include "../GLContext.hpp" #include "../VisualComp.hpp" #include "../SceneManager.hpp" #include "../VisualComponents/Label.hpp" #include "../VisualComponents/Image.hpp" void OnClickNewGame(VisualComp* v); void OnClickLoadGame(VisualComp* v); void OnClickOptions(VisualComp* v); /// \brief Classe pour la gestion du menu principal. /// /// Classe contenant les éléments du menu principal. /// class MainMenu : public Scene{ public: /// \brief Execute le constructeur de la scène lorsqu'elle est chargée. /// \param param Paramètre de transit /// \return Nouvelle instance de la scène MainMenu. static inline Scene* LoadMainMenu(void* param){ return new MainMenu(); } MainMenu() : Scene(){ GLContext::SetOrthogonal(); //à faire avec le ressource manager un jour ? Label* newgame = new Label({375, 380}, GetResource("endoralt100", Font), "- New Game -", {255, 255, 255, 255}, true); Label* loadgame = new Label({385, 500}, GetResource("endoralt100", Font), "- Load Save -", {255, 255, 255, 255}, true); Label* options = new Label({410, 620}, GetResource("endoralt100", Font), "- Options -", {255, 255, 255, 255}, true); //Verson a //AddOrtho(6, new Image("Background1.png", {0,0}, {1024,768}), new Label({310,54},"ENDORALT.ttf", 130, "Legend of S.I.M", {0,0,0,255}), new Label({300,50},"ENDORALT.ttf", 125, "Legend of S.I.M", {255,255,255,255}), newgame, loadgame, options); //Version b AddOrtho(6, new Image({0, 0}, {1024, 768}, GetResource("loading", Texture)->GetId()), new Label({250, 54}, GetResource("endoralt180", Font), "Legend of S.I.M", {0, 0, 0, 200}), new Label({240,50}, GetResource("endoralt180", Font), "Legend of S.I.M", {55, 175, 212, 255}), newgame, loadgame, options ); AddSubscription(SDL_MOUSEBUTTONUP, 3, newgame, loadgame, options); newgame->Add(SDL_MOUSEBUTTONUP, OnClickNewGame); loadgame->Add(SDL_MOUSEBUTTONUP, OnClickLoadGame); options->Add(SDL_MOUSEBUTTONUP, OnClickOptions); // Ajoutez ici les ItemInfos que va contenir l'ItemManager // ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ItemManager::AddInfo( 2, new ItemInfo(false, true, GetResource("PotionImg", Texture), "potion50", "Potion +50", "Ajoute 50 ptn de vie", Potion50::Constructor), new ItemInfo(true, false, GetResource("SwordImg", Texture), "sword", "Épée", "Attaque en appuyant sur ", SwordItem::Constructor) ); // ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ } /// \brief Affiche tout les VisualComp de la scène dans la fenêtre. void Draw(){ GLContext::ApplyOrthogonal(); glDisable(GL_DEPTH_TEST); for(auto it : ortho){ it.second->Draw(); } glEnable(GL_DEPTH_TEST); } }; /// \brief Passe à la scène de jeu. /// \param v Composantes visuelles. void OnClickNewGame(VisualComp* v){ int x, y; SDL_GetMouseState(&x, &y); if(v->IsInside({(double)x,(double)y})) SceneManager::GetCurrentScene<MainMenu>()->NotifySceneManager(FREE, "World"); } /// \brief Passe à la scène de sauvegardes. /// \param v Composantes visuelles. void OnClickLoadGame(VisualComp* v){ /* int x, y; SDL_GetMouseState(&x, &y); if(v->IsInside({(double)x,(double)y})) */ } /// \brief Passe à la scène d'options. void OnClickOptions(VisualComp* v){ int x, y; SDL_GetMouseState(&x, &y); if(v->IsInside({(double)x,(double)y})) SceneManager::GetCurrentScene<MainMenu>()->NotifySceneManager(PUSH, "MainOptions"); } #endif // MAINMENU_HPP
true
da31bbd9ca6b37c440dbc7b9e379f5f219502309
C++
Tasselmi/algorithms_in_cpp
/chapter08/equivalenceClasses.cpp
UTF-8
3,302
3.140625
3
[]
no_license
//// //// Created by Apple on 2020/6/23. //// // //#include "ArrayStack.h" //#include <utility> //#include <array> // //int main() //{ // const int n = 22; //22个元素 // const int r = 11; //11个数对 // // using pint = std::pair<int, int>; // array<pint, r> pairs; //11个数对 // pairs[0] = pint(1, 5); // pairs[1] = pint(1, 6); // pairs[2] = pint(3, 7); // pairs[3] = pint(4, 8); // pairs[4] = pint(5, 2); // pairs[5] = pint(6, 5); // pairs[6] = pint(4, 9); // pairs[7] = pint(9, 7); // pairs[8] = pint(7, 8); // pairs[9] = pint(3, 4); // pairs[10] = pint(6, 2); // // int theMax = 0; //所有元素的最大值 // auto list = new ArrayStack<int>[n + 1]; //下标为0的 ArrayStack 不使用,从1开始使用 // for (auto x : pairs) { // int s = x.first, t = x.second; // std::cout << s << ", " << t << endl; // list[s].push(t); // list[t].push(s); // // if (s > theMax) { theMax = s; } // if (t > theMax) { theMax = t; } // } // std::cout << "theMax: " << theMax << endl; // std::cout << "\n------------------\n"; // // for (int k = 1; k <= theMax; ++k) { // std::cout << k << "th stack: "; // while (!list[k].empty()) { // std::cout << list[k].top() << " "; // list[k].pop(); // } // std::cout << endl; // } // std::cout << "\n------------------\n"; // // //前面为了打印每个栈,将栈遍历清空了,因此需要重新插入1次 // for (auto x : pairs) { // int s = x.first, t = x.second; // list[s].push(t); // list[t].push(s); // } // // //unprocessedList存储的是尚未被检索到的栈的编号 // ArrayStack<int> unprocessedList; // // out的作用其实是一个标志位的作用,有输出过的不再重复输出 // array<bool, n + 1> out = {true, false}; //这个地方也可以不初始化 // for (auto &x : out) { x = false; } //引用类型可以修改源值 // // for (int i = 1; i <= theMax; ++i) { // if (!out[i]) { // std::cout << i << " "; // out[i] = true; // unprocessedList.push(i); // // while (!unprocessedList.empty()) { //第一层,每个编号为1th~9th的栈被处理到 // int j = unprocessedList.top(); // unprocessedList.pop(); // while (!list[j].empty()) { //第二层,循环穷尽栈内每个元素 // int q = list[j].top(); // list[j].pop(); // if (!out[q]) { // std::cout << q << " "; // out[q] = true; // //q是栈内的元素(已被处理),但是第q个栈还没处理到,所以需要添加到栈编号中去 // //虽然最外层的 i++ 循环中也能确保第 i th 个栈被处理到,但是这里是寻找等价类 // //因此所有的相关元素必须在一次i循环体中处理完毕,否则元素就错误的划分到另外的等价类中去了 // unprocessedList.push(q); // } // } // } // // std::cout << endl; // } // } // // return 0; //}
true
aebc9592bf56abe557d7efbec095d24de6784467
C++
EImethod/CourseProject
/Unix文件系统模拟--王俊俏,蔡毅,陈浩,陈佳明/UnixFileManage.cpp
UTF-8
22,549
3.0625
3
[]
no_license
 /* 操作系统大型实验 Unix 文件管理系统 Author: 王俊俏(zjut_DD) */ /* 第0块为引导块,存放用户名和密码等 第1块为系统初始化块,存放空闲i节点号栈,空闲盘快号栈等 第2~IB_num+1为i节点块 第IB_num+2~B_numb-1为数据块 */ #include<iostream> #include<stdio.h> #include<string> #include<time.h> using namespace std; #define B_size 1024 //块大小字节数 #define B_num 4096 //盘快数目 调试用128 最后用4096 #define FBS_size 20 //空闲盘快号栈大小 #define IB_num 20 //i节点盘快数 #define FIS_size 20 //空闲i节点号栈大小 //类声明 struct Identifier; //标识符类 struct File2I; //文件名对应i节点号类 struct INode; //i节点类 struct FIStack; //空闲i节点号栈 类 struct FBStack; //空闲盘块号栈 类 struct FileSysManager; //主进程类 struct Identifier{ //14字节 标识符类,记录文件名,文件拥有者,密码等 char buf[14]; Identifier(){} Identifier(char *str){ int i=0; while( str[i] ) buf[i]=str[i], i++; buf[i]='\0'; } bool operator==(const Identifier &b)const{ //判断两个名字是否相等 return strcmp(this->buf, b.buf) == 0; } }; struct File2I{ //16字节 文件->i节点编号 映射关系 Identifier fname; //文件名 short Iid; //i节点编号 }; struct INode{ // 72字节 可以放 1024*20/72= 300个i节点 int fsize; //文件大小(字节) short addr[6]; //文件地址,记录块号 4个直接地址,1个一次间址,1一个二次间址 short Iid; //i节点编号 Identifier user; //用户是谁 bool isDirection; //是否是目录 tm edit_t; //修改时间,引用time.h中的tm类 36字节 //初始化i节点 void init(int _fsize, bool _isDir, short _Iid, Identifier _user){ fsize=_fsize; isDirection=_isDir; Iid=_Iid; user=_user; edit_t=getCurTime(); } //找到文件的第index个字节的地址, 传引用 void fileIndex(FILE* &fp,int index){ if( index<4*B_size ){ //直接地址 short block=addr[ index/B_size ] , offset=index%B_size; //块号 和块内偏移量 fseek(fp,block*B_size+offset,0); }else if( index < 4*B_size+B_size/2*B_size ){ //一次间址 index-=4*B_size; short block, offset=index%B_size, temp=index/B_size; //addr[4]->temp->target fseek(fp,addr[4]*B_size+2*temp,0); fread(&block,sizeof(short),1,fp); fseek(fp,block*B_size+offset,0); }else{ //两次间址 index-=(4*B_size+B_size/2*B_size); short block, offset=index%B_size, block2=index/B_size, temp1,temp2; //addr[5]->temp1->temp2->target temp2=block2%(B_size/2), temp1=block2/(B_size/2); // fseek(fp,addr[5]*B_size+2*temp1,0); //一层一层找... fread(&block2,sizeof(short),1,fp); fseek(fp,block2*B_size+2*temp2,0); fread(&block,sizeof(short),1,fp); fseek(fp,block*B_size+offset,0); } } //给文件增加一个盘块号, 需要修改i节点信息中的addr[6] (调用这个之前,文件大小fsize必须已经更新!!) void addBlock(FILE* fp, short Bid); //在目录里添加文件项, 需要用到空闲盘快号栈,所以放到后面定义 void add(FILE* fp, File2I &item); //释放块空间 void freeBlock(FILE* fp); //给文件写入内容 void add(FILE* fp, char *ch, int length); //将文件的内容读取出来 void readContent(FILE* fp,char *ch); //将i节点写入磁盘 void update(FILE* fp){ findIpos(fp,Iid); fwrite(this,sizeof(INode),1,fp); } //定位第Iid个i节点的位置 static void findIpos(FILE* &fp,short Iid){ //i节点从2号块开始放 fseek(fp, 2*B_size + sizeof(INode)*Iid ,0); //第二块首地址 + 偏移地址 } //获取当前系统时间, 返回一个tm变量 static tm getCurTime(){ time_t t=time(NULL); return *localtime(&t); } }; struct FIStack{ //42字节 空闲节点号 栈 大小要小于INode的大小 short st[FIS_size], top; //栈顶 FIStack(){ top=0; //空栈 } //放入一个空闲i节点号 采用成组链接法 void push(FILE* fp, short Iid){ if( top== FIS_size ){ //栈满了 INode::findIpos(fp,Iid); fwrite(st,sizeof(short),top,fp); top=0; st[top++]=Iid; }else{ st[top++]=Iid; } } //弹出一个空闲i节点号 short pop(FILE* fp){ if( top==1 ){ //只剩一个了 int Iid=st[0]; INode::findIpos(fp,Iid); top=FIS_size; fread(st,sizeof(short),top,fp); return Iid; }else{ return st[--top]; } } //从磁盘上把FIStack读入内存 void init(FILE* fp){ fseek(fp,B_size,0); fread(this,sizeof(FIStack),1,fp); } //将 空闲i节点号栈 写入磁盘 void update(FILE* fp){ fseek(fp,B_size,0); fwrite(this,sizeof(FIStack),1,fp); } }; struct FBStack{ //42字节 空闲盘块号 栈 short st[FBS_size], top; // FBStack(){ top=0; } //放入一个空闲块编号 采用成组链接法 void push(FILE* fp, short Bid){ if( top== FIS_size ){ //栈满了 fseek(fp,Bid*B_size,0); fwrite(st,sizeof(short),top,fp); top=0; st[top++]=Bid; }else{ st[top++]=Bid; } } //弹出一个空闲盘块号 short pop(FILE* fp){ if( top==1 ){ //只剩一个了 int Bid=st[0]; fseek(fp,Bid*B_size,0); top=FIS_size; fread(st,sizeof(short),top,fp); return Bid; }else{ return st[--top]; } } //从磁盘上把FBStack读入内存 void init(FILE* fp){ fseek(fp, B_size + sizeof(FIStack) ,0); fread(this,sizeof(FBStack),1,fp); } //将 空闲盘块号栈 写入磁盘 void update(FILE* fp){ fseek(fp, B_size + sizeof(FIStack) ,0); fwrite(this,sizeof(FBStack),1,fp); } }; struct FileSysManager{ FILE *fp; //文件指针 FIStack FIS; //空闲节点号栈 FBStack FBS; //空闲盘块号栈 Identifier curUser; //当前用户 char curDir[50]; //当前目录 INode curINode; //当前文件的i节点 char cmd[50],arg[50]; //命令和参数 FileSysManager(){ } void systemInitial(){ fp=fopen("disk.txt","rb+"); //用户登录模块 int num=0; Identifier user[10],psw[10],u,p; fread(&num,sizeof(int),1,fp); //从0#中 读取全部用户名,密码 fread(user,sizeof(Identifier),num,fp); fread(psw,sizeof(Identifier),num,fp); printf("请输入用户名 密码登录:\n"); while( true ){ //循环测试 直到输入正确 scanf(" %s %s",u.buf, p.buf); getchar(); bool success=false; for(int i=0;i<num;i++){ if( user[i]==u && psw[i]==p ){ printf("登录成功\n"); success=true; break; } } if( success ){ curUser=u; // break; } printf("用户名或密码错误,请重新尝试!\n"); } // fseek(fp, B_size ,0); fread(&FIS,sizeof(FIStack),1,fp); //读取,这两个常驻内存的 fread(&FBS,sizeof(FBStack),1,fp); //载入home目录(根目录) memcpy(curDir,"/home\0",sizeof(char)*6); INode::findIpos(fp,0); fread(&curINode,sizeof(INode),1,fp); } void lsdir(){ if( curINode.isDirection == false ){ puts("当前文件不是目录!!"); return; } int num=curINode.fsize/sizeof(File2I); //当前目录有几项 File2I *items=new File2I[num]; for(int i=0;i<num;i++){ //全部读取出来 curINode.fileIndex(fp,i*sizeof(File2I)); fread(items+i,sizeof(File2I),1,fp); } INode inode; for(int i=0;i<num;i++){ //看用户名显示 INode::findIpos(fp,items[i].Iid); fread(&inode,sizeof(INode),1,fp); if( inode.user == curUser){ printf("%-10s %d/%02d/%02d %02d:%02d %7s %5d字节\n", items[i].fname.buf,inode.edit_t.tm_year+1900, inode.edit_t.tm_mon+1,inode.edit_t.tm_mday, inode.edit_t.tm_hour,inode.edit_t.tm_min, inode.isDirection?"文件夹":"文件", inode.fsize); } } delete[] items; } void mkdir(){ if( curINode.isDirection == false ){ puts("当前文件不是目录!!"); return; } File2I item; item.fname=arg; item.Iid=FIS.pop(fp); //弹出一个空闲i节点编号 INode inode; inode.init(0,true,item.Iid, curUser); inode.update(fp); //写入磁盘 curINode.add(fp, item); //写入当前文件夹中 puts("添加目录成功!"); } void mkfile(){ if( curINode.isDirection == false ){ puts("当前文件不是目录!!"); return; } File2I item; item.fname=arg; item.Iid=FIS.pop(fp); //弹出一个空闲i节点编号 INode inode; inode.init(0,false,item.Iid, curUser); inode.update(fp); //写入磁盘 curINode.add(fp, item); //写入当前文件夹中 puts("添加文件成功!"); } void cd(){ //arg为目录 if( memcmp(arg,"/home",5) !=0 ){ //内存比较 puts("Invalid Direction!"); }else{ int i=5; INode inode, tempNode; INode::findIpos(fp,0); fread(&inode,sizeof(INode),1,fp); //读取home目录i节点 bool suc=true; //设置成功 while(arg[i]){ i++; int j=0; Identifier f; while(arg[i] && arg[i]!='/') { f.buf[j]=arg[i]; i++,j++; } f.buf[j]='\0'; //获得下一级目录f if( inode.isDirection == false ){ //当前文件不是目录 suc=false; break; } int num=inode.fsize/sizeof(File2I); //当前目录有几项 File2I *items=new File2I[num]; for(int i=0;i<num;i++){ //全部读取出来 inode.fileIndex(fp,i*sizeof(File2I)); fread(items+i,sizeof(File2I),1,fp); } bool find=false; //是否找到 for(int i=0;i<num;i++){ INode::findIpos(fp,items[i].Iid); fread(&tempNode,sizeof(INode),1,fp); if( items[i].fname == f && tempNode.user==curUser ){ //判断条件注意有两个** find=true; inode=tempNode; break; } } delete[] items; if( find==false ) { suc=false; break; } } if( suc ){ //找到了要更新当前目录,和当前i节点 memcpy(curDir,arg,sizeof(arg)); curINode=inode; }else{ puts("Invalid Direction!"); } } puts("当前目录修改成功!"); } void chown(){ if( memcmp(curDir,"/home\0",6)==0 ) { puts("无法更改根目录的拥有者!!"); return; } curINode.user=arg; curINode.update(fp); //写入磁盘,固化 memcpy(curDir,"/home\0",sizeof(char)*6); //重新载入根目录 INode::findIpos(fp,0); fread(&curINode,sizeof(INode),1,fp); puts("文件拥有者修改成功!"); } void back(){ if( memcmp(curDir,"/home\0",6)==0 ) { puts("已经是根目录了,无法返回!!"); return; } memcpy(arg,curDir,sizeof(arg)); int i=strlen(arg)-1; while(arg[i]!='/') i--; arg[i]='\0'; cd(); // puts("成功返回上一级目录!"); } void rename(){ if( memcmp(curDir,"/home\0",6)==0 ) { puts("无法更改根目录的文件名!!"); return; } Identifier curName; Identifier nxtName=arg; //修改后的文件名 int i=strlen(curDir)-1; while( curDir[i]!='/') i--; curName=curDir+i+1; //当前文件名 back(); //先返回上一级目录 int num=curINode.fsize/sizeof(File2I); //当前目录有几项 File2I *items=new File2I[num]; for(int i=0;i<num;i++){ //全部读取出来 curINode.fileIndex(fp,i*sizeof(File2I)); fread(items+i,sizeof(File2I),1,fp); } for(int i=0;i<num;i++){ //重新写入 if( items[i].fname == curName ){ items[i].fname=nxtName; } curINode.fileIndex(fp,i*sizeof(File2I)); fwrite(items+i,sizeof(File2I),1,fp); } delete[] items; memcpy(arg,curDir,sizeof(arg)); i=strlen(arg); arg[i]='/'; memcpy(arg+i+1,nxtName.buf,strlen(nxtName.buf)+1); cd(); //回到这个路径 puts("文件名修改成功!"); } void write(){ if( curINode.isDirection == true ){ puts("当前路径是一个目录,无法写入数据!!"); return; } FILE* fptr=fopen(arg,"rb"); if( fptr==NULL ) { puts("你所指定的文件不存在!!"); return; } fseek(fptr,0,2); int len=ftell(fptr); if( len > 4*B_size + B_size/2*B_size + B_size/2*B_size/2*B_size ){ puts("内容太长,无法写入!!"); return; } fseek(fptr,0,0); char* buf=new char[len+2]; for(int i=0;i<len;i++){ fread(buf+i,sizeof(char),1,fptr); } fclose(fptr); //关闭文件 curINode.add(fp,buf,len); delete[] buf; puts("数据写入成功!"); } void show(){ if( curINode.isDirection==true ){ puts("当前路径是目录!!"); return; } char *buf=new char[ curINode.fsize+2 ]; curINode.readContent(fp,buf); //下面调用系统记事本显示内容 int i=strlen(curDir)-1; while( curDir[i]!='/' ) i--; Identifier fname=curDir+i+1; FILE *fptr=fopen(fname.buf,"wb"); for(int i=0;i<curINode.fsize;i++) { fwrite(buf+i,sizeof(char),1,fptr); } fclose(fptr); //要先关闭文件指针, 强行将内容从缓冲区写入磁盘 char command[50]="notepad.exe "; system(strcat(command,fname.buf) ); //系统调用 remove(fname.buf); //删除文件 delete[] buf; } void removeFile(){ //递归删除 Identifier target=arg; //要删除的目标 int num=curINode.fsize/sizeof(File2I); //当前目录有几项 File2I *items=new File2I[num]; for(int i=0;i<num;i++){ //全部读取出来 curINode.fileIndex(fp,i*sizeof(File2I)); fread(items+i,sizeof(File2I),1,fp); } INode tempNode; int pos=0; for(int i=0;i<num;i++){ if( items[i].fname == target ){ INode::findIpos(fp,items[i].Iid); fread(&tempNode,sizeof(INode),1,fp); _removeFile(tempNode); //删除这个目录 curINode.fsize-=sizeof(File2I); }else{ curINode.fileIndex(fp,pos); fwrite(items+i,sizeof(File2I),1,fp); pos+=sizeof(File2I); } } curINode.update(fp); puts("文件删除成功!"); } void _removeFile(INode father){ if( father.isDirection == false ){ //如果就是一个文件了,那么直接删除 father.freeBlock(fp); //回收盘块号 Thread.FIS.push(fp,father.Iid); Thread.FIS.update(fp); }else{ //如果是一个目录,那么递归删除 int num=father.fsize/sizeof(File2I); //当前目录有几项 File2I *items=new File2I[num]; for(int i=0;i<num;i++){ //全部读取出来 father.fileIndex(fp,i*sizeof(File2I)); fread(items+i,sizeof(File2I),1,fp); } INode tempNode; for(int i=0;i<num;i++){ //先删除子目录 INode::findIpos(fp,items[i].Iid); fread(&tempNode,sizeof(INode),1,fp); _removeFile(tempNode); } father.freeBlock(fp); //回收盘块号 Thread.FIS.push(fp,father.Iid); Thread.FIS.update(fp); } } void run(){ //运行主管理程序,接受用户命令 puts("Reduced Unix File Manage System [版本 2.1]"); puts("(C) 版权所有 2010-2011 王俊俏(zjut_DD)."); while( true ){ printf("%s ",curDir); //输出当前所在路径 char buf[100]; gets(buf); sscanf(buf," %s %s",cmd,arg); //字符串输入 if( strcmp(cmd,"exit")==0 ) { //退出系统 break; }else if( strcmp(cmd,"lsdir")==0 ){ //显示目录列表 lsdir(); }else if( strcmp(cmd,"mkdir")==0 ){ //添加一个目录 mkdir(); }else if( strcmp(cmd,"mkfile")==0 ){ //添加一个文件 mkfile(); }else if( strcmp(cmd,"cd")==0 ){ //改变当前目录 cd(); }else if( strcmp(cmd,"chown")==0 ){ //改变所有者 chown(); }else if( strcmp(cmd,"rename")==0 ){ //对当前目录重命名 rename(); }else if( strcmp(cmd,"back") ==0 ){ //返回上一级目录 back(); }else if( strcmp(cmd,"write")==0 ){ //将内容写入当前文件 write(); }else if( strcmp(cmd,"show") ==0 ){ //显示当前文件的内容 show(); }else if( strcmp(cmd,"remove") ==0 ){ //删除当前目录及其子目录 removeFile(); } } } ~FileSysManager(){ //是否一定会被调用到??? FIS.update(fp); FBS.update(fp); fclose(fp); //关闭 puts("析构函数已调用 文件指针已关闭!!"); } }Thread; void INode::addBlock(FILE* fp, short Bid){ short Bnum=(fsize-1)/B_size; //要添加的这个盘快是这个文件的第Bnum个盘快, base0 if(Bnum < 4 ){ //直接地址, 无需修改磁盘,只要更新addr就行了 addr[Bnum]=Bid; this->update(fp); //内存中i节点要和磁盘上的保持一致**** }else if( Bnum < 4+B_size/2 ){ //一次间址, 需要修改磁盘了 Bnum-=4; if( Bnum==0 ){ short nBid=Thread.FBS.pop(fp); //这里注意要再申请一个盘块!!!!!!! Thread.FBS.update(fp); addr[4]=nBid; // this->update(fp); } fseek(fp, addr[4]*B_size+Bnum*2, 0); fwrite(&Bid,sizeof(short),1,fp); }else { //二次间址, 需要修改磁盘 Bnum-=(4+B_size/2); if( Bnum==0 ){ short nBid=Thread.FBS.pop(fp); //这里注意要再申请一个盘块!!!!!!! Thread.FBS.update(fp); addr[5]=nBid; // this->update(fp); } short temp1=Bnum/(B_size/2) ,temp2=Bnum%(B_size/2) , B=addr[5]; if( temp2==0 ){ short nBid=Thread.FBS.pop(fp); //这里注意要再申请一个盘块!!!!!!! Thread.FBS.update(fp); fseek(fp,B*B_size+temp1*2,0); fwrite(&nBid,sizeof(short),1,fp); } fseek(fp,B*B_size+temp1*2,0); fread(&B,sizeof(short),1,fp); fseek(fp,B*B_size+temp2*2,0); fwrite(&Bid,sizeof(short),1,fp); // } } void INode::add(FILE* fp, File2I &item){ //在目录里添加文件项 int num1=fsize/B_size, num2=(fsize+sizeof(item))/B_size; if( fsize%B_size ) num1++; if( (fsize+sizeof(item))%B_size ) num2++; if( num1==num2 ){ //不需要申请新盘快 fileIndex(fp,fsize); fwrite(&item,sizeof(File2I),1,fp); fsize+=sizeof(item); }else{ short Bid=Thread.FBS.pop(fp); //申请一个新盘快 Thread.FBS.update(fp); // fsize+=sizeof(item); //这里注意执行顺序!!!! 要先申请新盘快,才能写入!! addBlock(fp,Bid); fileIndex(fp,fsize-sizeof(item)); fwrite(&item,sizeof(File2I),1,fp); } this->update(fp); //写磁盘 因为fsize改变了 } void INode::freeBlock(FILE* fp){ int block=fsize/B_size; if( fsize%B_size ) block++; //block 为文件所占的盘块数 fsize=0; //文件大小设置为0 for(int i=0;i<4 && block>0;i++){ //直接地址 Thread.FBS.push(fp,addr[i]); block--; } if( block>0 ){ //一次间址 for(int i=0;i<B_size/2 && block>0;i++){ short Bid; fseek(fp,addr[4]*B_size+i*2,0); fread(&Bid,sizeof(short),1,fp); Thread.FBS.push(fp,Bid); block--; } Thread.FBS.push(fp,addr[4]); //** } if( block>0 ){ //二次间址 short temp1,temp2; for(int i=0;i<B_size/2 && block>0;i++){ fseek(fp,addr[5]*B_size+i*2,0); fread(&temp1,sizeof(short),1,fp); for(int j=0;j<B_size/2 && block>0;j++){ fseek(fp,temp1*B_size+j*2,0); fread(&temp2,sizeof(short),1,fp); Thread.FBS.push(fp,temp2); block--; } Thread.FBS.push(fp,temp1); } Thread.FBS.push(fp,addr[5]); //** } this->update(fp); Thread.FBS.update(fp); //更新下 } void INode::add(FILE* fp, char *ch, int length){ //将文本ch写入文件 freeBlock(fp); while( length>0 ){ int temp; if( length<B_size ) temp=length; else temp=B_size; short Bid=Thread.FBS.pop(fp); fseek(fp,Bid*B_size,0); for(int i=0;i<temp;i++){ fwrite(ch,sizeof(char),1,fp); ch++; } fsize+=temp; length-=temp; addBlock(fp,Bid); } this->update(fp); Thread.FBS.update(fp); } void INode::readContent(FILE* fp,char *ch){ for(int h=0;h<this->fsize; ){ int r; if( fsize - h >= B_size ) r=B_size; else r=fsize - h; fileIndex(fp,h); for(int i=0;i<r;i++){ fread(ch,sizeof(char),1,fp); ch++; } h+=r; } } struct formatting{ //格式化 void addUser(){ FILE *fp=fopen("disk.txt","rb+"); printf("初始化几个用户,用end end结束\n"); int num=0; Identifier user[10],psw[10]; while( scanf(" %s %s",user[num].buf, psw[num].buf)!=EOF ){ if( user[num]=="end" && psw[num]=="end") { break; } num++; } fwrite(&num,sizeof(int),1,fp); fwrite(user,sizeof(Identifier),num,fp); fwrite(psw,sizeof(Identifier),num,fp); fclose(fp); //注意要fclose!!!!!!!!!!!!!!!!!!!!否则缓冲区可能各种runtime error!!!! puts("写入用户名密码成功"); } void testAddUser(){ FILE *fp=fopen("disk.txt","rb+"); int num=0; Identifier user[10],psw[10]; fread(&num,sizeof(int),1,fp); fread(user,sizeof(Identifier),num,fp); fread(psw,sizeof(Identifier),num,fp); fclose(fp); } void initFIStack(){ FILE *fp=fopen("disk.txt","rb+"); FIStack FIS; int num=IB_num*B_size / sizeof(INode); for(int i=num-1;i>=0;i--){ FIS.push(fp,i); } fseek(fp, B_size ,0); fwrite(&FIS,sizeof(FIStack),1,fp); fclose(fp); printf("空闲i节点号栈初始化结束!\n"); } void testFIStack(){ //不改变文件内容的 FILE *fp=fopen("disk.txt","rb+"); FIStack FIS; fseek(fp, B_size ,0); fread(&FIS,sizeof(FIStack),1,fp); int num=IB_num*B_size / sizeof(INode); int trace,count=0; while( true ){ trace=FIS.pop(fp); printf("%3d got! ",trace); count++; if( count%8==0 ) puts(""); if( trace==num-1) break; } fclose(fp); puts(""); } void initFBStack(){ FILE *fp=fopen("disk.txt","rb+"); FBStack FBS; for(int i=B_num-1;i>=2+IB_num;i--){ FBS.push(fp,i); } fseek(fp, B_size+sizeof(FIStack) ,0); fwrite(&FBS,sizeof(FBStack),1,fp); fclose(fp); printf("空闲盘块号栈初始化结束!\n"); } void testFBStack(){ //不改变文件内容的 FILE *fp=fopen("disk.txt","rb+"); FBStack FBS; fseek(fp, B_size+sizeof(FIStack) ,0); fread(&FBS,sizeof(FBStack),1,fp); int trace,count=0; while( true ){ trace=FBS.pop(fp); printf("%3d got! ",trace); count++; if( count%8==0 ) puts(""); if( trace==B_num-1) break; } fclose(fp); puts(""); } void initHomeDir(){ FILE *fp=fopen("disk.txt","rb+"); FIStack fis; fis.init(fp); INode val; val.init(0,true,0,""); int id=fis.pop(fp); val.update(fp); //printf("home目录i节点编号为: %d\n",id); fis.update(fp); fclose(fp); } void testHomeDir(){ FILE *fp=fopen("disk.txt","rb+"); INode val; fseek(fp,2*B_size,0); fread(&val,sizeof(INode),1,fp); fclose(fp); } }format; void TestDisk(){ bool needC=false; //need creat a disk ? FILE *fp=fopen("disk.txt","rb+"); if( fp==NULL ) needC=true; else{ fseek(fp,0,2); if( ftell(fp) != B_num*B_size) needC=true; fclose(fp); } if( needC ){ puts("Creating a virtual disk! Please wait a minute..."); fp=fopen("disk.txt","wb"); char ch='0'; for(int i=0;i<B_num*B_size;i++) fwrite(&ch,sizeof(char),1,fp); fclose(fp); puts("Done"); } } void again(){ TestDisk(); format.addUser(); format.testAddUser(); format.initFIStack(); format.initFBStack(); format.initHomeDir(); format.testHomeDir(); } int main(){ //again(); format.testFIStack(); format.testFBStack(); Thread.systemInitial(); Thread.run(); return 0; }
true
8536d92b73e7580f193619bbe7c8da550579615e
C++
sauravsi/jitd-cpp
/src/concatNode.cpp
UTF-8
384
2.609375
3
[]
no_license
#include "concatNode.h" #include "cog.h" #include "cogTypes.h" using namespace std; concatNode::concatNode( cog* &l, cog* &r ) : cog(CONCAT), left(l), right(r) {} cog* concatNode::getLeft(){ return left; } cog* concatNode::getRight(){ return right; } void concatNode::setLeft(cog* &l){ left = l; } void concatNode::setRight(cog* &r){ right = r; }
true
1808075597790ef995e9857fe654c8dd3c628908
C++
patr-schm/surface-maps-via-adaptive-triangulations
/src/SurfaceMaps/Viewer/ColorGenerator.cc
UTF-8
1,680
2.609375
3
[ "MIT" ]
permissive
/* * This file is part of * Surface Maps via Adaptive Triangulations * (https://github.com/patr-schm/surface-maps-via-adaptive-triangulations) * and is released under the MIT license. * * Authors: Patrick Schmidt, Janis Born */ #include "ColorGenerator.hh" #include <SurfaceMaps/Viewer/Colors.hh> namespace SurfaceMaps { namespace { static Color color_cycle[] = { BLUE_100, MAGENTA_100, GREEN_100, RED_100, PURPLE_100, YELLOW_100, PETROL_100, ORANGE_100, TEAL_100, MAY_GREEN_100, BORDEAUX_100, LILAC_100, BLUE_75, MAGENTA_75, GREEN_75, RED_75, PURPLE_75, YELLOW_75, PETROL_75, ORANGE_75, TEAL_75, MAY_GREEN_75, BORDEAUX_75, LILAC_75, BLUE_50, MAGENTA_50, GREEN_50, RED_50, PURPLE_50, YELLOW_50, PETROL_50, ORANGE_50, TEAL_50, MAY_GREEN_50, BORDEAUX_50, LILAC_50, BLUE_25, MAGENTA_25, GREEN_25, RED_25, PURPLE_25, YELLOW_25, PETROL_25, ORANGE_25, TEAL_25, MAY_GREEN_25, BORDEAUX_25, LILAC_25, }; template <class T, std::size_t N> constexpr int array_size(const T (&array)[N]) noexcept { return N; } } Color ColorGenerator::generate_next_color() { Color result = color_cycle[current_index]; // Advance index int n = array_size(color_cycle); if (cycle_size > 0) n = std::min(n, cycle_size); current_index = (current_index + 1) % n; return result; } std::vector<Color> ColorGenerator::generate_next_colors(int n) { std::vector<Color> colors(n); for (int i = 0; i < n; ++i) colors[i] = generate_next_color(); return colors; } }
true
7ccd8a79516dc3a23970387cbcf529e78d03a883
C++
Vineeth-97/iiser
/PHY_423/hw1/qn05_vineeth.cpp
UTF-8
626
3.046875
3
[]
no_license
#include<iostream> #include<cmath> #include<fstream> #include<iomanip> using namespace std; double gauss( float x , float a, float m) { return exp((-1/2)*(1/(a*a))*(x-m)*(x-m))/(2*4.0*atan(1.0)*a); } int main() { ofstream gfile ("gaussian.txt"); gfile<<"+------------+------------+\n"; gfile<<"| x | f(x) |\n"; gfile<<"+------------+------------+\n"; float x,a = 2, m = 0; for ( x = -10; x <= 10; x += 0.01) { gfile<<"|"<<setw(12)<<setprecision(6)<<x<<"|"<<setw(12)<<setprecision(6)<<gauss(x,a,m)<<"|\n"; gfile<<"+------------+------------+\n"; } gfile.close(); return (0); }
true
197a3be19e9b90955c98c68e91754962e9b03723
C++
ColinRaine/CPP_Projects
/Project4_CM/Source.cpp
UTF-8
6,015
4.09375
4
[]
no_license
/* Colin Martinez Project 4 10/13/2017 This Program displays a menu with various account options for the user to add, change, or display account information. */ #include <iostream> #include <string> using namespace std; // Abstract Data Types struct CustomerAccount { string cust_name; string cust_address; string city; string state; int zip; string telephone; double acc_balance; string date_lst_paymnt; }; // Function for displaying menu to user int displayMenu() { // Variable declaration int choice; // Display Menu cout << "\t\tCustomer Accounts\n\n" << "1. Enter new account information\n" << "2. Change account information\n" << "3. Display all account information\n" << "4. Exit the program\n\n" << "Enter Your Choice: "; // User Input cin >> choice; cin.ignore(); // Skip the remaining newline character return choice; } int main() { // Variable declaration CustomerAccount cust[20] = {}; bool exit = false; const int NEW_ACC = 1, CHNG_ACC = 2, DISP_ACC = 3, EXIT = 4; // While Loop while (!exit) { // Variable declaration int choice = displayMenu(); // Switch statement switch (choice) { // Case 1 switches to new customer account menu option case 1: { // If statement if (choice == NEW_ACC) { // Nested For loop for (int index = 0; index < 20; index++) { ////////////////Collects Customer data and stores in array//////////////////// cout << "Customer Name: "; getline(cin, cust[index].cust_name); cout << "Customer Address: "; getline(cin, cust[index].cust_address); cout << "City: "; getline(cin, cust[index].city); cout << "State: "; getline(cin, cust[index].state); cout << "ZIP Code: "; cin >> cust[index].zip; cin.ignore(); // Skip the remaining newline character cout << "Telephone: "; getline(cin, cust[index].telephone); cout << "Account Balance: "; cin >> cust[index].acc_balance; cin.ignore(); // Skip the remaining newline character cout << "Date of last payment: "; getline(cin, cust[index].date_lst_paymnt); ////////////////////////////////////////////////////////////////////////////// cout << "You have entered information for customer number " << index << "\n\n"; break; } } } // Case 2 switches to Change Account menu option case 2: // If statement if (choice == CHNG_ACC) { // Variable declaration int cust_num; // Prompt for customer number cout << "Please enter customer number: "; // User Input cin >> cust_num; // Assignment of user input to variabe index int index = cust_num; // Nested If statement if (index < 20) { ///////////////////Displays Customer Information///////////////////// cout << "Customer Name: "; cout << cust[index].cust_name << endl; cout << "Customer Address: "; cout << cust[index].cust_address << endl; cout << "City: "; cout << cust[index].city << endl; cout << "State: "; cout << cust[index].state << endl; cout << "ZIP Code: "; cout << cust[index].zip << endl; cin.ignore(); // Skip the remaining newline character cout << "Telephone: "; cout << cust[index].telephone << endl; cout << "Account Balance: "; cout << cust[index].acc_balance << endl; cout << "Date of Last Payment: "; cout << cust[index].date_lst_paymnt << endl; cout << "\n\n"; ///////////////////Change Customer Information/////////////////////// cout << "Change Customer Name: "; getline(cin, cust[index].cust_name); cout << "Change Customer Address: "; getline(cin, cust[index].cust_address); cout << "Change City: "; getline(cin, cust[index].city); cout << "Change State: "; getline(cin, cust[index].state); cout << "Change ZIP Code: "; cin >> cust[index].zip; cin.ignore(); // Skip the remaining newline character cout << "Telephone: "; getline(cin, cust[index].telephone); cout << "Change Account Balance: "; cin >> cust[index].acc_balance; cin.ignore(); // Skip the remaining newline character cout << "Change Date of last payment: "; getline(cin, cust[index].date_lst_paymnt); ///////////////////////////////////////////////////////////////////// // Confirmation prompt cout << "You have entered information for customer number " << index << "\n\n"; break; } else // If customer number(index) falls outside of array size cout << "Number exceeds Customer pool." << endl; cout << "\n\n"; break; } // Case 3 switches to Display All Account Info. menu option case 3: //If statement if (choice == DISP_ACC) // nested for loop for (int index = 0; index < 20; index++) { //////////////Displays all Customer Information///////////// cout << "Customer Name: "; cout << cust[index].cust_name << endl; cout << "Customer Address: "; cout << cust[index].cust_address << endl; cout << "City: "; cout << cust[index].city << endl; cout << "State: "; cout << cust[index].state << endl; cout << "ZIP Code: "; cout << cust[index].zip << endl; cout << "Telephone: "; cout << cust[index].telephone << endl; cout << "Account Balance: "; cout << cust[index].acc_balance << endl; cout << "Date of Last Payment: "; cout << cust[index].date_lst_paymnt << endl; cout << "\n\n"; //////////////////////////////////////////////////////////// // Prompt for continue before continuing to display customer info. cout << "Press 'Enter' to continue..."; cin.ignore(); } // Case 4 switches to exit program menu option case 4: if (choice == EXIT) return 0; } } }
true
817240a276bea4a1c73c00f5c9943ee79b294972
C++
KeshavChawla/Customized-Job-Parser
/job_parser_helper.cc
UTF-8
2,102
2.984375
3
[]
no_license
/******************************************************* * Copyright (C) 2021 Keshav Chawla * hello [at] keshavchawla.com * * This file is part of Job Parser Project. * * Unauthorized copying of this file, via any medium is strictly prohibited * * Job Parser Project can not be copied and/or distributed without the express * permission of Keshav Chawla. *******************************************************/ #include <algorithm> #include <map> #include <string> #include <vector> using namespace std; struct skillsPackage { vector<string>* skills_list; map<string, string>* skills_to_desc_map; }; // Modifies the word but converts to lowercase void convertToLowerCase(string& text_to_convert) { int strLen = text_to_convert.length(); for (int i = 0; i <= strLen; i++) { text_to_convert[i] = tolower(text_to_convert[i]); } } // Removes the special characters from the word_to_check // Modifies the word_to_check void word_normalizer(string& word_to_check) { vector<char> special_chars_to_remove = {',', '\"', '\\', '\'', ':', '.', '?', '!', '(', '-', ')', '[', ']', '*', '/', '=', '+'}; int num_of_special_chars = special_chars_to_remove.size(); for (int i = 0; i <= num_of_special_chars; i++) { word_to_check.erase(remove(word_to_check.begin(), word_to_check.end(), special_chars_to_remove[i]), word_to_check.end()); } } void sortPairVector(vector<pair<string, int>>& vec) { sort(vec.begin(), vec.end(), [](const pair<string, int>& a, const pair<string, int>& b) { return (a.second > b.second); }); } // Used to output file as a new CSV // The last parm newLine determines // if we end the current job row template <typename T> void outputToFileCSV(ofstream& output_file, T output_value, bool newLine = false) { output_file << output_value; if (newLine) output_file << endl; else output_file << ","; }
true
c37df7d9ec02d9726ae401579575ad67b00c6551
C++
AtigPurohit/Data-Structures-and-Algorithm
/Vector/vectorsort.cpp
UTF-8
467
2.828125
3
[]
no_license
#include<bits/stdc++.h> using namespace std; int main() { int n; cin>>n; vector<int> v; int data; for (int i = 0; i < n; i++) { cin>>data; v.push_back(data); } cout<<"Before sort - "; for(auto i= v.begin(); i != v.end(); ++i) cout<<*i<<" "; cout<<endl; sort(v.begin(),v.end()); cout<<"After sort - "; for(auto i= v.begin(); i != v.end(); ++i) cout<<*i<<" "; cout<<endl; return 0; }
true
6ce734cced3a478f206cb829560c4e43afa8f28a
C++
coaldigger1234/Final_Project
/V2_McIntyre_Robbins_Final_Project/GameManager.cpp
UTF-8
6,214
2.53125
3
[]
no_license
// // Created by Owner on 4/19/2021. // #include "GameManager.h" #include <iostream> // for standard input/output #include <fstream> using namespace std; // using the standard namespace #include <random> #include <ctime> #include <string> #include <SFML/Graphics.hpp> // include the SFML Graphics Library #include "Asteroid.h" #include "Player.h" #include "Missile.h" using namespace sf; GameManager::GameManager() { running = true; hasWon = false; isAlive = true; } Vector2f GameManager::getDimensions() { return Vector2f(WIDTH, HEIGHT); } int GameManager::startGame() { srand(time(0)); rand(); drawWindow(); CircleShape shotMissile; Player player; vector<Missile> missileVec; Clock clock; Asteroid setAst; vector<Player> currPlayerState; Font myFont; ifstream inFS("score.txt"); if(inFS.fail()){ ofstream outFS("score.txt"); cout << "No file found. File created" << endl; outFS << 0; outFS.close(); highscore = 0; } inFS >> highscore; inFS.close(); int numAsteroid = ( (double)rand() / RAND_MAX * 8 + 3 ) * ( ( WIDTH * HEIGHT ) / ( 640 * 640 ) ); Asteroid placeholderAst; placeholderAst.changeColor(); asteroidVec.push_back(placeholderAst); asteroidVec.push_back(placeholderAst); asteroidVec.push_back(placeholderAst); for (int fillAstVec = 0; fillAstVec < numAsteroid; ++fillAstVec) { Asteroid fillerAsteroid; asteroidVec.push_back(fillerAsteroid); } while(running) { if (!myFont.loadFromFile("arial.ttf")) { cerr << "An error has occurred" << endl; return -1; } Event event; while (window.pollEvent(event)) { // ask the window if any events occurred if (event.type == Event::Closed) { // if event type is a closed event // i.e. they clicked the X on the window if(hasWon) { ofstream outFS("score.txt"); if(outFS.fail()){ return -1; } outFS << highscore + 1; outFS.close();// then close our window } if(!isAlive){ ofstream outFS("score.txt"); if(outFS.fail()){ return -1; } outFS << 0; outFS.close();// then close our window } window.close(); running = false; } if (isAlive) { if (event.type == Event::KeyPressed) { switch (event.key.code) { case sf::Keyboard::Space: if (missileVec.size() > 2) { missileVec.erase(missileVec.begin() + 0); currPlayerState.erase(currPlayerState.begin() + 0); } Missile currMissile; currPlayerState.push_back(player); missileVec.push_back(currMissile); missileVec.at(missileVec.size() - 1).isShot(player); break; } } } player.onEvent(event); } if(isAlive) { window.clear(Color::Black); //Handle Missile/Asteroid collision for (int k = 0; k < missileVec.size(); ++k) { for (int asterID = 0; asterID < asteroidVec.size(); ++asterID) { missileVec.at(k).hitsAsteroid(asteroidVec, asterID); } window.draw(missileVec.at(k).getShape()); } //Handle Missile/Player collision for (int l = 0; l < missileVec.size(); ++l) { missileVec.at(l).updateMissile(currPlayerState.at(l)); player.collision(asteroidVec, l); } double time = clock.restart().asMilliseconds(); player.updatePlayer(time); window.draw(player); for (int i = 0; i < asteroidVec.size(); ++i) { window.draw(asteroidVec.at(i).getAsteroidShape()); } for (int j = 0; j < asteroidVec.size(); ++j) { asteroidVec.at(j).updateAsteroid(time); player.collision(asteroidVec, j); } Text livesText; livesText.setFont(myFont); livesText.setString("Lives Left: " + to_string(player.getLives())); livesText.setCharacterSize(40); livesText.setFillColor(Color::White); window.draw(livesText); Text winText; winText.setPosition(Vector2f(WIDTH / 3, HEIGHT / 3)); winText.setFont(myFont); winText.setString("You Win!"); winText.setCharacterSize(80); winText.setFillColor(Color::White); if (asteroidVec.size() - 3 == 0) { window.draw(winText); hasWon = true; } window.display(); if (player.getLives() <= 0) { isAlive = false; } } else { window.clear(); Text loseText; loseText.setPosition(Vector2f(WIDTH/3,HEIGHT/3)); loseText.setFont(myFont); loseText.setString("Game Over!"); loseText.setCharacterSize(80); loseText.setFillColor(Color::White); window.draw(loseText); window.display(); } } }; void GameManager::drawWindow() { if(window.isOpen()) { window.close(); } window.create(VideoMode(WIDTH, HEIGHT), "SFML Asteroids Game", Style::Close); window.setKeyRepeatEnabled(true); window.setFramerateLimit(60); } vector<Asteroid> GameManager::getAsteroidVec() { return asteroidVec; } void GameManager::setAsteroidVec(vector<Asteroid> newAsteroidVec) { asteroidVec = newAsteroidVec; }
true
3a8697918a44bd0180bc323b5d889c4ae8674a01
C++
Tenderest/CPP-Learning
/Cpp_Primer_Plus/Chapter4/numstr-correct.cpp
UTF-8
616
3.5625
4
[]
no_license
// numstr.cpp -- following number input with line input #include <iostream> int main(void) { using namespace std; cout << "What year was your house built?\n"; int year; /* Correct */ /* 1 */ cin >> year; cin.get(); // or cin.get(ch); /* 2 */ (cin >> year).get(); // or (cin >> year).get(ch); cout << "What is its street address?\n"; char address[80]; cin.getline(address, 80); cout << "Year built: " << year << endl; cout << "Address: " << address << endl; cout << "Done!\n"; return 0; }
true
06c85b8b8fb3e99bfc66550677a4804cb93fabec
C++
dooleyet/ECE387_GroupProject
/FlexiForceEdits.ino
UTF-8
878
2.984375
3
[]
no_license
//From the bildr article http://bildr.org/2012/11/flexiforce-arduino/ int flexiForcePin = A0; //analog pin 0 int transPin = 7; int n = 0; void setup(){ //Pin for transisto r gate pinMode(2, OUTPUT); pinMode(7, OUTPUT); Serial.begin(9600); //Turn alarm on digitalWrite(2, HIGH); digitalWrite(7, LOW); } void loop(){ //Read pressure sensor int flexiForceReading = analogRead(flexiForcePin); //Increment n for readings over 150 if(flexiForceReading > 150){ n++; } //Turn off alarm if n reaches 20 loops or 5 seconds if(n >= 20) { digitalWrite(2, LOW); digitalWrite(7, HIGH); } //Serial monitor troubleshooting Serial.print(flexiForceReading); Serial.print(" "); Serial.println(n); Serial.print("transceiver pin "); Serial.println(digitalRead(transPin)); delay(250); //just here to slow down the output for easier reading }
true
f714d112b72cea70b2d5a1c4bdd293ca50a10ae9
C++
envamp/Augmentations
/augs/entity_system/world.cpp
UTF-8
1,563
2.515625
3
[]
no_license
#include "world.h" #include "processing_system.h" #include "../../game_framework/messages/new_entity_message.h" namespace augs { world::world(overworld& parent_overworld) : parent_overworld(parent_overworld) {} void world::initialize_entity_and_component_pools(int maximum_elements) { entity_pool_capacity = maximum_elements; entities.initialize(entity_pool_capacity); for (auto& cont : component_containers.get_raw()) ((memory_pool*)cont.second)->resize(entity_pool_capacity); } world::~world() { delete_all_entities(); } entity_id world::create_entity(std::string debug_name) { entity_id res = entities.allocate(std::ref(*this)); res->debug_name = debug_name; #ifdef USE_NAMES_FOR_IDS res.set_debug_name(debug_name); assert(res.get_debug_name() != ""); #endif messages::new_entity_message msg; msg.subject = res; post_message(msg); return res; } void world::delete_all_entities() { entities.free_all(); } void world::delete_entity(entity_id e) { entities.free(e); } entity_id world::get_id_from_raw_pointer(entity* e) { auto new_id = entities.get_id(e); #ifdef USE_NAMES_FOR_IDS new_id.set_debug_name(e->debug_name); #endif return new_id; } std::vector<processing_system*>& world::get_all_systems() { return all_systems; } memory_pool& world::get_components_by_hash(size_t hash) { return *((memory_pool*)component_containers.find(hash)); } entity* world::entities_begin() { return entities.data(); } entity* world::entities_end() { return entities.data() + entities.size(); } }
true
1492ba0ee8a3fa47841934c96dbc5421146236cf
C++
shanche/Notes
/Quant/B组(组长:陈聪)/Quizzes/Quiz1_Sep29/quiz1_code_/quiz1Pro17.cpp
UTF-8
468
3.625
4
[]
no_license
#include<iostream> using namespace std; float maxProfit(float prices[], int size) { if (size <= 1) return 0.0; float profit = 0.0; for (int i = 1; i < size; i++) { float diff = prices[i] - prices[i-1]; if (diff > 0.0) { profit += diff; } } } int main() { float prices[4] = {1.2,3.2,2.5,4.6}; int size = 4; float profit = maxProfit(prices, 4); cout << "profit is " << profit << endl; return 0; }
true
f93df853ea706424979019d38159a7761e3f77e6
C++
AaronLin98/Algorithm
/Course Design_Approximation Algorithm in Steiner Tree/Course Design.cpp
GB18030
23,066
2.921875
3
[]
no_license
#include<iostream> #include<cmath> #include<vector> #include<set> #include<queue> #include<fstream> #include<algorithm> using namespace std; #define MAX 100 #define PI 3.1416 typedef struct POINT // { double x; double y; int index; friend bool operator < (struct POINT const &v1, struct POINT const &v2) { if (v1.x == v2.x) { return v1.y < v2.y; } else { return v1.x < v2.x; } } friend bool operator == (struct POINT const &v1, struct POINT const &v2) { return (v1.x == v2.x&&v1.y == v2.y); } friend bool operator !=(const POINT &a, const POINT &b) { if (a.x == b.x && a.y == b.y) { return false; } else { return true; } } }V; typedef struct EDGE { V a; V b; int index; double cost; vector<int> MST_T_index; //ڵMSTεк 0<=MST_T_index.size()<=2 friend bool operator < (struct EDGE const &e1, struct EDGE const &e2) { if (e1.a == e2.a) { return e1.b < e2.b; } else { return e1.a < e2.a; } } friend bool operator == (struct EDGE const &e1, struct EDGE const &e2) { return (e1.a == e2.a&&e1.b == e2.b) || (e1.a == e2.b&&e1.b == e2.a); } }E; typedef struct TRIANGLE { POINT a; POINT b; POINT c; int index; int MST_index; //MSTк friend bool operator ==(const TRIANGLE &t1, const TRIANGLE &t2) //жǷ { if (t1.a != t2.a &&t1.a != t2.b &&t1.a != t2.c) return false; else if (t1.b != t2.a &&t1.b != t2.b &&t1.b != t2.c) return false; else if (t1.c != t2.a &&t1.c != t2.b &&t1.c != t2.c) return false; else return true; } }T; struct ACS { //ڹϵ int index; //MSTεıкindex int ab_index, bc_index, ac_index; //MSTεab,bc,acڵMSTεк(Ϊ-1) }; struct edge //¼εı { POINT a, b; int adjtriangle; }; struct stPOINT //˹̹ɵ { int index; POINT point; }; struct triasmt //ͱȽsmtҪ { double smt; int index; POINT stainer; }; //ʷ int n; // vector<POINT> points; //ƽϵĵ㼯 vector<TRIANGLE> triangles; //ȷб vector<TRIANGLE> temp_triangles; //δȷб vector<TRIANGLE> split_triangles; //ָб //MST double G[MAX][MAX]; set<V> MST_set; set<E> edgesets; vector<E> edges; vector<E> MST_edges; //adjecent vector<ACS> acs; int PT_edges[MAX][MAX]; vector<T> MST_triangles; //˹̹ɵ vector<ACS> exisarc(acs); vector<POINT> steiner; vector<stPOINT> stainer; //SMT / MST double mst_cost = 0; double smt_cost = 0; //ʷ bool Compare(POINT a, POINT b) //ԵȽ { if (a.x <= b.x) { if (a.x == b.x && a.y > b.y) return false; else return true; } else return false; } bool CompareY(POINT a, POINT b) //ԵȽ { if (a.y <= b.y) { if (a.y == b.y && a.x > b.x) return false; else return true; } else return false; } void Input() //ƽ㼯겢 { POINT temp; cout << "ƽ㼯ж"; cin >> n; for (int i = 0; i < n; i++) { cout << "" << i + 1 << "xy꣺"; cin >> temp.x >> temp.y; points.push_back(temp); } sort(points.begin(), points.end(), Compare); //index for (int i = 0; i<points.size(); i++) { points[i].index = i; } } TRIANGLE Makesupert() //ȷ { TRIANGLE super; double left, right, up, down; //ֱҵ㼯ĸԵֵ double height, length; //ĵɵķεij͸ POINT a, b, c; left = points.front().x; right = points.front().x; up = points.front().y; down = points.front().y; for (vector<POINT>::iterator it = points.begin(); it != points.end(); it++) { if (left > it->x) left = it->x; if (right < it->x) right = it->x; if (up < it->y) up = it->y; if (down > it->y) down = it->y; } height = up - down; length = right - left; a.x = left + length / 2; //ʱɵǡðΧס㼯 a.y = up + length / 2; b.x = left - height; b.y = down; c.x = right + height; c.y = down; a.y += height / 2; b.x -= height; b.y -= height / 2; c.x += height; c.y -= height / 2; super.a = a; super.b = b; super.c = c; return super; } double Distance(POINT a, POINT b) // { return sqrt((a.x - b.x)*(a.x - b.x) + (a.y - b.y)*(a.y - b.y)); } double GetR(TRIANGLE t) //Բ뾶 { double R; double e1, e2, e3; e1 = Distance(t.a, t.b); e2 = Distance(t.b, t.c); e3 = Distance(t.c, t.a); R = e1*e2*e3 / sqrt((e1 + e2 + e3)*(e2 + e3 - e1)*(e1 - e2 + e3)*(e1 + e2 - e3)); return R; } POINT GetPoint(TRIANGLE t) //ԲԲ { POINT temp; temp.x = (t.a.x + t.b.x + t.c.x) / 3; temp.y = (t.a.y + t.b.y + t.c.y) / 3; return temp; } int PosCompare(TRIANGLE t, POINT p) //ȽϵԲλ { double R = GetR(t); POINT o = GetPoint(t); if (Distance(p, o) > R) { if (p.x > o.x + R) return 1; //ԲҲ࣬Ϊdelaunay else return 0; //Բ࣬ȷ } else return -1; //Բڲ࣬delaunay } bool Existed(TRIANGLE t) //жϸǷѴڲȷб { for (vector<TRIANGLE>::iterator it = temp_triangles.begin(); it != temp_triangles.end(); it++) { if (t == *it) return true; else continue; } return false; } void Split(POINT p) //delaunayηָȥشtemp_triangles { TRIANGLE temp; for (vector<TRIANGLE>::iterator it = split_triangles.begin(); it != split_triangles.end(); it++) { temp.a = it->a; temp.b = it->b; temp.c = p; if (!Existed(temp)) temp_triangles.push_back(temp); temp.a = it->b; temp.b = it->c; temp.c = p; if (!Existed(temp)) temp_triangles.push_back(temp); temp.a = it->c; temp.b = it->a; temp.c = p; if (!Existed(temp)) temp_triangles.push_back(temp); } } bool Related(TRIANGLE super, TRIANGLE t) //鵱ǰǷ볬й { if (t.a != super.a && t.a != super.b && t.a != super.c) { if (t.b != super.a && t.b != super.b && t.b != super.c) { if (t.c != super.a && t.c != super.b && t.c != super.c) return false; else return true; } else return true; } else return true; } void Delaunay() //Delaunayʷ { int judge; int i = 1; TRIANGLE super = Makesupert(); temp_triangles.push_back(super); //δδȷб for (vector<POINT>::iterator it = points.begin(); it != points.end(); it++) //˳е { for (vector<TRIANGLE>::iterator iter = temp_triangles.begin(); iter != temp_triangles.end();) //δȷбе { judge = PosCompare(*iter, *it); //жǷdelaunayλȷ if (judge == 1) { triangles.push_back(*iter); //delaunayΣȷб iter = temp_triangles.erase(iter); } else if (judge == 0) { iter++; //޷ȷ } else if (judge == -1) { split_triangles.push_back(*iter); iter = temp_triangles.erase(iter); } } Split(*it); } //ıϲtrianglestemp_triangles triangles.insert(triangles.end(), temp_triangles.begin(), temp_triangles.end()); //ȥ볬йص for (vector<TRIANGLE>::iterator it = triangles.begin(); it != triangles.end(); ) { if (Related(super, *it)) it = triangles.erase(it); else it++; } //ʱõtrianglesбΪʷе cout << triangles.size() << endl; //index for (int i = 0; i<triangles.size(); i++) { triangles[i].index = i; } //output for (vector<TRIANGLE>::iterator it = triangles.begin(); it != triangles.end(); it++) { cout << "(" << it->a.x << "," << it->a.y << ") (" << it->b.x << "," << it->b.y << ") (" << it->c.x << "," << it->c.y << ")" << endl; } } //MST double Compute_cost(V v1, V v2) { double cost = sqrt((v1.x - v2.x)*(v1.x - v2.x) + (v1.y - v2.y)*(v1.y - v2.y)); return cost; } bool cmp(E e1, E e2) { return e1.cost<e2.cost; } E reverse(E e) { E temp; temp.a = e.b; temp.b = e.a; temp.cost = e.cost; return temp; } void join_edges(T t) { E e1, e2, e3; double c1, c2, c3; c1 = Compute_cost(t.a, t.b); c2 = Compute_cost(t.c, t.b); c3 = Compute_cost(t.a, t.c); e1.a = t.a; e1.a.index = t.a.index; e1.b = t.b; e1.b.index = t.b.index; e1.cost = c1; if (!edgesets.count(e1) && !edgesets.count(reverse(e1))) { edgesets.insert(e1); edges.push_back(e1); } e2.a = t.c; e2.a.index = t.c.index; e2.b = t.b; e2.b.index = t.b.index; e2.cost = c2; if (!edgesets.count(e2) && !edgesets.count(reverse(e2))) { edgesets.insert(e2); edges.push_back(e2); } e3.a = t.c; e3.a.index = t.c.index; e3.b = t.a; e3.b.index = t.a.index; e3.cost = c3; if (!edgesets.count(e3) && !edgesets.count(reverse(e3))) { edgesets.insert(e3); edges.push_back(e3); } } void MST() { memset(G, -1, sizeof(G)); for (vector<T>::iterator it = triangles.begin(); it != triangles.end(); it++) { T t1 = (*it); join_edges(t1); } sort(edges.begin(), edges.end(), cmp); for (int i = 0; i<edges.size(); i++) { edges[i].index = i; } for (vector<E>::iterator it = edges.begin(); it != edges.end(); it++) { E e = (*it); if (!MST_set.count(e.a) || !MST_set.count(e.b)) { MST_edges.push_back(e); MST_set.insert(e.a); MST_set.insert(e.b); G[e.a.index][e.b.index] = e.cost; G[e.b.index][e.a.index] = e.cost; mst_cost+=e.cost; } } /* for (int i = 0; i<n; i++) { for (int j = 0; j<n; j++) { if (G[i][j]>0) { mst_cost += G[i][j]; } } } mst_cost = mst_cost / 2.0;*/ cout << "\nmst:\n" << "mst cost : " << mst_cost << endl; } //Ѱ int judge_mst_triangle(V a, V b) { //жmstڵıǷγһ E e; e.a = a; e.b = b; vector<E>::iterator result = find(edges.begin(), edges.end(), e); if (result != edges.end()) return 1; else return 0; } int Triangles_index(V a, V b, V c) { //õԭεк T t; t.a = a; t.b = b; t.c = c; vector<T>::iterator Tresult = find(triangles.begin(), triangles.end(), t); if (Tresult == triangles.end()) return -1; int index_T = (*Tresult).index; return index_T; } //push void MST_edge_triangles_push(E e, int index_T) { vector<E>::iterator it = find(edges.begin(), edges.end(), e); (*it).MST_T_index.push_back(index_T); } //MSTеı void MST_edge_triangles(int index_T) { E ab, bc, ac; ab.a = triangles[index_T].a; ab.b = triangles[index_T].b; MST_edge_triangles_push(ab, index_T); bc.a = triangles[index_T].b; bc.b = triangles[index_T].c; MST_edge_triangles_push(bc, index_T); ac.a = triangles[index_T].a; ac.b = triangles[index_T].c; MST_edge_triangles_push(ac, index_T); } int ACS_index(E e, int index_T) { //ACSõһڵ vector<E>::iterator qt = find(edges.begin(), edges.end(), e); auto p = find(MST_edges.begin(), MST_edges.end(), (*qt)); if (p == MST_edges.end()) return -2; else if ((*qt).MST_T_index.size() == 2) { if ((*qt).MST_T_index[0] == index_T) return (*qt).MST_T_index[1]; else return (*qt).MST_T_index[0]; } else return -1; } //ACSõԭεı void edges_for_triangle(E &ab, E &bc, E &ac, int index_T) { ab.a = triangles[index_T].a; ab.b = triangles[index_T].b; ac.a = triangles[index_T].a; ac.b = triangles[index_T].c; bc.a = triangles[index_T].b; bc.b = triangles[index_T].c; } void adjcent() { int MST_index = 0; //¼MSTMSTек for (int i = 0; i<n; i++) { int k = 0; V a, b, c; for (int j = 0; j<n; j++) { if (G[i][j]>0) { if (!k) { k++; a = points[j]; } else { k = 0; b = points[j]; if (judge_mst_triangle(a, b)) //жǷԭʷдڸ { c = points[i]; int index_T = Triangles_index(a, b, c); //ѰҶӦԭε if (index_T == -1) continue; triangles[index_T].MST_index = MST_index; //γMSTεк MST_triangles.push_back(triangles[index_T]); //пγɵMST MST_index++; MST_edge_triangles(index_T); //洢ÿпڵ } } } } } for (vector<T>::iterator it = MST_triangles.begin(); it != MST_triangles.end(); it++) { E ab, bc, ac; struct ACS acs1; int index_T = (*it).index; acs1.index = index_T; edges_for_triangle(ab, bc, ac, index_T); acs1.ab_index = ACS_index(ab, index_T); acs1.bc_index = ACS_index(bc, index_T); acs1.ac_index = ACS_index(ac, index_T); acs.push_back(acs1); } cout<<"\nMST:"<<endl; for (vector<ACS>::iterator it = acs.begin(); it != acs.end(); it++) { cout << " " << (*it).index << " " << (*it).ab_index << " " << (*it).ac_index << " " << (*it).bc_index << endl; } cout<<endl; } //˹̹ɵ double fabsarea(POINT p1, POINT p2, POINT p3)// { return fabs((p2.x - p1.x)*(p3.y - p1.y) - (p2.y - p1.y)*(p3.x - p1.x)); } POINT getcross(POINT a1, POINT a2, POINT b1, POINT b2)//߶ν ʽ { double s1, s2; s1 = fabsarea(a1, a2, b1); s2 = fabsarea(a1, a2, b2); POINT t; t.x = (b2.x*s1 + b1.x*s2) / (s1 + s2); t.y = (b2.y*s1 + b1.y*s2) / (s1 + s2); return t; } double stainerpoint(TRIANGLE t, POINT&stainer, int i) { POINT q, w, e;//w max EDGE ab, bc, ca; ab.cost = pow(t.a.x - t.b.x, 2) + pow(t.a.y - t.b.y, 2); ab.cost = sqrt(ab.cost); ab.a = t.a; ab.b = t.b; bc.cost = pow(t.b.x - t.c.x, 2) + pow(t.b.y - t.c.y, 2); bc.cost = sqrt(bc.cost); bc.a = t.b; bc.b = t.c; ca.cost = pow(t.c.x - t.a.x, 2) + pow(t.c.y - t.a.y, 2); ca.cost = sqrt(ca.cost); ca.a = t.c; ca.b = t.a; auto p = find(MST_edges.begin(), MST_edges.end(), ab); //ҵmstе if (p == MST_edges.end()) { w = t.c; q = t.a; e = t.b; } p = find(MST_edges.begin(), MST_edges.end(), bc); if (p == MST_edges.end()) { w = t.a; q = t.b; e = t.c; } p = find(MST_edges.begin(), MST_edges.end(), ca); if (p == MST_edges.end()) { w = t.b; q = t.c; e = t.a; } POINT trq, trq1, trq2, tre, tre1; trq.x = q.x - w.x; trq.y = q.y - w.y; //ȱ double j1, j2; j1 = 1.0 / 3.0 * PI; trq1.x = trq.x*cos(j1) - trq.y*sin(j1); trq1.y = trq.x*sin(j1) + trq.y*cos(j1); tre.x = e.x - w.x; tre.y = e.y - w.y; double anglecostrq, anglecosq, anglesintrq; anglesintrq = (trq1.x*(w.x - e.x) + trq1.y*(w.y - e.y)) / sqrt(trq1.x*trq1.x + trq1.y*trq1.y) / sqrt(pow(w.x - e.x, 2) + pow(w.y - e.y, 2)) - 0.5; anglecostrq = (trq1.x*tre.x + trq1.y*tre.y) / sqrt(trq1.x*trq1.x + trq1.y*trq1.y) / sqrt(tre.x*tre.x + tre.y * tre.y); anglecosq = ((q.x - w.x)*tre.x + (q.y - w.y)*tre.y) / sqrt((q.x - w.x)*(q.x - w.x) + (q.y - w.y)*(q.y - w.y)) / sqrt(tre.x*tre.x + tre.y * tre.y); if (anglesintrq>0 && anglecostrq < anglecosq) { tre1.x = tre.x*cos(j1) + tre.y*sin(j1); tre1.y = -tre.x*sin(j1) + tre.y*cos(j1); } else { trq1.x = trq.x*cos(j1) + trq.y*sin(j1); trq1.y = -trq.x*sin(j1) + trq.y*cos(j1); tre1.x = tre.x*cos(j1) - tre.y*sin(j1); tre1.y = tre.x*sin(j1) + tre.y*cos(j1); } trq.x = trq1.x + w.x; trq.y = trq1.y + w.y; tre.x = tre1.x + w.x; tre.y = tre1.y + w.y; POINT st=getcross(trq,e,tre,q); double opti; st.index = i; stainer.x = st.x; stainer.y = st.y; cout<<" steniar point "<<st.x<<" "<<st.y<<endl; opti = sqrt(pow(st.x - q.x, 2) + pow(st.y - q.y, 2)) + sqrt(pow(st.x - w.x, 2) + pow(st.y - w.y, 2)) + sqrt(pow(st.x - e.x, 2) + pow(st.y - e.y, 2)); cout<<"smt opti :"<<opti<<endl; double tempopti = sqrt(pow(w.x - q.x, 2) + pow(w.y - q.y, 2)) + sqrt(pow(w.x - e.x, 2) + pow(w.y - e.y, 2)); cout<<"mst opti :"<<tempopti<<endl; opti = opti / tempopti; return opti; } //stainer trique exist.ab index-corresponded //exist index->triangles->exist bool doubleadj(int a, int b, int c) //жǷmst { if (a == -2 && b == -2) { return 0; } else if (a == -2 && c == -2) { return 0; } else if (b == -2 && c == -2) { return 0; } else { return 1; } } double modifystainer(vector<ACS>& exist) //ŻͼG { POINT stainer; typedef struct cmpsmt { bool operator()(triasmt a, triasmt b) { return a.smt < b.smt; } }; priority_queue <triasmt, vector<triasmt>, cmpsmt> trique; //洢 int j; for (int i = 0; i < (int)exist.size(); i++) { j = exist[i].index; if (!doubleadj(exist[i].ab_index, exist[i].bc_index, exist[i].ac_index)) { continue; } triasmt t; t.index = i; t.smt = stainerpoint(triangles[j], stainer, i); t.stainer = stainer; if (t.smt < 1) { cout<<"---->smt/mst"<<t.smt<<endl; trique.push(t); } } cout<<endl; j = 0; EDGE adj1, adj2; smt_cost = mst_cost; while (trique.size() != 0) { double lzy_cut=0; double cut = 0; triasmt t = trique.top(); trique.pop(); j = t.index; if (exist[j].index == -1) //ƻ continue; if (exist[j].ab_index != -2) { if (exist[j].bc_index != -2) { adj1.index = exist[j].ab_index; adj1.a.index = triangles[exist[j].index].a.index; adj1.a.x = triangles[exist[j].index].a.x; adj1.a.y = triangles[exist[j].index].a.y; adj1.b.index = triangles[exist[j].index].b.index; adj1.b.x = triangles[exist[j].index].b.x; adj1.b.y = triangles[exist[j].index].b.y; adj2.index = exist[j].bc_index; adj2.a.index = triangles[exist[j].index].b.index; adj2.a.x = triangles[exist[j].index].b.x; adj2.a.y = triangles[exist[j].index].b.y; adj2.b.index = triangles[exist[j].index].c.index; adj2.b.x = triangles[exist[j].index].c.x; adj2.b.y = triangles[exist[j].index].c.y; } else { adj1.index = exist[j].ab_index; adj1.a.index = triangles[exist[j].index].a.index; adj1.a.x = triangles[exist[j].index].a.x; adj1.a.y = triangles[exist[j].index].a.y; adj1.b.index = triangles[exist[j].index].b.index; adj1.b.x = triangles[exist[j].index].b.x; adj1.b.y = triangles[exist[j].index].b.y; adj2.index = exist[j].ac_index; adj2.a.index = triangles[exist[j].index].a.index; adj2.a.x = triangles[exist[j].index].a.x; adj2.a.y = triangles[exist[j].index].a.y; adj2.b.index = triangles[exist[j].index].c.index; adj2.b.x = triangles[exist[j].index].c.x; adj2.b.y = triangles[exist[j].index].c.y; } } else { adj1.index = exist[j].bc_index; adj1.a.index = triangles[exist[j].index].c.index; adj1.a.x = triangles[exist[j].index].c.x; adj1.a.y = triangles[exist[j].index].c.y; adj1.b.index = triangles[exist[j].index].b.index; adj1.b.x = triangles[exist[j].index].b.x; adj1.b.y = triangles[exist[j].index].b.y; adj2.index = exist[j].ac_index; adj2.a.index = triangles[exist[j].index].a.index; adj2.a.x = triangles[exist[j].index].a.x; adj2.a.y = triangles[exist[j].index].a.y; adj2.b.index = triangles[exist[j].index].c.index; adj2.b.x = triangles[exist[j].index].c.x; adj2.b.y = triangles[exist[j].index].c.y; } TRIANGLE k = triangles[exist[j].index]; double cut_mst=0; //cut_smt<0 if (G[k.a.index][k.b.index] > 0) { cut -= G[k.a.index][k.b.index]; cut_mst-=G[k.a.index][k.b.index]; } G[k.a.index][k.b.index] = -1; G[k.b.index][k.a.index] = -1; if (G[k.b.index][k.c.index] > 0) { cut -= G[k.b.index][k.c.index]; cut_mst-=G[k.b.index][k.c.index]; } G[k.b.index][k.c.index] = -1; G[k.c.index][k.b.index] = -1; if (G[k.c.index][k.a.index] > 0) { cut -= G[k.c.index][k.a.index]; cut_mst-=G[k.c.index][k.a.index]; } G[k.c.index][k.a.index] = -1; G[k.a.index][k.c.index] = -1; // cout<<"ȥMSTߵֵ"<<cut_mst<<endl; double increase_smt=0; //size for (int i = 0; i <= n; i++) G[i][n] = -1; for (int i = 0; i <= n; i++) G[n][i] = -1; if (G[adj1.a.index][n] < 0) { G[adj1.a.index][n] = sqrt(pow(adj1.a.x - t.stainer.x, 2) + pow(adj1.a.y - t.stainer.y, 2)); G[n][adj1.a.index] = G[adj1.a.index][n]; cut += G[adj1.a.index][n]; increase_smt+=G[adj1.a.index][n]; } if (G[adj1.b.index][n] < 0) { G[adj1.b.index][n] = sqrt(pow(adj1.b.x - t.stainer.x, 2) + pow(adj1.b.y - t.stainer.y, 2)); G[n][adj1.b.index] = G[adj1.b.index][n]; cut += G[adj1.b.index][n]; increase_smt+=G[adj1.b.index][n]; } if (G[adj2.a.index][n] < 0) { G[adj2.a.index][n] = sqrt(pow(adj2.a.x - t.stainer.x, 2) + pow(adj2.a.y - t.stainer.y, 2)); G[n][adj2.a.index] = G[adj2.a.index][n]; cut += G[adj2.a.index][n]; increase_smt+=G[adj2.a.index][n]; } if (G[adj2.b.index][n] < 0) { G[adj2.b.index][n] = sqrt(pow(adj2.b.x - t.stainer.x, 2) + pow(adj2.b.y - t.stainer.y, 2)); G[n][adj2.b.index] = G[adj2.b.index][n]; cut += G[adj2.b.index][n]; increase_smt+=G[adj2.b.index][n]; } // cout<<"ӵSMTߵֵ"<<increase_smt<<endl; points.push_back(t.stainer); //㼯 int tcv = adj1.index; if (adj1.index >= 0) { exist[triangles[tcv].MST_index].index = -1; } tcv = adj2.index; if (adj2.index >= 0) { exist[triangles[tcv].MST_index].index = -1; } n++; lzy_cut=increase_smt+cut_mst; cout<<"SMTֲŻ"<<lzy_cut<<endl; // cout<<"sssssssssssssssssssssss "<<cut<<endl; smt_cost += lzy_cut; } cout << "\nsmt:\nsmt cost:" << smt_cost << endl; return 0; } int main(void) { double smt; Input(); Delaunay(); MST(); adjcent(); vector<ACS> exisarc(acs); modifystainer(exisarc); cout << "\nsmt/mst "<<smt_cost / mst_cost<<"\n\n"; system("pause"); return 0; }
true
1fce97e2fdb1c1489d7ff66a754497619b1fb98a
C++
deepdivenow/otus_task6
/matrix.cpp
UTF-8
238
2.953125
3
[]
no_license
#include <iostream> #include "Matrix.h" using namespace std; int main() { Matrix<int,-1> m; m[1][2]=5; m[1][3]=6; m[1][4]=7; m[1][5]=8; for(auto c: m) { cout << c.second << endl; } return 0; }
true
608ef894d8ef0a24dea0f1b320bfa75b58efe48f
C++
duliang1994/LeetCode
/022. Generate Parentheses/Generate Parentheses.cpp
UTF-8
1,068
3.015625
3
[]
no_license
class Solution { public: vector<string> generateParenthesis(int n) { vector<string> res; DFS(0, 0, "", n, res); return res; } void DFS(int left, int right, string path, int n, vector<string>& res){ if(right > left || left > n || right > n) return; if(left == n && right == n){ res.push_back(path); return; } DFS(left + 1, right, path + '(', n, res); DFS(left, right + 1, path + ')', n, res); } }; class Solution { public: vector<string> generateParenthesis(int n) { vector< vector<string> > dp(n + 1, vector<string>()); //vector<string> dp[n + 1]; dp[0].push_back(""); for(int i = 1; i <= n; i++){ for(int k = 0; k < i;k++){ for(string s2: dp[i-1-k]){ for(string s1: dp[k]){ dp[i].push_back("(" + s1 + ")" + s2); } } } } return dp[n]; } };
true
0de1f589166cb7bf0b026e5e5324c504971df8c7
C++
Creatiox/workaton-esp32
/Ejemplos/7. Ingresar Credenciales WiFi - ESP32 Modo AP/src/main.cpp
UTF-8
11,752
3.171875
3
[]
no_license
// NOTE Explicación Ejemplo /* * Ejemplo de conexión a WiFi por medio de un Smartphone: ? Connection to WiFi through a Smartphone: En este ejemplo, se utiliza la librería "AutoConnect", la cual crea un Portal de Conexión para ingresar las credenciales de una red WiFi por medio de un navegador en un Smartphone. El esquema del programa es el siguiente: 1. El equipo inicia, y busca una red WiFi existente. Red WiFi existente, se refiere a que si el ESP32 se ha conectado alguna vez a una red WiFi, las credenciales quedan guardadas, por ende, se intentará conectar a ella. 2. Si la red no existe y/o no se puede conectar, abre la conexión al Portal. Para ingresar a este, en el Smartphone se debe navegar hasta las redes wifi disponibles, y conectarse a la siguiente red (actualizar hasta verla disponible): - Nombre : esp32ap - Contraseña: 12345678 3. En los Smartphones más recientes, al conectarse a la red, inmediatamente lo redirige al Portal en el navegador. Si no es así, ingresar la siguiente dirección en el navegador: - Dirección: 172.217.28.1/_ac Al entrar al portal, tocar en la barra triple de la esquina superior derecha, y luego tocar en "Configure new AP". Elegir una red WiFi disponible, e ingresar la contraseña en "Passphrase". Activar el ticket "Enable DHCP", y luego presionar en "Apply". 4. Si las credenciales son correctas, el ESP32 intentará conectarse a Internet. Además, si estas credenciales son correctas, en un próximo reinicio se utilizarán como red principal para conectarse a Internet. 5. Para reiniciar el ESP32 y cerrar el Portal, presionar sobre el icono de barra triple, luego en "Reset...", y por último, presionar sobre el botón "RESET" que aparecerá. ? -> English: In this example, the "AutoConnect" library is used, which creates a Connection Portal to enter the credentials of a WiFi network through a browser on a Smartphone. The scheme of the program is as follows: 1. The computer starts up and searches for an existing WiFi network. Existing WiFi network, means that if the ESP32 has ever connected to a WiFi network, the credentials are saved, therefore, an attempt will be made to connect to it. 2. If the network does not exist and / or cannot connect, it opens the connection to the Portal. To enter this, on the Smartphone you must navigate to the available Wi-Fi networks, and connect to the following network (update until you see it available): - Name: esp32ap - Password: 12345678 3. In the latest Smartphones, when connecting to the network, it immediately redirects you to the Portal in the browser. If not, enter the following address in the browser: - Address: 172.217.28.1/_ac When entering the portal, tap on the triple bar in the upper right corner, and then tap on "Configure new AP". Choose an available WiFi network, and enter the password in "Passphrase". Activate the "Enable DHCP" ticket, and then click "Apply". 4. If the credentials are correct, ESP32 will try to connect to Internet. Also, if these credentials are correct, they will be used as the main network to connect to the Internet in a subsequent reboot. 5. To restart ESP32 and close the Portal, press on the triple bar icon, then on "Reset...", and finally, press on the "RESET" button that will appear. ! Información: ! Information: * - En este ejemplo, se configura un Timeout de 1 minuto, para intentar conectarse a una red. Si * pasa más de 1 minuto, el programa dentro del loop() comienza a ejecutarse. El portal no se * cerrará y se puede seguir conectándose a la red "esp32ap". * Si no se configura esto, la opción por defecto es que el programa dentro del loop() nunca se * ejecute hasta que tenga una conexión activa. ? - In this example, a 1 minute Timeout is configured to try to connect to a network. If more ? than 1 minute passes, the program inside the loop () starts running. The portal will not close ? and you can continue connecting to the "esp32ap" network. ? If this is not configured, the default is for the program inside loop () to never run until ? it has an active connection. * - No se ha hecho el ejemplo con conexión a Ubidots, para que sea simple de entender. ? - The example with connection to Ubidots has not been done, to make it simple to understand. * - Esta librería ocupa gran cantidad de memoria, ya que almacena todas las páginas del Portal, para * hacerlo más atractivo al usuario. Esta es una de las maneras que existen para guardar * credenciales en el ESP32, hay muchas otras, pero esta es una de las maneras más completas, ya * que tiene características como: auto conexión, múltiples redes, configuración de nuevas páginas, * etc. ? - This library occupies a large amount of memory, since it stores all the pages of the ? Portal, to make it more attractive to the user. This is one of the ways that exist to save ? credentials in the ESP32, there are many others, but this is one of the most complete ways, ? since it has features such as: auto connection, multiple networks, configuration of new pages, ? etc. */ #include <Arduino.h> // Incluirla siempre al utilizar PlatformIO // Always include it when using PlatformIO #include "delayMillis.h" // Para utilizar Delays no-bloqueantes // Non-blocking Delays #include "AutoConnect.h" // AutoConnect Captive Portal Library // NOTE Pines ESP32 /* -------------------------------------------------------------------------- */ // LED para indicar estado de conexión WiFi. // Por defecto, se utiliza el LED incluido en la placa. Si la placa no lo tiene, reemplazarlo por // otro pin digital del ESP32. /** * LED to indicate WiFi connection status. * By default, the LED included on the board is used. If the board doesn't have it, replace it with * another ESP32 digital pin. */ #define LED_WIFI LED_BUILTIN /* -------------------------------------------------------------------------- */ /* ---------------------------- Objetos (Objects) --------------------------- */ // Constructores básicos para inicializar un Portal de Conexión /* Constructors needed to start a Captive Portal */ WebServer server; AutoConnect portal(server); AutoConnectConfig config; // Delays DelayMillis t_parpadeo, t_cuenta; /* -------------------------------------------------------------------------- */ /* -------------- Declaracion Funciones (Function Declarations) ------------- */ void callbackWifiConectado(WiFiEvent_t event); // Se ejecuta cuando WiFi asoció dirección IP /* WiFi connected Callback */ void callbackWifiDesconectado(WiFiEvent_t event); // Se ejecuta cuando WiFi se desconecta /* WiFi disconnected Callback */ /* -------------------------------------------------------------------------- */ /* ---------------------- Página de Inicio (Root Page) ---------------------- */ void rootPage() { char content[] = "Hola Mundo"; // Mensaje de prueba /* Test message */ // Al ingresar a la página de inicio, mandar de vuelta un OK (codigo 200), // y el texto "Hola Mundo" (definido por el tipo de contenido HTML 'text/plain') /** * When entering the home page, send back an OK (code 200), * and the text "Hola Mundo" (defined by the HTML content type 'text/plain') */ server.send(200, "text/plain", content); } /* -------------------------------------------------------------------------- */ /* ------------------ Variables Globales (Global Variables) ----------------- */ bool wifi_on = false; // Indica si hay conexión activa a WiFi /* Indicates WiFi connection */ uint8_t num = 0; // Simple contador /* Simple counter */ /* -------------------------------------------------------------------------- */ // ANCHOR setup() // * --------------------------------------------------------------------------- void setup() { // Configurar pines /* Configure Pins */ pinMode(LED_WIFI, OUTPUT); // Configurar estado inicial Led WiFi /* Configure Initial State of WiFi Led */ digitalWrite(LED_WIFI, LOW); // Iniciar Puerto Serial /* Start Serial Port */ Serial.begin(115200); Serial.println(); // Esperar 2 segundos para abrir terminal y visualizar todo el texto /* Wait 2 seconds to open terminal */ delay(2000); // Iniciar delays /* Start delays */ t_parpadeo.empezar(500); t_cuenta.empezar(2000); // Llamar a rootPage() cuando se ingrese a la página principal /* Call rootPage() when you enter main page */ server.on("/", rootPage); WiFi.disconnect(true); WiFi.mode(WIFI_OFF); // Asociar Callbacks del WiFi /* Associate WiFi Callbacks */ WiFi.onEvent(callbackWifiConectado, SYSTEM_EVENT_STA_GOT_IP); WiFi.onEvent(callbackWifiDesconectado, SYSTEM_EVENT_STA_DISCONNECTED); Serial.println("[WIFI] Conectando..."); // Configuración personalizada del Portal /* Custom configuration of the Portal */ config.portalTimeout = 60000; // Timeout de 1 minuto /* 1 minute Timeout */ config.retainPortal = true; // Mantener portal abierto si no encuentra la red /* Keep Portal if it can't find the network */ config.autoReconnect = true; // Intentar reconectar a última red guardada /* Try to reconnect to last saved network */ portal.config(config); // Aplicar configuración /* Apply configuration */ // Iniciar conexión a una red o abrir portal // Si no se pudo encontrar una red existente, arrojar mensaje /* Start network connection, or open Portal */ /* If an existing network could not be found, display message */ if (!portal.begin()) { Serial.println("[WIFI] No se pudo conectar a la red WiFi!"); } } // * --------------------------------------------------------------------------- // ANCHOR loop() // * --------------------------------------------------------------------------- void loop() { // Si el WiFi (modo STATION) está activo, parpadear el Led cada "t_parpadeo" tiempo /* If WiFi (STATION mode) is active, blink the Led every "t_parpadeo" time */ if (wifi_on == true && t_parpadeo.finalizado()) { digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN)); t_parpadeo.repetir(); } // Contador simple para indicar que el loop() se encuentra ejecutándose /* Simple counter to indicate that loop() is running */ if (t_cuenta.finalizado()) { Serial.printf("[INFO] Cuenta: %u\n", num++); t_cuenta.repetir(); } // Esta sentencia debe ser llamada constantemente para encargarse de los mensajes entrantes /* This statement must be constantly called to deal with incoming messages */ portal.handleClient(); } // * --------------------------------------------------------------------------- // ANCHOR Callbacks WiFi // * --------------------------------------------------------------------------- void callbackWifiConectado(WiFiEvent_t event) { wifi_on = true; digitalWrite(LED_BUILTIN, HIGH); Serial.print("[WIFI] WiFi Conectado. IP: "); Serial.println(WiFi.localIP()); } void callbackWifiDesconectado(WiFiEvent_t event) { wifi_on = false; digitalWrite(LED_BUILTIN, LOW); Serial.println("[WIFI] WiFi Desconectado!"); } // * ---------------------------------------------------------------------------
true
064b38476f294ac47e56c5cff74be0ea97fa2835
C++
Irfan995/ArduinoCodes
/MyAvoidRobot/MyAvoidRobot.ino
UTF-8
2,192
2.53125
3
[]
no_license
#define inA 13 #define inB 3 #define inC 9 #define inD 8 #define ena 7 #define enb 6 int base_L=75; int base_R=75; int trigPin = 12; //Trig - green Jumper int echoPin = 5; //Echo - yellow Jumper long duration, cm, inches; long distance=15; int flag=0; ///////////////////////////////////////////////////////////////////////////////////////////////////// void setup() { mot_init(); Serial.begin (9600); //Define inputs and outputs pinMode(trigPin, OUTPUT); pinMode(echoPin, INPUT); } void loop() { //wheel(200,200); // line_follow(); sonarFollow(); digitalWrite(trigPin, LOW); delayMicroseconds(5); digitalWrite(trigPin, HIGH); delayMicroseconds(5); // digitalWrite(trigPin, LOW); pinMode(echoPin, INPUT); duration = pulseIn(echoPin, HIGH); // convert the time into a distance cm = (duration/2) / 29.1; //inches = (duration/2) / 74; //Serial.print(inches); //Serial.print("in, "); Serial.print(cm); Serial.print("cm"); Serial.println(); delay(250); if(cm<=distance) { flag=1; //wheel(0,0); } else if(cm>distance) { flag=0; // wheel(200,200); } //delay(1000); } void mot_init() { pinMode(inA,OUTPUT); pinMode(inB,OUTPUT); pinMode(inC,OUTPUT); pinMode(inD,OUTPUT); pinMode(ena,OUTPUT); pinMode(enb,OUTPUT); digitalWrite(inA,HIGH); digitalWrite(inB,HIGH); digitalWrite(inC,HIGH); digitalWrite(inD,HIGH); } void wheel(int lm, int rm) { if(lm==0) { digitalWrite(inC,HIGH); digitalWrite(inD,HIGH); } else if(lm>0) { digitalWrite(inC,HIGH); digitalWrite(inD,LOW); } else if(lm<0) { digitalWrite(inC,LOW); digitalWrite(inD,HIGH); } if(rm==0) { digitalWrite(inA,HIGH); digitalWrite(inB,HIGH); } else if(rm>0) { digitalWrite(inA,HIGH); digitalWrite(inB,LOW); } else if(rm<0) { digitalWrite(inA,LOW); digitalWrite(inB,HIGH); } if(lm>254) lm=254; if(lm<-254) lm=-254; if(rm>254) rm=254; if(rm<-254) rm=-254; analogWrite(ena,abs(rm)); analogWrite(enb,abs(lm)); } void sonarFollow() { if(flag==1) { wheel(0,0); delay(500); } else { wheel(170,130); } }
true
4224f5ecf636965e0b47f28be165d4e1c366222a
C++
AaronFlower/leetcode
/239-Sliding-Window-Max/solution.h
UTF-8
4,384
3.546875
4
[]
no_license
#ifndef LEETCODE_SOLUTION_H__ #define LEETCODE_SOLUTION_H__ #include <vector> #include <queue> #include <set> using std::vector; using std::priority_queue; using std::pair; using std::make_pair; using std::multiset; using std::deque; class Solution { public: /** * 使用 deque 和 heap 的方法一样。 */ vector<int> maxSlidingWindowDeque1(vector<int> &nums, int k) { deque<pair<int, int>> q; vector<int> res; int len = nums.size(); if (len > 0) { q.push_back({nums[0], 0}); for (int i = 1; i < k - 1; ++i) { if (nums[i] >= q.front().first) { q.push_front({nums[i], i}); } else { q.push_back({nums[i], i}); } } for (int i = k - 1; i < len; ++i) { if (!q.empty() && nums[i] >= q.front().first) { q.push_front({nums[i], i}); } else { q.push_back({nums[i], i}); } res.push_back(q.front().first); while (!q.empty() && q.front().second <= (i + 1) - k) { q.pop_front(); } } } return res; } /** * 使用 deque 优化下循环 */ vector<int> maxSlidingWindowDeque2(vector<int> &nums, int k) { deque<pair<int, int>> q; // 创建的是一个降序 deque, 队首永远是最大的元素 vector<int> res; for (int i = 0; i < (int)nums.size(); ++i) { // 先从尾向头删除到可以插入的位置 while (!q.empty() && q.back().first <= nums[i]) { q.pop_back(); } q.push_back({nums[i], i}); if (i >= k - 1) { res.push_back(q.front().first); } // 再从头向尾删除超出范围的元素 while (!q.empty() && q.front().second <= (i + 1) - k) { q.pop_front(); } } return res; } /** * Naive */ vector<int> maxSlidingWindowNaive(vector<int> &nums, int k) { vector<int> res; int i, j, max; int len = nums.size(); for (i = 0; i < len - k +1; ++i) { max = nums[i]; for (j = i + 1; j < i + k ; ++j) { max = max > nums[j] ? max : nums[j]; } res.push_back(max); } return res; } /** * 用 heap 来实现,删除 heap 的 top() 时检查其下标是否超过下一个窗口的下标范围。 */ vector<int> maxSlidingWindowHeap1(vector<int> &nums, int k) { vector<int> res; priority_queue<pair<int, int>> q; for (int i =0; i < k; ++i) { q.push({nums[i], i}); } res.push_back(q.top().first); int len = nums.size(); for (int i = k; i < len; ++i) { // 如果最大值的下标还在下一个窗口的范围内就继续保留,否则就删除。delete-lazily while (q.top().second <= i - k) { q.pop(); } q.push({nums[i], i}); res.push_back(q.top().first); } return res; } /** * 用 heap 来实现,删除 heap 的 top() 时检查其下标是否超过下一个窗口的下标范围, 代码优化。 */ vector<int> maxSlidingWindowHeap2(vector<int> &nums, int k) { vector<int> res; priority_queue<pair<int, int>> q; int len = nums.size(); for (int i = 0; i < len; ++i) { while (!q.empty() && q.top().second <= i - k) { q.pop(); } q.push({nums[i], i}); if (i >= k - 1) { res.push_back(q.top().first); } } return res; } /** * 用 multiset 实现。multiset 支持重复的 key, 默认是按 less 排序的。 */ vector<int> maxSlidingWindowMultiSet(vector<int> &nums, int k) { vector<int> res; multiset<int> s; for (int i = 0; i < (int)nums.size(); ++i) { s.insert(- nums[i]); if (i >= k - 1) { res.push_back(- *s.begin()); s.erase(- nums[i - k + 1]); } } return res; } }; #endif
true
ff45884fca62fbc3c845828042218618af3220ac
C++
Mular8/NOKIA-PK
/COMMON/Traits/EnumTraits.hpp
UTF-8
3,561
3.25
3
[]
no_license
#pragma once #include <type_traits> #include <utility> #include <stdexcept> namespace common { template <typename Enum, typename Return=std::underlying_type_t<Enum>> constexpr Return enumUnderlyingValue(Enum value) { return static_cast<Return>(value); } template <typename Enum, typename Value = std::underlying_type_t<Enum>> constexpr Enum enumValue(Value value) { return static_cast<Enum>(value); } template <typename Enum> struct EnumFirst : std::integral_constant<Enum, enumValue<Enum>(0u)> {}; template <typename Enum> struct EnumLast : std::integral_constant<Enum, enumValue<Enum>(enumUnderlyingValue(Enum::AfterLast) - 1)> {}; template <typename Enum, Enum Current> struct EnumNext : std::integral_constant<Enum, enumValue<Enum>(enumUnderlyingValue(Current) + 1)> {}; template <typename Enum, Enum First = EnumFirst<Enum>::value, Enum Last = EnumLast<Enum>::value> class EnumRange; template <typename Enum, Enum Value> class EnumRange<Enum, Value, Value> { public: template <template <Enum> class Functor, typename ...Args> static constexpr decltype(auto) forEach(Args&& ...args); template <template <Enum> class Functor, typename ...Args> static /*constexpr*/ decltype(auto) forOne(Enum theOne, Args&& ...args); static constexpr std::size_t size() { return 1u; } }; template <typename Enum, Enum First, Enum Last> class EnumRange { public: template <template <Enum> class Functor, typename ...Args> static constexpr decltype(auto) forEach(Args&& ...args); template <template <Enum> class Functor, typename ...Args> static constexpr decltype(auto) forOne(Enum theOne, Args&& ...args); static constexpr std::size_t size() { return ForFirst::size() + ForSecondToLast::size(); } private: using ForFirst = EnumRange<Enum, First, First>; using ForSecondToLast = EnumRange<Enum, EnumNext<Enum, First>::value, Last>; }; template <typename Enum, Enum Value> template <template <Enum> class Functor, typename ...Args> constexpr decltype(auto) EnumRange<Enum, Value, Value>::forEach(Args&& ...args) { return Functor<Value>{}(std::forward<Args>(args)...); }; template <typename Enum, Enum Value> template <template <Enum> class Functor, typename ...Args> /*constexpr*/ decltype(auto) EnumRange<Enum, Value, Value>::forOne(Enum theOne, Args&& ...args) { return (Value == theOne) ? EnumRange<Enum, Value, Value>::template forEach<Functor>(std::forward<Args>(args)...) : throw std::out_of_range(std::to_string(enumUnderlyingValue(theOne)) + "!=" + std::to_string(enumUnderlyingValue(Value))); }; template <typename Enum, Enum First, Enum Last> template <template <Enum> class Functor, typename ...Args> constexpr decltype(auto) EnumRange<Enum, First, Last>::forEach(Args&& ...args) { return ForFirst::template forEach<Functor>(std::forward<Args>(args)...), ForSecondToLast::template forEach<Functor>(std::forward<Args>(args)...); }; template <typename Enum, Enum First, Enum Last> template <template <Enum> class Functor, typename ...Args> constexpr decltype(auto) EnumRange<Enum, First, Last>::forOne(Enum theOne, Args&& ...args) { return (First == theOne) ? ForFirst::template forEach<Functor>(std::forward<Args>(args)...) : ForSecondToLast::template forOne<Functor>(theOne, std::forward<Args>(args)...); }; }
true
c1c8d539b548b9f770c37fba2d508bb2c728dbb7
C++
grai2022/leetcode_accepted
/31nextPermutation.cpp
UTF-8
1,247
3.390625
3
[]
no_license
/* Problem - https://leetcode.com/problems/next-permutation/submissions/ */ class Solution { public: void nextPermutation(vector<int>& nums) { int length = nums.size() -1; int swapIndex = -1; for(int i = length ; i>0;i--){ if(nums[i] > nums[i-1]){ swapIndex = i-1; break; } } if(swapIndex != -1){ int temp = nums[swapIndex]; for(int i = length ; i >=0 ; i--){ if(nums[i]> temp){ int t = nums[i]; nums[i] = nums[swapIndex]; nums[swapIndex] = t; break; } } swap(nums, swapIndex+1, length); }else{ swap(nums, 0, length); } return; } void swap(vector<int>& nums , int startIndex, int endIndex){ while(startIndex < endIndex){ int temp = nums[endIndex]; nums[endIndex] = nums[startIndex]; nums[startIndex] = temp; startIndex++; endIndex--; } return; } };
true
d71590a812e6cd6572dae750467dc28861d6d4d0
C++
dotnet/dotnet-api-docs
/snippets/cpp/VS_Snippets_CLR/Cryptography.RC2CryptoServiceProvider/cpp/example.cpp
UTF-8
1,873
3.421875
3
[ "MIT", "CC-BY-4.0" ]
permissive
//<SNIPPET1> using namespace System; using namespace System::IO; using namespace System::Text; using namespace System::Security::Cryptography; int main() { array <Byte>^ originalBytes = ASCIIEncoding::ASCII->GetBytes("Here is some data."); //Create a new RC2CryptoServiceProvider. RC2CryptoServiceProvider^ rc2Provider = gcnew RC2CryptoServiceProvider(); rc2Provider->UseSalt = true; rc2Provider->GenerateKey(); rc2Provider->GenerateIV(); //Encrypt the data. MemoryStream^ encryptionMemoryStream = gcnew MemoryStream(); CryptoStream^ encryptionCryptoStream = gcnew CryptoStream( encryptionMemoryStream, rc2Provider->CreateEncryptor( rc2Provider->Key, rc2Provider->IV), CryptoStreamMode::Write); //Write all data to the crypto stream and flush it. encryptionCryptoStream->Write(originalBytes, 0, originalBytes->Length); encryptionCryptoStream->FlushFinalBlock(); //Get encrypted array of bytes. array<Byte>^ encryptedBytes = encryptionMemoryStream->ToArray(); //Decrypt the previously encrypted message. MemoryStream^ decryptionMemoryStream = gcnew MemoryStream(encryptedBytes); CryptoStream^ decryptionCryptoStream = gcnew CryptoStream(decryptionMemoryStream, rc2Provider->CreateDecryptor(rc2Provider->Key,rc2Provider->IV), CryptoStreamMode::Read); array<Byte>^ unencryptedBytes = gcnew array<Byte>(originalBytes->Length); //Read the data out of the crypto stream. decryptionCryptoStream->Read(unencryptedBytes, 0, unencryptedBytes->Length); //Convert the byte array back into a string. String^ plainText = ASCIIEncoding::ASCII->GetString(unencryptedBytes); //Display the results. Console::WriteLine("Unencrypted text: {0}", plainText); Console::ReadLine(); } //</SNIPPET1>
true
dc2696954e40dd072aa35e8d7c9e59da87abdca7
C++
iczero/i-cant-opengl
/src/main.cpp
UTF-8
2,421
2.90625
3
[]
no_license
#include <iostream> #include <glad/glad.h> #include <GLFW/glfw3.h> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> #include "window.hpp" #include "shaders.hpp" #include "geometry.hpp" constexpr int DEFAULT_WIDTH = 800; constexpr int DEFAULT_HEIGHT = 600; // why terminate stuff manually when c++ can do it for you! class GLFWGuard { public: GLFWGuard() { glfwInit(); } ~GLFWGuard() { glfwTerminate(); } }; void render_geometry_at(Graphics &graphics, Geometry &geometry, glm::vec3 position, float scale = 1.0f, bool spinny = false) { glm::mat4 model = glm::mat4(1.0f); model = glm::translate(model, position); model = glm::scale(model, glm::vec3(scale, scale, scale)); if (spinny) model = glm::rotate(model, (float) glfwGetTime() * glm::radians(50.0f), glm::vec3(0.5f, 1.0f, 0.0f)); graphics.set_model(model); geometry.draw(); } int main() { // initialize glfw GLFWGuard glfw_guard; // opengl 4.6 glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 6); // create window GLFWwindow *glfw_window = glfwCreateWindow(DEFAULT_WIDTH, DEFAULT_HEIGHT, "yay opengl", NULL, NULL); if (!glfw_window) { std::cerr << "Failed to create glfw window" << std::endl; return 1; } glfwMakeContextCurrent(glfw_window); // initialize gl bindings with glad if (!gladLoadGLLoader((GLADloadproc) glfwGetProcAddress)) { std::cerr << "Failed to initialize glad" << std::endl; return 1; } // everything above MUST be run before any OpenGL routines // window "managing" thing? idk Window window(glfw_window); window.update_viewport(DEFAULT_WIDTH, DEFAULT_HEIGHT); Graphics &graphics = window.graphics; // create a sphere IcosphereGeometry sphere_geometry(10); // main loop while (!window.should_close()) { graphics.camera.process_input(); // render { graphics.begin_render(); render_geometry_at(graphics, sphere_geometry, glm::vec3(0.0f, 0.0f, 0.0f), 1.0f, true); render_geometry_at(graphics, sphere_geometry, glm::vec3(5.0f, 6.0f, -7.0f), 1.5f, false); render_geometry_at(graphics, sphere_geometry, glm::vec3(-4.3f, 1.6f, -9.1f), 0.4, true); } window.frame_done(); } return 0; }
true
4991502672d8e13df7b1e8235b83aa6f5afefa29
C++
rtpax/redblack
/rb_tree.hh
UTF-8
4,749
2.84375
3
[ "MIT" ]
permissive
#ifndef RB_TREE_HH #define RB_TREE_HH #include <functional> #include <utility> #include <memory> #include <limits> #include "rb_iterator.hh" #include "rb_node.hh" template<class T, class Cmp = std::less<T>, class Alloc = std::allocator<T>> class rb_tree { friend rb_test<T,Cmp,Alloc>; public: typedef rb_iterator<T,Cmp,Alloc,false,false> iterator; typedef rb_iterator<T,Cmp,Alloc,true ,false> const_iterator; typedef rb_iterator<T,Cmp,Alloc,false,true > reverse_iterator; typedef rb_iterator<T,Cmp,Alloc,true ,true > const_reverse_iterator; private: typedef rb_node<T,Cmp,Alloc> node_type; static constexpr typename node_type::color_type black = node_type::black; static constexpr typename node_type::color_type red = node_type::red; Cmp cmp_; Alloc alloc_; rb_node<T,Cmp,Alloc>* rend_; rb_node<T,Cmp,Alloc>* end_; rb_node<T,Cmp,Alloc>* root_; size_t size_; template<class... Args> T* alloc_new(Args&&... args) { T* p = alloc_.allocate(1); //TODO handle potential std::bad_alloc exception return ::new((void *)p) T(std::forward<Args>(args)...);//TODO handle potential error in constructor } void alloc_delete(T* p) { p->~T(); //TODO handle potential error in destructor alloc_.deallocate(p, 1); } void rotate_right(rb_node<T,Cmp,Alloc>*); void rotate_left(rb_node<T,Cmp,Alloc>*); void balance_insertion(rb_node<T,Cmp,Alloc>*); void balance_right_deletion(rb_node<T,Cmp,Alloc>*); void balance_left_deletion(rb_node<T,Cmp,Alloc>*); void treat_as_delete(rb_node<T,Cmp,Alloc>*); std::pair<rb_node<T,Cmp,Alloc>*,bool> unbalanced_insert(const T& value) { return unbalanced_insert(value, root_); } std::pair<rb_node<T,Cmp,Alloc>*,bool> unbalanced_insert(const T& value, rb_node<T,Cmp,Alloc>* node); rb_node<T,Cmp,Alloc>* unbalanced_delete(rb_node<T,Cmp,Alloc>*); void swap_nodes(rb_node<T,Cmp,Alloc>*,rb_node<T,Cmp,Alloc>*); public: rb_tree() : cmp_(), alloc_(), rend_(new rb_node<T,Cmp,Alloc>(nullptr, black, nullptr)), end_(new rb_node<T,Cmp,Alloc>(nullptr, red, rend_)), root_(rend_), size_(0) { rend_->right = end_; } rb_tree(const Cmp& cmp, const Alloc& alloc = Alloc()) : cmp_(cmp), alloc_(alloc), rend_(new rb_node<T,Cmp,Alloc>(nullptr, black, nullptr)), end_(new rb_node<T,Cmp,Alloc>(nullptr, red, rend_)), root_(rend_), size_(0) { rend_->right = end_; } rb_tree(const Alloc& alloc) : rb_tree(Cmp(), alloc) {} rb_tree(std::initializer_list<T> init, const Cmp& cmp = Cmp(), const Alloc& alloc = Alloc()) : rb_tree(cmp, alloc) { for(const T& t : init) { insert(t); } } template <class It> rb_tree(It first, It last, Cmp cmp = Cmp()) : rb_tree(cmp) { while(first != last) { insert(*first); ++first; } } rb_tree(const rb_tree& copy, Alloc alloc) : rb_tree(alloc) { for(const T& t : copy) { insert(t); } } rb_tree(const rb_tree& copy) : rb_tree(copy, Alloc()) {} rb_tree(rb_tree&& steal) { cmp_ = steal.cmp_; alloc_ = steal.alloc_; root_ = steal.root_; root_ = steal.end_; root_ = steal.rend_; size_ = steal.size_; steal.rend_ = new rb_node<T,Cmp,Alloc>(nullptr, black, nullptr); steal.end_ = new rb_node<T,Cmp,Alloc>(nullptr, red, rend_); steal.root_ = rend_; steal.size_ = 0; steal.rend_->right = steal.end_; } rb_tree(rb_tree&& steal, Alloc alloc) : rb_tree(steal, alloc) {} std::pair<iterator, bool> insert(const T& value); bool contains(const T& value) const; iterator find(const T& value); const_iterator find(const T& value) const; iterator erase(iterator); size_t max_size() const { return std::numeric_limits<size_t>::max; } size_t size() const { return size_; } bool empty() const { return size_ == 0; } Cmp key_comp() const { return cmp_; } Cmp value_comp() const { return cmp_; } iterator begin() { return ++iterator(rend_); } iterator end() { return iterator(end_); } const_iterator cbegin() const { return ++const_iterator(rend_); } const_iterator cend() const { return const_iterator(end_); } reverse_iterator rbegin() { return ++reverse_iterator(end_); } reverse_iterator rend() { return reverse_iterator(rend_); } const_reverse_iterator crbegin() const { return ++const_reverse_iterator(end_); } const_reverse_iterator crend() const { return const_reverse_iterator(rend_); } }; #include "rb_tree.tcc" #endif
true
470bf3fcb54cb11df6cf98c2855496edde34d349
C++
stden/inf_ege
/cpp/Kabc/main.cpp
UTF-8
314
3.140625
3
[]
no_license
#include <iostream> int main() { //double a * x + b = 0 ; double a = 2; double b = 4; std::cout << "a = "; std::cin >> a; std::cout << "b = "; std::cin >> b; double x = -b / a; std::cout << "x = " << x << std::endl; std::cout << "a * x + b = " << (a * x + b) << std::endl; return 0; }
true
89b3b5251f0196958039e7572b904991ad0730e9
C++
pblxptr/Malware-families-detector
/src/gui/src/predictdialog.cpp
UTF-8
988
2.5625
3
[]
no_license
#include <QtWidgets/QFileDialog> #include <QtWidgets/QMessageBox> #include "../include/predictdialog.hpp" #include "ui_predictdialog.h" PredictDialog::PredictDialog(QWidget *parent) : QDialog(parent), ui(new Ui::PredictDialog) { ui->setupUi(this); ui->filepathTextEdit->setReadOnly(true); } PredictDialog::~PredictDialog() { delete ui; } void PredictDialog::on_selectFilepathPushButton_clicked() { _filepath = QFileDialog::getOpenFileName(nullptr, tr("Wybierz plik"), "/home/pp/CLionProjects/thesis", tr("Plik JPG (*.jpg)")); ui->filepathTextEdit->setText(_filepath); } void PredictDialog::on_confirmPushButton_clicked() { if (!isValid()) { QMessageBox box; box.setWindowTitle("Uwaga!"); box.setText("Uzupełnij wymagane pola."); box.exec(); return; } accept(); } void PredictDialog::on_cancelPushButton_clicked() { reject(); } bool PredictDialog::isValid() { return !_filepath.isEmpty(); }
true
1dc13da30f591fadc0988191453d132861f89216
C++
jseric/3D-KD_Tree
/solution/3D-Vanity-KD_Tree/Engine/Repository/KD Tree/Tree/Tree.cpp
UTF-8
17,243
3.390625
3
[]
no_license
#include "pch.h" #include "Tree.h" #include "../Macros/KDTreeMacros.h" #include <algorithm> #include <cmath> #include <fstream> #include <iostream> #include <limits> #include <sstream> namespace vxe { #pragma region Private /// Allocate new node Node* Tree::CreateNewNode(const DirectX::VertexPosition& targetPoint) { try { Node *target = new Node{ targetPoint }; return target; } catch (std::bad_alloc& ba) { UNREFERENCED_PARAMETER(ba); std::cout << "ERROR!!!" << std::endl; std::cout << "Allocation Error!!!" << std::endl; return nullptr; } } /// Initialize tree with multiple nodes void Tree::InitTreeWithMultiplePoints(std::vector<DirectX::VertexPosition> points) { // Get index of median point auto firstNodeIndex{ GetIndexOfMedianNode(points) }; // Allocate node with median point and insert it to tree Node *node = CreateNewNode(points[firstNodeIndex]); if (!node) return; root.next = node; // Remove median point from vector points.erase(points.begin() + firstNodeIndex); // Insert remaining nodes Insert(points); } /// Sort points by X-value and return median node index unsigned int Tree::GetIndexOfMedianNode(std::vector<DirectX::VertexPosition>& points) { Tree::SortPointsByXValue(points); return ((unsigned int) points.size() / 2); } /// Read points from file void Tree::ReadFromFile(std::string& fileName) { // Open file std::ifstream file(fileName); // Coordinate buffers float x{ 0.0f }; float y{ 0.0f }; float z{ 0.0f }; std::vector<DirectX::VertexPosition> points; // Read points' data from file while (!file.eof()) { file >> x >> y >> z; points.push_back(DirectX::VertexPosition{ x, y, z }); } // Close file file.close(); // Init tree InitTreeWithMultiplePoints(points); } /// Shift current dimension to next one /// X->Y, Y->Z, Z->X /// Note: X=0, Y=1, Z=2 void Tree::IncrementDimension(unsigned int& dimension) { dimension = (dimension + 1) % NUMBER_OF_DIMENSIONS; } /// Delete the node provided as argument /// and all of his children void Tree::DeleteAll(Node* current) { if (current) { DeleteAll(current->left); DeleteAll(current->right); delete current; } } /// Delete node (if it exists) inside subtree with target data int Tree::Delete(DirectX::VertexPosition& targetPoint, Node* current, unsigned int currentDimension) { // Get next dimension unsigned int nextDimension{ currentDimension }; IncrementDimension(nextDimension); if (!current) { // Point not found return RETURN_DELETE_POINT_NOT_FOUND; } if (AreEqual(targetPoint, current->point)) { // Point to delete found if (current->right) { // Right subtree exists // Set the point of current node to be // min(current dimension) of right subtree // and delete that point current->point = FindMin(current->right, currentDimension, nextDimension); return Delete(current->point, current->right, nextDimension); } else if (current->left) { // Left subtree exists // Set the point of current node to be // max(current dimension) of left subtree // and delete that point current->point = FindMax(current->left, currentDimension, nextDimension); return Delete(current->point, current->left, nextDimension); } else { // Target node is a leaf DeleteAll(current); return RETURN_DELETE_OK; } } // Continue the search if (targetPoint[currentDimension] < current->point[currentDimension]) { // Search left subtree return Delete(targetPoint, current->left, nextDimension); } else { // Search right subtree return Delete(targetPoint, current->right, nextDimension); } } /// Find point in subtree that contains point with minimum value /// in given target dimension DirectX::VertexPosition Tree::FindMin(Node* current, unsigned int targetDimension, unsigned int currentDimension) { if (!current) { // Subtree is empty // Note: as FindMin returns a float4 object, // it is not possible to return nullptr, // so we are returning a float point with // coordinates x = y = z = max_float_value float returnBuffer{ std::numeric_limits<float>::max() }; return DirectX::VertexPosition(returnBuffer, returnBuffer, returnBuffer); } if (currentDimension == targetDimension) { // We are searching in the correct dimension if (!current->left) { // Current node contains the min value return current->point; } // Increment dimension and continue search in left subtree IncrementDimension(currentDimension); return FindMin(current->left, targetDimension, currentDimension); } // Increment dimension and return minimum value of // current node data, left subtree minimum and // right subtree minimum IncrementDimension(currentDimension); DirectX::VertexPosition left{ FindMin(current->left, targetDimension, currentDimension) }; DirectX::VertexPosition right{ FindMin(current->right, targetDimension, currentDimension) }; if (left[targetDimension] <= right[targetDimension] && left[targetDimension] <= current->point[targetDimension]) return left; if (right[targetDimension] <= left[targetDimension] && right[targetDimension] <= current->point[targetDimension]) return right; return current->point; } /// Find point in subtree that contains point with maximum value /// in given target dimension DirectX::VertexPosition Tree::FindMax(Node* current, unsigned int targetDimension, unsigned int currentDimension) { if (!current) { // Subtree is empty // Note: as FindMin returns a float4 object, // it is not possible to return nullptr, // so we are returning a float point with // coordinates x = y = z = min_float_value float returnBuffer{ std::numeric_limits<float>::min() }; return DirectX::VertexPosition(returnBuffer, returnBuffer, returnBuffer); } if (currentDimension == targetDimension) { // We are searching in the correct dimension if (!current->right) { // Current node contains the max value return current->point; } // Increment dimension and continue search in right subtree IncrementDimension(currentDimension); return FindMax(current->right, targetDimension, currentDimension); } // Increment dimension and return maximum value of // current node data, left subtree maximum and // right subtree maximum IncrementDimension(currentDimension); DirectX::VertexPosition left{ FindMin(current->left, targetDimension, currentDimension) }; DirectX::VertexPosition right{ FindMin(current->right, targetDimension, currentDimension) }; if (left[targetDimension] >= right[targetDimension] && left[targetDimension] >= current->point[targetDimension]) return left; if (right[targetDimension] >= left[targetDimension] && right[targetDimension] >= current->point[targetDimension]) return right; return current->point; } /// Search the tree for the nearest neighbour /// (the node containing the closest point of /// the target point) void Tree::NearestNeighbourSearch(DirectX::VertexPosition& targetPoint, Node* current, unsigned int dimension, DirectX::VertexPosition& nearestPoint, float& nearestDistance) { // Get distance between target and current float distance{ Distance(targetPoint, current->point) }; if (distance < nearestDistance) { // Found new nearest point nearestDistance = distance; nearestPoint = current->point; } if (!current->left && !current->right) { // Current node is a leaf return; } const float targetDimensionValue{ targetPoint[dimension] }; if (targetDimensionValue <= current->point[dimension]) { // First search left subtree if (current->left && (targetDimensionValue - nearestDistance) <= current->point[dimension]) { // There is a possibility that the nearest point is // in the left subtree IncrementDimension(dimension); NearestNeighbourSearch(targetPoint, current->left, dimension, nearestPoint, nearestDistance); } if (current->right && (targetDimensionValue + nearestDistance) > current->point[dimension]) { // There is a possibility that the nearest point is // in the right subtree IncrementDimension(dimension); NearestNeighbourSearch(targetPoint, current->right, dimension, nearestPoint, nearestDistance); } } else { // First search right subtree if (current->right && (targetDimensionValue + nearestDistance) > current->point[dimension]) { // There is a possibility that the nearest point is // in the right subtree IncrementDimension(dimension); NearestNeighbourSearch(targetPoint, current->right, dimension, nearestPoint, nearestDistance); } if (current->left && (targetDimensionValue - nearestDistance) <= current->point[dimension]) { // There is a possibility that the nearest point is // in the left subtree IncrementDimension(dimension); NearestNeighbourSearch(targetPoint, current->left, dimension, nearestPoint, nearestDistance); } } } /// Print current node data and all of his children data std::string Tree::ToString(Node* current) { std::stringstream ss{}; if (current) { ss << current->ToString(); ss << ToString(current->left); ss << ToString(current->right); } return ss.str(); } #pragma endregion #pragma region Public /// Default constructor /// Initializes empty tree Tree::Tree(void) : root{} { } /// Overloaded constructor 1 /// Takes 1 point /// Initializes tree with 1 point Tree::Tree(const DirectX::VertexPosition& point) : root{ CreateNewNode(point) } { } /// Overloaded constructor 2 /// Takes a vector of points /// Initializes tree with multiple points Tree::Tree(std::vector<DirectX::VertexPosition> points) { InitTreeWithMultiplePoints(points); } /// Overloaded constructor 3 /// Takes a string containing name of file /// Reads points from file, and initializes the /// tree with those points Tree::Tree(std::string& fileName) { ReadFromFile(fileName); } /// Destructor /// Remove all nodes from tree Tree::~Tree(void) { delete root.next; } /// Insert node to tree int Tree::Insert(DirectX::VertexPosition& targetPoint) { // If tree is empty if (!root.next) { // Insert as first node Node* target = CreateNewNode(targetPoint); if (!target) return RETURN_BAD_ALLOCATION; root.next = target; return RETURN_INSERT_OK; } Node* previous{ nullptr }; Node* current{ root.next }; unsigned int dimension{ 0 }; // Travel through tree while (current) { if (AreEqual(targetPoint, current->point)) { // Point already exists return RETURN_INSERT_DUPLICATE_POINT; } if (targetPoint[dimension] < current->point[dimension]) { // Go left previous = current; current = current->left; } else { // Go right previous = current; current = current->right; } if (current) IncrementDimension(dimension); } // Allocate new node Node* target = CreateNewNode(targetPoint); if (!target) return RETURN_BAD_ALLOCATION; if (targetPoint[dimension] < previous->point[dimension]) { // Insert left previous->left = target; } else { // Insert right previous->right = target; } return RETURN_INSERT_OK; } /// Insert multiple nodes to tree int Tree::Insert(std::vector<DirectX::VertexPosition>& points) { int returnValue{ 0 }; for (unsigned int i{ 0 }; i < points.size(); i++) { returnValue = Insert(points[i]); if (returnValue != RETURN_INSERT_OK) return returnValue; } return RETURN_INSERT_OK; } /// Find (and if found) delete the node /// with target coordinates int Tree::Delete(DirectX::VertexPosition& targetPoint) { int returnValue{ Delete(targetPoint, root.next, 0) }; return returnValue; } /// Search the tree for the nearest neighbour /// (the node containing the closest point of /// the target point) DirectX::VertexPosition Tree::NearestNeighbourSearch(DirectX::VertexPosition& targetPoint) { // Set initial distance to be max float value and // set the target point to be (0, 0, 0, 1) float nearestDistance{ std::numeric_limits<float>::max() }; DirectX::VertexPosition nearestPoint{ 0.0f, 0.0f, 0.0f }; NearestNeighbourSearch(targetPoint, root.next, 0, nearestPoint, nearestDistance); return nearestPoint; } /// Search for point inside tree /// If found, return true, else false bool Tree::Find(DirectX::VertexPosition& point) { Node* current{ root.next }; unsigned int dimension{ 0 }; while (current) { if (AreEqual(point, current->point)) { // Point Found return RETURN_FIND_POINT_FOUND; } // Continue search if (point[dimension] < current->point[dimension]) { // Search left subtree current = current->left; } else { // Search right current = current->right; } IncrementDimension(dimension); } // Point not found return RETURN_FIND_POINT_NOT_FOUND; } /// For each method /// Execute target method on all points in tree void Tree::Foreach(std::function<void(DirectX::VertexPosition&)> targetMethod) { root.RunOnNode(targetMethod); } /// Return tree data as a string. /// Often used for displaying object information /// in console std::string Tree::ToString(void) { return ToString(root.next); } #pragma endregion #pragma region Static /// Sort points by X-value void Tree::SortPointsByXValue(std::vector<DirectX::VertexPosition>& points) { std::sort(points.begin(), points.end(), Tree::SortByXCriterion); } /// Criterion for sorting points by X-value bool Tree::SortByXCriterion(DirectX::VertexPosition& v1, DirectX::VertexPosition& v2) { return (v1[0] < v2[0]); } #pragma endregion }
true
7d2bb096c4e1090668e30e90442428463de86543
C++
kyordhel/FSEm
/practica07/src/arduino-test-dc.cpp
UTF-8
1,500
3.015625
3
[ "MIT" ]
permissive
/* * arduino-test-dc.cpp * * Author: Mauricio Matamoros * Date: 2020.03.01 * License: MIT * * Controls the power output of a resistive load using * zero-cross detection and a TRIAC. Code for Arduino UNO * */ #include <avr/io.h> // Digital 2 is Pin 2 in UNO #define ZXPIN 2 // Digital 3 is Pin 3 in UNO #define TRIAC 3 // Globals volatile bool flag = false; int pdelay = 7000; int inc = -10; // Prototypes void turnLampOn(void); void zxhandle(void); /** * Setup the Arduino */ void setup(void){ // Setup interupt pin (input) pinMode(ZXPIN, INPUT); // digitalPinToInterrupt may not work, so we choose directly the // interrupt number. It is Zero for pin 2 on Arduino UNO // attachInterrupt(digitalPinToInterrupt(ZXPIN), zxhandle, RISING); attachInterrupt(0, zxhandle, RISING); // Setup output (triac) pin pinMode(TRIAC, OUTPUT); // Blink led on interrupt pinMode(TRIAC, OUTPUT); } void loop(){ // Do nothing till the next zero-cross if(!flag) return; // Reset flag flag = !flag; // Keep power off for pdelay microseconds delayMicroseconds(pdelay); // Power up TRIAC turnLampOn(); // Increment/reset power factor pdelay+= inc; if(pdelay <= 1000) inc = 10; else if(pdelay >= 7000) inc = -10; } void turnLampOn(){ // Turn sentinel LED on digitalWrite(13, HIGH); // Send a 10us pulse to the TRIAC digitalWrite(TRIAC, HIGH); delayMicroseconds(20); digitalWrite(TRIAC, LOW); } void zxhandle(){ flag = true; // Turn TRIAC off digitalWrite(TRIAC, LOW); digitalWrite(13, LOW); }
true
f544030517ca21df5d516d7f1795781fa63a0144
C++
NielsBeyen/i2c_pi_trex_master_student
/I2C.cpp
UTF-8
367
2.546875
3
[]
no_license
#include "I2C.h" #include <string.h> namespace TRexLib{ /* * Constructor * * @device the device path of the I2C bus (for example /dev/i2c-1) * @i2caddress the I2C slave device address */ I2C::I2C(const char * device, int i2caddress) { // Copy the device path strcpy(this->device, device); } }
true
aa53a01f9edea2f147ee96afb493ab70e49b9f88
C++
Jiltseb/Leetcode-Solutions
/solutions/473.matchsticks-to-square.246166430.ac.cpp
UTF-8
945
3.046875
3
[ "MIT" ]
permissive
class Solution { public: bool makesquare(vector<int> &nums) { return nums.size() && canPartitionKSubsets(nums, 4); } bool canPartitionKSubsets(vector<int> &nums, int k) { int sm = 0; for (int n : nums) sm += n; if (sm % k) return false; sm /= k; int n = nums.size(); vector<bool> visited(n); return f(nums, visited, k, sm); } bool f(vector<int> &nums, vector<bool> &visited, int k, int target, int j = 0, int currentSum = 0) { if (k == 0) return true; if (currentSum == target) return f(nums, visited, k - 1, target); for (int i = j; i < nums.size(); i++) { if (!visited[i] && nums[i] <= target - currentSum) { visited[i] = true; if (f(nums, visited, k, target, i + 1, currentSum + nums[i])) { // visited[i] = false; return true; } visited[i] = false; } } return false; } };
true
cac149b95c207accfb3eab06ebb144b60e8914cc
C++
hectorpla/Leetcode
/Tree/populate_next.cpp
UTF-8
1,064
3.4375
3
[]
no_license
#include "TreeLinkNode.h" #include <iostream> using namespace std; class Solution { public: void connect(TreeLinkNode *root) { helper(root); } void helper(TreeLinkNode *root) { if ( !root ) return; if ( root->left ) { root->left->next = root->right; if ( root->next ) { root->right->next = root->next->left; } helper(root->left); helper(root->right); } } }; void printLevel(TreeLinkNode* head) { while ( head ) { cout << head->val << " "; head = head->next; } cout << endl; } int main(int argc, char const *argv[]) { int a[] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15}; vector<int> v(a, a + sizeof(a) / sizeof(int)); TreeLinkNode *root = createTree(v); printTree(root); cout << "------------------------------" << endl; Solution sol; sol.connect(root); TreeLinkNode* head = root; while ( head ) { printLevel(head); head = head->left; } return 0; }
true
b723dc1c55142d7acaf4e9271139904dda6428b5
C++
ParagSaini/Competitive-Practice
/Babbar_series/Sets and Map/Intermediate/SubArrayWithzeroSum.cpp
UTF-8
899
3.828125
4
[]
no_license
#include <iostream> #include<vector> #include<unordered_set> using namespace std; // Time complexity = O(n); very nice // whenever we find the subarray with sum 0, the sum of total // array till that is equal to some previous sum. /* ex: ar = {5,4,2,-3,1,6}; subarray with sum 0 = {2,-3,1}; sum till element 1 = 9(5+4); */ bool Subarraywithzerosum(vector<int> ar) { unordered_set<int> sumTillNow; int sum = 0; for(int i=0; i<ar.size(); i++) { sum += ar[i]; if(sum == 0 || sumTillNow.count(sum)) { return true; } sumTillNow.insert(sum); } return false; } int main() { system("cls"); vector<int> ar = {5,4,2,-3,1,6,0}; if(Subarraywithzerosum(ar)) { cout<<"Their exists a subarray with zero sum"; } else { cout<<"Their is no such subarray exist with zero sum"; } return 0; }
true
2d0390907b0dfc1a9fa34b1e56582389f532ed5c
C++
escape0707/usaco_trainings
/race3.cpp
UTF-8
2,655
3.28125
3
[]
no_license
/* ID: totheso1 LANG: C++14 TASK: race3 */ #include <algorithm> #include <fstream> #include <iterator> #include <queue> #include <utility> #include <vector> using namespace std; static ifstream fin("race3.in"); static ofstream fout("race3.out"); #define endl '\n' template <typename T> T fin_get() { return *istream_iterator<T>(fin); } template <typename C> C fin_get_collection(const int size) { C ret; copy_n(istream_iterator<typename C::value_type>(fin), size, back_inserter(ret)); return ret; } static vector<vector<int>> adjacency_list(1); static void initialize() { for (int input; fin >> input, input != -1;) { if (input == -2) { adjacency_list.emplace_back(); } else { adjacency_list.back().push_back(input); } } adjacency_list.pop_back(); } static void solve() { const int vertex_count = adjacency_list.size(); vector<bool> first_bfs_visited; const auto bfs_avoid = [&](const int avoid) -> bool { queue<int> que({0}); first_bfs_visited[0] = true; while (!que.empty()) { const int curr_vertex = que.front(); que.pop(); for (const int to : adjacency_list[curr_vertex]) { if (first_bfs_visited[to] || to == avoid) { continue; } if (to == vertex_count - 1) { return true; } que.push(to); first_bfs_visited[to] = true; } } return false; }; const auto bfs_can_go_back = [&](const int start) -> bool { vector<bool> visited(vertex_count, false); queue<int> que({start}); visited[start] = true; while (!que.empty()) { const int curr_vertex = que.front(); que.pop(); for (const int to : adjacency_list[curr_vertex]) { if (visited[to]) { continue; } if (first_bfs_visited[to]) { return true; } que.push(to); visited[to] = true; } } return false; }; vector<int> unavoidable_point_collection; vector<int> splitting_point_collection; for (int vertex = 0; vertex < vertex_count - 1; ++vertex) { first_bfs_visited.assign(vertex_count, false); if (!bfs_avoid(vertex)) { unavoidable_point_collection.push_back(vertex); if (!bfs_can_go_back(vertex)) { splitting_point_collection.push_back(vertex); } } } fout << unavoidable_point_collection.size(); for (const int v : unavoidable_point_collection) { fout << ' ' << v; } fout << endl << splitting_point_collection.size(); for (const int v : splitting_point_collection) { fout << ' ' << v; } fout << endl; } int main() { initialize(); solve(); }
true
c08473552294d7d746d667504e2bbac32b8bfac9
C++
shadeops/euled-up
/Week_8_Boid_Simulation/brd/scene.cpp
UTF-8
2,783
3.046875
3
[]
no_license
#include <random> #include "scene.h" Scene::Scene(int num_boids) { std::default_random_engine generator; std::uniform_int_distribution<> distr_pos_x(0, screen_width); std::uniform_int_distribution<> distr_pos_y(0, screen_height); std::uniform_real_distribution<> distr_vel(-0.5, 0.5); for (int i = 0; i < num_boids; i++) { auto boid_position = Vector2D(distr_pos_x(generator), distr_pos_y(generator)); auto boid_velocity = Vector2D(distr_vel(generator), distr_vel(generator)); this->add_boid(i, boid_position, boid_velocity); boid_centre = boid_centre + boid_position; } } void Scene::add_boid(int id, Vector2D start_pos, Vector2D start_velocity) { auto boid = Boid(id); boid.set_position(start_pos); boid.set_velocity(start_velocity); boid_list.push_back(boid); } Vector2D Scene::centre_of_mass(Boid boid) { auto perceived_pos = boid_centre/(get_boid_no()-1); auto out_velocity = (perceived_pos - boid.position)/100; return out_velocity; } Vector2D Scene::no_collision(Boid boid) { Vector2D c; for(auto it_boid : boid_list) { if (boid.id != it_boid.id) { auto diff_vector = it_boid.get_position() - boid.get_position(); if (diff_vector.magnitude() < 50) { c = c - diff_vector; } } } return c; } Vector2D Scene::match_velocity(Boid boid) { Vector2D v; for(auto it_boid : boid_list) { if (boid.id != it_boid.id) { v = v + it_boid.get_velocity(); } } v = v/(get_boid_no()-1); return (v - boid.get_velocity())/8; } Vector2D Scene::bound_position(Boid boid) { Vector2D v; int nudge_unit = 20; auto boid_pos = boid.get_position(); if (boid_pos.x < 50) {v.x = nudge_unit;} else if (boid_pos.x > screen_height - 50) {v.x = -nudge_unit;} if (boid_pos.y < 50) {v.y = nudge_unit;} else if (boid_pos.y > screen_width - 50) {v.y = -nudge_unit;} return v; } void Scene::recalc_scene() { for(auto boid = std::begin(boid_list); boid != std::end(boid_list); ++boid) { boid_centre = boid_centre - boid->get_position(); // rule one auto v1 = centre_of_mass(*boid); // rule two auto v2 = no_collision(*boid); // rule three auto v3 = match_velocity(*boid); // rule four auto v4 = bound_position(*boid); auto new_velocity = boid->get_velocity() + v1 + v2 + v3 + v4; // velocity limiting happens when the velocity is set boid->set_velocity(new_velocity); boid->set_position(boid->get_position() + boid->get_velocity()); boid_centre = boid_centre + boid->get_position(); } }
true
f68aa18c093ea00340c10265dc9b398ae4d5bdee
C++
knupel/Rope_of_framework
/rope/function/rand_fast.cpp
UTF-8
1,748
3.03125
3
[ "Apache-2.0" ]
permissive
/** * ROPE FUNCTIONS * v 0.1.0 * 2020-2020 */ #include "./rand_fast.hpp" #include "../template/utils/r_utils.hpp" /** * RANDOM FAST */ /** * random fast * https://en.wikipedia.org/wiki/Xorshift */ // fast 128 float random_fast_128(vec4<uint32_t> &seed, float max) { float res = random_fast_128(seed) / static_cast<float>(UINT_MAX); return map<float>(res,0,1,0,max); } float random_fast_128(vec4<uint32_t> &seed, float min, float max) { float res = random_fast_128(seed) / static_cast<float>(UINT_MAX); return map<float>(res,0,1,min,max); } uint32_t random_fast_128(vec4<uint32_t> &seed) { static uint32_t x = seed.x(); static uint32_t y = seed.y(); static uint32_t z = seed.z(); static uint32_t w = seed.w(); uint32_t t; t = x ^ (x << 11); x = y; y = z; z = w; return w = w ^ (w >> 19) ^ (t ^ (t >> 8)); } // fast 32 float random_fast_32(uint32_t seed, float max) { float res = random_fast_32(seed) / static_cast<float>(UINT_MAX); return map<float>(res,0,1,0,max); } float random_fast_32(uint32_t seed, float min, float max) { float res = random_fast_32(seed) / static_cast<float>(UINT_MAX); return map<float>(res,0,1,min,max); } uint32_t random_fast_32(uint32_t seed) { uint32_t x = seed; x ^= x << 13; x ^= x >> 17; x ^= x << 5; return x; } // fast 64 double random_fast_64(uint32_t seed, double max) { double res = random_fast_64(seed) / static_cast<double>(ULONG_MAX); return map<double>(res,0,1,0,max); } double random_fast_64(uint32_t seed, double min, double max) { double res = random_fast_64(seed) / static_cast<double>(ULONG_MAX); return map<double>(res,0,1,min,max); } uint64_t random_fast_64(uint32_t seed) { uint64_t x = seed; x ^= x << 13; x ^= x >> 7; x ^= x << 17; return x; }
true
e66c7d3e56e4a1df1dfb1a502b84d224a1bb4224
C++
manproffi/CPP_pool
/d04/ex00/Sorcerer.hpp
UTF-8
1,494
2.640625
3
[]
no_license
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* Sorcerer.hpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: sprotsen <sprotsen@student.unit.ua> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/11/03 19:52:39 by sprotsen #+# #+# */ /* Updated: 2017/11/03 19:52:46 by sprotsen ### ########.fr */ /* */ /* ************************************************************************** */ #ifndef SORCERER_HPP # define SORCERER_HPP # include <iostream> # include "Victim.hpp" #include "Peon.hpp" class Sorcerer { private: std::string name; std::string title; public: Sorcerer(); Sorcerer(std::string name, std::string title); Sorcerer(Sorcerer& a); ~Sorcerer(); Sorcerer& operator= (Sorcerer const & a); std::string getName()const; std::string getTitle()const; void setName(std::string name); void setTitle(std::string title); void polymorph(Victim const &) const; void polymorph(Peon const &) const; }; std::ostream& operator << (std::ostream& ss, Sorcerer const & ref); #endif
true
4c36f7ca0feb24e569900596360f562bcc3f9b2d
C++
OOP2019lab/lab8-182171Naeemraza
/date_impl.cpp
UTF-8
2,352
3.765625
4
[]
no_license
#include"date.h" static string monthNames[13] = {"","January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"} ; Date::Date() { year=2000; month=1; day=1; } Date::Date(int m,int d,int y) { if(y<=2100&&y>=1800) year=y; if(d>=1&&d<=30) day=d; if(m<=12&&m>=1) month=m; else { year=2000; month=1; day=1; } } Date::Date(Date& d) { d.year=2000; d.month=1; d.day=1; } ostream& operator<<(ostream& osObject, const Date& d) { osObject<<monthNames[d.month]<<" "<<d.day<<" , "<<d.year<<endl; return osObject; } bool Date:: operator==(const Date& d) const { if(this->day==d.day&&this->month==d.month&&this->year==d.year) return true; else return false; } istream& operator>>(istream& isObject, Date& date) { int d=date.day; int m=date.month; int y=date.year; char a,b; cout<<"Enter date in \"day-month-year\" format:"<<endl; isObject>>d>>a>>m>>b>>y; if(d>=1&&d<=30&&a=='-'&&(m>=1&&m<=12)&&b=='-'&&(y>=1000&&y<=9999)) { date.month=m; date.day=d; date.year=y; } return isObject; } Date& Date:: operator=(const Date& obj) { this->day=obj.day; this->month=obj.month; this->year=obj.year; return *this; } Date& Date:: operator+( int i) { if(this->day+i<=30) { this->day=this->day+i; } else if(this->day+i>30) { this->month+1; if(this->month+1>12) { this->year=this->year+1; this->month=1; this->day=(this->day+i)-30; } } return *this; } Date& Date::operator--() { if(this->day>=2) this->day=this->day-1; else { this->day=30; this->month=this->month-1; if(this->month<=1) { this->month=12; this->year=this->year-1; } } return*this; } const Date Date::operator -- (int val) // postfix decrement operator { if (this->day == 1) { this->day = 30; if (this->month == 1) { this->month = 12; this->year=this->year-1; } else this->month=this->month-1; } else this->day=this->day-1; return *this; } int Date::operator [] (int index) const { if(index==0) return this->day; else if(index==1) return this->month; else if(index==2) return this->year; else cout << "index can only be 0, 1 or 2" << endl; }
true