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
7f7fc2e4dd948fa2bfb624f157510caefc1955fd
C++
GAYATRI-gajula25/pps-lab
/pps lab/New folder/c++16.cpp
UTF-8
418
3.671875
4
[]
no_license
#include <stdio.h> int main() { int num, msb; /* Input number from user */ printf("Enter any number: "); scanf("%d", &num); /* Move first bit of 1 to highest order */ msb = 1 << (BITS - 1); /* Perform bitwise AND with msb and num */ if(num & msb) printf("MSB of %d is set (1).", num); else printf("MSB of %d is unset (0).", num); return 0; }
true
223ec6e9cbf9b561595a4c5080d39d5defcb5243
C++
NVZGUL/nbody
/Nbody_sim/main.cpp
UTF-8
1,430
2.703125
3
[]
no_license
#include <iostream> #include <ctime> #include <math.h> #include "general.h" #include "Task.h" #include "Simple.h" #include "Nbody_thread.h" #include "Nbody_openMP.h" using namespace std; float3 getPoint(float r) { const float phi = rand(PI_M2), sintheta = rand(-1.f, 1.f), costheta = std::sqrt(1.f - sintheta*sintheta); float3 point{ r * std::cos(phi) * sintheta, r * std::sin(phi) * sintheta, r * costheta }; return point; } int main() { Body particles[N]; Body test; test.position = getPoint(1.00); //randomly generating N Particles for (int i = 0; i < N; i++) { float rx = float(1e18*exp(-1.8)*(.5 - rand())); float3 point = getPoint(rx); particles[i].position.x = point.x; particles[i].position.y = point.y; particles[i].position.z = point.z; float vx = float(1e18*exp(-1.8)*(.5 - rand())); particles[i].velocity.x = vx; float vy = float(1e18*exp(-1.8)*(.5 - rand())); particles[i].velocity.y = vy; float vz = float(1e18*exp(-1.8)*(.5 - rand())); particles[i].velocity.z = vz; float mass = float(1.98892e30*rand() * 10 + 1e20); particles[i].m = mass; } int numberofiterations = 800; clock_t start = clock(); //Nbody_simple(particles, numberofiterations); //Nbody_thread(particles, numberofiterations); Nbody_openMP(particles, numberofiterations); clock_t end = clock(); std::cout << "time is: " << (float)(end - start) / CLOCKS_PER_SEC << std::endl; return 0; }
true
0312f593e339a4c533e7a50b4142eb727dd406e6
C++
win18216001/tpgame
/GServerEngine/NetLibrary/AcceptManager.h
GB18030
584
2.71875
3
[]
no_license
/* * File : AcceptManager.h * Brief : Accept,ûAccept OO˼,ϣ * Author: Expter * Creat Date: [2009/11/11] */ #pragma once #include "Accept.h" class CAcceptManager { CAccept Accept; public: CAcceptManager(void) {}; ~CAcceptManager(void){}; /* * 󶨶˿ */ void CreateAccept( int Port ) { Accept._socket_bind( Port ); Accept._start_thread(); }; /* * رն˿ */ void CloseAccept() { Accept._destroy_accept() ; } };
true
dedd7d352ba5b1aae5715f9537953c7ad3d3b7b3
C++
dsbabkov/procedural_cpp
/lab5/other.h
UTF-8
949
3.09375
3
[]
no_license
#include <iostream> //Прототипы используемых в данном задании функций: template <typename T> void printArray(const T *arr, int n) { for (int i = 0; i < n; ++i) { std::cout << arr[i] << '\t'; } std::cout << '\n'; } void Sort(char* pcFirst, int nNumber, int size, void (*Swap)(void*, void*), int (*Compare)(void*, void*) ); void SwapInt(void* p1, void* p2); int CmpInt(void* p1, void* p2); double Sum(double first, double second); double Sub(double first, double second); double Mul(double first, double second); double Div(double first, double second); int indexOf(const char arr[], int size, char c); void SwapInt(void *p1, void *p2); int CmpInt(void *p1, void *p2); void SwapDouble(void *p1, void *p2); int CmpDouble(void *p1, void *p2); void SwapStr(void *p1, void *p2); int CmpStr(void *p1, void *p2); const char* GetString1(); const char* GetString2();
true
27056456c3ef44e08ee4f23c992949fa55d6bf93
C++
hcmarchezi/manipulator-robot-api
/domain/PartialRobotTrajectory.cpp
UTF-8
1,918
2.765625
3
[ "MIT" ]
permissive
#include "PartialRobotTrajectory.h" PDC::PartialRobotTrajectory::PartialRobotTrajectory() { } void PDC::PartialRobotTrajectory::Calculate(PDC::RobotPosition initialRobotPosition,PDC::RobotPosition finalRobotPosition) { // Should not accept two robot positions with different link position array sizes if (initialRobotPosition.GetLinkPositionsSize() != finalRobotPosition.GetLinkPositionsSize()) { return; } _initialTime = initialRobotPosition.GetInstantTime(); _finalTime = finalRobotPosition.GetInstantTime(); unsigned int linkPositionsSize = initialRobotPosition.GetLinkPositionsSize(); for(unsigned int index=0; index < linkPositionsSize; index++) { PDC::LinkTrajectory linkTrajectory = PDC::LinkTrajectory(); PDC::LinkPosition initialLinkPosition = initialRobotPosition.GetLinkPosition(index); PDC::LinkPosition finalLinkPosition = finalRobotPosition.GetLinkPosition(index); PDC::LinkTrajectoryParams params; params.initialTime = initialRobotPosition.GetInstantTime(); params.finalTime = finalRobotPosition.GetInstantTime(); params.initialPosition = initialLinkPosition.GetJointPosition(); params.finalPosition = finalLinkPosition.GetJointPosition(); params.initialVelocity = initialLinkPosition.GetJointVelocity(); params.finalVelocity = finalLinkPosition.GetJointVelocity(); linkTrajectory.Calculate(params); _linkTrajectories.push_back(linkTrajectory); } } double PDC::PartialRobotTrajectory::GetInitialTime() const { return _initialTime; } double PDC::PartialRobotTrajectory::GetFinalTime() const { return _finalTime; } int PDC::PartialRobotTrajectory::GetLinkTrajectorySize() { return _linkTrajectories.size(); } PDC::LinkTrajectory PDC::PartialRobotTrajectory::GetLinkTrajectory(int order) { return _linkTrajectories[order]; }
true
0be84512eaa07f265f7213b704a2655087b148c0
C++
RakibulRanak/Solved-ACM-problems
/Codeforces/Dreamoon and Stairs CF 476A.cpp
UTF-8
560
2.5625
3
[]
no_license
#include<bits/stdc++.h> using namespace std; int main() { double n,m; cin>>n>>m; if(m>n) cout<<-1<<endl; else { int minstep=ceil(n/2); if(minstep%(int)m!=0) { while(minstep<=n) { minstep++; if(minstep%(int)m==0){ cout<<minstep<<endl; break; } } if(minstep>n) cout<<-1<<endl; } else cout<<minstep<<endl; } return 0; }
true
6618fb38ed466d8317787cc98ef6f9c395cae430
C++
S-ngularity/ProjetoIntegrado-POO-ISI-ED1_2014-1_Cinema
/Cinema.cpp
UTF-8
16,343
3.125
3
[]
no_license
#include "Cinema.h" using namespace std; Cinema::Cinema(){ telaInicial(); } Cinema::~Cinema(){} void Cinema::telaInicial(){ int opcao; do{ clearScreen(); cout << endl; cout << "1. Gerenciar salas" << endl << endl; cout << "2. Gerenciar sessões" << endl << endl; cout << "3. Venda" << endl << endl; cout << "4. Sair" << endl << endl; cout << "Escolha uma opcao "; cin >> opcao; cout << endl; switch(opcao){ case 1: opcaoSala(); break; case 2: opcaoSessao(); break; case 3: venderIngresso(); break; case 4: break; default: cout << "Opção inválida" << endl; } cout << endl; }while(opcao!=4); cout << endl ; } void Cinema::opcaoSala(){ int opcao; do{ clearScreen(); cout << endl; cout << "1. Cadastrar sala" << endl << endl; cout << "2. Editar sala" << endl << endl; cout << "3. Voltar ao menu principal" << endl << endl; cout << "Escolha uma opção: "; cin >> opcao; cout << endl; switch(opcao){ case 1: cadastrarSala(); break; case 2: editarSala(); break; case 3: break; default: cout << "Opção inválida" << endl; } cout << endl; }while(opcao!=3); } void Cinema::cadastrarSala(){ int numSala; int capacidade; int qtdeFileiras; int qtdeAssentosFileira; int opcao; char idFileira; clearScreen(); do{ cout << endl << "Informe o número da sala (maior que 0): " << endl; cin >> numSala; }while(numSala <= 0); do{ cout << endl << "Informe a capacidade da sala (maior que 0): " << endl; cin >> capacidade; }while(capacidade <= 0); clearScreen(); Sala *salaTemp; salaTemp = new Sala(numSala, capacidade); do { cout << endl << *salaTemp << endl << endl; cout << "1. Adicionar fileira(s)"<< endl << endl; cout << "2. Excluir uma fileira" << endl << endl; cout << "3. Alterar número de assentos de uma fileira" << endl << endl; cout << "4. Alterar número da sala" << endl << endl; cout << "5. Confirmar" << endl << endl; cout << "6. Cancelar" << endl << endl; cout << "Escolha uma opção: "; cin >> opcao; switch(opcao) { case 1: clearScreen(); cout << *salaTemp << endl; do{ cout << endl << "Quantidade de fileiras (maior que 0): " << endl; cin >> qtdeFileiras; }while(qtdeFileiras <= 0); do{ cout << endl <<"Quantidade de assentos por fileira (maior que 0): " << endl; cin >> qtdeAssentosFileira; }while(qtdeAssentosFileira <= 0); try{ salaTemp->addFileirasComAssentos(qtdeFileiras, qtdeAssentosFileira); clearScreen(); cout << "Fileira(s) adicionada com sucesso." << endl << endl << endl; } // catch(bad_alloc) / catch(const char *s) do erro de exceder capacidade ? catch(const char *s) {clearScreen(); cout << endl << s << endl << endl << endl; } break; case 2: clearScreen(); cout << *salaTemp << endl; cout << "Informe fileira: " << endl; cin >> idFileira; try{ salaTemp->removeFileira(idFileira); clearScreen(); cout << "Fileira " << idFileira << " removida com sucesso." << endl << endl << endl; } catch(const char *s) {clearScreen(); cout << endl << s << endl << endl << endl; } break; case 3: clearScreen(); cout << *salaTemp << endl; cout << "Informe fileira: "<< endl; cin >> idFileira; do{ cout << "Informe novo número de assentos (maior que 0): " << endl; cin >> qtdeAssentosFileira; }while(qtdeAssentosFileira <= 0); try{ salaTemp->setQtdeAssentosNaFileira(idFileira, qtdeAssentosFileira); clearScreen(); cout << "Fileira alterada com sucesso." << endl << endl << endl; }// catch(bad_alloc) / catch(const char *s) do erro de exceder capacidade ? catch(const char *s) {clearScreen(); cout << endl << s << endl << endl << endl; } break; case 4: clearScreen(); cout << *salaTemp << endl; do{ cout << endl << "Informe o novo número da sala (maior que 0): " << endl; cin >> numSala; }while(numSala <= 0); salaTemp->setNumSala(numSala); clearScreen(); break; case 5: listaSalas.insere(salaTemp); // catch(bad_alloc) ? break; case 6: delete salaTemp; break; default: cout << "Opção inválida." << endl << endl << endl; } }while(opcao != 5 && opcao != 6); } void Cinema::editarSala(){ int opcao; int numSala, novaQtd, novaCapacidade;; char idFileira; Sala *salaEscolhida; do{ clearScreen(); cout << "Salas existentes:" << endl << endl; listaSalas.imprimirListaSala(); do{ do{ cout << endl << "Informe o número da sala (0 para voltar): " << endl; cin >> numSala; }while(numSala < 0); if(numSala == 0) break; try{ salaEscolhida = NULL; salaEscolhida = listaSalas.busca(numSala); clearScreen(); } catch(const char *s) { cout << endl << s << endl << endl << endl; } }while(salaEscolhida == NULL); if(numSala == 0) break; do{ cout << *salaEscolhida << endl << endl; cout << "1. Adicionar uma fileira" << endl << endl; cout << "2. Alterar número de assentos de uma fileira" << endl << endl; cout << "3. Excluir uma fileira" << endl << endl; cout << "4. Alterar capacidade da sala" << endl << endl; cout << "5. Alterar a situação da sala" << endl << endl; cout << "6. Excluir sala" << endl << endl; cout << "7. Editar outra sala" << endl << endl; cout << "8. Voltar ao menu sala" << endl << endl; cout << "Escolha uma opcao "; cin >> opcao; cout << endl; switch(opcao){ case 1: do{ cout << endl <<"Quantidade de assentos na fileira (maior que 0): " << endl; cin >> novaQtd; }while(novaQtd <= 0); try{ salaEscolhida->addFileirasComAssentos(1, novaQtd); clearScreen(); cout << "Fileira(s) adicionada com sucesso." << endl << endl << endl; } // catch(bad_alloc) / catch(const char *s) do erro de exceder capacidade ? catch(const char *s) {clearScreen(); cout << endl << s << endl << endl << endl; } break; case 2: clearScreen(); cout << *salaEscolhida << endl; cout << "Informe fileira: "<< endl; cin >> idFileira; do{ cout << "Informe novo número de assentos (maior que 0): " << endl; cin >> novaQtd; }while(novaQtd <= 0); try{ salaEscolhida->setQtdeAssentosNaFileira(idFileira, novaQtd); clearScreen(); cout << "Fileira alterada com sucesso." << endl << endl << endl; }// catch(bad_alloc) / catch(const char *s) do erro de exceder capacidade ? catch(const char *s) {clearScreen(); cout << endl << s << endl << endl << endl; } break; case 3: clearScreen(); cout << *salaEscolhida << endl; cout << "Informe fileira: "<< endl; cin >> idFileira; try{ salaEscolhida->removeFileira(idFileira); clearScreen(); cout << "Fileira " << idFileira << " removida com sucesso." << endl << endl << endl; } catch(const char *s) {clearScreen(); cout << endl << s << endl << endl << endl; } break; case 4: clearScreen(); cout << *salaEscolhida << endl; cout << "Informe nova capacidade: " << endl; cin >> novaCapacidade; try{ salaEscolhida->setCapacidade(novaCapacidade); clearScreen(); cout << "Capacidade alterada com sucesso." << endl << endl << endl; } // catch(const char *s) do erro de exceder capacidade ? catch(const char *s) {clearScreen(); cout << endl << s << endl << endl << endl; } break; case 5: clearScreen(); cout << *salaEscolhida << endl; int opcSituacao; cout << endl << "Opções" << endl; cout << " 1. Disponível" << endl << endl; cout << " 2. Manutenção de equipamento" << endl << endl; cout << " 3. Reforma" << endl << endl; cout << " 4. Manutenção geral" << endl << endl; cout << endl << "Informe a nova situação da sala: " << endl; cin >> opcSituacao; switch(opcSituacao) { case 1: salaEscolhida->setSituacao(disponivel); clearScreen(); cout << endl << "Situacao da sala alterada com sucesso." << endl << endl << endl; break; case 2: salaEscolhida->setSituacao(manuEquipamento); clearScreen(); cout << endl << "Situacao da sala alterada com sucesso." << endl << endl << endl; break; case 3: salaEscolhida->setSituacao(reforma); clearScreen(); cout << endl << "Situacao da sala alterada com sucesso." << endl << endl << endl; break; case 4: salaEscolhida->setSituacao(manuGeral); clearScreen(); cout << endl << "Situacao da sala alterada com sucesso." << endl << endl << endl; break; default: clearScreen(); cout << endl << "Situacao inválida." << endl << endl << endl; } break; case 6: clearScreen(); cout << *salaEscolhida << endl; if(confirmacao()) { listaSalas.removerSala(numSala); cout << "Sala removida com sucesso." << endl << endl << endl; } else { clearScreen(); opcao = 0; } break; case 7: break; case 8: break; default: cout << "Opção inválida." << endl << endl << endl; } cout << endl; }while(opcao != 6 && opcao != 7 && opcao != 8); }while(opcao != 6 && opcao != 8); } void Cinema::opcaoSessao(){ int opcao; do{ clearScreen(); listaSessoes.imprimirTodas(); cout << endl; cout << "1. Cadastrar sessão" << endl << endl; cout << "2. Excluir sessão" << endl << endl; cout << "3. Voltar ao Menu Principal" << endl << endl; cout << "Escolha uma opção: "; cin >> opcao; //salaEscolhida = listaSalas.busca(numSala); switch(opcao) { case 1: cadastrarSessao(); break; case 2: excluirSessao(); break; case 3: break; default: cout << "Opção inválida." << endl << endl << endl; } }while(opcao != 3); } void Cinema::cadastrarSessao(){ Sessao *novaSessao; Sala *salaEscolhida; int numSala; Horario hInicio, hFim; string filme; clearScreen(); cout << "Informe o nome do filme "; cin >> filme; cout << endl << "Informe o horário de início (hh:mm): " << endl; cin >> hInicio; cout << endl << "Informe o horário de fim (hh:mm): " << endl; cin >> hFim; //listarSalasDisponiveis // salas que tem um período livre de pelo menos tanto quanto o período entre hInicio e hFim // FUCKING HARD MODE do{ cout << endl << endl << "Salas: " << endl; listaSalas.imprimirListaSala(); do{ cout << "Informe o número da sala para a sessão (0 para voltar): " << endl; cin >> numSala; }while(numSala < 0); if(numSala == 0) break; try{ salaEscolhida = NULL; salaEscolhida = listaSalas.busca(numSala); } catch(const char *s) { cout << endl << endl << endl << s << endl << endl; } }while(salaEscolhida == NULL); // confirmar se sala escolhida tem período disponível, se não mostrar erro // HARD MODE (dica no txt da interface) if(numSala != 0) { try{ novaSessao = new Sessao(filme, hInicio, hFim, salaEscolhida); } catch(const char *s) { cout << endl << s << endl << endl << endl; } listaSessoes.insere(novaSessao); //INSERIR ORDENADO (por hInicio -- util para se for checar se há período na sala) } } void Cinema::excluirSessao() { int codSessao; Sessao *sessaoEscolhida; clearScreen(); listaSessoes.imprimirTodas(); do{ do{ cout << endl << "Informe o código da sessão a excluir (0 para voltar): " << endl; cin >> codSessao; }while(codSessao < 0); if(codSessao == 0) break; try{ sessaoEscolhida = NULL; sessaoEscolhida = listaSessoes.busca(codSessao); } catch(const char *s) { cout << endl << s << endl << endl << endl; } }while(sessaoEscolhida == NULL); if(codSessao != 0) listaSessoes.removeSessao(codSessao); } void Cinema::venderIngresso(){ int opcao; do{ clearScreen(); listaSessoes.imprimirDisponiveis(); cout << "1. Iniciar nova venda: " << endl << endl; cout << "2. Voltar ao menu principal" << endl << endl; cout << "Escolha uma opção: "; cin >> opcao; cout << endl; switch(opcao){ case 1: novaVenda(); break; case 2: break; default: cout << "Opção inválida." << endl << endl << endl; } cout << endl; }while(opcao != 2); } void Cinema::novaVenda(){ Venda *novaVenda; Sessao *sessaoEscolhida; Ingresso *tempIngresso; int opcao; int codSessao; clearScreen(); listaSessoes.imprimirDisponiveis(); cout << endl << endl << endl; do{ do{ cout << endl << "Informe o código da sessão (0 para voltar): " << endl; cin >> codSessao; }while(codSessao < 0); if(codSessao == 0) break; try{ sessaoEscolhida = NULL; sessaoEscolhida = listaSessoes.busca(codSessao); } catch(const char *s) { cout << endl << s << endl << endl << endl; } }while(sessaoEscolhida == NULL); if(codSessao == 0) return; novaVenda = new Venda(*sessaoEscolhida); do{ clearScreen(); sessaoEscolhida->imprimirSala(); novaVenda->listarIngressos(); cout << endl; cout << "Valor total: R$" << novaVenda->calcularValorTotal() << endl << endl << endl; cout << "1. Adicionar novo ingresso" << endl << endl; cout << "2. Remover ingresso" << endl << endl; cout << "3. Confirmar venda" << endl << endl; cout << "4. Cancelar venda" << endl << endl; cout << "Escolha uma opcao "; cin >> opcao; cout << endl; switch(opcao){ case 1: clearScreen(); sessaoEscolhida->imprimirSala(); char idFileira; int idAssento; bool disponivel; do{ cout << endl; cout << "Informe a fileira: "; cin >> idFileira; cout << endl << "Informe o assento: "; cin >> idAssento; try{ disponivel = false; disponivel = sessaoEscolhida->verificaDispAssento(idFileira, idAssento); } catch(const char *s) {cout << endl << s << endl << endl << endl; } if(!disponivel) cout << "Assento indisponível. Selecione outro:" << endl << endl; }while(!disponivel); Tipo tipo; int opcaoTipo; do{ cout << endl << endl; cout << "Informe o tipo do ingresso: " << endl; cout << " 1. Inteiro" << endl; cout << " 2. Meio" << endl; cin >> opcaoTipo; switch(opcaoTipo) { case 1: tipo = inteiro; break; case 2: tipo = meia; break; default: cout << endl << "Tipo inválido." << endl << endl; } }while(opcaoTipo != 1 && opcaoTipo != 2); float valor; do{ cout << endl << endl; cout << "Informe o valor do ingresso: "; cin >> valor; if(valor < 0) cout << "Valor inválido." << endl << endl; }while(valor < 0); tempIngresso = new Ingresso(tipo, valor, *sessaoEscolhida, idFileira, idAssento); novaVenda->addIngresso(*tempIngresso); tempIngresso = NULL; break; case 2: clearScreen(); novaVenda->listarIngressos(); int codIngresso; do{ cout << "Remover ingresso número (0 para voltar): " << endl; cin >> codIngresso; }while(codIngresso < 0); if(codIngresso == 0) break; try{ novaVenda->removeIngresso(codIngresso); clearScreen(); cout << "Ingresso removido com sucesso." << endl << endl << endl; } catch(const char *s) {clearScreen(); cout << endl << endl << endl << s << endl << endl; } break; case 3: if(novaVenda->calcularValorTotal() > 0) { novaVenda->emitirIngresso(); listaVendas.insere(novaVenda); } else delete novaVenda; break; case 4: delete novaVenda; break; default: cout << "Opcao inválida." << endl; } }while(opcao != 3 && opcao != 4); } bool Cinema::confirmacao(){ char confirmacao; do { cout << "Digite s para sim e n para não: " << endl; cin >> confirmacao; if(confirmacao == 's' || confirmacao == 'S') { cout << "Operacao concluída." << endl; return true; } else if(confirmacao == 'n' || confirmacao == 'N') { cout << "Operacao cancelada." << endl; return false; } else cout << "Entrada inválida." << endl; }while(1); } void Cinema::clearScreen() { cout << string( 100, '\n' ); }
true
756161ecccdc5024013fcbd9fd0139a684808782
C++
systelab/cpp-gtest-allure-utilities
/src/GTestAllureUtilities/Model/TestCase.h
UTF-8
1,085
2.609375
3
[ "MIT" ]
permissive
#pragma once #include "Stage.h" #include "Status.h" #include "Step.h" #include <memory> #include <string> #include <vector> namespace systelab { namespace gtest_allure { namespace model { class TestCase { public: TestCase(); TestCase(const TestCase&); virtual ~TestCase() = default; std::string getName() const; Status getStatus() const; Stage getStage() const; time_t getStart() const; time_t getStop() const; void setName(const std::string&); void setStatus(Status); void setStage(Stage); void setStart(time_t); void setStop(time_t); unsigned int getStepCount() const; const Step* getStep(unsigned int index) const; Step* getStep(unsigned int index); void addStep(std::unique_ptr<Step>); virtual TestCase& operator= (const TestCase&); friend bool operator== (const TestCase& lhs, const TestCase& rhs); friend bool operator!= (const TestCase& lhs, const TestCase& rhs); private: std::string m_name; Status m_status; Stage m_stage; time_t m_start; time_t m_stop; std::vector< std::unique_ptr<Step> > m_steps; }; }}}
true
e12c205bd12193f0b3e12549735fe89dee85f26f
C++
GabrielRavier/randomAsm
/c++/xmmintrin.cpp
UTF-8
7,135
2.515625
3
[]
no_license
#include <stdint.h> /* The Intel API is flexible enough that we must allow aliasing with other vector types, and their scalar components. */ typedef float __m128 __attribute__ ((__vector_size__ (16), __may_alias__)); /* Unaligned version of the same type. */ typedef float __m128_u __attribute__ ((__vector_size__ (16), __may_alias__, __aligned__ (1))); /* Internal data types for implementing the intrinsics. */ typedef float __v4sf __attribute__ ((__vector_size__ (16))); /* The Intel API is flexible enough that we must allow aliasing with other vector types, and their scalar components. */ typedef int __m64 __attribute__ ((__vector_size__ (8), __may_alias__)); /* Unaligned version of the same type */ typedef int __m64_u __attribute__ ((__vector_size__ (8), __may_alias__, __aligned__ (1))); /* Internal data types for implementing the intrinsics. */ typedef int32_t __v2si __attribute__ ((__vector_size__ (8))); typedef int16_t __v4hi __attribute__ ((__vector_size__ (8))); typedef char __v8qi __attribute__ ((__vector_size__ (8))); typedef int64_t __v1di __attribute__ ((__vector_size__ (8))); typedef float __v2sf __attribute__ ((__vector_size__ (8))); #define _MM_EXCEPT_MASK 0x003f #define _MM_EXCEPT_INVALID 0x0001 #define _MM_EXCEPT_DENORM 0x0002 #define _MM_EXCEPT_DIV_ZERO 0x0004 #define _MM_EXCEPT_OVERFLOW 0x0008 #define _MM_EXCEPT_UNDERFLOW 0x0010 #define _MM_EXCEPT_INEXACT 0x0020 #define _MM_MASK_MASK 0x1f80 #define _MM_MASK_INVALID 0x0080 #define _MM_MASK_DENORM 0x0100 #define _MM_MASK_DIV_ZERO 0x0200 #define _MM_MASK_OVERFLOW 0x0400 #define _MM_MASK_UNDERFLOW 0x0800 #define _MM_MASK_INEXACT 0x1000 #define _MM_ROUND_MASK 0x6000 #define _MM_ROUND_NEAREST 0x0000 #define _MM_ROUND_DOWN 0x2000 #define _MM_ROUND_UP 0x4000 #define _MM_ROUND_TOWARD_ZERO 0x6000 #define _MM_FLUSH_ZERO_MASK 0x8000 #define _MM_FLUSH_ZERO_ON 0x8000 #define _MM_FLUSH_ZERO_OFF 0x0000 /* Create a selector for use with the SHUFPS instruction. */ #define _MM_SHUFFLE(fp3,fp2,fp1,fp0) \ (((fp3) << 6) | ((fp2) << 4) | ((fp1) << 2) | (fp0)) #define extern #define __inline #define __gnu_inline__ #define __always_inline__ #define __artificial__ /* Create an undefined vector. */ extern __inline __m128 __attribute__((__gnu_inline__, __always_inline__, __artificial__)) _mm_undefined_ps (void) { __m128 __Y = __Y; return __Y; } /* Create a vector of zeros. */ extern __inline __m128 __attribute__((__gnu_inline__, __always_inline__, __artificial__)) _mm_setzero_ps (void) { return __extension__ (__m128){ 0.0f, 0.0f, 0.0f, 0.0f }; } extern __inline __m128 __attribute__((__gnu_inline__, __always_inline__, __artificial__)) _mm_add_ps (__m128 __A, __m128 __B) { return (__m128) ((__v4sf)__A + (__v4sf)__B); } extern __inline __m128 __attribute__((__gnu_inline__, __always_inline__, __artificial__)) _mm_sub_ps (__m128 __A, __m128 __B) { return (__m128) ((__v4sf)__A - (__v4sf)__B); } extern __inline __m128 __attribute__((__gnu_inline__, __always_inline__, __artificial__)) _mm_mul_ps (__m128 __A, __m128 __B) { return (__m128) ((__v4sf)__A * (__v4sf)__B); } extern __inline __m128 __attribute__((__gnu_inline__, __always_inline__, __artificial__)) _mm_div_ps (__m128 __A, __m128 __B) { return (__m128) ((__v4sf)__A / (__v4sf)__B); } /* Create a vector with element 0 as F and the rest zero. */ extern __inline __m128 __attribute__((__gnu_inline__, __always_inline__, __artificial__)) _mm_set_ss (float __F) { return __extension__ (__m128)(__v4sf){ __F, 0.0f, 0.0f, 0.0f }; } /* Create a vector with all four elements equal to F. */ extern __inline __m128 __attribute__((__gnu_inline__, __always_inline__, __artificial__)) _mm_set1_ps (float __F) { return __extension__ (__m128)(__v4sf){ __F, __F, __F, __F }; } extern __inline __m128 __attribute__((__gnu_inline__, __always_inline__, __artificial__)) _mm_set_ps1 (float __F) { return _mm_set1_ps (__F); } /* Create a vector with element 0 as *P and the rest zero. */ extern __inline __m128 __attribute__((__gnu_inline__, __always_inline__, __artificial__)) _mm_load_ss (float const *__P) { return _mm_set_ss (*__P); } /* Create a vector with all four elements equal to *P. */ extern __inline __m128 __attribute__((__gnu_inline__, __always_inline__, __artificial__)) _mm_load1_ps (float const *__P) { return _mm_set1_ps (*__P); } extern __inline __m128 __attribute__((__gnu_inline__, __always_inline__, __artificial__)) _mm_load_ps1 (float const *__P) { return _mm_load1_ps (__P); } /* Load four SPFP values from P. The address must be 16-byte aligned. */ extern __inline __m128 __attribute__((__gnu_inline__, __always_inline__, __artificial__)) _mm_load_ps (float const *__P) { return *(__m128 *)__P; } /* Load four SPFP values from P. The address need not be 16-byte aligned. */ extern __inline __m128 __attribute__((__gnu_inline__, __always_inline__, __artificial__)) _mm_loadu_ps (float const *__P) { return *(__m128_u *)__P; } #ifdef __x86_64__ /* Load four SPFP values in reverse order. The address must be aligned. */ extern __inline __m128 __attribute__((__gnu_inline__, __always_inline__, __artificial__)) _mm_loadr_ps (float const *__P) { __v4sf __tmp = *(__v4sf *)__P; return (__m128) __builtin_ia32_shufps (__tmp, __tmp, _MM_SHUFFLE (0,1,2,3)); } #endif /* Create the vector [Z Y X W]. */ extern __inline __m128 __attribute__((__gnu_inline__, __always_inline__, __artificial__)) _mm_set_ps (const float __Z, const float __Y, const float __X, const float __W) { return __extension__ (__m128)(__v4sf){ __W, __X, __Y, __Z }; } /* Create the vector [W X Y Z]. */ extern __inline __m128 __attribute__((__gnu_inline__, __always_inline__, __artificial__)) _mm_setr_ps (float __Z, float __Y, float __X, float __W) { return __extension__ (__m128)(__v4sf){ __Z, __Y, __X, __W }; } /* Stores the lower SPFP value. */ extern __inline void __attribute__((__gnu_inline__, __always_inline__, __artificial__)) _mm_store_ss (float *__P, __m128 __A) { *__P = ((__v4sf)__A)[0]; } extern __inline float __attribute__((__gnu_inline__, __always_inline__, __artificial__)) _mm_cvtss_f32 (__m128 __A) { return ((__v4sf)__A)[0]; } /* Store four SPFP values. The address must be 16-byte aligned. */ extern __inline void __attribute__((__gnu_inline__, __always_inline__, __artificial__)) _mm_store_ps (float *__P, __m128 __A) { *(__m128 *)__P = __A; } /* Store four SPFP values. The address need not be 16-byte aligned. */ extern __inline void __attribute__((__gnu_inline__, __always_inline__, __artificial__)) _mm_storeu_ps (float *__P, __m128 __A) { *(__m128_u *)__P = __A; } #if !defined __clang__ && !defined __INTEL_COMPILER /* Sets the low S * PFP value of A from the low value of B. */ extern __inline __m128 __attribute__((__gnu_inline__, __always_inline__, __artificial__)) _mm_move_ss (__m128 __A, __m128 __B) { return (__m128) __builtin_shuffle ((__v4sf)__A, (__v4sf)__B, __extension__ (__attribute__((__vector_size__ (16))) int) {4,1,2,3}); } #endif
true
913029dab12b70e7c9d4af66ebda896ce49fadb7
C++
lmidang/CIS22B_Project
/CIS22B_Project/Book.cpp
UTF-8
2,753
3.328125
3
[]
no_license
#define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <string> #include "Book.h" /* default constructor that initializes the member variables with 0 or " ". the date member variable is initialized as 0000/00/00 (YYYY-MM-DD) */ Book::Book() { mISBN = "00000000"; mTitle = " "; mAuthor = " "; mPublisher = " "; mDateAdded = "0000/00/00"; // YYYY-MM-DD mQuantOnHand = 0; mWholeSale = 00.00; mRetail = 00.00; } /* eight argument constructor that initializes all the member variables */ Book::Book(std::string i, std::string t, std::string a, std::string p, std::string d, int q, double w, double r) { mISBN = i; mTitle = t; mAuthor = a; mPublisher = p; mDateAdded = d; //YYYY-MM-DD mQuantOnHand = q; mWholeSale = w; mRetail = r; } /* mutator method for the mISBN member variable */ void Book::setISBN(std::string i) { mISBN = i; } /* mutator method for the mTitle member variable */ void Book::setTitle(std::string t) { mTitle = t; } /* mutator method for the mAuthor member variable */ void Book::setAuthor(std::string a) { mAuthor = a; } /* mutator method for the mPublisher member variable */ void Book::setPublish(std::string p) { mPublisher = p; } /* mutator method for the mDateAdded member variable */ void Book::setDateAdd(std::string da) { mDateAdded = da; } /* mutator method for the mQuantOnHand member variable */ void Book::setQuantity(int q) { mQuantOnHand = q; } /* mutator method for the mWholeSale member variable */ void Book::setWholeSale(double ws) { mWholeSale = ws; } /* mutator method for the mRetail member variable */ void Book::setRetail(double r) { mRetail = r; } /* accessor method for the mISBN member variable */ std::string Book::getISBN() const { return mISBN; } /* accessor method for the mTitle member variable */ std::string Book::getTitle() const { return mTitle; } /* accessor method for the mAuthor member variable */ std::string Book::getAuthor() const { return mAuthor; } /* accessor method for the mPublisher member variable */ std::string Book::getPublish() const { return mPublisher; } /* accessor method for the mDateAdded member variable */ std::string Book::getDateAdd() const { return mDateAdded; } /* accessor method for the mQuantOnHand member variable */ int Book::getQuantity() const { return mQuantOnHand; } /* accessor method for the mWholeSale member variable */ double Book::getWholeSale() const { return mWholeSale; } /* accessor method for the mRetail member variable */ double Book::getRetail() const { return mRetail; }
true
9b26495ca26df3cd8d5095d1ad1342ac6efd45d7
C++
sega-dreamcast/renesas-sh-instruction-set
/s-exprpp.cpp
UTF-8
6,299
2.5625
3
[ "MIT" ]
permissive
/* s-exprpp - a simple preprocessor to convert s-expressions into C/C++. Copyright (C) 2013-2015 Oleg Endo This is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version. This software is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this software; see the file LICENSE. If not see <http://www.gnu.org/licenses/>. */ #include <iostream> #include <string> #include <vector> #include <algorithm> #include <exception> #include <cassert> std::istream& skip_spaces (std::istream& in) { while (in.good () && std::isspace (in.peek ())) in.get (); return in; } static const std::string ID_STR = "__sexpr"; struct expr { std::vector<expr> args; std::string name; expr (void) = default; expr (const std::string& n) : name (n) { } bool is_symbol (void) const { return args.empty (); } void print (std::ostream& out, int indent = 0) const { if (is_symbol ()) out << name << " "; else { out << " ([" << args.size () << "] "; bool first = true; for (const auto& a : args) { a.print (out); // if (!first) // out << " | "; first = false; } out << ") "; } } void parse (std::istream& in, size_t max_args = std::numeric_limits<size_t>::max ()) { // std::cout << "\nparse " << this; skip_spaces (in); std::string cur_symbol; int in_string = 0; int in_raw_string = 0; while (true) { char c; in >> std::noskipws >> c; if (!in.good ()) return; // skip preprocessor directives (line, file markers) if (c == '#' && in_string == 0 && in_raw_string == 0) { in.ignore (std::numeric_limits<std::streamsize>::max (), '\n'); continue; } if (c == '{' /* && in_raw_string == 0 */ ) { if (in_raw_string > 0) // output nested '{' cur_symbol += c; in_raw_string ++; continue; } if (c == '}' && in_raw_string) { in_raw_string --; if (in_raw_string > 0) cur_symbol += c; continue; } if (c == '"' && in_string) { in_string --; cur_symbol += c; continue; } if (c == '"' && in_string == 0) { in_string ++; cur_symbol += c; continue; } if (in_string || in_raw_string) { assert (in_string >= 0 && in_raw_string >= 0); cur_symbol += c; continue; } if ((c == '(' || c == ')' || isspace (c)) && !cur_symbol.empty ()) { // std::cout << "\ncur_symbol = " << cur_symbol; args.emplace_back (cur_symbol); cur_symbol.clear (); } if (c == '(') { args.emplace_back (); args.back ().parse (in); if (args.size () >= max_args) return; skip_spaces (in); continue; } if (c == ')') return; if (!isspace (c)) cur_symbol += c; else skip_spaces (in); } } void transform_to_cpp_var (std::ostream& out) { out << args[1].name << " ("; args[2].transform_to_cpp (out, false); out << ");"; } void transform_to_cpp_func (std::ostream& out) { out << args[1].name << "\n{\n"; args[2].transform_to_cpp (out, false); out << ";\n}"; } void transform_to_cpp_code (std::ostream& out) { args[1].transform_to_cpp (out, false); out << ";"; } void transform_to_cpp (std::ostream& out, bool allow_special = true) { if (allow_special && !is_symbol () && args[0].name == "var") transform_to_cpp_var (out); else if (allow_special && !is_symbol () && args[0].name == "func") transform_to_cpp_func (out); else if (allow_special && !is_symbol () && args[0].name == "code") transform_to_cpp_code (out); else if (allow_special && !is_symbol () && args[0].name == ID_STR) args[1].transform_to_cpp (out); else { if (is_symbol ()) out << name; else { if (args[0].is_symbol ()) { out << args[0].name << " ("; for (size_t i = 1; i < args.size (); ++i) { args[i].transform_to_cpp (out, false); if (i + 1 < args.size ()) out << ", "; } out << ")"; } } } } }; int main (void) { char tmpbuf[8]; size_t tmpbuf_sz = 0; int match_str_pos = 0; while (std::cin.good ()) { char c; std::cin.get (c); if (!std::cin.good ()) break; tmpbuf[tmpbuf_sz ++] = c; if (c == ID_STR[match_str_pos]) { match_str_pos ++; if (match_str_pos == ID_STR.size ()) { expr expr_tree; expr_tree.parse (std::cin, 1); // the first arg is a dummy list because of the "__sexpr (" expr_tree.args[0].transform_to_cpp (std::cout); tmpbuf_sz = 0; match_str_pos = 0; } } else { std::cout.write (tmpbuf, tmpbuf_sz); match_str_pos = 0; tmpbuf_sz = 0; } } // std::cout.flush (); // std::cout.close (); // std::cout.put (0); // std::cout.flush (); std::cout << std::endl; return 0; } #endif /* static const std::vector<std::string> test_inputs { R"_( __sexpr (var { static const arg } (arg_UIWindow (objc_type "UIWindow") (to_cpp "cocoa::ui::Window::attach_obj (%s)") (cpp_type "const obj_ptr<Window>&") (to_objc "%s->objc_obj<UIWindow> ()"))) )_" , R"_( __sexpr (func { thing define_thing (void) } (return (thing (name "hello") (text_a "text text")))) )_" , R"_( __sexpr (code (thing (name "hello") (text_a "text text"))) )_" , R"_( __sexpr (func { int test_int_func (void) } (return ((3)5))) )_" , R"_( __sexpr (func { class test (void) } (return (classs (objc_name "UIScreen") (cpp_name "Screen") (filename_prefix "uiscreen") (inherits_from (classs (objc_name "NSObject") (cpp_name "cocoa::ns::Object"))) nothing (method (name "applicationFrame") f_const ret_Rect) )) )_" }; */
true
ab056832f25375d35dbe48b853efac8484acbaa4
C++
AABNassim/DPPML-Worker-Source
/PPML/MLSP.cpp
UTF-8
800
2.875
3
[]
no_license
// // Created by root on 30/06/19. // #include "MLSP.h" MLSP::MLSP() { if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) { printf("\n Socket creation error \n"); return; } serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons(port); // Convert IPv4 and IPv6 addresses from text to binary form if(inet_pton(AF_INET, csp_ip, &serv_addr.sin_addr)<=0) { printf("\nInvalid address/ Address not supported \n"); return; } if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) { printf("\nConnection Failed \n"); return; } /*send(sock , hello , strlen(hello) , 0 ); printf("Hello message sent\n"); valread = read(sock , buffer, 1024); printf("%s\n",buffer );*/ }
true
62f9dee22b618325394102a6f8be49b1cbc032cb
C++
zhonghe987/cproject
/src/oss_client/op_client.h
UTF-8
1,134
2.625
3
[]
no_license
#ifndef OP_CLIENT_H #define OP_CLIENT_H #include<iostream> #include<string> #include<curl/curl.h> enum HttpOp {OP_GET,OP_PUT,OP_DEL,OP_POST}; class Client { public: Client(std::string url_base):http_base(url_base){} virtual ~Client(){} virtual int op_url(HttpOp method,char *key,char *out,char *data=NULL) = 0; //virtual int getUrl(char *method,char *key,char *out ) = 0; //virtual int postUrl(char *method,char *key,char *out) = 0; //virtual int delUrl(char *method,char *key,char *out) = 0; //virtual int putUrl(char *method,char *key,char *out) = 0; std::string getBase(){return http_base;} private: std::string http_base; }; class OpCurlClient: public Client { public: OpCurlClient(std::string url):Client(url){} ~OpCurlClient(){} int op_url(HttpOp method,char *key,char *out,char *data=NULL); //virtual int getUrl(char *method,char *key,char *out); //virtual int postUrl(char *method,char *key,char *out); //virtual int delUrl(char *method,char *key,char *out); //virtual int putUrl(char *method,char *key,char *out); }; int op_test(); #endif
true
2df38fc2d238c7c247bd0a7b2c906c7388d40612
C++
Minhan93/Financial-Computing-With-C-
/HW10/HW10_1/HW10_1/Tree_TIAN.h
UTF-8
4,878
2.8125
3
[]
no_license
#pragma once #include "Tree_CRR.h" class BinomialTree_TIAN { private: double spot; double strike; double sigma; double r; double T; int N; //steps double delta_t; double u; //up factor double d; //down factor double pu; //probability-up double pd; //probability-down vector<vector<pair<double, double>>> Tree_binomial; public: BinomialTree_TIAN() {}; BinomialTree_TIAN(double spot_, double strike_, double sigma_, double r_, double T_, int N_) : spot(spot_), strike(strike_), sigma(sigma_), r(r_), T(T_), N(N_) { delta_t = T / N; double R = exp(r*delta_t); double V = exp(pow(sigma, 2)*delta_t); u = R*V / 2 * (V + 1 + sqrt(pow(V, 2) + 2 * V - 3)); d = R*V / 2 * (V + 1 - sqrt(pow(V, 2) + 2 * V - 3)); pu = (exp(r*delta_t) - d) / (u - d); pd = 1 - pu; } ~BinomialTree_TIAN() { for (int i = 0; i < static_cast<int>(Tree_binomial.size()); i++) { Tree_binomial[i].clear(); } Tree_binomial.clear(); } void build_BinomialTree() { Tree_binomial.resize(N + 1); for (int i = 0; i < N + 1; i++) { Tree_binomial[i].resize(i + 1); } Tree_binomial[0][0].first = spot; for (int i = 1; i < N + 1; i++) { for (int j = 0; j < i; j++) { Tree_binomial[i][j].first = d*Tree_binomial[i - 1][j].first; } Tree_binomial[i][i].first = u*Tree_binomial[i - 1][i - 1].first; } } void print_Tree() { cout << "The tree is:" << endl; for (int i = 0; i <static_cast<int>( Tree_binomial.size()); i++) { for (int j = 0; j <static_cast<int>( Tree_binomial[i].size()); j++) { cout << Tree_binomial[i][j].first << "(" << Tree_binomial[i][j].second << ")" << " "; } cout << endl; } return; } void finalprice() { for (int i = 0; i < static_cast<int>(Tree_binomial[N].size()); i++) { Tree_binomial[N][i].second = max(0.0, Tree_binomial[N][i].first - strike); } } double pricing() { for (int i = N - 1; i >= 0; i--) { for (int j = 0; j < static_cast<int>(Tree_binomial[i].size()); j++) { Tree_binomial[i][j].second = exp(-r*delta_t)*(pu*Tree_binomial[i + 1][j + 1].second + pd*Tree_binomial[i + 1][j].second); } } return Tree_binomial[0][0].second; } double pricing_pruning_setzero() { double s_up = spot*exp((r - sigma*sigma / 2)*T + 6 * sigma*sqrt(T)); double s_low = spot*exp((r - sigma*sigma / 2)*T - 6 * sigma*sqrt(T)); for (int i = N - 1; i >= 0; i--) { for (int j = 0; j < static_cast<int>(Tree_binomial[i].size()); j++) { if (Tree_binomial[i + 1][j].first >= s_low&&Tree_binomial[i + 1][j + 1].first <= s_up) { Tree_binomial[i][j].second = exp(-r*delta_t)*(pu*Tree_binomial[i + 1][j + 1].second + pd*Tree_binomial[i + 1][j].second); } else { Tree_binomial[i][j].second = 0; } } } return Tree_binomial[0][0].second; } double pricing_pruning_intrinsicvalue() { double s_up = spot*exp((r - sigma*sigma / 2)*T + 6 * sigma*sqrt(T)); double s_low = spot*exp((r - sigma*sigma / 2)*T - 6 * sigma*sqrt(T)); for (int i = N - 1; i >= 0; i--) { for (int j = 0; j < static_cast<int>(Tree_binomial[i].size()); j++) { if (Tree_binomial[i + 1][j].first >= s_low&&Tree_binomial[i + 1][j + 1].first <= s_up) { Tree_binomial[i][j].second = exp(-r*delta_t)*(pu*Tree_binomial[i + 1][j + 1].second + pd*Tree_binomial[i + 1][j].second); } else { Tree_binomial[i][j].second = max(spot - strike*exp(-r*delta_t*(N - i)), 0.0); } } } return Tree_binomial[0][0].second; } double pricing_pruning_linearapprox() { double s_up = spot*exp((r - sigma*sigma / 2)*T + 6 * sigma*sqrt(T)); double s_low = spot*exp((r - sigma*sigma / 2)*T - 6 * sigma*sqrt(T)); for (int i = N - 1; i >= 0; i--) { for (int j = 0; j < static_cast<int>(Tree_binomial[i].size()); j++) { if (Tree_binomial[i + 1][j].first >= s_low&&Tree_binomial[i + 1][j + 1].first <= s_up) { Tree_binomial[i][j].second = exp(-r*delta_t)*(pu*Tree_binomial[i + 1][j + 1].second + pd*Tree_binomial[i + 1][j].second); } else { Tree_binomial[i][j].second = 0.5*Tree_binomial[i + 1][j + 1].second + 0.5*Tree_binomial[i + 1][j].second; } } } return Tree_binomial[0][0].second; } double pricing_RichardsonExtrapolation() { BinomialTree_TIAN TIAN1(spot, strike, sigma, r, T, N); TIAN1.build_BinomialTree(); TIAN1.finalprice(); BinomialTree_TIAN TIAN2(spot, strike, sigma, r, T, N / 2); TIAN2.build_BinomialTree(); TIAN2.finalprice(); double k = 1.0408; double p = (pow(2, k)*TIAN1.pricing() - TIAN2.pricing()) / (pow(2, k) - 1); return p; } };
true
dc2f9c93740d85e615b2c6b636c27a56c54f6dfb
C++
wanghongsheng01/thread
/thread.cpp
UTF-8
1,232
3.6875
4
[]
no_license
/* * [C++ thread] * @Author wanghongsheng01 * @DateTime 2021-07-07T22:02:30+0800 */ #include<iostream> #include<thread> using namespace std; void func1(){ cout<<"do some work"<<endl; } void func2(int i, double d, string s){ cout<<"i="<<i<<"; d="<<d<<"; s="<<s<<endl; } int main(){ /** * 创建线程 */ std::thread t1(func1); // do some work,提供线程函数(或函数对象) t1.join(); // join 函数阻塞线程,直到线程函数执行结束,如果有返回值,返回值将被忽略 std::thread t2(func2, 100, 23.00, "string"); //i=100; d=23; s=string,还可以指定函数参数 t2.join(); std::thread t3(func1); t3.detach(); //无返回值,如果不希望线程被阻塞,调用 detach 将线程和线程对象分离,detach 后和线程失联 // std::bind 创建线程 std::thread t6(std::bind(func1)); t6.join(); // lambda 表达式创建线程 std::thread t7([](int i, double d){std::cout<<"i="<<i<<"; d="<<d<<endl;}, 1, 2); t7.join(); // i=1; d=2 /** * 移动线程,线程不复制,但可移动 */ std::thread t4(func1); t4.join(); std::thread t5(std::move(t4)); // 线程被移动后,线程对象 t4 不代表任何线程了 return 0; }
true
45d6ce2002993fcee608e3c7c968d301dbfc4470
C++
SimonKocurek/Algorithms-and-Fun
/c++/stack-sorter.cpp
UTF-8
1,264
3.71875
4
[]
no_license
#include <bits/stdc++.h> using namespace std; // Sorting based on 1 or 2 stack and no other data structures template<class T> void sort_stack(stack<T> &sorted) { stack<T> secondary; while (!sorted.empty()) { auto inserted = sorted.top(); sorted.pop(); while (!secondary.empty() && secondary.top() > inserted) { sorted.push(secondary.top()); secondary.pop(); } secondary.push(inserted); while (!sorted.empty() && sorted.top() >= secondary.top()) { secondary.push(sorted.top()); sorted.pop(); } } while (!secondary.empty()) { sorted.push(secondary.top()); secondary.pop(); } } int main() { stack<int> a; int a_values[] {34, 3, 31, 98, 92, 23}; for (auto i : a_values) { a.push(i); } stack<int> b; int b_values[] {3, 5, 1, 4, 2, 8}; for (auto i : b_values) { b.push(i); } sort_stack(a); sort_stack(b); while (!a.empty()) { auto i = a.top(); a.pop(); cout << i << " "; } cout << "\n"; while (!b.empty()) { auto i = b.top(); b.pop(); cout << i << " "; } cout << "\n"; return 0; }
true
6fcd9f5d3fb1a7ad553783e3de70601f5f7ef8e1
C++
rishindramani/Competitive-Coding
/approach_techn/dp/subset_sum.cpp
UTF-8
666
2.625
3
[]
no_license
// // Created by Rishi on 14-Oct-19. // #include<bits/stdc++.h> #define ll long long using namespace std; vector<ll> v; void sub(ll arr[],ll a,ll b,ll sum) { if(a>b) { v.push_back(sum); return; } sub(arr,a+1,b,sum); sub(arr,a+1,b,sum+arr[a]); } int main() { ll t; cin>>t; while(t--) { v.clear(); ll n; cin>>n; ll arr[n]; for(ll i=0;i<n;i++) { cin>>arr[i]; } sub(arr,0,n-1,0); sort(v.begin(),v.end()); for(ll i=0;i<v.size();i++) { cout<<v[i]<<" "; } cout<<endl; } return 0; }
true
ea4b8495a7a92fa6e24fd883cf2b401515647241
C++
drlongle/leetcode
/algorithms/problem_1366/solution.cpp
UTF-8
4,476
3.046875
3
[]
no_license
/* 1366. Rank Teams by Votes Medium In a special ranking system, each voter gives a rank from highest to lowest to all teams participated in the competition. The ordering of teams is decided by who received the most position-one votes. If two or more teams tie in the first position, we consider the second position to resolve the conflict, if they tie again, we continue this process until the ties are resolved. If two or more teams are still tied after considering all positions, we rank them alphabetically based on their team letter. Given an array of strings votes which is the votes of all voters in the ranking systems. Sort all teams according to the ranking system described above. Return a string of all teams sorted by the ranking system. Example 1: Input: votes = ["ABC","ACB","ABC","ACB","ACB"] Output: "ACB" Explanation: Team A was ranked first place by 5 voters. No other team was voted as first place so team A is the first team. Team B was ranked second by 2 voters and was ranked third by 3 voters. Team C was ranked second by 3 voters and was ranked third by 2 voters. As most of the voters ranked C second, team C is the second team and team B is the third. Example 2: Input: votes = ["WXYZ","XYZW"] Output: "XWYZ" Explanation: X is the winner due to tie-breaking rule. X has same votes as W for the first position but X has one vote as second position while W doesn't have any votes as second position. Example 3: Input: votes = ["ZMNAGUEDSJYLBOPHRQICWFXTVK"] Output: "ZMNAGUEDSJYLBOPHRQICWFXTVK" Explanation: Only one voter so his votes are used for the ranking. Example 4: Input: votes = ["BCA","CAB","CBA","ABC","ACB","BAC"] Output: "ABC" Explanation: Team A was ranked first by 2 voters, second by 2 voters and third by 2 voters. Team B was ranked first by 2 voters, second by 2 voters and third by 2 voters. Team C was ranked first by 2 voters, second by 2 voters and third by 2 voters. There is a tie and we rank teams ascending by their IDs. Example 5: Input: votes = ["M","M","M","M"] Output: "M" Explanation: Only team M in the competition so it has the first rank. Constraints: 1 <= votes.length <= 1000 1 <= votes[i].length <= 26 votes[i].length == votes[j].length for 0 <= i, j < votes.length. votes[i][j] is an English upper-case letter. All characters of votes[i] are unique. All the characters that occur in votes[0] also occur in votes[j] where 1 <= j < votes.length. */ #include <algorithm> #include <atomic> #include <bitset> #include <cassert> #include <cmath> #include <condition_variable> #include <functional> #include <future> #include <iostream> #include <iterator> #include <list> #include <map> #include <numeric> #include <queue> #include <set> #include <sstream> #include <stack> #include <thread> #include <unordered_map> #include <unordered_set> #include <vector> using namespace std; #define ll long long #define ull unsigned long long class Solution { public: unordered_map <char, vector<int>> score; string rankTeams(vector<string>& votes) { int vsz = votes[0].size(); for (auto& vote: votes) { for (int i = vsz-1; i >= 0; --i) { char ch = vote[i]; if (score.count(ch) == 0) score[ch] = vector<int>(vsz, 0); score[ch][i]++; } } string res; for (auto& p: score) res.push_back(p.first); auto lambda = [this, vsz] (auto c1, auto c2) { vector<int>& sc1 = score[c1]; vector<int>& sc2 = score[c2]; for (int i = 0; i < vsz; ++i) { if (sc1[i] > sc2[i]) return true; else if (sc1[i] < sc2[i]) return false; } return c1 < c2; }; sort(begin(res), end(res), lambda); return res; } }; int main() { Solution sol; vector<string> votes; // Output: "ACB" votes = {"ABC","ACB","ABC","ACB","ACB"}; // Output: "XWYZ" //votes = {"WXYZ","XYZW"}; // Output: "ZMNAGUEDSJYLBOPHRQICWFXTVK" //votes = {"ZMNAGUEDSJYLBOPHRQICWFXTVK"}; // Output: "ABC" //votes = {"BCA","CAB","CBA","ABC","ACB","BAC"}; // Output: "M" //votes = {"M","M","M","M"}; cout << sol.rankTeams(votes) << endl; return 0; }
true
fab6fe28bd5dbbd357cb61bb31109c978649420e
C++
fairy-tale/leetcode
/84.cpp
UTF-8
912
3.453125
3
[]
no_license
//since need to record the heights before, use stack. //two pointer can't be used in this case, since need know all the information between two pointers. //push_back a '0' at the end of array, which could pop all the heights in array, no missing. class Solution { public: int largestRectangleArea(vector<int>& heights) { int n = heights.size(); if (!n) return 0; int max_area = 0; stack<int> s; heights.push_back(0); s.push(0); for (int i = 1; i <= n; ++i) { if (heights[s.top()] < heights[i]) { s.push(i); } else if (heights[s.top()] > heights[i]) { int last = s.top(); while (!s.empty() && heights[s.top()] > heights[i]) { max_area = max(max_area, heights[s.top()] * (i - s.top())); last = s.top(); s.pop(); } if (s.empty() || heights[s.top()] < heights[i]) { heights[last] = heights[i]; s.push(last); } } } return max_area; } };
true
3203b34ae6af77fa00fb1141646ea388ebeb76b8
C++
lucasilvas2/projeto-petfera
/include/profissional.hpp
UTF-8
897
3.1875
3
[ "MIT" ]
permissive
#pragma once #include <iomanip> #include <iostream> #include <memory> using std::string; using std::cout; using std::endl; using std::ostream; enum tpProf{ veterinario, tratador }; class Profissional{ protected: tpProf tipoProfissional; string nome; string contato; string endereco; public: Profissional(); Profissional(string nome, string contato, string endereco); virtual ~Profissional(); //gets tpProf getTipoProf() const; string getNome() const; string getContato() const; string getEndereco() const; //sets void setNome(string nome); void setContato(string contato); void setEndereco(string endereco); friend ostream& operator<<(ostream& o, Profissional const &pro); private: virtual ostream& print(ostream&) const = 0; };
true
c9821ca8c08dbefdc5291fe441c052bd0c349b0b
C++
plalit/GeeksForGeeks
/max_product_triplet_ARRAY.cpp
UTF-8
853
3.328125
3
[]
no_license
#include<iostream> #include<stdio.h> #include<stdlib.h> using namespace std; int main() { int n; cin>>n; int arr[n]; for(int i=0;i<n;i++) cin>>arr[i]; int first = -100000, second = -100000, third = -100000, negfirst = 100000, negsecond = 100000; for(int i=0;i<n;i++) { if(arr[i] > third) { int temp = third; third = arr[i]; first = second; second = temp; } else if(arr[i] > second) { first = second; second = arr[i]; } else if(arr[i] > first) first = arr[i]; if(arr[i] < negsecond) { negfirst = negsecond; negsecond = arr[i]; } else if(arr[i] < negfirst) negfirst = arr[i]; }// 10, 3, 5, 6, 20 //-10, -3, -5, -6, -20 //1, -4, 3, -6, 7, 0 int pos = first*second*third; int negpos = third*negfirst*negsecond; if(pos > negpos) cout<<pos<<endl; else cout<<negpos<<endl; }
true
4e846c554e7871c0cf09e9da363f4d98027d0e09
C++
sb565/Algorithms_Implementation
/Codes/Heapsort.cpp
UTF-8
770
3.40625
3
[]
no_license
#include<iostream> #include<vector> using namespace std; void heapify(int a[],int &n,int r) { int large=r,left=(2*r),right=(2*r+1); if(left<=n) if(a[large]<a[left]) large=left; if(right<=n) if(a[large]<a[right]) large=right; if(r!=large){ swap(a[large],a[r]); heapify(a,n,large); } } void createheap(int a[],int n) { for(int i=n/2;i>0;i--) { heapify(a,n,i); } } void heapsort(int a[],int n) { createheap(a,n); while(n>0){ swap(a[n],a[1]); n--; heapify(a,n,1); } } int main() { int n; cout<<"Enter the number of elements :";cin>>n; int arr[n+1]; cout<<"Enter the elements :\n"; for(int i=1;i<=n;i++) cin>>arr[i]; heapsort(arr,n); cout<<"elements after sorting :\n"; for(int i=1;i<=n;i++) cout<<arr[i]<<' '; return 0; }
true
9dfde467ec7bf9557ffbc5c9b1d15b4429ce022e
C++
nbirkbeck/ennes
/src/highres_boundary_test.cc
UTF-8
1,832
2.71875
3
[]
no_license
#include "gtest/gtest.h" #include "highres_boundary.h" TEST(HighresBoundaryTest, MaskUpsample2) { nacb::Image8 input(4, 4, 1); input = 0; input(1, 1) = 255; input(1, 2) = 255; input(2, 1) = 255; input(2, 2) = 255; nacb::Imagef result = HighresBoundarySimple(input, 2); ASSERT_EQ(8, result.w); ASSERT_EQ(8, result.h); ASSERT_EQ(1, result.nchannels); for (int x = 0; x < 2; ++x) { for (int y = 0; y < result.h; ++y) { EXPECT_LE(result(x, y), 0.5); EXPECT_LE(result(result.w - x - 1, y), 0.5); } } for (int y = 0; y < 2; ++y) { for (int x = 0; x < result.w; ++x) { EXPECT_LE(result(x, y), 0.5); EXPECT_LE(result(x, result.h - 1 - y), 0.5); } } for (int y = 2; y < result.h - 2; ++y) { for (int x = 2; x < result.w - 2; ++x) { EXPECT_GE(result(x, y), 0.5); } } } TEST(HighresBoundaryTest, ColorUpsample) { nacb::Image8 input(3, 4, 3); input = 0; input(1, 1, 0) = 255; input(1, 1, 1) = 0; input(1, 1, 2) = 0; input(1, 2, 0) = 0; input(1, 2, 1) = 255; input(1, 2, 2) = 0; Color3b bg(0, 0, 0); nacb::Image8 result = HighresBoundaryColor(input, HighresBoundarySimple, 2, &bg); ASSERT_EQ(6, result.w); ASSERT_EQ(8, result.h); ASSERT_EQ(4, result.nchannels); for (int x = 0; x < 3; ++x) { for (int y = 1; y < 7; ++y) { EXPECT_EQ(y < 4 ? 255 : 0, result(x, y, 0)) << x << "," << y; EXPECT_EQ(y < 4 ? 0 : 255, result(x, y, 1)) << x << "," << y; } // Outside pixels shouldn't be black--should be close color. EXPECT_EQ(255, result(x, 0, 0) | result(x, 0, 1)); EXPECT_EQ(255, result(x, 7, 0) | result(x, 7, 1)); EXPECT_LE(result(x, 0, 3), 10); EXPECT_LE(result(x, 7, 3), 10); } } int main(int ac, char* av[]) { testing::InitGoogleTest(&ac, av); return RUN_ALL_TESTS(); }
true
217fe8899f74e11d13cc39d74dd8bff2da0bd485
C++
lintianfang/cleaning_cobotics
/cgv/utils/statistics.h
UTF-8
1,485
2.703125
3
[]
no_license
#pragma once #include <iostream> #include <cmath> #include "lib_begin.h" namespace cgv { namespace utils { /** incrementally accumulate statistical information */ class CGV_API statistics { public: /// initialize with no value considered yet statistics(); /// initialize and consider one value statistics(const double& v); /// initialize and consider n equal values statistics(const double& v, unsigned int n); /// initialize void init(); /// initialize and consider one value void init(const double& v); /// initialize and consider n equal values void init(const double& v, unsigned int n); /// consider another value void update(const double& v); /// consider another value count times void update(const double& v, unsigned int n); /// compute average of the considered values double get_average() const; /// compute standard deviation of the considered value double get_standard_deviation() const; /// get the sum of the considered variables double get_sum() const; /// get the sum of the considered variables double get_sum_of_squares() const; /// get the minimum of the considered variables double get_min() const; /// get the maximum of the considered variables double get_max() const; /// get the number of considered variables unsigned int get_count() const; protected: double min, max, sum, sms; unsigned int cnt; }; extern CGV_API std::ostream& operator << (std::ostream& os, const statistics& s); } } #include <cgv/config/lib_end.h>
true
42a923df49fcace07d0361d9e9efd338bc66dddb
C++
mphe/GameLib
/include/gamelib/utils/Factory.hpp
UTF-8
1,629
3.09375
3
[ "MIT" ]
permissive
#ifndef GAMELIB_FACTORY_HPP #define GAMELIB_FACTORY_HPP #include <cassert> #include <memory> #include <unordered_map> namespace gamelib { template <typename Base, typename Key, typename... Args> class Factory { public: typedef std::unique_ptr<Base> BasePtr; public: typedef BasePtr(*CreatorFunction)(Args...); public: template <typename Derive> static BasePtr defaultCreator(Args&&... args) { return BasePtr(new Derive(std::forward<Args>(args)...)); } public: BasePtr create(const Key& id, Args&&... args) const { assert(_makers.find(id) != _makers.end()); return _makers.find(id)->second(std::forward<Args>(args)...); } void add(const Key& id, CreatorFunction callback) { _makers[id] = callback; } template <typename Derive> void add(const Key& id) { add(id, defaultCreator<Derive>); } void remove(const Key& id) { _makers.erase(id); } bool hasKey(const Key& id) const { return _makers.find(id) != _makers.end(); } void clear() { _makers.clear(); } size_t size() const { return _makers.size(); } private: std::unordered_map<Key, CreatorFunction> _makers; }; } #endif
true
7311731631aea5fae772ed0fee0318f399cd5c4c
C++
hyller/GladiatorLibrary
/Ivor_Horton_Beginning_Visual_C++_2010/Ch09/Ex9_08/Ex9_08.cpp
UTF-8
726
3.671875
4
[ "Unlicense" ]
permissive
// Ex9_08.cpp // Using a base class pointer to call a virtual function #include <iostream> #include "GlassBox.h" // For CBox and CGlassBox using std::cout; using std::endl; int main() { CBox myBox(2.0, 3.0, 4.0); // Declare a base box CGlassBox myGlassBox(2.0, 3.0, 4.0); // Declare derived box of same size CBox* pBox(nullptr); // Declare a pointer to base class objects pBox = &myBox; // Set pointer to address of base object pBox->ShowVolume(); // Display volume of base box pBox = &myGlassBox; // Set pointer to derived class object pBox->ShowVolume(); // Display volume of derived box cout << endl; return 0; }
true
68e95eeded99bfcf19b00ebdcf0365ef73c7e976
C++
chokomancarr/chokoengine2
/include/ce2/scene/transform.hpp
UTF-8
1,582
2.5625
3
[ "Apache-2.0" ]
permissive
#pragma once #include "chokoengine.hpp" #include "enums/transform_space.hpp" CE_BEGIN_NAMESPACE /* The Transform class contains the transformation * data and methods of a SceneObject. * A Transform object cannot be created directly. * Use `SceneObject::New()->transform()` instead */ class Transform { CE_CLASS_COMMON Transform(); Transform& operator =(const Transform&) = default; _SceneObject* _object; //????????? Vec3 _localPosition; Vec3 _worldPosition; Quat _localRotation; Vec3 _localRotationEuler; Quat _worldRotation; Vec3 _worldRotationEuler; Vec3 _localScale; Mat4x4 _localMatrix; Mat4x4 _worldMatrix; void UpdateLocalMatrix(); void UpdateParentMatrix(); public: CE_GET_MEMBER(localPosition); CE_SET_MEMBER_F(localPosition); CE_GET_MEMBER(worldPosition); CE_SET_MEMBER_F(worldPosition); CE_GET_MEMBER(localRotation); CE_SET_MEMBER_F(localRotation); CE_GET_MEMBER(worldRotation); CE_SET_MEMBER_F(worldRotation); CE_GET_MEMBER(localRotationEuler); CE_SET_MEMBER_F(localRotationEuler); CE_GET_MEMBER(worldRotationEuler); CE_SET_MEMBER_F(worldRotationEuler); void Rotate(const Vec3& v, TransformSpace sp = TransformSpace::Self); CE_GET_MEMBER(localScale); CE_SET_MEMBER_F(localScale); CE_GET_MEMBER(localMatrix); CE_GET_MEMBER(worldMatrix); Vec3 forward() const; void forward(const Vec3&); Vec3 right() const; void right(const Vec3&); Vec3 up() const; void up(const Vec3&); friend class _SceneObject; }; CE_END_NAMESPACE
true
658186741818590527e5199fcc9be3a214f36fd1
C++
andrijanamikovic/oop1
/red/Project1/red.cpp
UTF-8
822
3.359375
3
[]
no_license
#include "red.h" #include <iostream> #include <cstdlib> using namespace std; Red::Red(int k) { arr = new int[k]; cap = k; first = last = 0; } Red::Red(const Red& rd) { arr = new int[rd.cap]; for (int i = 0; i < rd.cap; i++) { arr[i] = rd.arr[i]; } cap = rd.cap; last = rd.last; l = rd.l; first = rd.first; } Red::Red(Red&& rd) { arr = rd.arr; cap = rd.cap; last = rd.last; l = rd.l; first = rd.first; rd.arr = nullptr; } Red::~Red() { delete []arr; } void Red::put(int k) { if (l == cap) exit(1); arr[last++] = k; if (last == cap) last = 0; l++; } int Red::get() { if (l == 0) exit(2); int b = arr[first++]; if (first == cap) first = 0; l--; return b; } void Red::print()const { if (l == 0) cout <<"Red je prazan"; for (int i = 0; i < l; i++) { cout << arr[first + i] << " "; } }
true
60354ae49f8b23d325c47a652c4174187f6872be
C++
rodstrom/yomibubble
/Game/codebase/AI/TottAIStates.h
UTF-8
657
2.625
3
[]
no_license
#ifndef _TOTT_AI_STATES_H_ #define _TOTT_AI_STATES_H_ #include "AIPrereq.h" class TottAIStateMove : public AIState{ public: TottAIStateMove(const TottMoveAIDef& def); virtual ~TottAIStateMove(void){} void Enter(); void Exit(); bool Update(float dt); protected: Ogre::String m_animation; Ogre::Vector3 m_current_position; Ogre::Vector2 m_target_position; }; class TottAIStateWait : public AIState { public: TottAIStateWait(const TottWaitAIDef& def); virtual ~TottAIStateWait(void){} void Enter(); void Exit(); bool Update(float dt); protected: Ogre::String m_animation; float m_target_time; float m_timer; }; #endif // _TOTT_AI_STATES_H_
true
c3460c59df662732c4c8e0e636bc17f72e2cc7cb
C++
d4daveshep/arduino
/TestMaths/TestMaths.ino
UTF-8
1,820
3.109375
3
[]
no_license
const float EarthRadius = 6371000.0; // radius of earth in m // coords of start pin const float pinlat = -36.8317; const float pinlon = 174.7485; // coords of start committee hut const float commlat = -36.8355; const float commlon = 174.7470; void setup() { // put your setup code here, to run once: Serial.begin(9600); Serial.println("Test GPS Maths"); // calculate start line float bearingPinToComm = bearingDeg(pinlat,pinlon,commlat,commlon); Serial.print("Bearing Pin to Comm = "); Serial.println(bearingPinToComm); float distPinToComm = distance(pinlat,pinlon,commlat,commlon); Serial.print("Dist Pin to Comm = "); Serial.print(distPinToComm); Serial.println(" m"); //print("------") } void loop() { // put your main code here, to run repeatedly: } // distance and bearing formulas from http://www.movable-type.co.uk/scripts/latlong.html // distance between two points using Haversine formula float distance( float lat1, float lon1, float lat2, float lon2 ) { // lat, lon in degrees float L1 = radians(lat1); float L2 = radians(lat2); float dLat = radians(lat2-lat1); float dLon = radians(lon2-lon1); float a = sin(dLat/2.0) * sin(dLat/2.0) + cos(L1) * cos(L2) * sin(dLon/2.0) * sin(dLon/2.0); float c = 2.0 * atan2(sqrt(a), sqrt(1.0-a)); float dist = EarthRadius * c; return dist; } // calculate bearing from point1 to point2 in degrees float bearingDeg(float lat1, float lon1, float lat2, float lon2) { // lat, lon in degrees float L1 = radians(lat1); float L2 = radians(lat2); float dLon = radians(lon2-lon1); float y = sin(dLon)*cos(L2); float x = cos(L1)*sin(L2) - sin(L1)*cos(L2)*cos(dLon); float brng = atan2(y, x); float brngdeg = degrees(brng); brngdeg = brngdeg - 360.0 * floor(brngdeg/360.0); return brngdeg; }
true
29c1d91d7e61fee7fb79639a902fe6fbcd415ae1
C++
pawarashish10/Coding-Challange-I
/object_oriented_design/main.cpp
UTF-8
789
2.8125
3
[]
no_license
#include <string> #include <vector> #include <iostream> #include "Kennel.h" #include "Kennel.cpp" using namespace std; int main() { Kennel kennel; kennel.AddCat("Garfield"); kennel.AddDog("Odie"); kennel.AddDog("Pluto"); kennel.AddCat("Felix"); kennel.AddCat("Sylvester"); kennel.AddCat("Scratchy"); kennel.AddDog("Scooby Doo"); kennel.AddCat("Puss in Boots"); kennel.AddDog("Goofy"); kennel.AddDog("Old Yeller"); kennel.RollCall(); /* output will be: * * Garfield says Meow * Odie says Woof * Pluto says Woof * Felix says Meow * Sylvester says Meow * Scratchy says Meow * Scooby Doo says Woof * Puss in Boots says Meow * Goofy says Woof * Old Yeller says Woof * */ }
true
ff815661f89b8ad848b1366ffc47254ebc989110
C++
appinho/SAGoogleCodeEventTemplate
/CompleteSearch/pylons_PAR.cpp
UTF-8
2,240
3.34375
3
[]
no_license
// CJ19/1A // HARD // Backtracing/Random #include <iostream> #include <vector> #include <utility> using namespace std; static int R, C; bool dfs(int x, int y, vector<vector<bool> > & visited, vector<pair<int,int> > & path){ //cerr << path.size() << " " << x << " " << y << endl; if(path.size() == R*C){ //cerr << "DONE" << endl; return true; } vector<pair<int,int> > next_nodes; for(int r = 0; r < R; r++){ for(int c = 0; c < C; c++){ if(!visited[r][c]){ if(x != r && y != c && (x+y) != (r+c) && (x-y) != (r-c)){ next_nodes.push_back(make_pair(r, c)); } } } } if(!next_nodes.empty()){ for(int i = 0; i < next_nodes.size(); i++){ int nx = next_nodes[i].first; int ny = next_nodes[i].second; visited[nx][ny] = true; path.push_back(make_pair(nx, ny)); if(dfs(nx, ny, visited, path)){ return true; } else{ visited[nx][ny] = false; path.pop_back(); } } } return false; } void pylons(){ int rend = (R+1)/2; int cend = (C+1)/2; for(int r = 0; r < rend; r++){ for(int c = 0; c < cend; c++){ //cerr << "START " << r << " " << c << endl; vector<vector<bool> > visited(R, vector<bool>(C, false)); vector<pair<int,int> > path; visited[r][c] = true; path.push_back(make_pair(r, c)); if(dfs(r, c, visited, path)){ cout << "POSSIBLE" << endl; for(auto const & p: path){ cout << (p.first + 1) << " " << (p.second + 1) << endl; } return; } } } cout << "IMPOSSIBLE" << endl; } int main() { int T; cin >> T; // Loop over test cases for(int t = 1; t <= T; ++t){ cin >> R >> C; //time_t startt = clock(); cout << "Case #" << t << ": "; pylons(); //cerr << "~ #" << t << " done! time : " << (double)(clock()-startt)/CLOCKS_PER_SEC << "s." << endl; } return 0; }
true
ab19c96791df8d0a811b57efef2553559a2502df
C++
TobbyT/example
/example_algo/dongtaiguihua/740.cpp
UTF-8
317
2.578125
3
[]
no_license
#include "general.h" int main() { int amount = 8; vector<int> coins = {2, 3, 8}; vector<int> res(amount + 1, 0); res[0] = 1; for(int i = 0; i < coins.size(); ++i){ for(int j = coins[i]; j <= amount; ++j){ res[j] += res[j - coins[i]]; } } PrintVector(res); }
true
0ee850853f4bcc1ab4d87d2bb60804a538e0289c
C++
ralucado/SFMLGameTemplate
/MyGame.hpp
UTF-8
679
2.625
3
[]
no_license
#ifndef MYGAME_H #define MYGAME_H #include "Game.hpp" class MyGame : public Game { public: MyGame(int scrwidth, int scrheight, std::string title, int style); ~MyGame(); void update(float deltaTime); void draw(); void processEvents(); private: //The components of the game sf::RectangleShape player; sf::Vector2f _position; int _scrwidth, _scrheight; float _scont, _speed, _acc, _friction, _movx, _movy; enum Direction { Down, Left, Right, Up , None}; const int mx[5] = {0, -1, 1, 0, 0}; const int my[5] = {1, 0, 0, -1, 0}; Direction _dir; //bool onScreen(float posX, float posY); }; #endif // MYGAME_H
true
a80491e864c6c73c59378c983f37a9fa1c9ae9ee
C++
KieranWebber/ROS-Instinct
/ros_instinct_actions/include/ros_instinct_actions/instinct_action_service.h
UTF-8
2,095
2.578125
3
[ "MIT" ]
permissive
#pragma once #include <ros/ros.h> #include <actionlib/server/simple_action_server.h> #include <instinct_msgs/InstinctAction.h> /** * Extendable interface providing ROS-Instinct actions using a actionlib server. * * Actions are implemented by extending executeAction. * Service calls to executeActions are performed on a separate thread and are permitted to be blocking. * Long running actions should take care to query ros::ok and actionServer_.isPreemptRequested() to see if the task * should be aborted. The action server is automatically advertised on instantiation */ class InstinctActionService { public: InstinctActionService(ros::NodeHandle& nh, const std::string& serviceName = "action_service"); protected: /** * Callback used on an action request. * Runs on a dedicated thread allowing a action request to be blocking * * @param actionId Id of the action to execute * @param actionValue Parameter of the action (if applicable) * @return A Instinct Action status code */ virtual unsigned char executeAction(const int actionId, const int actionValue) = 0; ros::NodeHandle nh_; actionlib::SimpleActionServer<instinct_msgs::InstinctAction> actionServer_; /** * Publish feedback back to the planner node for consumption by the action client * * @param feedback Feedback status code */ void publishFeedback(int feedback); private: instinct_msgs::InstinctActionFeedback feedback_; instinct_msgs::InstinctActionResult result_; /** * Callback wrapping executeAction that handles extracting params from the goal, performing the action * and returning the result * * @param goal Goal message the action request */ void actionSeverRequest(const instinct_msgs::InstinctGoalConstPtr& goal); /** * Set the action status for reading by the client. * Called automatically by actionServerRequest after executing the action * * @param result Action result status - Sent to client */ void setActionResult(unsigned char result); };
true
8fa2e7e8be78d51ffcd8e18d8919f442e26d4671
C++
nitish166/HackerEarth
/Recursion/lastIndex.cpp
UTF-8
405
3.015625
3
[]
no_license
#include<bits/stdc++.h> using namespace std; int lastIndex(int* arr, int n, int x) { int l=0; int r=n-1; if(l>r) return -1; int ans = lastIndex(arr+1, n-1, x); if(ans !=-1) return ans+1; if(arr[0]==x) return 0; return -1; } int main() { int n,x; cin>>n>>x; int* arr = new int[n]; for(int i=0;i<n;i++) { cin>>arr[i]; } int ans = lastIndex(arr, n, x); cout<<ans<<endl; return 0; }
true
1f3c90ca410236bca29e5f371547d4aadf915ab0
C++
wjk20120522/leetcode
/cplusplus_version/Sqrt(x).cpp
UTF-8
388
2.84375
3
[]
no_license
class Solution { public: int sqrt(int x) { int64_t begin = 0, end = 50000; int64_t mid = (begin + end) / 2; while (true) { int64_t sqr = mid*mid; if (sqr < x) { if ((mid + 1)*(mid + 1) > x) return mid; begin = mid + 1; } else if (sqr > x) { end = mid - 1; } else { return mid; } mid = (begin + end) / 2; } } };
true
0bccefbcb4fde0b209060290d2193f6845e32f76
C++
LecomteEmerick/MathProjet
/CyrusBeck/CyrusBeck/Source.cpp
ISO-8859-1
2,606
2.71875
3
[]
no_license
#include<windows.h> #include<GL/glut.h> #include<stdlib.h> #include <ctime> #include<stdio.h> #include<cfloat> #include "Point.h" #include<gl\GL.h> void afficherPoint() { glBegin(GL_POLYGON); glColor3f(1.0, 1.0, 1.0); glVertex2f(0, 0); glVertex2f(0, 1); glVertex2f(1, 1); glVertex2f(1, 0); glColor3f(0.95f, 0.207, 0.031f); srand((unsigned int)time(NULL)); float random=5.0f; float X = 0; float Y = 0; Point poly[32]; bool save_first_point = false; Point firstPoint; for (int i = 0; i < 31; i++) { random = ((float)rand() / (float)(RAND_MAX)) * 500; X = random; random = ((float)rand() / (float)(RAND_MAX)) * 500; Y = random; Point p(X, Y); if (!save_first_point) { save_first_point = true; firstPoint = p; } poly[i] = p; } poly[32] = firstPoint; glEnd(); } bool CyrusBeck(int X1, int Y1, int X2, int Y2, Point poly[], Point normal[], int nbSom) { float tinf = FLT_MIN; float tsup = FLT_MAX; float DX = X2 - X1; float DY = Y2 - Y1; float DN = 0.f; float WN = 0.f; int nbSeg = nbSom - 1; Point c; float t = 0.f; for (int i = 0; i < nbSeg; i++) { c = poly[i]; DN = DX * normal[i].x_get() + DY * normal[i].y_get(); WN = (X1 - c.x_get()) * normal[i].x_get() + (Y1 - c.x_get()) * normal[i].y_get(); if (DN == 0) { return WN >= 0; } else{ t = -WN / DN; if (DN > 0) { if (t > tinf) { tinf = t; } } else { if (t < tsup) { tsup = t; } } } } if (tinf < tsup) { if (tinf < 0 && tsup > 1) { return true; } else { if (tinf > 1 || tsup < 0) { return false; } else { if (tinf < 0) { tinf = 0.f; } else { if (tsup > 1) { tsup = 1; } } X2 = X1 + DX * tsup; Y2 = Y1 + DX * tsup; X1 = X1 + DX * tinf; Y1 = Y1 + DX * tinf; return true; } } } return false; } int main(int argc, char **argv) { glutInit(&argc, argv); // Initialisation glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB | GLUT_DEPTH); // mode d'affichage RGB, et test prafondeur glutInitWindowSize(500, 500); // dimension fentre glutInitWindowPosition(100, 100); // position coin haut gauche glutCreateWindow("Un carr dans tous ses tats"); // nom /* Repre 2D dlimitant les abscisses et les ordonnes*/ gluOrtho2D(-250.0, 250.0, -250.0, 250.0); /* Initialisation d'OpenGL */ glClearColor(0.0, 0.0, 0.0, 0.0); glColor3f(1.0, 1.0, 1.0); // couleur: blanc glPointSize(2.0); Point test[32]; Point test2[32]; CyrusBeck(5, 5, 6, 6, test, test2, 32); }
true
70fb59cd12ef9531636c660859ae31de284eb13d
C++
PandoraLS/C-Programming
/Ch09/Chrono.cpp
GB18030
6,494
3.234375
3
[ "MIT" ]
permissive
/* * @Author: seenli * @Date: 2020-09-28 14:30:55 * @LastEditors: seenli * @LastEditTime: 2021-01-06 18:47:14 * @FilePath: \Ch09\Chrono.cpp * @Description: Programming Principles and Practice Using C++ Second Edition */ #include "Chrono.h" namespace Chrono { Date::Date(int y, Month m, int d) : m_year{y}, m_month{m}, m_day{d} { if(!is_date(y, m, d)) throw std::runtime_error("Invalid Date!"); days_from_zero(); } Date default_date() { static const Date dd{2001, Month::jan, 1}; // 21Ϳʼ return dd; } Date::Date() : m_year{default_date().get_year()}, m_month{default_date().get_month()}, m_day{default_date().get_day()} { days_from_zero(); } // void Date::add_day(const int n) { if (n < 0) throw std::runtime_error("cannot add negative days!"); if (n > 0) { for (int i{1}; i <= n; ++i) { int t = m_day + 1; switch (m_month) { case Chrono::Month::feb: if (t <= (leap_year(m_year) ? 29 : 28)) { m_day = t; } else { m_month = Month::mar; m_day = 1; } break; case Chrono::Month::dec: if (t <= 31) { m_day = t; } else { m_month = Month::jan; m_day = 1; ++m_year; } break; default: if (t <= month_day.at((int)m_month - 1)) { m_day = t; } else { m_month = Month((int)m_month + 1); m_day = 1; } break; } } days_from_zero(); } } // add month will clamp to last day to the n month // ·, nµһ void Date::add_month(const int n) { if (n < 0) throw std::runtime_error("cannot add negative months!"); if (n > 0) { int months = n; int years{}; // ¼صݣ· if (n >= 12 && n != 0) { int add_months{n / 12}; // 12 óʣµ years = add_months; months -= add_months * 12; // ֮· } // ǰ+ʣµ· Ȼ1 if ((int)m_month + months > 12) { m_month = Month((int)m_month + months - 12); years += 1; } else { m_month = Month((int)m_month + months); } // ǰǸ죬µһ if(m_day > month_day.at((int)m_month - 1)) { if(m_month == Month::feb && !leap_year(m_year)) { // 2m_yearƽ m_day = 29; } m_day = month_day.at((int)m_month - 1); } days_from_zero(); add_year(years); } } // void Date::add_year(const int n) { if (n < 0) throw std::runtime_error("cannot add negative years!"); if (n > 0) { // ע if (m_month == Month::feb && m_day == 29 && !leap_year(m_year + n)) { // Ӧ229յƽ,ʱ31ƽ m_month = Month::mar; m_day = 1; } m_year += n; days_from_zero(); } } void Date::days_from_zero() { std::tm now{}; now.tm_mday = m_day; now.tm_mon = (int)m_month - 1; now.tm_year = m_year - 1900; std::time_t today = std::mktime(&now); auto n = std::chrono::system_clock::from_time_t(day_zero); auto t = std::chrono::system_clock::from_time_t(today); m_days = std::chrono::duration_cast<std::chrono::hours>(t - n).count() / 24; } // helper functions bool is_date(int y, Month m, int d) { // yearvalid if (d <= 0) return false; // dayΪ if (Month::dec < m || m < Month::jan) return false; int days_in_month{31}; // ·31 switch (m) { case Month::feb: days_in_month = (leap_year(y)) ? 29 : 28; break; case Month::apr: case Month::jun: case Month::sep: case Month::nov: days_in_month = 30; // С30 break; } if (days_in_month < d) return false; return true; } // ж, ֻҪ֮һ // 1: ܱ400 // 2ܱ4ܱ100 bool leap_year(int y) { if (!(y % 400)) { return true; } if (y % 100 && !(y % 4)) { return true; } return false; } bool operator==(const Date& a, const Date& b) { return a.m_days == b.m_days; } bool operator!=(const Date& a, const Date& b) { return !(a == b); } bool operator>(const Date& a, const Date& b) { return a.m_days > b.m_days; } bool operator<(const Date& a, const Date& b) { return a.m_days < b.m_days; } bool operator>=(const Date& a, const Date& b) { return a > b || a == b; } bool operator<=(const Date& a, const Date& b) { return a < b || a == b; } std::ostream& operator<<(std::ostream& os, const Date& d) { return os << '(' << d.m_year << ',' << (int)d.m_month << ',' << d.m_day << ')'; } std::istream& operator>>(std::istream& is, Date& dd) { int y, m, d; char ch1, ch2, ch3, ch4; is >> ch1 >> y >> ch2 >> m >> ch3 >> d >> ch4; if (!is) return is; // ʽ if (ch1 != '(' || ch2 != ',' || ch3 != ',' || ch4 != ')') { is.clear(std::ios_base::failbit); // fail bit return is; } dd.m_year = y; dd.m_month = Month(m); dd.m_day = d; return is; } Day day_of_week(const Date& d) { // good for κθ int y{d.get_year()}; int m{static_cast<int>(d.get_month())}; static const std::array<int, 12> t{0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4}; // ʲô if (d.get_month() < Month::mar) { --y; } return Day((y + y / 4 - y / 100 + y / 400 + t.at(m - 1) + d.get_day()) % 7); } Date next_sunday(const Date& d) { Date date_now{d}; Day day_now{day_of_week(d)}; date_now.add_day(7 - (int)day_now); return date_now; } Date next_weekday(const Date& d) { Date date_now{d}; date_now.add_day(1); return date_now; } Date next_workday(const Date& d) { Date nwd{d}; // Ƿĩ auto day{day_of_week(d)}; switch (day) { case Day::fri: nwd.add_day(3); break; case Day::sat: nwd.add_day(2); break; default: nwd.add_day(1); break; } return nwd; } int week_of_year(const Date& d) { Date date{d.get_year(), Month::jan, 1}; int week_number{}; while (d >= date) { date = next_sunday(date); // ȡһ if (date.get_year() == d.get_year()) { // һղı, week1 ++week_number; } else if (date.get_day() != 1) { // ٶÿܵĵһ(ϰ11) week_number = 1; } } return week_number; } } // Chrono
true
b269c03901559b215cc7e19b6622dad3ad9c4852
C++
csu-xiao-an/SolutionCode
/01 Count number of binary strings without consecutive 1/01 Count number of binary strings without consecutive 1.cpp
UTF-8
645
3.171875
3
[]
no_license
// 01 Count number of binary strings without consecutive 1.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。 // #include <iostream> using namespace std; int num = 0; int dfs(int deep, int bit, int lastbit, int n) { if (lastbit == 1 && bit == 1) { return 0; } if (deep == n) { num++; return 0; } dfs(deep + 1, 0, bit, n); dfs(deep + 1, 1, bit, n); } int dp(int n) { int* a = new int[n + 1]{ 0,2,3 }; for (int i = 3; i < n + 1; i++) { a[i] = a[i - 1] + a[i - 2]; } return a[n]; } int main() { int n = 6; cout << dp(n) << endl; dfs(1, 0, 0, n); dfs(1, 1, 0, n); cout << num << endl; }
true
859bf3bcee0ddf7143e2fe9a40bf4113394eb780
C++
1whatleytay/ares
/src/text.cpp
UTF-8
1,370
3.015625
3
[]
no_license
#include <ares/text.h> namespace ares { // bool BuilderText::stoppable(char value) { // return std::isspace(value) || (std::find(hard.begin(), hard.end(), value) != hard.end()); // } size_t BuilderText::get() { return index; } void BuilderText::set(size_t value) { index = value; } void BuilderText::push() { while (index < text.size() && std::isspace(text[index])) { index++; } } std::string BuilderText::pull(size_t size) { return text.substr(index, std::min(size, text.size() - index)); } void BuilderText::pop(size_t size) { index += size; push(); } size_t BuilderText::until(const Stoppable &stoppable) { size_t size = 0; if (stoppable(&text[index], text.size() - index)) { return 1; } while ((index + size) < text.size()) { if (stoppable(&text[index + size], text.size() - index - size)) { break; } size++; } return size; } bool BuilderText::complete(size_t size, const Stoppable &stoppable) { return (index + size >= text.size()) || stoppable(&text[index + size], text.size() - index - size); } BuilderText::BuilderText(std::string text) : text(std::move(text)) { push(); } }
true
41cdcd2641b150f9b7d76b5151db1f957ec32f8e
C++
lys8325/boj_study
/04948/main.cpp
UTF-8
794
2.953125
3
[]
no_license
#include <iostream> #include <vector> using namespace std; int main() { int n, maxNum = 0, cnt = 0; bool isPrime[250000]; vector<int> v; while(1){ cin>>n; if(n == 0){ break; }else{ if(maxNum < n){ maxNum = n; } v.push_back(n); } } maxNum *= 2; for(int i=2;i<=maxNum;++i){ isPrime[i] = true; } for(int i=2;i*i<=maxNum;++i){ if(isPrime[i]){ for(int j=i*i;j<=maxNum;j+=i){ isPrime[j] = false; } } } for(int i : v){ cnt = 0; for(int j=i+1;j<=2*i;++j){ if(isPrime[j]){ ++cnt; } } cout<<cnt<<"\n"; } return 0; }
true
c2f8c83258d696ef4b665aa403dd156450be6e69
C++
juanmard/juegocpp
/Clases/ActorGraphic.cpp
UTF-8
2,073
2.921875
3
[]
no_license
/// /// @file ActorGraphic.cpp /// @brief Fichero de implementación de la clase "ActorGraphic". /// @author Juan Manuel Rico /// @date Octubre 2015 /// @version 1.0.0 /// #include "ActorGraphic.h" #include "Actor.h" ActorGraphic::ActorGraphic (): owner(NULL), graph_free (true) { }; ActorGraphic::ActorGraphic (Actor* a): owner(a), graph_free (true) { }; ActorGraphic::~ActorGraphic () { }; void ActorGraphic::update () { }; void ActorGraphic::init () { }; void ActorGraphic::draw (BITMAP* bmp) { }; void ActorGraphic::draw (int x, int y, BITMAP* bmp) { }; unsigned int ActorGraphic::get_w () const { return 0; }; unsigned int ActorGraphic::get_h () const { return 0; }; int ActorGraphic::get_x () const { return (int)(owner->get_x()); }; int ActorGraphic::get_y () const { return (int)(owner->get_y()); }; Mask* ActorGraphic::get_mask () const { return NULL; }; ActorGraphic* ActorGraphic::clone (Actor* propietario) const { return new ActorGraphic(); }; /// @todo Agrupar los valores de posición y dimensiones en un bloque, /// para así poder imprimir directamente en el formato del bloque. std::string& ActorGraphic::print () const { std::ostringstream cadena; cadena << "Propietario: " << owner->get_nombre() << std::endl; cadena << "Posición: [" << get_x() << ", " << get_y() << "]" << std::endl; cadena << "Dimensiones: [" << get_h() << ", " << get_w() << "]" << std::endl; return *new std::string(cadena.str()); }; Actor* ActorGraphic::getActor () const { return owner; }; std::ifstream& ActorGraphic::leer (std::ifstream& ifs) { return ifs; }; std::ifstream& operator>> (std::ifstream& ifs, ActorGraphic& grafico) { return grafico.leer(ifs); }; void ActorGraphic::setOwner (Actor& propietario) { if (!owner) this->owner = &propietario; }; bool ActorGraphic::is_free () { return graph_free; }; void ActorGraphic::set_free (bool estate) { graph_free = estate; };
true
14b07e31d1a6c5f79d6ae8a5b49355f1e35265c3
C++
kuningfellow/Kuburan-CP
/yellowfellow-ac/UVA/12531/12093827_AC_0ms_0kB.cpp
UTF-8
407
2.71875
3
[]
no_license
//UVA 12531 Hours and Minutes #include <stdio.h> #include <vector> using namespace std; int lis[361]; int main() { int d; for (int i=0;i<12;i++) { for (int j=0;j<60;j++) { d=((i*30+j/12*6)-j*6+360)%360; lis[min(d,(360-d))]=1; } } while (scanf("%d",&d)!=EOF) { if (lis[d]==1)printf ("Y\n"); else printf ("N\n"); } }
true
cdc0333d4aa59e61303b98b5a12028cc815ed568
C++
assuntad23/COMP302
/WordCounts/IOFile.cpp
UTF-8
1,406
3.359375
3
[]
no_license
/* * IOFile.cpp * * Created on: Nov 12, 2017 * Author: Assunta */ #include "IOFile.h" #include <map> #include <string> #include <iostream> #include <fstream> #include <iomanip> IOFile::IOFile() { // TODO Auto-generated constructor stub } IOFile::~IOFile() { // TODO Auto-generated destructor stub } std::ifstream IOFile::OpeningForReading(){ //declaring variable to hold file name std::string userInput; //ask user for file name std::cout<<"Enter file name with .txt extension"; //inputting string into userInput std::cin>>userInput; // open the file for reading try{ std::ifstream userInputFile( userInput ); return userInputFile; } catch (const std::ifstream::failure& e) { std::runtime_error MyException( "Error opening file" ); throw( MyException ); } } void IOFile::OpeningAndWriting(std::map<std::string,int> WordCounts){ //Creating & Opening File try{ // Open a file to write the word count to std::ofstream WordCountFile( "WordCount.txt" ); // Iterate through the map and write each count for (auto elem : WordCounts){ WordCountFile << std::setw(20) << elem.first << ": " << elem.second << std::endl; } WordCountFile.close(); } catch (const std::ifstream::failure& e) { std::runtime_error MyException( "Error opening file" ); throw( MyException ); } }
true
230b1007781cb2c7db175aa231cc532eb6933fc1
C++
chenchukun/UNP
/snf/example/handle/sockHandle.cpp
UTF-8
896
2.6875
3
[]
no_license
#include "SockHandle.h" #include <time.h> #include <assert.h> #include <iostream> using namespace snf; using namespace std; int main() { SockHandle sockHandle; assert(sockHandle.open(AF_INET, SOCK_STREAM)==0); int val; assert(sockHandle.getOption(SOL_SOCKET, SO_RCVBUF, val)==0); cout << val << endl; assert(sockHandle.setOption(SOL_SOCKET, SO_RCVBUF, val)==0); // 至少是MSS值的4倍, 设置的真实值是val的两倍? assert(sockHandle.getOption(SOL_SOCKET, SO_RCVBUF, val)==0); cout << val << endl; struct timeval tval = {1, 1}; assert(sockHandle.getOption(SOL_SOCKET, SO_RCVTIMEO, tval)==0); cout << tval.tv_sec << "." << tval.tv_usec<< endl; tval.tv_sec = tval.tv_usec = 100; assert(sockHandle.setOption(SOL_SOCKET, SO_RCVTIMEO, tval)==0); assert(sockHandle.getOption(SOL_SOCKET, SO_RCVTIMEO, tval)==0); cout << tval.tv_sec << "." << tval.tv_usec<< endl; return 0; }
true
6b757a41cc47cfa6f70733d71251e80fc99b4a67
C++
SamuelLouisCampbell/chili_framework-1
/Engine/Keyboard.cpp
UTF-8
3,862
2.53125
3
[]
no_license
/****************************************************************************************** * Chili DirectX Framework Version 16.07.20 * * Keyboard.cpp * * Copyright 2016 PlanetChili.net <http://www.planetchili.net> * * * * This file is part of The Chili DirectX Framework. * * * * The Chili DirectX Framework is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * The Chili DirectX Framework is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with The Chili DirectX Framework. If not, see <http://www.gnu.org/licenses/>. * ******************************************************************************************/ #include "Keyboard.h" template<typename Task> struct do_final { do_final() = delete; do_final( const do_final& ) = delete; do_final( do_final&& ) = delete; do_final& operator=( const do_final& )=delete; do_final& operator=(do_final&&)=delete; do_final( Task&& _task )noexcept : m_task( _task ) {} ~do_final() { m_task(); } Task m_task; }; bool Keyboard::KeyIsPressed( unsigned char keycode ) const noexcept { return keystates[keycode]; } std::optional<Keyboard::Event> Keyboard::ReadKey()noexcept { do_final task( [ this ]() { if( !keybuffer.empty() ) { keybuffer.pop(); } } ); return (!keybuffer.empty())? std::optional<Keyboard::Event>{keybuffer.front()}: std::optional<Keyboard::Event>{}; } std::optional<char> Keyboard::ReadChar()noexcept { do_final task( [ this ]() {if( !charbuffer.empty() ) { charbuffer.pop(); } } ); return ( !charbuffer.empty() ) ? std::optional<char>{ charbuffer.front() } : std::optional<char>{ std::nullopt }; } void Keyboard::FlushKey()noexcept { keybuffer = std::queue<Event>(); } void Keyboard::FlushChar()noexcept { charbuffer = std::queue<char>(); } void Keyboard::Flush()noexcept { FlushKey(); FlushChar(); } void Keyboard::EnableAutorepeat()noexcept { autorepeatEnabled = true; } void Keyboard::DisableAutorepeat()noexcept { autorepeatEnabled = false; } bool Keyboard::AutorepeatIsEnabled() const noexcept { return autorepeatEnabled; } void Keyboard::OnKeyPressed( unsigned char keycode ) { keystates[ keycode ] = true; keybuffer.push( Keyboard::Event( Keyboard::Event::Type::Press,keycode ) ); TrimBuffer( keybuffer ); } void Keyboard::OnKeyReleased( unsigned char keycode ) { keystates[ keycode ] = false; keybuffer.push( Keyboard::Event( Keyboard::Event::Type::Release,keycode ) ); TrimBuffer( keybuffer ); } void Keyboard::OnChar( char character )noexcept { charbuffer.push( character ); TrimBuffer( charbuffer ); } template<typename T> void Keyboard::TrimBuffer( std::queue<T>& buffer )noexcept { while( buffer.size() > bufferSize ) { buffer.pop(); } } Keyboard::Event::Event() noexcept : type( Type::Invalid ), code( 0u ) {} Keyboard::Event::Event( Type type, unsigned char code ) noexcept : type( type ), code( code ) {} bool Keyboard::Event::IsPress()const noexcept { return type == Type::Press; } bool Keyboard::Event::IsRelease() const noexcept { return type == Type::Release; } bool Keyboard::Event::IsValid() const noexcept { return type != Type::Invalid; } unsigned char Keyboard::Event::GetCode() const noexcept { return code; }
true
007be97045ea08e6e5bbd73b701223a575702db9
C++
bobsira/Cpp
/chapter3/question2.cpp
UTF-8
290
3.046875
3
[]
no_license
#include<iostream> int main(int argc, char const *argv[]) { int number_one, number_two; std::cout << "Enter number one" << '\n'; std::cin >> number_one; std::cout << "Enter number two" << '\n'; std::cin >> number_two; std::cout << number_one + number_two << '\n'; return 0; }
true
a07d0fb483663365fca1485b78d598b11b949761
C++
srivathsanmurali/MLearn
/NeuralNets/CommonImpl.h
UTF-8
1,309
2.75
3
[ "MIT" ]
permissive
#ifndef MLEARN_COMMON_NEURAL_NETS_FUNCS_H_FILE #define MLEARN_COMMON_NEURAL_NETS_FUNCS_H_FILE // MLearn includes #include <MLearn/Core> #include "ActivationFunction.h" namespace MLearn{ namespace NeuralNets{ namespace InternalImpl{ /*! * \brief Helper class for efficient computation of derivatives * \details If the logistic activation is used, the specialization is called, allowing for efficient computations */ template < ActivationType TYPE > struct DerivativeWrapper{ template < typename WeightType > static inline void derive( Eigen::Ref< const MLVector< WeightType > > pre_activations, Eigen::Ref< const MLVector< WeightType > > activations, Eigen::Ref< MLVector< WeightType > > derivatives ){ derivatives = pre_activations.unaryExpr(std::pointer_to_unary_function<WeightType,WeightType>(ActivationFunction<TYPE>::first_derivative)); } }; template <> struct DerivativeWrapper< ActivationType::LOGISTIC >{ template < typename WeightType > static inline void derive( Eigen::Ref< const MLVector< WeightType > > pre_activations, Eigen::Ref< const MLVector< WeightType > > activations, Eigen::Ref< MLVector< WeightType > > derivatives ){ derivatives = activations - activations.cwiseProduct(activations); } }; } } } #endif
true
9f944e0a6730b6d2d4b0ab9a498a0e57fc67f2d9
C++
kuningfellow/Kuburan-CP
/yellowfellow-ac/UVA/722/11896124_AC_0ms_0kB.cpp
UTF-8
1,272
2.609375
3
[]
no_license
//UVA 722 Lakes #include <stdio.h> #include <iostream> #include <string.h> using namespace std; char ar[101][101]; int dim=0; int sid; int dfs(int x, int y) { int ret=0; if (ar[x][y]=='0') { ret++; ar[x][y]='1'; } else if (ar[x][y]!='0') { return 0; } if (x+1<dim)ret+=dfs(x+1,y); if (y+1<sid)ret+=dfs(x,y+1); if (x-1>=0)ret+=dfs(x-1,y); if (y-1>=0)ret+=dfs(x,y-1); return ret; } int main() { int tc; cin>>tc; while (tc--) { char num[60]; num[0]='\0'; while (strlen(num)==0) { scanf("%[^\n]s",num); getchar(); } int i,j; i=(num[0]-'0')*10+num[1]-'0'; j=(num[3]-'0')*10+num[4]-'0'; char temp[101]; temp[0]='\0'; int first=1; dim=0; while (first==1||strlen(temp)!=0) { temp[0]='\0'; scanf("%[^\n]s",temp); getchar(); if (strlen(temp)==0&&first==0)break; if (strlen(temp)!=0) { sid=strlen(temp); strcpy(ar[dim++],temp); first=0; } } printf ("%d\n",dfs(i-1,j-1)); if (tc>0)printf ("\n"); } }
true
2d431b7b070bedde363a4ed4f02a64dd484eab30
C++
jetming/LibEBC
/lib/include/ebc/EmbeddedFile.h
UTF-8
1,267
2.96875
3
[ "Apache-2.0" ]
permissive
#pragma once #include <string> #include <vector> namespace ebc { class EmbeddedFile { public: enum class Type { Bitcode, Exports, File, LTO, Object, Xar, }; enum class CommandSource { Clang, Swift, }; EmbeddedFile(std::string name); virtual ~EmbeddedFile() = default; std::string GetName() const; /// Get all commands passed to the compiler to create this embedded file. /// /// @return A vector of strings with the clang front-end commands. const std::vector<std::string>& GetCommands() const; /// Set all commands passed to the compiler to create this embedded file. /// /// @param commands A vector of strings with the clang front-end /// commands. void SetCommands(const std::vector<std::string>& commands, CommandSource source); /// Remove the underlying file from the file system. void Remove() const; Type GetType() const; CommandSource GetCommandSource() const; protected: EmbeddedFile(std::string name, Type type); private: std::string _name; Type _type; std::vector<std::string> _commands; CommandSource _commandSource; }; inline bool operator==(const EmbeddedFile& lhs, const EmbeddedFile& rhs) { return lhs.GetName() == rhs.GetName(); } }
true
a5bf7a3db7aea25746761960b048a0a454058d76
C++
yosef8234/test
/spbstu_cpp/05_Arrays_v3/05smpl/Systems/Main.cpp
WINDOWS-1251
1,532
3.171875
3
[]
no_license
#include <iostream> #include <locale.h> using namespace std; int main(void) { setlocale(LC_ALL, "Russian"); cout<<" p- 10-"<<endl; int p; do { cout<<" p (2...36): "; cin>>p; } while (p<2 || p>36); const int MAX_LEN = 30; // cout<<" ( "<<MAX_LEN<<" ): "; char x[MAX_LEN+1]; // cin.getline(x, 1, '\n'); // cin.getline(x, MAX_LEN+1, '\n'); int n=0; // 10- for (int i=0; x[i]!=0; i++) // - { n *= p; int d=-1; // if (x[i]>='0' && x[i]<='9') d=x[i]-'0'; // '0'...'9' => 0...9 else if (x[i]>='a' && x[i]<='z') d=10+x[i]-'a'; // 'a'...'z' => 10...35 else if (x[i]>='A' && x[i]<='Z') d=10+x[i]-'A'; // 'A'...'Z' => 10...35 if (d<0 || d>=p) // { cout<<" "<<x[i]<<" "<<endl; return 0; } n += d; } cout<<" : "<<n<<endl; return 0; }
true
0b6cae64187f2db122f19721094c518ff310bd4c
C++
JJavier98/Support
/1º/MP/examenesResueltos/septiembre2013/sep2013ej1/src/entero.cpp
UTF-8
470
3.359375
3
[]
no_license
#include "entero.h" using namespace std; Entero::Entero(const Entero &otro){ v=new int; *v=*(otro.v); } Entero & Entero::operator*(int valor) const { Entero *resultado=new Entero(*(this->v)*valor); return *resultado; } const Entero & Entero::operator=(const Entero &otro){ delete v; v=new int; *v=*(otro.v); return *this; } ostream & operator<<(ostream & flujo, const Entero &objeto){ flujo << *(objeto.v) << endl; return flujo; }
true
36e12fed452ced5e0ae1a2ed140dab1c1938e85a
C++
brianhang/justintime
/JustinTime/stage/stage.h
UTF-8
413
2.609375
3
[]
no_license
#pragma once #include <SFML/Graphics.hpp> class Stage { public: virtual ~Stage() { }; // Called to update the stage each frame. virtual void update(float deltaTime) = 0; // Called to draw the stage for the frame. virtual void draw(sf::RenderWindow &window) = 0; // Called when an event was received. virtual void onEvent(const sf::Event &e) = 0; };
true
a1c03f898cf005654410e0682e9c68c57e50fa06
C++
xijun/cppa
/src/main.cc
UTF-8
10,421
3.1875
3
[]
no_license
#include <boost/container/flat_map.hpp> #include <chrono> #include "polynomial.hh" int main() { using clock = std::chrono::steady_clock; /* ******************************************** Label and Weight tests ******************************************/ std::cout << std::boolalpha << "\033[33m" << "\n\t****** Label tests ******\n" << "\033[0m" << std::endl; /* int labels tests */ std::cout << "\n\033[4m" << "Int labels:\n\n" << "\033[0m"; Label<int> label(2); /* test << */ std::cout << "\tprint test, label = " << label << std::endl; Label<int> label2(3); Label<int> int_label_test = label + label2; /* test + */ std::cout << "\t" << label << " + " << label2 << " = " << int_label_test << (int_label_test.get_label() == label.get_label() + label2.get_label() ? "\033[32m [OK]" : "\033[31m [KO]") << "\033[0m" << std::endl; /* test < */ std::cout << "\t" << label << " < " << label2 << " = " << (label < label2) << ((label.get_label() < label2.get_label()) == (label < label2) ? "\033[32m [OK]" : "\033[31m [KO]") << "\033[0m" << std::endl; std::cout << "\t" << label2 << " < " << label << " = " << (label2 < label) << ((label2.get_label() < label.get_label()) == (label2 < label) ? "\033[32m [OK]" : "\033[31m [KO]") << "\033[0m" << std::endl; /* test == */ Label<int> label1(2); std::cout << "\t" << label << " == " << label1 << " ? " << (label == label1) << ((label.get_label() == label1.get_label()) == (label == label1) ? "\033[32m [OK]" : "\033[31m [KO]") << "\033[0m" << std::endl; std::cout << "\t" << label << " == " << label2 << " ? " << (label == label2) << ((label.get_label() == label2.get_label()) == (label == label2) ? "\033[32m [OK]" : "\033[31m [KO]") << "\033[0m" << std::endl; /* string labels tests */ std::cout << "\n\033[4m" <<"String labels:\n\n" << "\033[0m"; Label<std::string> label3("xx"); /* test << */ std::cout << "\tprint test, label = \'" << label3 << "\'" << std::endl; Label<std::string> label4("y"); Label<std::string> str_label_test = label3 + label4; /* test + */ std::cout << "\t\'" << label3 << "\' + \'" << label4 << "\' = \'" << str_label_test << "\'" << (str_label_test.get_label() == label3.get_label() + label4.get_label() ? "\033[32m [OK]" : "\033[31m [KO]") << "\033[0m" << std::endl; /* test < */ unsigned long label3_size = label3.get_label().size(); unsigned long label4_size = label4.get_label().size(); std::cout << "\t" << label3 << " < " << label4 << " = " << (label3 < label4) << ((label3_size < label4_size || (label3_size == label4_size && label3.get_label() < label4.get_label())) == (label3 < label4) ? "\033[32m [OK]" : "\033[31m [KO]") << "\033[0m" << std::endl; std::cout << "\t" << label4 << " < " << label3 << " = " << (label4 < label3) << ((label4_size < label3_size || (label4_size == label3_size && label4.get_label() < label3.get_label())) == (label4 < label3)? "\033[32m [OK]" : "\033[31m [KO]") << "\033[0m" << std::endl; /* test == */ Label<std::string> label5("xx"); std::cout << "\t" << label3 << " == " << label4 << " ? " << (label3 == label4) << ((label3.get_label() == label4.get_label()) == (label3 == label4) ? "\033[32m [OK]" : "\033[31m [KO]") << "\033[0m" << std::endl; std::cout << "\t" << label3 << " == " << label5 << " ? " << (label3 == label5) << ((label3.get_label() == label5.get_label()) == (label3 == label5) ? "\033[32m [OK]" : "\033[31m [KO]") << "\033[0m" << std::endl; std::cout << "\033[33m" << "\n\t****** Weight tests ******\n" << "\033[0m" << std::endl; /* int weights tests */ std::cout << "\n\033[4m" <<"Int weights:\n\n" << "\033[0m"; Weight<int> weight(15); /* test << */ std::cout << "\tprint test, weight = " << weight << std::endl; Weight<int> weight2(12); Weight<int> int_weight_test = weight + weight2; /* test + */ std::cout << "\t" << weight << " + " << weight2 << " = " << int_weight_test << (int_weight_test.get_label() == weight.get_label() + weight2.get_label() ? "\033[32m [OK]" : "\033[31m [KO]") << "\033[0m" << std::endl; /* test < */ std::cout << "\t" << weight << " < " << weight2 << " = " << (weight < weight2) << ((weight.get_label() < weight2.get_label()) == (weight < weight2) ? "\033[32m [OK]" : "\033[31m [KO]") << "\033[0m" << std::endl; std::cout << "\t" << weight2 << " < " << weight << " = " << (weight2 < weight) << ((weight2.get_label() < weight.get_label()) == (weight2 < weight) ? "\033[32m [OK]" : "\033[31m [KO]") << "\033[0m" << std::endl; /* test == */ Weight<int> weight1(15); std::cout << "\t" << weight << " == " << weight1 << " ? " << (weight == weight1) << ((weight.get_label() == weight1.get_label()) == (weight == weight1) ? "\033[32m [OK]" : "\033[31m [KO]") << "\033[0m" << std::endl; std::cout << "\t" << weight << " == " << weight2 << " ? " << (weight == weight2) << ((weight.get_label() == weight2.get_label()) == (weight == weight2) ? "\033[32m [OK]" : "\033[31m [KO]") << "\033[0m" << std::endl; /* test * */ std::cout << "\t" << weight << " * " << weight2 << " = " << weight * weight2 << (weight * weight2 == weight.get_label() * weight2.get_label() ? "\033[32m [OK]" : "\033[31m [KO]") << "\033[0m" << std::endl; /* bool weights tests */ std::cout << "\n\033[4m" <<"Bool weights:\n\n" << "\033[0m"; Weight<bool> weight3(false); /* test << */ std::cout << "\tprint test, weight = " << weight3 << std::endl; Weight<bool> weight4(true); Weight<bool> bool_weight_test = weight3 + weight4; /* test + */ std::cout << "\t" << weight3 << " + " << weight4 << " = " << bool_weight_test << (bool_weight_test.get_label() == weight3.get_label() + weight4.get_label() ? "\033[32m [OK]" : "\033[31m [KO]") << "\033[0m" << std::endl; /* test < */ std::cout << "\t" << weight3 << " < " << weight4 << " = " << (weight3 < weight4) << ((weight3.get_label() < weight4.get_label()) == (weight3 < weight4) ? "\033[32m [OK]" : "\033[31m [KO]") << "\033[0m" << std::endl; std::cout << "\t" << weight4 << " < " << weight3 << " = " << (weight4 < weight3) << ((weight4.get_label() < weight3.get_label()) == (weight4 < weight3) ? "\033[32m [OK]" : "\033[31m [KO]") << "\033[0m" << std::endl; /* test == */ Weight<bool> weight5(true); std::cout << "\t" << weight4 << " == " << weight5 << " ? " << (weight4 == weight5) << ((weight4.get_label() == weight5.get_label()) == (weight4 == weight5) ? "\033[32m [OK]" : "\033[31m [KO]") << "\033[0m" << std::endl; std::cout << "\t" << weight3 << " == " << weight4 << " ? " << (weight3 == weight4) << ((weight3.get_label() == weight4.get_label()) == (weight3 == weight4) ? "\033[32m [OK]" : "\033[31m [KO]") << "\033[0m" << std::endl; /* test * */ std::cout << "\t" << weight3 << " * " << weight4 << " = " << weight3 * weight4 << (weight3 * weight4 == weight3.get_label() * weight4.get_label() ? "\033[32m [OK]" : "\033[31m [KO]") << "\033[0m" << std::endl; std::cout << "\t" << weight5 << " * " << weight4 << " = " << weight5 * weight4 << (weight5 * weight4 == weight5.get_label() * weight4.get_label() ? "\033[32m [OK]" : "\033[31m [KO]") << "\033[0m" << std::endl; /* ******************************************** BENCHMARK ******************************************/ std::chrono::duration<double, std::nano> d; std::cout << std::boolalpha << "\033[33m" << "\n\t****** THE REAL STUFF ******\n" << "\033[0m" << std::endl; /* Ordered vector */ std::cout << "\n\033[4m" <<"Ordered vector:\n\n" << "\033[0m"; Label<std::string> l("x"); Label<std::string> l2("y"); Label<std::string> l3("z"); Label<std::string> l4("xy"); Weight<int> w5(2); Weight<int> w6(3); Weight<int> w7(4); Weight<std::string> w8("toto"); auto poly = new Polynomial<std::string, int, std::vector, std::pair<Label<std::string>, Weight<int>>>(); poly->add_monomial(l, w5); poly->add_monomial(l2, w6); poly->add_monomial(l3, w7); std::cout << "\tp1 = " << *poly << std::endl; auto p = new Polynomial<std::string, int, std::vector, std::pair<Label<std::string>, Weight<int>>>(); p->add_monomial(l, w5); p->add_monomial(l2, w6); p->add_monomial(l3, w7); std::cout << "\tp2 = " << *p << std::endl; clock::time_point p1_addition_start = clock::now(); *poly = *poly + *p; clock::time_point p1_addition_end = clock::now(); std::cout << "\tp1 += p2 = " << *poly << std::endl; clock::time_point p1_multi_start = clock::now(); *poly = *poly * *p; clock::time_point p1_multi_end = clock::now(); std::cout << "\tp1 *= p2 = " << *poly << std::endl; /* flat_map */ std::cout << "\n\033[4m" <<"Flat map:\n\n" << "\033[0m"; auto p2 = new Polynomial<std::string, int, boost::container::flat_map, Label<std::string>, Weight<int>, myless<Label<std::string>>>(); p2->add_monomial(l, w5); p2->add_monomial(l2, w6); p2->add_monomial(l3, w7); std::cout << "\tp3 = " << *p2 << std::endl; auto p3 = new Polynomial<std::string, int, boost::container::flat_map, Label<std::string>, Weight<int>, myless<Label<std::string>>>(); p3->add_monomial(l, w5); p3->add_monomial(l2, w6); p3->add_monomial(l3, w7); std::cout << "\tp4 = " << *p3 << std::endl; clock::time_point p2_addition_start = clock::now(); *p2 = *p2 + *p3; clock::time_point p2_addition_end = clock::now(); std::cout << "\tp3 += p4 = " << *p2 << std::endl; clock::time_point p2_multi_start = clock::now(); *p2 = *p2 * *p3; clock::time_point p2_multi_end = clock::now(); std::cout << "\tp3 *= p4 = " << *p2 << std::endl; d = p1_addition_end - p1_addition_start; double p1_addition = d.count(); d = p1_multi_end - p1_multi_start; double p1_multi = d.count(); d = p2_addition_end - p2_addition_start; double p2_addition = d.count(); d = p2_multi_end - p2_multi_start; double p2_multi = d.count(); std::cout << "\n\033[4m" <<"Addition:" << "\033[0m" << " Ordered vector:" << p1_addition << " ns" << std::endl; std::cout << "\t\tFlat_map:" << p2_addition << " ns" << std::endl; std::cout << "\n\033[4m" <<"Multi:" << "\033[0m" << " Ordered vector:" << p1_multi << " ns" << std::endl; std::cout << "\t\tFlat_map:" << p2_multi << " ns" << std::endl; }
true
803f13f005dafb6044747be074174ab8c632d776
C++
king-yyf/poj-
/categery/math/bigInteger.cpp
UTF-8
1,759
2.84375
3
[]
no_license
// // main.cpp // bigint // // Created by Yang Yunfei on 2017/5/25. // Copyright © 2017年 Yang Yunfei. All rights reserved. // #include<cstdio> #include<cstring> using namespace std; struct BigInteger{ int digit[1000]; int size; void init(){ size = 0; memset(digit,0,sizeof(digit)); } void save(char str[]){ init(); int len = strlen(str); int weigh = 1,cur = 0, cnt = 0; for(int i = len - 1; i > -1; --i){ cur += (str[i] - '0') * weigh; //tmp += cur; cnt++; weigh *= 10; if(cnt == 4 || i == 0){ digit[size++] = cur; cnt = cur = 0; weigh = 1; } } } void output(){ printf("%d",digit[size - 1]); for(int i = size - 2; i >= 0; --i){ printf("%04d",digit[i]); } printf("\n"); } BigInteger operator + (const BigInteger & other) const { BigInteger * ret = new BigInteger(); ret->init(); int carry = 0; for(int i = 0; i < other.size || i < size; ++i){ int tmp = other.digit[i] + digit[i] + carry; carry = tmp / 10000; tmp %= 10000; ret->digit[ret->size ++] = tmp; } if(carry){ ret->digit[ret->size++] = carry; } return *ret; } }var1, var2, sum; char str1[1002], str2[1002]; int main(){ printf("main\n"); while(scanf("%s%s",str1,str2) != EOF){ // printf("%s\n",str1); // printf("%s\n",str2); var1.save(str1); //var1.output(); var2.save(str2); // var2.output(); sum = var1 + var2; sum.output(); } return 0; }
true
305eac50d4f656c631e899b9c40dfc8775b1d31c
C++
bhaskarraksabh/projectEuler
/projectEuler/Su Doku/main.cpp
UTF-8
4,183
2.984375
3
[]
no_license
//मनुष्य होना मेरा भाग्य लेकिन //हिन्दू होना मेरा सौभाग्य है..!! //"रामसेतू" और अयोध्या में "मन्दिर" उस समय से है..!! //जब इस धरती पर न जीजस थे, //और न ही इस्लाम का कोई अस्तित्व था..!! //जय श्री राम //everything could depending on what you do today #include <algorithm> #include <bitset> #include <cmath> #include <complex> #include <cstdio> #include <cstdlib> #include <cstring> #include <deque> #include <functional> #include <iomanip> #include <iostream> #include <iterator> #include <limits> #include <list> #include <map> #include <numeric> #include <queue> #include <set> #include <sstream> #include <stack> #include <string> #include <unordered_map> #include <unordered_set> #include <vector> #define em emplace_back #define mp make_pair using namespace std; class solution { int n; vector<vector<int>>input; public: solution () { input.resize(9,vector<int>(9,0)); } bool checkEven(long long num) { if(!(num&1)) return false; else return true; } inline int mod(int a, int b) { int ret = a%b; return ret>=0? ret: ret+b; } template<typename T> int getLength(T &input) { return input.size(); } template<typename T,typename Q> void swap(T &a,Q &b) { a=a^b; b=a^b; a=a^b; } template<typename T> void display(vector<T>input) { for(auto i:input) cout<<i<<" "; cout<<endl; } template<typename T> void display2D(vector<vector<T>>input) { for(auto i:input) { for(auto j:i) { cout<<j<<" "; } cout<<endl; } } template<typename T> void displayPair(vector<pair<T,T>>input) { for(auto i:input) cout<<i.first<<" "<<i.second<<endl; } void takeInput() { for(int i=0;i<9;i+=1) { string str; cin>>str; for(int j=0;j<str.size();j+=1) input[i][j]=str[j]-'0'; } //display2D(input); } void solve() { findAns(0,0); } bool issafe(int row,int col,int num) { for(int i=0;i<9;i+=1) { if(input[row][i]==num) return false; } for(int i=0;i<9;i+=1) { if(input[i][col]==num) return false; } int r=3*(row/3); int c=3*(col/3); for(int i=r;i<r+3;i+=1) { for(int j=c;j<c+3;j+=1) { if(input[i][j]==num) return false; } } return true; } bool findAns(int row,int col) { if(row>=9) { display2D(input); return true; } if(col>=9) { col=0; row+=1; } if(row>=9) { display2D(input); return true; } if(input[row][col]==0) { for(int i=1;i<=9;i+=1) { if(issafe(row,col,i)) { input[row][col]=i; if(findAns(row,col+1)) return true; input[row][col]=0; } } } else { if(findAns(row,col+1)) return true; } return false; } string getAns() { string str; str+=to_string(input[0][0]); str+=to_string(input[0][1]); str+=to_string(input[0][2]); return str; } }; int main() { string str; long long sum=0; while(cin>>str && !cin.eof()) { solution sc; cin>>str; sc.takeInput(); sc.solve(); string ans=sc.getAns(); sum+=stoi(ans); } cout<<sum<<endl; return 0; }
true
dfe3a77b5d2c5a3137f3ad075a762b5509084595
C++
risenjesus/MicroPrograms
/Failed-Programs/Failed-Cookie-Clicker.cpp
UTF-8
1,416
3.234375
3
[]
no_license
#include <iostream> using namespace std; int points; bool start; string input; int clickercounter; bool startclickercounter; int main() { start = true; cout << "-------------------------------------" << endl; cout << "| Hello! Welcome to Cookie Clicker! |" << endl; cout << "-------------------------------------" << endl; // -- Controls cout << "|------------------------------------|" << endl; cout << "|- Available Options: -|" << endl; cout << "|------------------------------------|" << endl; cout << "| Type 'P' to see your points. |" << endl; cout << "| Type 'buy Clicker' to buy the clicker|" << endl; cout << "|------------------------------------|" << endl; while (start == true){ cin >> input; if(input == "P"){ cout << "Your points are: " << points << endl; } if(input == "buy Clicker"){ clickercounter = true; startclickercounter = true; if (clickercounter == true){ while(clickercounter != 5){ points = points +1; clickercounter = 0; } while(startclickercounter == true){ clickercounter = clickercounter + 1; } } } if(input == ""){ } if(input == ""){ } } return 0; }
true
7f7d0845040d9218a582286dca7e80ef4e61e90f
C++
JPereira1330/Banco
/BancoServidor/BancoDB.cpp
UTF-8
2,042
2.765625
3
[]
no_license
/* * File: BancoDB.cpp * Author: nyex * * Created on 14 de julho de 2019, 20:40 */ #include <iostream> #include <stdio.h> #include <stdlib.h> #include <cstdio> #include "BancoDB.h" #include "Conta.h" #define DIR_BANCO "banco.db" BancoDB::BancoDB() { } BancoDB::BancoDB(const BancoDB& orig) { } BancoDB::~BancoDB() { for (list<Conta *>::iterator it = this->contas.begin(); it != this->contas.end(); ++it) { delete(*it); } } void BancoDB::add(Conta* conta) { this->contas.push_back(conta); } int BancoDB::saveFile() { DBCONTA dbconta; FILE *fp; fp = fopen(DIR_BANCO, "w"); if (!fp) { return 0; } for (list<Conta *>::iterator it = this->contas.begin(); it != this->contas.end(); ++it) { dbconta.numero_conta = (*it)->getNumeroConta(); dbconta.saldo_conta = (*it)->getSaldoDisponivel(); snprintf(dbconta.nome_dono, sizeof(dbconta.nome_dono), "%s", (*it)->getTitularConta().c_str()); fwrite(&dbconta,1,sizeof(DBCONTA), fp); } fclose(fp); return 1; } int BancoDB::loadFile() { DBCONTA dbconta; FILE *fp; fp = fopen(DIR_BANCO, "r"); int lenFile, totalContas; Conta *conta; if(contas.size()){ return 0; } if(!fp){ return 0; } fseek(fp, 0L, SEEK_END); lenFile = ftell(fp); rewind(fp); totalContas = lenFile / sizeof(DBCONTA); for(int i = 0; i < totalContas; i++){ fread(&dbconta,1,sizeof(DBCONTA), fp); conta = new Conta(); conta->setTitularConta(string(dbconta.nome_dono)); conta->setNumeroConta(dbconta.numero_conta); conta->setSaldoDisponivel(dbconta.saldo_conta); this->add(conta); } return 1; } Conta* BancoDB::searchFile(int numeroConta) { for (list<Conta *>::iterator it = this->contas.begin(); it != this->contas.end(); ++it) { if( (*it)->getNumeroConta() == numeroConta ){ return *it; } } return NULL; }
true
dde47a60338c81bf5773548fbcdb009e8213e274
C++
alien111/oop_exercise_06
/Source.cpp
UTF-8
3,073
3.515625
4
[]
no_license
#include <iostream> #include <map> #include <string> #include <algorithm> #include <tuple> #include <list> #include "rectangle.h" #include "Stack.h" #include "Allocator.h" #include "Vector.h" #include "Allocator.h" #include <map> void menu() { std::cout << "0 : EXIT\n"; std::cout << "1 : FILL THE VECTOR\n"; std::cout << "2 : GET ITEM CENTER BY INDEX\n"; std::cout << "3 : GET AMOUNT OF OBJECTS WITH SQUARE LESS THAN...\n"; std::cout << "4 : GO THROUGH VECTOR WITH ITERATOR AND SHOW EVERY STEP\n"; std::cout << "5 : CHANGE OBJECT BY INDEX\n"; std::cout << "6 : RESIZE VECTOR\n"; std::cout << "> "; } int main() { std::map<int,int,std::less<>, Allocators::Allocator<int,100000>> m; for (int i = 0; i < 10; ++i) { m[i] = i * i; } m.erase(1); m.erase(2); int cmd; std::cout << "Enter size of your vector : "; size_t size; std::cin >> size; Containers::Vector< rectangle< int >, Allocators::Allocator< rectangle< int >, 1000 > > vec; vec.Resize(size); while(true) { menu(); std::cin >> cmd; if (cmd == 0) return 0; else if (cmd == 1) { for (int i = 0; i < vec.Size(); i++) { std::cout << "Element number " << i << '\n'; std::cout << "Enter vertices : \n"; rectangle<int> rect(std::cin); vec[i] = rect; } } else if (cmd == 2) { std::cout << "Enter index : "; int index; std::cin >> index; std::cout << vec[index].center(); } else if (cmd == 3) { int res = 0; std::cout << "Enter your square : "; double square; std::cin >> square; int cmdcmd; std::cout << "Do you want to use std::count_if? : 1 - yes; 0 - no; : "; std::cin >> cmdcmd; if (cmdcmd == 1) res = std::count_if(vec.begin(), vec.end(), [&square](rectangle<int>& i) {return i.area() < square;}); else { auto it = vec.begin(); auto end = vec.end(); while (it != end) { if ((*it).area() < square) res++; ++it; } } std::cout << "Amount is " << res << '\n'; } else if (cmd == 4) { int cmdcmd; std::cout << "Do you want to use std::for_each? : 1 - yes; 0 - no; : "; std::cin >> cmdcmd; if (cmdcmd == 1) std::for_each(vec.begin(), vec.end(), [](rectangle<int>& i) -> void{i.print();}); else { auto it = vec.begin(); auto end = vec.end(); int n = 0; while (it != end) { std::cout << "___OBJECT_" << n << "__\n"; std::cout << *it; ++it; n++; } } } else if (cmd == 5) { int index; std::cout << "Enter index : "; std::cin >> index; if (index < 0 || index >= vec.Size()) { std::cout << "Out of range.\n"; } else { std::cout << "Enter vertices : \n"; rectangle<int> rect(std::cin); vec[index] = rect; } } else if (cmd == 6) { int size; std::cin >> size; if (size < 0) { std::cout << "Can't resize to non positive numbers.\n"; } else { vec.Resize(size); } } } }
true
cd795cbaea9492c26792b768a7441316866627b3
C++
porzell/Duke-Spookem-3D
/src/Monster.h
UTF-8
1,795
2.5625
3
[]
no_license
#pragma once #ifndef _MONSTER_H #define _MONSTER_H #include "Entity.h" #include "Timer.h" #include "SoundEngine.h" enum MONSTER_TYPE { NO_MONSTER, MINOTAUR_MONSTER, SWAMP_MONSTER, ZOMBIE_MONSTER, NAZI_MONSTER, HITLER_BOSS, CYBORG_MONSTER, MAX_MONSTER }; class Monster : public Entity { //static Timer shotTimer; protected: bool mIsStunned; bool mIsAlerted; bool mIsFleeing; bool mIsDying; Timer mDeathTimer; float mRotation; Vec3d playerPos; Timer mFreezeTimer; MONSTER_TYPE mMonsterType; Vec3d mVelocity; Sound *mVoice; public: Monster(Vec3d pos); virtual ~Monster(); //Check if the monster is dying. inline bool isDying() { return mIsDying; } virtual void collide(Entity* other); virtual void think(const double elapsedTime); virtual void draw(); virtual void kill(); virtual void setFrozen(bool frozen); virtual void spawnGib(float velocity); virtual void addAttachment(Entity *attachment); virtual void shutUp(); virtual void stun(Vec3d velocity); virtual void makeMonsterNoise(bool priority = false); virtual bool isSpeaking() { if(mVoice) return !mVoice->isFinished(); else return false; } virtual void speak(std::string *soundFile, bool shouldInterrupt = false); virtual void speak(std::string soundFile, bool shouldInterrupt = false); virtual void removeAttachment(Entity *toBeRemoved); virtual void removeAttachment(std::string index); virtual void takeDamage(float hp = 0); virtual std::string getSoundFireScream(); virtual std::string getAttackSound() { return "sound/minotaur/minotaur.ogg"; } virtual void attack(); inline MONSTER_TYPE Monster::getMonsterType() { return mMonsterType; } }; #endif
true
eb4a296cab40499cc896cee489b793524142958e
C++
ak188269/placement_preparation
/reverse_array.cpp
UTF-8
529
3.65625
4
[]
no_license
#include <bits/stdc++.h> using namespace std; // reversing an aray void reverse(int arr[], int n) { for (int i = 0; i < n / 2; ++i) swap(arr[i], arr[n - 1 - i]); } int32_t main() { int size; //taking size of matrix form user cin >> size; int arr[size]; //taking array as input for (int i = 0; i < size; ++i) { cin >> arr[i]; } reverse(arr, size); //printing array for (int i = 0; i < size; i++) cout << arr[i] << " "; return 0; } //output 7 6 5 4 3 2 1
true
5a5062ec2bb0c8989d319602c4a23cec32c76cd6
C++
amitsingh19975/cache_manager
/main.cpp
UTF-8
1,682
2.921875
3
[]
no_license
#include <iostream> #include "cache_manager.hpp" // template<typename T> // void print(std::ostream& os, T const& c){ // using value_type = typename T::value_type; // os << "[ "; // std::copy(c.begin(), c.end() - 1, std::ostream_iterator<value_type const&>(os, ", ")); // os << c.back() << "]\n"; // } std::ostream& operator<<(std::ostream& os, boost::numeric::ublas::cache_info const& c){ return os << "LineSize: " << c.line_size << ", Assoc: " << c.associativity << ", Sets: " << c.sets; } void normalize_size(std::ostream& os, std::size_t s) noexcept{ auto n = (s >> 10); if(n == 0ul){ os << s << "B"; } s = n; n >>= 10; if(n == 0ul) os << s << "KiB"; else os << n << "MiB"; } #ifdef BOOST_NUMERIC_UBLAS_NO_MAKE_CACHE_MANAGER namespace boost::numeric::ublas{ constexpr cache_manager_t make_cache_manager() noexcept{ return cache_manager_t{ cache_info{64,4,256}, cache_info{64,8,512} }; } } #endif int main(){ std::cout<<"Cache initialing...\n"; std::cout<<"Register(SIMD) Width[Float]: " << boost::numeric::ublas::detail::simd_register_width<float><<'\n'; std::cout<<"Register(SIMD) Width[Double]: " << boost::numeric::ublas::detail::simd_register_width<double><<'\n'; auto m = boost::numeric::ublas::cache_manager; for(std::size_t j = 1ul, i = 0ul; auto const& l : m){ std::cout<<"Level(" << j++ << ") => "; if(!l.has_value()) { std::cout<<"None\n"; continue; } std::cout<<*l<<", Size: "; normalize_size(std::cout, m.size(i++).value()); std::cout<<'\n'; } return 0; }
true
8482634b17fcae985aa24a3539bb265cd6ad3675
C++
PaulLGibbs/Leetcode
/maximum-product-subarray/maximum-product-subarray.cpp
UTF-8
343
2.84375
3
[]
no_license
class Solution { public: int maxProduct(vector<int>& nums) { int n = nums.size(); int ans = nums[0]; int l = 0, r = 0; for(int i = 0; i < n;i++){ l = (l ? l : 1) * nums[i]; r = (r ? r : 1) * nums[n - 1 - i]; ans = max(ans,max(l,r)); } return ans; } };
true
835566038c853b834ba925d4110135612cae30bb
C++
dxx-git/DataStruct
/datastruct/maze/test.cpp
GB18030
7,797
3.15625
3
[]
no_license
//#define _CRT_SECURE_NO_WARNINGS //#include <iostream> //#include <assert.h> //#include <stack> //using namespace std; // //const int N = 10;//ȫֱԹĴСԹΪΣȣ // //struct Pos //{ // int Row; // int Col; //}; ////void GetMaze(int (*maze)[N])//ȡԹ ////void GetMaze(int **maze)//ȡԹ(Ҫ̬ٿռ) ////void GetMaze(int maze[][N])//ȡԹ //void GetMaze(int *maze)//ȡԹ //{ // FILE* pf = fopen("MazeMap.txt","r"); // assert(pf); // char value = 0; // for(size_t i = 0; i<N; i++) // { // for (size_t j = 0; j<N;) // { // value = fgetc(pf); // if(value == '0' || value == '1') // { // maze[i*N+j] = value - '0'; // j++; // } // else if(value == EOF) // { // cout<<"maze error!"<<endl; // return; // } // } // } // fclose(pf); //} //void PrintMaze(int *maze)//ӡԹ //{ // for(size_t i = 0; i<N; i++) // { // for (size_t j = 0; j<N; j++) // { // cout<<maze[i*N+j]<<' '; // } // cout<<endl; // } //} //bool CheckIsAccess(int* maze,Pos path)//ǷϷ //{ // if( (path.Row >= 0) && (path.Row < N) // && (path.Col >= 0) && (path.Col < N) // && (maze[path.Row*N + path.Col]) == 0) // return true; // else // return false; //} //void GetMazePath(int* maze,Pos entry,stack<Pos>& s)//ͨ· //{ // assert(maze); // Pos cur = entry; // maze[cur.Row*N+cur.Col] = 2;//ͨΪ2 // s.push(entry); // Pos next = cur; // // //̽ĸǷͨ // while(!s.empty()) // { // if(s.top().Row == N-1) // { // cout<<"ҵͨ·"<<endl; // return; // } // // // next = s.top(); // next.Row -= 1; // if(CheckIsAccess(maze,next)) // { // s.push(next); // maze[next.Row*N+next.Col] = 2; // continue; // } // // // next = s.top(); // next.Col += 1; // if(CheckIsAccess(maze,next)) // { // s.push(next); // maze[next.Row*N+next.Col] = 2; // continue; // } // // // next = s.top(); // next.Row += 1; // if(CheckIsAccess(maze,next)) // { // s.push(next); // maze[next.Row*N+next.Col] = 2; // continue; // } // // // next = s.top(); // next.Col -= 1; // if(CheckIsAccess(maze,next)) // { // s.push(next); // maze[next.Row*N+next.Col] = 2; // continue; // } // // // // // next = s.top(); // s.pop(); // maze[next.Row*N+next.Col] = 3; // } // cout<<"Թͨ·"<<endl; //} // //int main() //{ // int maze[N][N]; // Pos entry = {2,0}; // stack<Pos> s; // GetMaze((int*)maze); // GetMazePath((int*)maze,entry,s); // PrintMaze((int*)maze); // system("pause"); // return 0; //} // // // ////ݹʵ //#define _CRT_SECURE_NO_WARNINGS //#include <iostream> //#include <assert.h> //#include <stack> //using namespace std; // //const int N = 10;//ȫֱԹĴСԹΪΣȣ // //struct Pos //{ // int Row; // int Col; //}; // ////void GetMaze(int (*maze)[N])//ȡԹ ////void GetMaze(int **maze)//ȡԹ(Ҫ̬ٿռ) ////void GetMaze(int maze[][N])//ȡԹ //void GetMaze(int *maze)//ȡԹ //{ // FILE* pf = fopen("MazeMap.txt","r"); // assert(pf); // char value = 0; // for(size_t i = 0; i<N; i++) // { // for (size_t j = 0; j<N;) // { // value = fgetc(pf); // if(value == '0' || value == '1') // { // maze[i*N+j] = value - '0'; // j++; // } // else if(value == EOF) // { // cout<<"maze error!"<<endl; // return; // } // } // } // fclose(pf); //} //void PrintMaze(int *maze)//ӡԹ //{ // for(size_t i = 0; i<N; i++) // { // for (size_t j = 0; j<N; j++) // { // cout<<maze[i*N+j]<<' '; // } // cout<<endl; // } //} //bool CheckIsAccess(int* maze,Pos path)//ǷϷ //{ // if( (path.Row >= 0) && (path.Row < N) // && (path.Col >= 0) && (path.Col < N) // && (maze[path.Row*N + path.Col]) == 0) // return true; // else // return false; //} //void GetMazePath(int* maze,Pos entry,stack<Pos>& s)//ͨ· //{ // assert(maze); // Pos next = entry; // maze[next.Row*N+next.Col] = 2;//ͨΪ2 // s.push(entry); // // // //̽ĸǷͨ // if(entry.Row == N-1) // { // cout<<"ҵͨ·"<<endl; // return; // } // // // next = entry; // next.Row -= 1; // if(CheckIsAccess(maze,next)) // { // GetMazePath(maze,next,s); // } // // // next = entry; // next.Col += 1; // if(CheckIsAccess(maze,next)) // { // GetMazePath(maze,next,s); // } // // // next = entry; // next.Row += 1; // if(CheckIsAccess(maze,next)) // { // GetMazePath(maze,next,s); // } // // // next = entry; // next.Col -= 1; // if(CheckIsAccess(maze,next)) // { // GetMazePath(maze,next,s); // } //} //int main() //{ // int maze[N][N]; // Pos entry = {2,0}; // stack<Pos> s; // GetMaze((int*)maze); // GetMazePath((int*)maze,entry,s); // PrintMaze((int*)maze); // system("pause"); // return 0; //} // // // #define _CRT_SECURE_NO_WARNINGS #include <iostream> using namespace std; #include <assert.h> #include <stack> #include<iomanip> const int N = 10;//ȫֱԹĴСԹΪΣȣ struct Pos { int Row; int Col; }; //void GetMaze(int (*maze)[N])//ȡԹ //void GetMaze(int **maze)//ȡԹ(Ҫ̬ٿռ) //void GetMaze(int maze[][N])//ȡԹ void GetMaze(int *maze)//ȡԹ { FILE* pf = fopen("MazeMap.txt","r"); assert(pf); char value = 0; for(size_t i = 0; i<N; i++) { for (size_t j = 0; j<N;) { value = fgetc(pf); if(value == '0' || value == '1') { maze[i*N+j] = value - '0'; j++; } else if(value == EOF) { cout<<"maze error!"<<endl; return; } } } fclose(pf); } void PrintMaze(int *maze)//ӡԹ { cout<<setw(3); for(size_t i = 0; i<N; i++) { for (size_t j = 0; j<N; j++) { cout<<maze[i*N+j]<<setw(3); } cout<<endl; } } bool CheckIsAccess(int* maze,Pos cur,Pos next)//ǷϷ { //һǷ if( (next.Row < 0) || (next.Row >= N) || (next.Col < 0) || (next.Col >= N)) { return false; } //һϷ if(maze[next.Row*N + next.Col] == 0) { return true; } //һǰ߹ if(maze[next.Row*N + next.Col] > maze[cur.Row*N + cur.Col]+1) { return true; } return false; } void GetMazeMinPath(int* maze,Pos entry,stack<Pos>& path,stack<Pos>& min)//ͨ· { assert(maze); path.push(entry); Pos cur = entry; Pos next = cur; //ҵͨ· if(cur.Col == N-1) { if(min.empty() || path.size()<min.size()) { min = path; //cout<<"ҵͨ·"<<endl; } path.pop(); return; } //̽ĸǷͨ // next = cur; next.Row -= 1; if(CheckIsAccess(maze,cur,next)) { maze[next.Row*N+next.Col] = maze[cur.Row*N+cur.Col] + 1; GetMazeMinPath(maze,next,path,min); } // next = cur; next.Col += 1; if(CheckIsAccess(maze,cur,next)) { maze[next.Row*N+next.Col] = maze[cur.Row*N+cur.Col] + 1; GetMazeMinPath(maze,next,path,min); } // next = cur; next.Row += 1; if(CheckIsAccess(maze,cur,next)) { maze[next.Row*N+next.Col] = maze[cur.Row*N+cur.Col] + 1; GetMazeMinPath(maze,next,path,min); } // next = cur; next.Col -= 1; if(CheckIsAccess(maze,cur,next)) { maze[next.Row*N+next.Col] = maze[cur.Row*N+cur.Col] + 1; GetMazeMinPath(maze,next,path,min); } path.pop(); } int main() { int maze[N][N]; Pos entry = {2,0}; stack<Pos> path; stack<Pos> minpath; GetMaze((int*)maze); maze[2][0] = 2; //ԹڸֵΪ2 PrintMaze((int*)maze); cout<<endl<<endl; GetMazeMinPath((int*)maze,entry,path,minpath); PrintMaze((int*)maze); system("pause"); return 0; }
true
ef8c5dc692885f9a1082afae8a41df65ca5a7cdd
C++
Wytrix/Gluttonous-Snake-Game
/Code/wall.cpp
UTF-8
645
2.53125
3
[]
no_license
#include "wall.h" #include "constants.h" #include <QPainter> Wall::Wall(int x,int y) { setPos(x, y); setData(GD_Type,GO_Wall); } QRectF Wall::boundingRect() const { return QRectF(-WALL_SIZE / 2, -WALL_SIZE / 2, WALL_SIZE, WALL_SIZE); } QPainterPath Wall::shape() const { QPainterPath path; path.addRoundedRect(0,0,WALL_SIZE,WALL_SIZE,4,4); return path; } void Wall::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { painter->save(); painter->setRenderHint(QPainter::Antialiasing); painter->fillPath(shape(),Qt::gray); painter->restore(); }
true
921d597036c42cc9a9204b9225de85179b890854
C++
wanghai233/hello_world
/qtProject02/1214Qdatatime/mytime.cpp
UTF-8
1,342
2.515625
3
[]
no_license
#include "mytime.h" #include "ui_mytime.h" #include <QDateTime> #include <QDebug> myTime::myTime(QWidget *parent) : QDialog(parent), ui(new Ui::myTime) { ui->setupUi(this); this->time = new QTimer(this);//new出来,父窗口 time->setInterval(1000);//时间间隔 time->start();//启动定时器 connect(this->time,&QTimer::timeout,this,&myTime::mySlot); //关联信号和槽 } myTime::~myTime() { delete ui; } void myTime::mySlot(){ QDateTime dt; QString str; dt = QDateTime::currentDateTime(); str = dt.toString("yyyy年MM月dd日 hh:mm:ss"); ui->labTimer->setText(str); } void myTime::on_button_clicked() { QStringList str; str<<"COM1"<<"COM2"<<"COM3"<<"COM4"<<"COM5"; for(int i=0;i<str.size();i++){ qDebug()<<str.at(i); } ui->comboBox->addItems(str); ui->listWidget->addItems(str); ui->comboBox->setCurrentIndex(3); ui->listWidget->setCurrentRow(2); //ui->listWidget->setCurrentIndex(2); } void myTime::on_spinBox_valueChanged(int arg1) { qDebug()<<arg1; int value2 = ui->spinBox_2->value(); int res = arg1 + value2; qDebug()<<"result"<<res; } void myTime::on_spinBox_2_valueChanged(int arg1) { qDebug()<<arg1; int value1 = ui->spinBox->value(); int res = arg1 + value1; qDebug()<<"result"<<res; }
true
35bc8b68ddc5e9fb143802a4c2f3769f9002820c
C++
hoaf13/SPOJ_PTIT_DSA
/P178PROG.cpp
UTF-8
550
2.578125
3
[]
no_license
#include <iostream> using namespace std; int main (){ int n; while (1){ cin>>n; if (n==0) break; string S1, S2, S; cin>>S1>>S2>>S; int dem=0; int kt=1; while (1){ if (kt==0) break; dem++; if (dem>50){ kt=0; break; } string Stg=""; for (int i=0; i<n; i++){ Stg=Stg+S2[i]; Stg=Stg+S1[i]; } if (Stg==S){ kt=1; break; } else{ for (int i=0; i<n; i++){ S1[i]=Stg[i]; S2[i]=Stg[i+n]; } } } if (kt==0) cout<<"-1"<<endl; else cout<<dem<<endl; } return 0; }
true
3628ee41cd3b0dac3144760c782b0ab996f60402
C++
VulcanForge/Benchmark
/Benchmark.cpp
UTF-8
2,379
2.828125
3
[]
no_license
#include "Benchmark.h" Benchmark::Benchmark () { std::random_device rd; lcg.seed (rd ()); using result_type = std::random_device::result_type; result_type ranluxSeed[std::ranlux24_base::word_size]; std::generate (std::begin (ranluxSeed), std::end (ranluxSeed), std::ref (rd)); std::seed_seq ranluxSeedSequence (std::begin (ranluxSeed), std::end (ranluxSeed)); ranlux.seed (ranluxSeedSequence); result_type mtSeed[std::mt19937::state_size]; std::generate (std::begin (mtSeed), std::end (mtSeed), std::ref (rd)); std::seed_seq mtSeedSequence (std::begin (mtSeed), std::end (mtSeed)); mt.seed (mtSeedSequence); } using std::chrono::high_resolution_clock; using duration = high_resolution_clock::duration; duration Benchmark::TimeOnce (std::function<void ()> function) { auto start = high_resolution_clock::now (); function (); auto end = high_resolution_clock::now (); return end - start; } duration Benchmark::TimeOnce (std::function<void (uint64_t)> function, uint64_t iterations) { auto start = high_resolution_clock::now (); function (iterations); auto end = high_resolution_clock::now (); return end - start; } duration Benchmark::TimeOnLCG (std::function<void (std::minstd_rand&, uint64_t)> function, uint64_t iterations) { auto start = high_resolution_clock::now (); function (lcg, iterations); auto end = high_resolution_clock::now (); return end - start; } duration Benchmark::TimeOnMersenneTwister (std::function<void (std::mt19937&, uint64_t)> function, uint64_t iterations) { auto start = high_resolution_clock::now (); function (mt, iterations); auto end = high_resolution_clock::now (); return end - start; } duration Benchmark::TimeOnRANLUX (std::function<void (std::ranlux24_base&, uint64_t)> function, uint64_t iterations) { auto start = high_resolution_clock::now (); function (ranlux, iterations); auto end = high_resolution_clock::now (); return end - start; } duration Benchmark::TimeOnRandomData (std::function<void (std::vector<uint32_t>&)> function, uint64_t iterations) { std::vector<uint32_t> data (iterations); std::generate (data.begin (), data.end (), std::ref (mt)); auto start = high_resolution_clock::now (); function (data); auto end = high_resolution_clock::now (); return end - start; }
true
71582f02b419561d986841b8fef7ce873a1257d5
C++
barretuino/linguagemC
/Fonte Aula II/exemplo04.cpp
ISO-8859-1
744
3.59375
4
[]
no_license
/** Trabalhando com Structs Autor: Paulo Barreto Data: 10/08/2019 **/ #include <stdio.h> #include <stdlib.h> //Declarao de um registro (struct em C) struct Produto{ int id; float quantidade; }; main(){ //Declarar uma varivel do tipo 'Produto' struct Produto produto; produto.id = 123; produto.quantidade = 75.14; printf("Codigo do Produto %d\n", produto.id); printf("Quantidade do Produto %.2f\n", produto.quantidade); struct Produto outro; printf("Informe o Codigo "); scanf("%d", &outro.id); printf("Informe a Quantidade "); scanf("%f", &outro.quantidade); printf("Codigo do Produto %d\n", outro.id); printf("Quantidade do Produto %.2f\n", outro.quantidade); system("PAUSE"); }
true
257241378964aaac5d13fe692f77e90820766e99
C++
shanecarey17/Maze
/Maze/Game.cpp
UTF-8
4,170
3.515625
4
[]
no_license
// // Game.cpp // Maze // // Created by Shane Carey on 11/13/14. // Copyright (c) 2014 Shane Carey. All rights reserved. // #include "Game.h" Game::Game(int levels, int width, int depth, int creatures) { // Construct the maze maze = new Maze(levels, width, depth); // Construct the player player = new Player(maze); // We need an array of creatures createCreatures(creatures); // Launch our game logic in another thread // we need to save our main thread for graphics gameLoopThread = std::thread(&Game::runGameLoop, this); } Game::~Game() { // Join the game logic thread gameLoopThread.join(); // Delete everything delete maze; delete player; for (Creature **creature = creatures; *creature != NULL; creature++) { delete creature; } delete [] creatures; } void Game::createCreatures(int numCreatures) { // This is a null terminated array, so we need an extra space creatures = new Creature *[numCreatures + 1]; // Loop through and create creatures for (int i = 0; i <= numCreatures; i++) { // Create the creatures if(i < numCreatures) { // Somehow we need to choose what type of creature to create if(i % 2 == 0 ) creatures[i] = new Runner(maze); else creatures[i] = new Jumper(maze); } else { // On the last space, set it null creatures[i] = NULL; } } } void Game::runGameLoop() { // This thread never ends while (true) { // Until the player reaches the end while (player->getPosition() != maze->getFinishCell()) { // Update the display with respect to the player's position Renderer::updateDisplay(player->getPosition()); // We need to lock our creatures down for their move cycle mutex.lock(); // All the creatures make their move for (int i = 0; creatures[i] != NULL; i++) { creatures[i]->travel(); } // Now we are safe to move onward mutex.unlock(); // Slow everything down to human speeds usleep(100000); } // We may need to wait for the solving thread to finish (to prevent segfault) try { solveThread.join(); } catch (std::__1::system_error error) { // No thread to join } // Once the game is over get a new maze! resetMaze(); } } void Game::movePlayer(Direction direction) { // Move the player player->movePlayerDirection(direction); // Update the graphics Renderer::updateDisplay(player->getPosition()); } Maze *Game::getMaze() { // Give them a reference to the maze return maze; } void Game::solveMaze() { // If we are not already solving the maze if(!isSolving) { // Set the flag and solve the maze on another thread isSolving = true; solveThread = std::thread(&Game::solveMazeThread, this); } } void Game::solveMazeThread() { // Initiate recursive solving of the maze via the player player->solveMaze(); // Set the flag that solving is done isSolving = false; } void Game::resetMaze() { // If the game is solving itself, we cannot reset (will disturb other solving thread) if(isSolving) return; // Lock the mutex mutex.lock(); // Delete in game stuff int numCreatures = 0; for (Creature **creature = &creatures[0]; *creature != NULL; creature++) { delete *creature; numCreatures++; } delete [] creatures; delete player; // New maze int levels = maze->getHeight(); int width = maze->getWidth(); int depth = maze->getDepth(); delete maze; // Re initialize everything maze = new Maze(levels, width, depth); player = new Player(maze); createCreatures(numCreatures); // Update display Renderer::updateDisplay(maze->getStartCell()); // Now we can unlock mutex.unlock(); }
true
26e572d3b2c770cd7e6686bd00f07b8f790a7112
C++
nleeseely/nleeseely-CSCI20-Fall2017
/lab45/lab45.cpp
UTF-8
2,848
3.9375
4
[]
no_license
//Created by: Nick LS //Created on: 11/9/17 /*the following file is meant to take in user input of a first and last name, run it through some checkpoints for warnings and then output some username options at the end*/ /*got some stack overflow info on functions to use in regards to counting string size: https://stackoverflow.com/questions/20180874/how-to-get-length-of-a-string-using-strlen-function */ #include <iostream> #include <cstring> #include <string> using namespace std; int main(){ string first_name; //C string of size 50 is made for first name. string last_name; //C string of size 50 is made for last name. int i[3] = {1,1,1}; //Int variable used for loops and stuff. while(i[2] != 0) { //This loop is the overall loop, which is related to the comparison of the first and last name strings later on. while(i[0] != 0) { //Loop will iterate as long as i has a value other than 0. cout << "Please enter your first name: " << endl; getline(cin, first_name); if(first_name.length() > 10) { cout << "First Name entered is too long, please enter a name under character limit of 10" << endl; } else{ i[0] = 0; //This will break the loop if the user inputs a first name of the correct length. } } while(i[1] != 0) { //Loop will iterate as long as i has a value other than 0. cout << "Please enter your last name: " << endl; getline(cin, last_name); if(last_name.length() > 20) { cout << "Last Name entered is too long, please enter a name under character limit of 20" << endl; } else{ i[1] = 0; //This breaks the loop if the user inputs a last name of the correct length. } } if(first_name == last_name) { //If the names are the same, it resets the loop breaker variable values, and loops back to the beginning of the overall loop. cout << "First and Last name are the same, please have different names for each. Sending you back to the beginning now." << endl; i[0] = 1; i[1] = 1; } else{ //If the names are not the same, the overall loop is broken and proceed to the end. i[2] = 0; } } cout << "Thank you for your info, now generating suggested user names: " << endl; cout << "User Name 1: " << first_name[0] << first_name[1] << last_name << endl; cout << "User Name 2: " << first_name << last_name << endl; cout << "User Name 3: " << first_name[0] << last_name << endl; return 0; }
true
e5e0ad61abba443f88ae5853a510fdb693cdd581
C++
tabris233/slove-problems
/2018-7/21/2018美团复赛E.cpp
UTF-8
5,808
2.671875
3
[]
no_license
/* https://www.nowcoder.com/acm/contest/152/E 涉及算法,dfs序,扫描线,线段树,lca dfs序后 每加一条边 两点关系的bool矩阵中 就有2/4个矩形部分 没有了 if lca(a,b)==b||lca(a,b)==a : 4个 设fa[x]=lca(a,b) a,b中a的深度大 那么{<x,y>|x \in [L[a],R[a]] ,y \in ([1,L[x]-1] and [R[x]+1,n])就被灭掉了 else: 2个 那么{<x,y>|x \in [L[a],R[a]] ,y \in [L[x],R[x]] 就被灭掉了 别忘了把{<x,x>|x \in [1,n]} 给去掉 */ #include <bits/stdc++.h> typedef long long int LL; using namespace std; const int N = 1e5+7; /****************************************************************/ int n,m; struct edge{ int to,next; }G[N<<1]; int head[N],cnt; void add(int u,int v){ G[cnt].to=v,G[cnt].next=head[u],head[u]=cnt++; G[cnt].to=u,G[cnt].next=head[v],head[v]=cnt++; } int L[N],R[N],tot; int f[N][20],dep[N]; void dfs(int u,int fa = 0){ L[u] = ++tot; dep[u] = dep[fa] + 1; f[u][0] = fa; for(int i=1;i<20;i++){ f[u][i] = f[f[u][i-1]][i-1]; } for(int i=head[u],to;i!=-1;i=G[i].next){ to = G[i].to; if(to == fa) continue; dfs(to,u); } R[u] = tot; } int LCA(int u,int v){ int lca = 0; if(dep[u] < dep[v]) swap(u,v); for(int i=19;i>=0;i--){ if(dep[f[u][i]] >= dep[v]) u = f[u][i]; } if(u == v) lca = u; else { for(int i=19;i>=0;i--){ if(dep[f[u][i]] != dep[f[v][i]]){ u = f[u][i]; v = f[v][i]; } } lca = f[u][0]; } return lca; } int get(int u,int v){ if(dep[u] < dep[v]) swap(u,v); for(int i=19;i>=0;i--){ if(dep[f[u][i]] > dep[v]) u = f[u][i]; } return u; } bool judge(int u,int v){ int lca = LCA(u,v); // printf("lca(%d,%d)=%d\n",u,v,lca); return u == lca || v == lca; } int sum[N<<2],cntt[N<<2]; void pushup(int rt,int l,int r){ if(cntt[rt]) sum[rt] = r+1 - l; //lisanhua else if(r == l) sum[rt] = 0; else sum[rt] = sum[rt<<1]+sum[rt<<1|1]; } void build(int rt,int l,int r){ cntt[rt] = sum[rt] = 0; if(l >= r) return ; int m = (r+l) >> 1; build(rt<<1 ,l ,m); build(rt<<1|1,m+1,r); } void update(int rt,int l,int r,int L,int R,int v){ // printf("[%d,%d] (%d,%d)\n",l,r,L,R); if(L<=l && r<=R){ cntt[rt]+=v; pushup(rt,l,r); return ; } int m = (r+l)>>1; if(L<=m) update(rt<<1 ,l ,m,L,R,v); if(R> m) update(rt<<1|1,m+1,r,L,R,v); pushup(rt,l,r); } void init(){ memset(head,-1,sizeof(head)); cnt = tot = 0; build(1,1,n); dep[0]=0; } int main(){ while(~scanf("%d%d",&n,&m)){ init(); for(int i=2,u,v;i<=n;i++){ scanf("%d%d",&u,&v); add(u,v); } dfs(1); vector<pair<pair<int,int>,pair<int,int> > > ve; for(int i=1,u,v;i<=m;i++){ scanf("%d%d",&u,&v); // printf("%d %d <<--\n",u,v); if(judge(u,v)){ if(dep[u] < dep[v]) swap(u,v); v = get(u,v); // printf("%d %d\n",u,v ); // printf("L[%d]=%d R[%d]=%d | L[%d]=%d R[%d]=%d \n",u,L[u],u,R[u],v,L[v],v,R[v]); //(L[u],R[u]) - (1 -> L[v]-1) // printf("-[%d,%d,%d -> %d]\n",L[u],R[u],1,L[v]-1); if(1<=L[v]-1){ //puts("++"); ve.push_back({{1-1,1},{L[u],R[u]}}); ve.push_back({{L[v]-1,2},{L[u],R[u]}}); } //(L[u],R[u]) - (R[v]+1 -> n) // printf("-[%d,%d,%d -> %d]\n",L[u],R[u],R[v]+1,n); if(R[v]+1<=n){ //puts("++"); ve.push_back({{R[v]+1-1,1},{L[u],R[u]}}); ve.push_back({{n,2},{L[u],R[u]}}); } //(1,L[v]-1) - (L[u]->R[u]) // printf("-[%d,%d,%d -> %d]\n",1,L[v]-1,L[u],R[u]); if(1<=L[v]-1){ //puts("++"); ve.push_back({{L[u]-1,1},{1,L[v]-1}}); ve.push_back({{R[u],2},{1,L[v]-1}}); } //(R[v]+1,n) - (L[u] ->R[u]) // printf("-[%d,%d,%d -> %d]\n",R[v]+1,n,L[u],R[u]); if(R[v]+1<=n){ //puts("++"); ve.push_back({{L[u]-1,1},{R[v]+1,n}}); ve.push_back({{R[u],2},{R[v]+1,n}}); } } else{ //(L[u],R[u]) - (L[v] -> R[v]) // printf("+[%d,%d,%d -> %d]\n",L[u],R[u],L[v],R[v]); ve.push_back({{L[v]-1,1},{L[u],R[u]}}); ve.push_back({{R[v],2},{L[u],R[u]}}); //(L[v],R[v]) - (L[u] -> R[u]) // printf("+[%d,%d,%d -> %d]\n",L[v],R[v],L[u],R[u]); ve.push_back({{L[u]-1,1},{L[v],R[v]}}); ve.push_back({{R[u],2},{L[v],R[v]}}); } } for(int i=1;i<=n;i++){ ve.push_back({{i-1, 1},{i,i}}); ve.push_back({{i ,2},{i,i}}); } sort(ve.begin(), ve.end()); // for(int i=1;i<=n;i++)printf("%d %d\n",L[i],R[i]); int p = 0; LL ans = 0; for(auto a: ve){ // printf("<%d,%d><%d,%d>\n",a.first.first,a.first.second,a.second.first,a.second.second); if(a.first.second == 1){ ans += 1LL*sum[1]*(a.first.first-p); update(1,1,n,a.second.first,a.second.second,1); } else { ans += 1LL*sum[1]*(a.first.first-p); update(1,1,n,a.second.first,a.second.second,-1); } p = a.first.first; } printf("%lld\n",1LL*n*n-ans); } }
true
1a436538a0d7043de644c7d128b8da1415c6d2a7
C++
tkloong/sudoku
/sudoku.cpp
UTF-8
6,837
3.015625
3
[]
no_license
#include "sudoku.h" #include <iostream> #include <cstdlib> #include <algorithm> #include <unistd.h> #include <curses.h> #include <locale.h> #include <time.h> #include <fstream> using namespace std; static int num[9]; // number from 1~9 Sudoku::Sudoku(int &level){ // constructor generation(level); } void Sudoku::initCoordinate(){ for (int r=0; r<9; r++) for (int c=0; c<9; c++){ questionYX[r][c] = 0; coordinateYX[r][c] = 0; } } void Sudoku::initIsNumLegal(int *num){ for (int i=0; i<9; i++){ num[i] = 1; } } void Sudoku::initNum(int *num){ for (int i=0; i<9; i++){ num[i] = i+1; } } void Sudoku::checkLegalNum(int &row, int &col, int &totalLegalNumber){ int isNumLegal[9]; // At the beginning, every number is legal initNum(num); initIsNumLegal(isNumLegal); totalLegalNumber = 9; // There are temporarily 9(all) numbers which can fill into the grid. int count; if (col != 0){ // Delegitimize the number in the same row. count = col-1; while (count >= 0){ isNumLegal[coordinateYX[row][count]-1] = 0; count--; } } if (row != 0){ // Delegitimize the number in the same column. count = row-1; while (count >= 0){ isNumLegal[coordinateYX[count][col]-1] = 0; count--; } } if (row % 3 != 0){ // Delegitimize the numbers in each block If they are not in the first row. int colBlock[9]={0,0,0,3,3,3,6,6,6}; int r = row-1, c = colBlock[col]; count = 0; while (count < (row%3)){ // Determine how many row(s) should I check. while(1){ isNumLegal[coordinateYX[r][c]-1] = 0; if ((c+1)%3==0){ // Check if the number has reached block's wall. c-=2; break; } else c++; } r--; count++; } } for (int i=0; i<9; i++) if (isNumLegal[i] == 0) totalLegalNumber--; // Calculate total of legal numbers. int moveItem = 0, last = 8; bool isSwapNum = FALSE; if (totalLegalNumber == 0) { // Check one more time. row--; col = 0; // re-assign the number from the beginning column. checkLegalNum(row, col, totalLegalNumber); } else if (totalLegalNumber != 9) { // swap num[] for (int i=0; last>=i; ) { if (!isSwapNum && isNumLegal[i]==0) { // Find the number that is illegal. moveItem = i; // Need to move i-th item. i += 1; isSwapNum = TRUE; } else if (isSwapNum && isNumLegal[last]==1) { // Find the legal number from the end of num[]. isNumLegal[last] = 0; isNumLegal[moveItem] = 1; swap(num[moveItem], num[last]); last -= 1; isSwapNum = FALSE; } else if (isSwapNum) { // if isNumLegal[last] is illegal, then go to next number. last--; } else i++; } } } void Sudoku::difficulty(int &level){ /*dig hole*/ int last; int nrand; initNum(num); for (int row=0; row<9; row++){ last = 9; for (int i=0; i < level; i++) { nrand = rand() % last; swap(num[nrand], num[last]); last--; questionYX[row][nrand] = coordinateYX[row][nrand] = 0; questionYX[nrand][row] = coordinateYX[nrand][row] = 0; } } } void Sudoku::generation(int &level){ // Generate a new Sudoku initCoordinate(); // Initialize coordinate before generation srand(time(NULL)); int totalLegalNumber; int nrand; for (int row=0; row<9; row++){ for (int col=0; col<9; col++){ checkLegalNum(row, col, totalLegalNumber); nrand = rand() % totalLegalNumber; questionYX[row][col] = coordinateYX[row][col] = num[nrand]; } } difficulty(level); } void Sudoku::printMap(int y, int x){ // print Sudoku map/table start_pos_y = y; start_pos_x = x; mvaddstr(start_pos_y, start_pos_x, "┌───┬───┬───┬───┬───┬───┬───┬───┬───┐"); mvaddstr(start_pos_y+1, start_pos_x, "│ | | │ │ │ │ | | │"); mvaddstr(start_pos_y+2, start_pos_x, "├---|---|---│---|---|---│---|---|---┤"); mvaddstr(start_pos_y+3, start_pos_x, "│ | | │ | | │ | | │"); mvaddstr(start_pos_y+4, start_pos_x, "├---|---|---│---|---|---│---|---|---┤"); mvaddstr(start_pos_y+5, start_pos_x, "│ | | │ | | │ | | │"); mvaddstr(start_pos_y+6, start_pos_x, "├───┼───┼───┼───┼───┼───┼───┼───┼───┤"); mvaddstr(start_pos_y+7, start_pos_x, "│ | | │ | | │ | | │"); mvaddstr(start_pos_y+8, start_pos_x, "├---|---|---│---|---|---│---|---|---┤"); mvaddstr(start_pos_y+9, start_pos_x, "│ | | │ | | │ | | │"); mvaddstr(start_pos_y+10, start_pos_x, "├---|---|---│---|---|---│---|---|---┤"); mvaddstr(start_pos_y+11, start_pos_x, "│ | | │ | | │ | | │"); mvaddstr(start_pos_y+12, start_pos_x, "├───┼───┼───┼───┼───┼───┼───┼───┼───┤"); mvaddstr(start_pos_y+13, start_pos_x, "│ | | │ | | │ | | │"); mvaddstr(start_pos_y+14, start_pos_x, "├---|---|---│---|---|---│---|---|---┤"); mvaddstr(start_pos_y+15, start_pos_x, "│ | | │ | | │ | | │"); mvaddstr(start_pos_y+16, start_pos_x, "├---|---|---│---|---|---│---|---|---┤"); mvaddstr(start_pos_y+17, start_pos_x, "│ | | │ | | │ | | │"); mvaddstr(start_pos_y+18, start_pos_x, "└───┴───┴───┴───┴───┴───┴───┴───┴───┘"); } void Sudoku::printQ(){ // print Sudoku question int row = 0, col = 0; for (int r=0; r<9; r++){ if (r==0) row = start_pos_y+1; else row += 2; for (int c=0; c<9; c++){ if (c==0) col = start_pos_x+2; else col += 4; move(row, col); if (coordinateYX[r][c] == 0) printw(" "); else { if(questionYX[r][c] != 0) { attron(A_BOLD); attron(A_UNDERLINE); } printw("%d", coordinateYX[r][c]); attrset(A_NORMAL); } } } } void Sudoku::modify(int &c_y, int &c_x, int num){ // Enable user to type the answer if (questionYX[c_y][c_x] == 0) coordinateYX[c_y][c_x] = num; } bool Sudoku::isCorrect(){ // Check the answer int sumHor, sumVer; for (int r=0; r<9; r++){ sumHor = 0; sumVer = 0; for (int c=0; c<9; c++){ sumHor += coordinateYX[r][c]; // The sum of every column sumVer += coordinateYX[c][r]; // The sum of every row } if (sumHor!=45 || sumVer!=45) return 0; //the sum of every row or column must be 1+2+...+9=45, otherwise the answer is wrong } return 1; //The answer is correct } void Sudoku::outputQ() { ofstream sudokuQ("Sudoku.txt", ios::out); if (!sudokuQ) { cerr << "File could not be opened!" << endl; exit(1); } for (int row=0; row<9; row++) { for (int col=0; col<9; col++) { sudokuQ << questionYX[row][col]; } sudokuQ << endl; } }
true
695bf6e3f0b34cfcea129ed851205ade6b1f7544
C++
twix20/sdizo_project
/Sdizo_Projekt3/GreedyTravellingSalesman.h
UTF-8
608
2.734375
3
[]
no_license
#pragma once #include "ITravellingSalesmanStrategy.h" struct tempPath { int from; int to; int cost; tempPath() { } tempPath(int from, int to, int cost) { this->from = from; this->to = to; this->cost = cost; } }; class GreedyTravellingSalesman : public ITravellingSalesmanStrategy { private: std::unique_ptr<bool[]> _visited; tempPath selectNextMinCostPath(std::shared_ptr<MyTable<tempPath>> allPaths, int from) const; public: GreedyTravellingSalesman(); ~GreedyTravellingSalesman(); std::shared_ptr<MyTable<int>> compute(Town town) override; std::string getName() override; };
true
b2cb27df987edd268470a9d795d87d4aafcff78b
C++
Anubhav12345678/competitive-programming
/PRINTBINARYTREESPECIALVVVVIMPLEETCODE655.cpp
UTF-8
2,473
3.421875
3
[]
no_license
/** Print a binary tree in an m*n 2D string array following these rules: The row number m should be equal to the height of the given binary tree. The column number n should always be an odd number. The root node's value (in string format) should be put in the exactly middle of the first row it can be put. The column and the row where the root node belongs will separate the rest space into two parts (left-bottom part and right-bottom part). You should print the left subtree in the left-bottom part and print the right subtree in the right-bottom part. The left-bottom part and the right-bottom part should have the same size. Even if one subtree is none while the other is not, you don't need to print anything for the none subtree but still need to leave the space as large as that for the other subtree. However, if two subtrees are none, then you don't need to leave space for both of them. Each unused space should contain an empty string "". Print the subtrees following the same rules. Example 1: Input: 1 / 2 Output: [["", "1", ""], ["2", "", ""]] Example 2: Input: 1 / \ 2 3 \ 4 Output: [["", "", "", "1", "", "", ""], ["", "2", "", "", "", "3", ""], ["", "", "4", "", "", "", ""]] Example 3: Input: 1 / \ 2 5 / 3 / 4 Output: [["", "", "", "", "", "", "", "1", "", "", "", "", "", "", ""] ["", "", "", "2", "", "", "", "", "", "", "", "5", "", "", ""] ["", "3", "", "", "", "", "", "", "", "", "", "", "", "", ""] ["4", "", "", "", "", "", "", "", "", "", "", "", "", "", ""]] */ class Solution { public: int height(TreeNode* r) { if(!r) return 0; return 1+max(height(r->left),height(r->right)); } void solve(vector<vector<string>> &res,int l,int r,int st,TreeNode* root,int h) { if(l>r||!root||st>=h) return; int mid = (l+r)/2; res[st][mid] = to_string(root->val); solve(res,l,mid-1,st+1,root->left,h); solve(res,mid+1,r,st+1,root->right,h); } vector<vector<string>> printTree(TreeNode* root) { vector<vector<string>> res; if(!root) return res; int h = height(root); res = vector<vector<string>>(h,vector<string>((1<<h)-1,"")); cout<<res.size()<<" "<<res[0].size()<<endl; int n = 1<<h; int l=0,r=n-1; solve(res,l,r,0,root,h); return res; } };
true
b8a65e1c509b7bb334cbe147dc88a6cf370731a8
C++
foges/aml
/test/cpu/gtest_expression.cpp
UTF-8
19,283
2.875
3
[ "Apache-2.0" ]
permissive
#include <cmath> #include <gtest/gtest.h> #include <aml/aml.h> class ExpressionTest : public ::testing::Test { public: ExpressionTest() { h.init(); } ~ExpressionTest() { h.destroy(); } protected: aml::Handle h; }; /** PLUS **********************************************************************/ TEST_F(ExpressionTest, PlusAA) { auto x = aml::ones<double, 2>(h, aml::CPU, {1, 2}); auto y = aml::ones<double, 2>(h, aml::CPU, {1, 2}); auto z = aml::nans<double, 2>(h, aml::CPU, {1, 2}); aml::eval(h, z, x + y); EXPECT_EQ(z.data()[0], 2); EXPECT_EQ(z.data()[1], 2); } TEST_F(ExpressionTest, PlusAE) { auto x = aml::ones<double, 2>(h, aml::CPU, {1, 2}); auto y = aml::make_expression(aml::ones<double, 2>(h, aml::CPU, {1, 2})); auto z = aml::nans<double, 2>(h, aml::CPU, {1, 2}); aml::eval(h, z, x + y); EXPECT_EQ(z.data()[0], 2); EXPECT_EQ(z.data()[1], 2); } TEST_F(ExpressionTest, PlusEA) { auto x = aml::make_expression(aml::ones<double, 2>(h, aml::CPU, {1, 2})); auto y = aml::ones<double, 2>(h, aml::CPU, {1, 2}); auto z = aml::nans<double, 2>(h, aml::CPU, {1, 2}); aml::eval(h, z, x + y); EXPECT_EQ(z.data()[0], 2); EXPECT_EQ(z.data()[1], 2); } TEST_F(ExpressionTest, PlusEE) { auto x = aml::make_expression(aml::ones<double, 2>(h, aml::CPU, {1, 2})); auto y = aml::make_expression(aml::ones<double, 2>(h, aml::CPU, {1, 2})); auto z = aml::nans<double, 2>(h, aml::CPU, {1, 2}); aml::eval(h, z, x + y); EXPECT_EQ(z.data()[0], 2); EXPECT_EQ(z.data()[1], 2); } TEST_F(ExpressionTest, PlusSE) { auto x = 1.0; auto y = aml::make_expression(aml::ones<double, 2>(h, aml::CPU, {1, 2})); auto z = aml::nans<double, 2>(h, aml::CPU, {1, 2}); aml::eval(h, z, x + y); EXPECT_EQ(z.data()[0], 2); EXPECT_EQ(z.data()[1], 2); } TEST_F(ExpressionTest, PlusES) { auto x = aml::make_expression(aml::ones<double, 2>(h, aml::CPU, {1, 2})); auto y = 1.0; auto z = aml::nans<double, 2>(h, aml::CPU, {1, 2}); aml::eval(h, z, x + y); EXPECT_EQ(z.data()[0], 2); EXPECT_EQ(z.data()[1], 2); } TEST_F(ExpressionTest, PlusSA) { auto x = 1.0; auto y = aml::ones<double, 2>(h, aml::CPU, {1, 2}); auto z = aml::nans<double, 2>(h, aml::CPU, {1, 2}); aml::eval(h, z, x + y); EXPECT_EQ(z.data()[0], 2); EXPECT_EQ(z.data()[1], 2); } TEST_F(ExpressionTest, PlusAS) { auto x = aml::ones<double, 2>(h, aml::CPU, {1, 2}); auto y = 1.0; auto z = aml::nans<double, 2>(h, aml::CPU, {1, 2}); aml::eval(h, z, x + y); EXPECT_EQ(z.data()[0], 2); EXPECT_EQ(z.data()[1], 2); } /** MINUS *********************************************************************/ TEST_F(ExpressionTest, MinusAA) { auto x = aml::zeros<double, 2>(h, aml::CPU, {1, 2}); auto y = aml::ones<double, 2>(h, aml::CPU, {1, 2}); auto z = aml::nans<double, 2>(h, aml::CPU, {1, 2}); aml::eval(h, z, x - y); EXPECT_EQ(z.data()[0], -1); EXPECT_EQ(z.data()[1], -1); } TEST_F(ExpressionTest, MinusAE) { auto x = aml::zeros<double, 2>(h, aml::CPU, {1, 2}); auto y = aml::make_expression(aml::ones<double, 2>(h, aml::CPU, {1, 2})); auto z = aml::nans<double, 2>(h, aml::CPU, {1, 2}); aml::eval(h, z, x - y); EXPECT_EQ(z.data()[0], -1); EXPECT_EQ(z.data()[1], -1); } TEST_F(ExpressionTest, MinusEA) { auto x = aml::make_expression(aml::zeros<double, 2>(h, aml::CPU, {1, 2})); auto y = aml::ones<double, 2>(h, aml::CPU, {1, 2}); auto z = aml::nans<double, 2>(h, aml::CPU, {1, 2}); aml::eval(h, z, x - y); EXPECT_EQ(z.data()[0], -1); EXPECT_EQ(z.data()[1], -1); } TEST_F(ExpressionTest, MinusEE) { auto x = aml::make_expression(aml::zeros<double, 2>(h, aml::CPU, {1, 2})); auto y = aml::make_expression(aml::ones<double, 2>(h, aml::CPU, {1, 2})); auto z = aml::nans<double, 2>(h, aml::CPU, {1, 2}); aml::eval(h, z, x - y); EXPECT_EQ(z.data()[0], -1); EXPECT_EQ(z.data()[1], -1); } TEST_F(ExpressionTest, MinusSE) { auto x = 0.0; auto y = aml::make_expression(aml::ones<double, 2>(h, aml::CPU, {1, 2})); auto z = aml::nans<double, 2>(h, aml::CPU, {1, 2}); aml::eval(h, z, x - y); EXPECT_EQ(z.data()[0], -1); EXPECT_EQ(z.data()[1], -1); } TEST_F(ExpressionTest, MinusES) { auto x = aml::make_expression(aml::zeros<double, 2>(h, aml::CPU, {1, 2})); auto y = 1.0; auto z = aml::nans<double, 2>(h, aml::CPU, {1, 2}); aml::eval(h, z, x - y); EXPECT_EQ(z.data()[0], -1); EXPECT_EQ(z.data()[1], -1); } TEST_F(ExpressionTest, MinusSA) { auto x = 0.0; auto y = aml::ones<double, 2>(h, aml::CPU, {1, 2}); auto z = aml::nans<double, 2>(h, aml::CPU, {1, 2}); aml::eval(h, z, x - y); EXPECT_EQ(z.data()[0], -1); EXPECT_EQ(z.data()[1], -1); } TEST_F(ExpressionTest, MinusAS) { auto x = aml::zeros<double, 2>(h, aml::CPU, {1, 2}); auto y = 1.0; auto z = aml::nans<double, 2>(h, aml::CPU, {1, 2}); aml::eval(h, z, x - y); EXPECT_EQ(z.data()[0], -1); EXPECT_EQ(z.data()[1], -1); } /** MULTIPLY ******************************************************************/ TEST_F(ExpressionTest, MultiplyAA) { auto x = aml::zeros<double, 2>(h, aml::CPU, {1, 2}); auto y = aml::ones<double, 2>(h, aml::CPU, {1, 2}); auto z = aml::nans<double, 2>(h, aml::CPU, {1, 2}); aml::eval(h, z, x * y); EXPECT_EQ(z.data()[0], 0); EXPECT_EQ(z.data()[1], 0); } TEST_F(ExpressionTest, MultiplyAE) { auto x = aml::zeros<double, 2>(h, aml::CPU, {1, 2}); auto y = aml::make_expression(aml::ones<double, 2>(h, aml::CPU, {1, 2})); auto z = aml::nans<double, 2>(h, aml::CPU, {1, 2}); aml::eval(h, z, x * y); EXPECT_EQ(z.data()[0], 0); EXPECT_EQ(z.data()[1], 0); } TEST_F(ExpressionTest, MultiplyEA) { auto x = aml::make_expression(aml::zeros<double, 2>(h, aml::CPU, {1, 2})); auto y = aml::ones<double, 2>(h, aml::CPU, {1, 2}); auto z = aml::nans<double, 2>(h, aml::CPU, {1, 2}); aml::eval(h, z, x * y); EXPECT_EQ(z.data()[0], 0); EXPECT_EQ(z.data()[1], 0); } TEST_F(ExpressionTest, MultiplyEE) { auto x = aml::make_expression(aml::zeros<double, 2>(h, aml::CPU, {1, 2})); auto y = aml::make_expression(aml::ones<double, 2>(h, aml::CPU, {1, 2})); auto z = aml::nans<double, 2>(h, aml::CPU, {1, 2}); aml::eval(h, z, x * y); EXPECT_EQ(z.data()[0], 0); EXPECT_EQ(z.data()[1], 0); } TEST_F(ExpressionTest, MultiplySE) { auto x = 0.0; auto y = aml::make_expression(aml::ones<double, 2>(h, aml::CPU, {1, 2})); auto z = aml::nans<double, 2>(h, aml::CPU, {1, 2}); aml::eval(h, z, x * y); EXPECT_EQ(z.data()[0], 0); EXPECT_EQ(z.data()[1], 0); } TEST_F(ExpressionTest, MultiplyES) { auto x = aml::make_expression(aml::zeros<double, 2>(h, aml::CPU, {1, 2})); auto y = 1.0; auto z = aml::nans<double, 2>(h, aml::CPU, {1, 2}); aml::eval(h, z, x * y); EXPECT_EQ(z.data()[0], 0); EXPECT_EQ(z.data()[1], 0); } /** DIVIDE ********************************************************************/ TEST_F(ExpressionTest, DivideAA) { auto x = aml::zeros<double, 2>(h, aml::CPU, {1, 2}); auto y = aml::ones<double, 2>(h, aml::CPU, {1, 2}); auto z = aml::nans<double, 2>(h, aml::CPU, {1, 2}); aml::eval(h, z, x / y); EXPECT_EQ(z.data()[0], 0); EXPECT_EQ(z.data()[1], 0); } TEST_F(ExpressionTest, DivideAE) { auto x = aml::zeros<double, 2>(h, aml::CPU, {1, 2}); auto y = aml::make_expression(aml::ones<double, 2>(h, aml::CPU, {1, 2})); auto z = aml::nans<double, 2>(h, aml::CPU, {1, 2}); aml::eval(h, z, x / y); EXPECT_EQ(z.data()[0], 0); EXPECT_EQ(z.data()[1], 0); } TEST_F(ExpressionTest, DivideEA) { auto x = aml::make_expression(aml::zeros<double, 2>(h, aml::CPU, {1, 2})); auto y = aml::ones<double, 2>(h, aml::CPU, {1, 2}); auto z = aml::nans<double, 2>(h, aml::CPU, {1, 2}); aml::eval(h, z, x / y); EXPECT_EQ(z.data()[0], 0); EXPECT_EQ(z.data()[1], 0); } TEST_F(ExpressionTest, DivideEE) { auto x = aml::make_expression(aml::zeros<double, 2>(h, aml::CPU, {1, 2})); auto y = aml::make_expression(aml::ones<double, 2>(h, aml::CPU, {1, 2})); auto z = aml::nans<double, 2>(h, aml::CPU, {1, 2}); aml::eval(h, z, x / y); EXPECT_EQ(z.data()[0], 0); EXPECT_EQ(z.data()[1], 0); } TEST_F(ExpressionTest, DivideSE) { auto x = 0.0; auto y = aml::make_expression(aml::ones<double, 2>(h, aml::CPU, {1, 2})); auto z = aml::nans<double, 2>(h, aml::CPU, {1, 2}); aml::eval(h, z, x / y); EXPECT_EQ(z.data()[0], 0); EXPECT_EQ(z.data()[1], 0); } TEST_F(ExpressionTest, DivideES) { auto x = aml::make_expression(aml::zeros<double, 2>(h, aml::CPU, {1, 2})); auto y = 1.0; auto z = aml::nans<double, 2>(h, aml::CPU, {1, 2}); aml::eval(h, z, x / y); EXPECT_EQ(z.data()[0], 0); EXPECT_EQ(z.data()[1], 0); } TEST_F(ExpressionTest, DivideSA) { auto x = 0.0; auto y = aml::ones<double, 2>(h, aml::CPU, {1, 2}); auto z = aml::nans<double, 2>(h, aml::CPU, {1, 2}); aml::eval(h, z, x / y); EXPECT_EQ(z.data()[0], 0); EXPECT_EQ(z.data()[1], 0); } TEST_F(ExpressionTest, DivideAS) { auto x = aml::zeros<double, 2>(h, aml::CPU, {1, 2}); auto y = 1.0; auto z = aml::nans<double, 2>(h, aml::CPU, {1, 2}); aml::eval(h, z, x / y); EXPECT_EQ(z.data()[0], 0); EXPECT_EQ(z.data()[1], 0); } /** MIN ***********************************************************************/ TEST_F(ExpressionTest, MinAA) { auto x = aml::zeros<double, 2>(h, aml::CPU, {1, 2}); auto y = aml::ones<double, 2>(h, aml::CPU, {1, 2}); auto z = aml::nans<double, 2>(h, aml::CPU, {1, 2}); aml::eval(h, z, aml::min(x, y)); EXPECT_EQ(z.data()[0], 0); EXPECT_EQ(z.data()[1], 0); } TEST_F(ExpressionTest, MinAE) { auto x = aml::zeros<double, 2>(h, aml::CPU, {1, 2}); auto y = aml::make_expression(aml::ones<double, 2>(h, aml::CPU, {1, 2})); auto z = aml::nans<double, 2>(h, aml::CPU, {1, 2}); aml::eval(h, z, aml::min(x, y)); EXPECT_EQ(z.data()[0], 0); EXPECT_EQ(z.data()[1], 0); } TEST_F(ExpressionTest, MinEA) { auto x = aml::make_expression(aml::zeros<double, 2>(h, aml::CPU, {1, 2})); auto y = aml::ones<double, 2>(h, aml::CPU, {1, 2}); auto z = aml::nans<double, 2>(h, aml::CPU, {1, 2}); aml::eval(h, z, aml::min(x, y)); EXPECT_EQ(z.data()[0], 0); EXPECT_EQ(z.data()[1], 0); } TEST_F(ExpressionTest, MinEE) { auto x = aml::make_expression(aml::zeros<double, 2>(h, aml::CPU, {1, 2})); auto y = aml::make_expression(aml::ones<double, 2>(h, aml::CPU, {1, 2})); auto z = aml::nans<double, 2>(h, aml::CPU, {1, 2}); aml::eval(h, z, aml::min(x, y)); EXPECT_EQ(z.data()[0], 0); EXPECT_EQ(z.data()[1], 0); } TEST_F(ExpressionTest, MinSE) { auto x = 0.0; auto y = aml::make_expression(aml::ones<double, 2>(h, aml::CPU, {1, 2})); auto z = aml::nans<double, 2>(h, aml::CPU, {1, 2}); aml::eval(h, z, aml::min(x, y)); EXPECT_EQ(z.data()[0], 0); EXPECT_EQ(z.data()[1], 0); } TEST_F(ExpressionTest, MinES) { auto x = aml::make_expression(aml::zeros<double, 2>(h, aml::CPU, {1, 2})); auto y = 1.0; auto z = aml::nans<double, 2>(h, aml::CPU, {1, 2}); aml::eval(h, z, aml::min(x, y)); EXPECT_EQ(z.data()[0], 0); EXPECT_EQ(z.data()[1], 0); } TEST_F(ExpressionTest, MinSA) { auto x = 0.0; auto y = aml::ones<double, 2>(h, aml::CPU, {1, 2}); auto z = aml::nans<double, 2>(h, aml::CPU, {1, 2}); aml::eval(h, z, aml::min(x, y)); EXPECT_EQ(z.data()[0], 0); EXPECT_EQ(z.data()[1], 0); } TEST_F(ExpressionTest, MinAS) { auto x = aml::zeros<double, 2>(h, aml::CPU, {1, 2}); auto y = 1.0; auto z = aml::nans<double, 2>(h, aml::CPU, {1, 2}); aml::eval(h, z, aml::min(x, y)); EXPECT_EQ(z.data()[0], 0); EXPECT_EQ(z.data()[1], 0); } /** MAX ***********************************************************************/ TEST_F(ExpressionTest, MaxAA) { auto x = aml::zeros<double, 2>(h, aml::CPU, {1, 2}); auto y = aml::ones<double, 2>(h, aml::CPU, {1, 2}); auto z = aml::nans<double, 2>(h, aml::CPU, {1, 2}); aml::eval(h, z, aml::max(x, y)); EXPECT_EQ(z.data()[0], 1); EXPECT_EQ(z.data()[1], 1); } TEST_F(ExpressionTest, MaxAE) { auto x = aml::zeros<double, 2>(h, aml::CPU, {1, 2}); auto y = aml::make_expression(aml::ones<double, 2>(h, aml::CPU, {1, 2})); auto z = aml::nans<double, 2>(h, aml::CPU, {1, 2}); aml::eval(h, z, aml::max(x, y)); EXPECT_EQ(z.data()[0], 1); EXPECT_EQ(z.data()[1], 1); } TEST_F(ExpressionTest, MaxEA) { auto x = aml::make_expression(aml::zeros<double, 2>(h, aml::CPU, {1, 2})); auto y = aml::ones<double, 2>(h, aml::CPU, {1, 2}); auto z = aml::nans<double, 2>(h, aml::CPU, {1, 2}); aml::eval(h, z, aml::max(x, y)); EXPECT_EQ(z.data()[0], 1); EXPECT_EQ(z.data()[1], 1); } TEST_F(ExpressionTest, MaxEE) { auto x = aml::make_expression(aml::zeros<double, 2>(h, aml::CPU, {1, 2})); auto y = aml::make_expression(aml::ones<double, 2>(h, aml::CPU, {1, 2})); auto z = aml::nans<double, 2>(h, aml::CPU, {1, 2}); aml::eval(h, z, aml::max(x, y)); EXPECT_EQ(z.data()[0], 1); EXPECT_EQ(z.data()[1], 1); } TEST_F(ExpressionTest, MaxSE) { auto x = 0.0; auto y = aml::make_expression(aml::ones<double, 2>(h, aml::CPU, {1, 2})); auto z = aml::nans<double, 2>(h, aml::CPU, {1, 2}); aml::eval(h, z, aml::max(x, y)); EXPECT_EQ(z.data()[0], 1); EXPECT_EQ(z.data()[1], 1); } TEST_F(ExpressionTest, MaxES) { auto x = aml::make_expression(aml::zeros<double, 2>(h, aml::CPU, {1, 2})); auto y = 1.0; auto z = aml::nans<double, 2>(h, aml::CPU, {1, 2}); aml::eval(h, z, aml::max(x, y)); EXPECT_EQ(z.data()[0], 1); EXPECT_EQ(z.data()[1], 1); } TEST_F(ExpressionTest, MaxSA) { auto x = 0.0; auto y = aml::ones<double, 2>(h, aml::CPU, {1, 2}); auto z = aml::nans<double, 2>(h, aml::CPU, {1, 2}); aml::eval(h, z, aml::max(x, y)); EXPECT_EQ(z.data()[0], 1); EXPECT_EQ(z.data()[1], 1); } TEST_F(ExpressionTest, MaxAS) { auto x = aml::zeros<double, 2>(h, aml::CPU, {1, 2}); auto y = 1.0; auto z = aml::nans<double, 2>(h, aml::CPU, {1, 2}); aml::eval(h, z, aml::max(x, y)); EXPECT_EQ(z.data()[0], 1); EXPECT_EQ(z.data()[1], 1); } /** POW ***********************************************************************/ TEST_F(ExpressionTest, PowAA) { auto x = aml::zeros<double, 2>(h, aml::CPU, {1, 2}); auto y = aml::ones<double, 2>(h, aml::CPU, {1, 2}); auto z = aml::nans<double, 2>(h, aml::CPU, {1, 2}); aml::eval(h, z, aml::pow(x, y)); EXPECT_EQ(z.data()[0], 0); EXPECT_EQ(z.data()[1], 0); } TEST_F(ExpressionTest, PowAE) { auto x = aml::zeros<double, 2>(h, aml::CPU, {1, 2}); auto y = aml::make_expression(aml::ones<double, 2>(h, aml::CPU, {1, 2})); auto z = aml::nans<double, 2>(h, aml::CPU, {1, 2}); aml::eval(h, z, aml::pow(x, y)); EXPECT_EQ(z.data()[0], 0); EXPECT_EQ(z.data()[1], 0); } TEST_F(ExpressionTest, PowEA) { auto x = aml::make_expression(aml::zeros<double, 2>(h, aml::CPU, {1, 2})); auto y = aml::ones<double, 2>(h, aml::CPU, {1, 2}); auto z = aml::nans<double, 2>(h, aml::CPU, {1, 2}); aml::eval(h, z, aml::pow(x, y)); EXPECT_EQ(z.data()[0], 0); EXPECT_EQ(z.data()[1], 0); } TEST_F(ExpressionTest, PowEE) { auto x = aml::make_expression(aml::zeros<double, 2>(h, aml::CPU, {1, 2})); auto y = aml::make_expression(aml::ones<double, 2>(h, aml::CPU, {1, 2})); auto z = aml::nans<double, 2>(h, aml::CPU, {1, 2}); aml::eval(h, z, aml::pow(x, y)); EXPECT_EQ(z.data()[0], 0); EXPECT_EQ(z.data()[1], 0); } TEST_F(ExpressionTest, PowSE) { auto x = 0.0; auto y = aml::make_expression(aml::ones<double, 2>(h, aml::CPU, {1, 2})); auto z = aml::nans<double, 2>(h, aml::CPU, {1, 2}); aml::eval(h, z, aml::pow(x, y)); EXPECT_EQ(z.data()[0], 0); EXPECT_EQ(z.data()[1], 0); } TEST_F(ExpressionTest, PowES) { auto x = aml::make_expression(aml::zeros<double, 2>(h, aml::CPU, {1, 2})); auto y = 1.0; auto z = aml::nans<double, 2>(h, aml::CPU, {1, 2}); aml::eval(h, z, aml::pow(x, y)); EXPECT_EQ(z.data()[0], 0); EXPECT_EQ(z.data()[1], 0); } TEST_F(ExpressionTest, PowSA) { auto x = 0.0; auto y = aml::ones<double, 2>(h, aml::CPU, {1, 2}); auto z = aml::nans<double, 2>(h, aml::CPU, {1, 2}); aml::eval(h, z, aml::pow(x, y)); EXPECT_EQ(z.data()[0], 0); EXPECT_EQ(z.data()[1], 0); } TEST_F(ExpressionTest, PowAS) { auto x = aml::zeros<double, 2>(h, aml::CPU, {1, 2}); auto y = 1.0; auto z = aml::nans<double, 2>(h, aml::CPU, {1, 2}); aml::eval(h, z, aml::pow(x, y)); EXPECT_EQ(z.data()[0], 0); EXPECT_EQ(z.data()[1], 0); } /** ABS ***********************************************************************/ TEST_F(ExpressionTest, AbsA) { auto x = aml::ones<double, 2>(h, aml::CPU, {1, 2}); auto z = aml::nans<double, 2>(h, aml::CPU, {1, 2}); aml::eval(h, z, aml::abs(x)); EXPECT_EQ(z.data()[0], 1); EXPECT_EQ(z.data()[1], 1); } TEST_F(ExpressionTest, AbsE) { auto x = aml::make_expression(aml::ones<double, 2>(h, aml::CPU, {1, 2})); auto z = aml::nans<double, 2>(h, aml::CPU, {1, 2}); aml::eval(h, z, aml::abs(x)); EXPECT_EQ(z.data()[0], 1); EXPECT_EQ(z.data()[1], 1); } /** EXP ***********************************************************************/ TEST_F(ExpressionTest, ExpA) { auto x = aml::ones<double, 2>(h, aml::CPU, {1, 2}); auto z = aml::nans<double, 2>(h, aml::CPU, {1, 2}); aml::eval(h, z, aml::exp(x)); EXPECT_EQ(z.data()[0], std::exp(1.0)); EXPECT_EQ(z.data()[1], std::exp(1.0)); } TEST_F(ExpressionTest, ExpE) { auto x = aml::make_expression(aml::ones<double, 2>(h, aml::CPU, {1, 2})); auto z = aml::nans<double, 2>(h, aml::CPU, {1, 2}); aml::eval(h, z, aml::exp(x)); EXPECT_EQ(z.data()[0], std::exp(1.0)); EXPECT_EQ(z.data()[1], std::exp(1.0)); } /** LOG ***********************************************************************/ TEST_F(ExpressionTest, LogA) { auto x = aml::ones<double, 2>(h, aml::CPU, {1, 2}); auto z = aml::nans<double, 2>(h, aml::CPU, {1, 2}); aml::eval(h, z, aml::log(x)); EXPECT_EQ(z.data()[0], 0); EXPECT_EQ(z.data()[1], 0); } TEST_F(ExpressionTest, LogE) { auto x = aml::make_expression(aml::ones<double, 2>(h, aml::CPU, {1, 2})); auto z = aml::nans<double, 2>(h, aml::CPU, {1, 2}); aml::eval(h, z, aml::log(x)); EXPECT_EQ(z.data()[0], 0); EXPECT_EQ(z.data()[1], 0); } /** NEGATIVE ******************************************************************/ TEST_F(ExpressionTest, NegativeA) { auto x = aml::ones<double, 2>(h, aml::CPU, {1, 2}); auto z = aml::nans<double, 2>(h, aml::CPU, {1, 2}); aml::eval(h, z, -x); EXPECT_EQ(z.data()[0], -1); EXPECT_EQ(z.data()[1], -1); } TEST_F(ExpressionTest, NegativeE) { auto x = aml::make_expression(aml::ones<double, 2>(h, aml::CPU, {1, 2})); auto z = aml::nans<double, 2>(h, aml::CPU, {1, 2}); aml::eval(h, z, -x); EXPECT_EQ(z.data()[0], -1); EXPECT_EQ(z.data()[1], -1); } /** SQRT **********************************************************************/ TEST_F(ExpressionTest, SqrtA) { auto x = aml::ones<double, 2>(h, aml::CPU, {1, 2}); auto z = aml::nans<double, 2>(h, aml::CPU, {1, 2}); aml::eval(h, z, aml::sqrt(x)); EXPECT_EQ(z.data()[0], 1); EXPECT_EQ(z.data()[1], 1); } TEST_F(ExpressionTest, SqrtE) { auto x = aml::make_expression(aml::ones<double, 2>(h, aml::CPU, {1, 2})); auto z = aml::nans<double, 2>(h, aml::CPU, {1, 2}); aml::eval(h, z, aml::sqrt(x)); EXPECT_EQ(z.data()[0], 1); EXPECT_EQ(z.data()[1], 1); }
true
27eb6b73bf18f571c29669e4e2a4ca04ff44e075
C++
KozeevMaxim/BMSTU_LAB5
/Lab5.cpp
UTF-8
1,357
3.46875
3
[]
no_license
#include <iostream> #include <stdio.h> #include <stdlib.h> #include <locale.h> using namespace std; double sum(float a, float b) { return a + b; } double sub(float a, float b) { return a - b; } double mult(float a, float b) { return a * b; } int main(int argc, char *argv[]) { int a, b; if (argc < 3) { printf_s("Ошибка, параметров в командной строке не хватает для задания исходных данных. Для завершения нажмите любую клавишу\n"); system("pause"); return 1; } if (sscanf_s(argv[1], "%d", &a) < 1) { printf_s("Ошибка, неверный формат первого входного параметра. Для завершения нажмите любую клавишу\n"); system("pause"); return 1; } if (sscanf_s(argv[2], "%d", &b) < 1) { printf_s("Ошибка, неверный формат первого входного параметра. Для завершения нажмите любую клавишу\n"); system("pause"); return 1; } cout << "a + b = " << sum(a, b) << endl; cout << "a - b = " << sub(a, b) << endl; cout << "a * b = " << mult(a, b) << endl; system("pause"); return 0; }
true
6976a9b5ad5f0d1fd9d97d865d516ddc7a28da24
C++
hongxchen/algorithm007-class01
/Week_03/G20200343040045/LeetCode-590-0045.cpp
UTF-8
918
3.703125
4
[]
no_license
#include <iostream> #include <vector> using namespace std; class Node { public: int val; vector<Node*> children; Node() { } Node(int _val) { val = _val; } Node(int _val, vector<Node*> _children) { val = _val; children = _children; } }; /** * 题目:N叉树的后序遍历 * Solution: 递归法:使用辅助函数或者全局变量存放遍历结果 * 时间复杂度为O(n) 空间复杂度为O(n) * test Cases:空树[],[1,null,3,2,4,null.5,6] */ class Solution { public: vector<int> postorder(Node* root) { vector<int> res; helper(root, res); return res; } void helper(Node* root, vector<int>& res) { if (root != NULL) { for (int i = 0; i < root->children.size(); i++) helper(root->children[i], res); res.push_back(root->val); } } };
true
2dda7bb5718f89730c16bfa89e0b96ec5fc1acea
C++
karikera/ken
/KR3/common/text/nullterm.h
UTF-8
871
2.71875
3
[]
no_license
#pragma once #include "buffer.h" namespace kr { template <typename Buffer> class ToSZ : public Bufferable<ToSZ<Buffer>, BufferInfo<typename Buffer::Component, method::CopyTo, true, true>> { static_assert(IsBuffer<Buffer>::value, "Buffer is not buffer"); using Super = Bufferable<ToSZ<Buffer>, BufferInfo<typename Buffer::Component, method::CopyTo, true, true>>; public: using typename Super::Component; ToSZ(const Buffer& buffer) noexcept : m_buffer(buffer) { } size_t $copyTo(typename Buffer::Component * dest) const noexcept { size_t sz = m_buffer.copyTo(dest); if (!Buffer::szable) dest[sz] = (Component)0; return sz; } size_t $size() const noexcept { return m_buffer.size(); } private: const Buffer& m_buffer; };; template <class Buffer> ToSZ<Buffer> toSz(const Buffer &buffer) noexcept { return buffer; } }
true
bb8967a6626959a589cc03705c7f111d1ea99788
C++
SebiCoroian/pbinfo-sources
/monede.cpp
UTF-8
225
2.53125
3
[]
no_license
#include <iostream> using namespace std; int main() { int a, b, c, S, na, nb, nc; cin >> a >> b >> c >> S; nc = S/c, S %= c; nb = S/b, S %= b; na = S/a, S %= a; cout << na << " " << nb << " " << nc; return 0; }
true
b08e65cd916ecc2cdeb6cc76e4ea445aaf9a26d6
C++
yakirhelets/234218_DS
/HW2/GenericHashTable.h
UTF-8
5,432
3.078125
3
[]
no_license
// // Created by Yakir on 06/06/2017. // #ifndef WET2SPRING17_GENERICHASHTABLE_H #define WET2SPRING17_GENERICHASHTABLE_H #include <iostream> #define SIZE 6 #define C 3 template <class Data> class HashTable { public: class HashElement { Data data; int key; public: HashElement(const Data& data, int key) : data(data), key(key) {}; const Data& getData() const { return data; } Data& getData() { return data; } void setData(Data& data) { this->data = data; } const int& getKey() const { return key; } int& getKey() { return key; } void setKey(int key) { this->key = key; } }; private: static int resizeCount; int arrSize; int numOfVars; HashElement** arr; bool* isTakenForSearch; public: HashTable() { arrSize=resizeCount; numOfVars=0; arr = new HashElement*[arrSize]; isTakenForSearch = new bool[arrSize]; for (int i=0 ; i<arrSize ; i++) { arr[i]=NULL; isTakenForSearch[i]=false; } } ~HashTable() { for (int i=0 ; i<arrSize ; i++) { delete arr[i]; } delete[] arr; delete[] isTakenForSearch; } void insert(const Data& data, int key) { int index = key%arrSize; int r = 1+(key%(resizeCount/2))*2; while (arr[index] != NULL) { if (arr[index]->getKey()==key) { throw KeyAlreadyExists(); } index=(index+r)%arrSize; } if (arr[index]!=NULL) { throw KeyAlreadyExists(); } HashElement* newHashElement = new HashElement(data, key); arr[index] = newHashElement; numOfVars++; if (arrSize==numOfVars) { this->expand(); } } void remove(int key) { int index = key%arrSize; int r = 1+(key%(resizeCount/2))*2; int count=0; while (count++<arrSize &&((arr[index] == NULL && isTakenForSearch[index]) || (arr[index] != NULL && arr[index]->getKey()!=key))) { index=(index+r)%arrSize; } if (arr[index]==NULL || count >= arrSize) { throw KeyDoesNotExist(); } else { delete arr[index]; arr[index]=NULL; isTakenForSearch[index]=true; numOfVars--; } if ((arrSize/4)==numOfVars) { this->shrink(); } } const bool doesExist(int key) const { int index = key%arrSize; int r = 1+(key%(resizeCount/2))*2; int count=0; while (count++<arrSize &&((arr[index] == NULL && isTakenForSearch[index]) || (arr[index] != NULL && arr[index]->getKey()!=key))) { index=(index+r)%arrSize; } if(count >= arrSize){ return false; } return (arr[index] != NULL); } const Data& get(int key) const { int index = key%arrSize; int r = 1+(key%(resizeCount/2))*2; int count=0; while (count++<arrSize &&((arr[index] == NULL && isTakenForSearch[index]) || (arr[index] != NULL && arr[index]->getKey()!=key))) { index=(index+r)%arrSize; } if (arr[index]==NULL || count >= arrSize) { throw KeyDoesNotExist(); } else { return arr[index]->getData(); } } void expand() { resizeCount*=2; int oldSize=arrSize; arrSize=resizeCount; numOfVars=0; HashElement** oldArr = arr; arr = new HashElement*[arrSize]; bool* oldIsTaken = isTakenForSearch; isTakenForSearch = new bool[arrSize]; for (int i=0 ; i<arrSize ; i++) { arr[i]=NULL; isTakenForSearch[i]=false; } for (int i=0 ; i<oldSize ; i++) { if (oldArr[i]) { insert(oldArr[i]->getData(),oldArr[i]->getKey()); delete oldArr[i]; } } delete[] oldArr; delete[] oldIsTaken; } void shrink() { if (resizeCount == 1){ return; } resizeCount/=2; int oldSize=arrSize; arrSize=resizeCount; numOfVars=0; HashElement** oldArr = arr; arr = new HashElement*[arrSize]; bool* oldIsTaken = isTakenForSearch; isTakenForSearch = new bool[arrSize]; for (int i=0 ; i<arrSize ; i++) { arr[i]=NULL; isTakenForSearch[i]=false; } for (int i=0 ; i<oldSize ; i++) { if (oldArr[i]) { insert(oldArr[i]->getData(), oldArr[i]->getKey()); delete oldArr[i]; } } delete[] oldArr; delete[] oldIsTaken; } template<class Function> void forEach(Function func) { for (int i=0 ; i<arrSize ; i++) { if (arr[i]) { func(this->arr[i]->getData()); } } } class KeyAlreadyExists {}; class KeyDoesNotExist {}; }; template <class Data> int HashTable<Data>::resizeCount=4; #endif //WET2SPRING17_GENERICHASHTABLE_H
true
accce3c674f57af9e3be1ce06171ce0af337aaff
C++
ConsciousCoder07/Dcoder
/Easy/NumberedTriangle.cpp
UTF-8
279
2.828125
3
[]
no_license
#include <iostream> using namespace std; int main() { int n, row, col; cin >> n; for(row = 1; row <= n; row++) { for( col = 1; col <=row; col++) (col==row) ? cout << col : cout << col << " "; cout << "\n"; } return 0; }
true
bc56bc01f3854a2544187037920ab170804c6ff5
C++
friackazoid/Eigen_test
/quaternion_inv.cpp
UTF-8
876
3.046875
3
[]
no_license
#include <iostream> #include <iterator> #include <vector> #include <Eigen/Dense> #include <Eigen/Geometry> int main () { // (w, x, y, x) order Eigen::Quaterniond q(-0.00727927, 0.132765, 0.991118, 0.00251783); std::cout << "Q1: \n" << q.coeffs() << std::endl; std::cout << "Euler from Q1:\n " << q.toRotationMatrix().eulerAngles(0,1,2) << std::endl; Eigen::Quaterniond q1(0.00727927, -0.132765, -0.991118, -0.00251783); std::cout << "Q2: \n" << q1.coeffs() << std::endl; std::cout << "Euler from Q2:\n " << q1.toRotationMatrix().eulerAngles(0,1,2) << std::endl; std::cout << "=======================================\n"; q = Eigen::Quaterniond( -(q.coeffs()) ); std::cout << "Q1 flipped: \n" << q.coeffs() << std::endl; std::cout << "Euler from Q1:\n " << q.toRotationMatrix().eulerAngles(0,1,2) << std::endl; return 0; }
true
d54deea771ee7582a206600bfa6e8f6173c66c3d
C++
rabitdash/practice
/shiyanlou/Queue/src/Event.hpp
UTF-8
412
2.671875
3
[ "MIT" ]
permissive
#ifndef Event_hpp #define Event_hpp #include "Random.hpp" #define RANDOM_PARAMETER 100 struct Event { int occur_time; // -1 represents arrival, >=0 means diposal and the number represents service window. int event_type; Event *next; Event (int occur_time = Random::uniform (RANDOM_PARAMETER), int event_type = -1):occur_time (occur_time), event_type (event_type), next (NULL) { }}; #endif
true
982d068ff00f19f9c709c7912e5676a695f1e9c0
C++
leclem/satsolver_cpp
/include/base/clause.h
UTF-8
6,243
2.921875
3
[]
no_license
#ifndef CLAUSE_BASE_H #define CLAUSE_BASE_H #include "base/container.h" #include "base/literal.h" // class for clauses vars template<SATheuristic _ALG, LitChoice _WAT, ClauseChoice _CL> class CClause_vars { typedef CLiteral<_ALG, _WAT, _CL> Literal; public: virtual ~CClause_vars(){} protected: std::list<Literal> m_unassignedLit; std::list<Literal> m_goodAssignedLit; std::list<Literal> m_wrongAssignedLit; }; // class that can be inherited by clauses to specialize template<SATheuristic _ALG, LitChoice _WAT, ClauseChoice _CL> class CClause_base : virtual public CClause_vars<_ALG, _WAT, _CL> { typedef CLiteral<_ALG, _WAT, _CL> Literal; protected: using CClause_vars<_ALG, _WAT, _CL>::m_unassignedLit; using CClause_vars<_ALG, _WAT, _CL>::m_goodAssignedLit; using CClause_vars<_ALG, _WAT, _CL>::m_wrongAssignedLit; public: // return true if we can deduce something from a clause, and give the deduced literal bool deduction(Literal& lit) { // if the clause if verified, nothing to do. if(!m_goodAssignedLit.empty()) return false; // else if the clause is singleton if(CClause_vars<_ALG, _WAT, _CL>::m_unassignedLit.size() == 1) { lit = CClause_vars<_ALG, _WAT, _CL>::m_unassignedLit.front(); return true; } return false; } bool isVerified() { return !m_goodAssignedLit.empty();} void update(){} }; // class for all clauses operations template <SATheuristic _ALG, LitChoice _WAT, ClauseChoice _CL> class CClause : public CClause_base<_ALG, _WAT, _CL> { // Literal type typedef CLiteral<_ALG, _WAT, _CL> Literal; typedef typename std::list<Literal>::iterator LitIter; protected: using CClause_vars<_ALG, _WAT, _CL>::m_unassignedLit; using CClause_vars<_ALG, _WAT, _CL>::m_goodAssignedLit; using CClause_vars<_ALG, _WAT, _CL>::m_wrongAssignedLit; public: bool isTrivial() { // copy std::list<Literal> lit_list0 = m_unassignedLit; std::list<Literal> lit_list1 = m_goodAssignedLit; std::list<Literal> lit_list2 = m_wrongAssignedLit; lit_list0.splice(lit_list0.begin(), lit_list1); lit_list0.splice(lit_list0.begin(), lit_list1); lit_list0.sort(); typename std::list<Literal>::iterator it1 = lit_list0.begin(); typename std::list<Literal>::iterator it0 = it1++; for(;it1 != lit_list0.end();) { if(it0->variable() == it1->variable()) return true; it0++; it1++; } return false; } std::list<Literal>& assigneds(bool good) { if(good) return m_goodAssignedLit; else return m_wrongAssignedLit; } std::list<Literal>& unassigneds() { return m_unassignedLit;} bool conflict() { return m_unassignedLit.empty() && m_goodAssignedLit.empty(); } bool contains(Literal _l) { typename std::list<Literal>::iterator it; for(it = m_unassignedLit.begin(); it!= m_unassignedLit.end(); it++) if (*it == _l) return true; for(it = m_goodAssignedLit.begin(); it!= m_goodAssignedLit.end(); it++) if (*it == _l) return true; for(it = m_wrongAssignedLit.begin(); it!= m_wrongAssignedLit.end(); it++) if (*it == _l) return true; return false; } void addLiteral(Literal _l) { if(contains(_l)) return; if(!_l.variable()->isAssigned()) m_unassignedLit.push_front(_l); else { if(_l.logicValue() == _l.variable()->assignement()) m_goodAssignedLit.push_front(_l); else m_wrongAssignedLit.push_front(_l); } } void setAssigned() { for(LitIter it = m_unassignedLit.begin(); it != m_unassignedLit.end(); it++) it->variable()->numUnassignedClauses(it->logicValue())--; for(LitIter it = m_goodAssignedLit.begin(); it != m_goodAssignedLit.end(); it++) it->variable()->numUnassignedClauses(it->logicValue())--; for(LitIter it = m_wrongAssignedLit.begin(); it != m_wrongAssignedLit.end(); it++) it->variable()->numUnassignedClauses(it->logicValue())--; } void setUnassigned() { for(LitIter it = m_unassignedLit.begin(); it != m_unassignedLit.end(); it++) it->variable()->numUnassignedClauses(it->logicValue())++; for(LitIter it = m_goodAssignedLit.begin(); it != m_goodAssignedLit.end(); it++) it->variable()->numUnassignedClauses(it->logicValue())++; for(LitIter it = m_wrongAssignedLit.begin(); it != m_wrongAssignedLit.end(); it++) it->variable()->numUnassignedClauses(it->logicValue())++; } }; template<SATheuristic _ALG, LitChoice _WAT, ClauseChoice _CL> std::ostream& operator << (std::ostream& out , CClause<_ALG, _WAT, _CL>& c) { if (c.unassigneds().empty() && c.assigneds(true).empty() && c.assigneds(false).empty()) { out << "[ empty clause ]"; return out; } out << "[ "; if (!c.assigneds(true).empty()) { out << "sat("; typename std::list<CLiteral<_ALG, _WAT, _CL> >::iterator it = c.assigneds(true).begin(); out << " " << *(it++) << " "; for (; it != c.assigneds(true).end(); it++) out << "| " << *it << " "; out << ") "; } if (!c.assigneds(false).empty()) { out << "unsat("; typename std::list<CLiteral<_ALG, _WAT, _CL> >::iterator it = c.assigneds(false).begin(); out << " " << *(it++) << " "; for (; it != c.assigneds(false).end(); it++) out << "| " << *it << " "; out << ") "; } if (!c.unassigneds().empty()) { out << "free("; typename std::list<CLiteral<_ALG, _WAT, _CL> >::iterator it = c.unassigneds().begin(); out << " " << *(it++) << " "; for (; it != c.unassigneds().end(); it++) out << "| " << *it << " "; out << ") "; } out << "]"; return out; } #endif // CLAUSE_BASE_H
true
8d7f565327e3870a5abdaf89542193d430586b05
C++
Bassant-Yehia/Programs-using-different-languages
/E3rf Borgak.cpp
UTF-8
2,113
3.4375
3
[]
no_license
#include <iostream> using namespace std; int main() { int month,day; cout << "Enter your month of birth!" << endl; cin>>month; cout << "Enter your day of birth!" << endl; cin>>day; if(month>0&&month<=12||day>0&&day<=30) { if(month==1||month==12) { if (month==1&&day<22||month==12&&day>=22) cout<<"El-Gadi"<<endl; } if(month==2||month==1) { if (month==2&&day<22||month==1&&day>=22) cout<<"El-Dalw"<<endl; } if(month==3||month==2) { if (month==3&&day<22||month==2&&day>=22) cout<<"El-Howt"<<endl; } if(month==4||month==3) { if (month==4&&day<22||month==3&&day>=22) cout<<"El-Hamal"<<endl; } if(month==5||month==4) { if (month==5&&day<22||month==4&&day>=22) cout<<"El-Thoor"<<endl; } if(month==6||month==5) { if (month==6&&day<22||month==5&&day>=22) cout<<"El-Gawzaa"<<endl; } if(month==7||month==6) { if (month==7&&day<22||month==6&&day>=22) cout<<"El-Sartan"<<endl; } if(month==8||month==7) { if (month==8&&day<22||month==7&&day>=22) cout<<"El-Asad"<<endl; } if(month==9||month==8) { if (month==9&&day<22||month==8&&day>=22) cout<<"El-Azraa"<<endl; } if(month==10||month==9) { if (month==10&&day<22||month==9&&day>=22) cout<<"El-Mezan"<<endl; } if(month==11||month==10) { if (month==11&&day<22||month==10&&day>=22) cout<<"El-Akrab"<<endl; } if(month==12||month==11) { if (month==12&&day<22||month==11&&day>=22) cout<<"El-Koos"<<endl; } } return 0; }
true
f457bbbce96090375d4d2b30f9ceb597eb9a9f21
C++
zhaoyang110157/SE
/SE232/homework/bucket effect/bucket effect/main.cpp
UTF-8
1,296
3.078125
3
[]
no_license
// // main.cpp // bucket effect // // Created by 朱朝阳 on 2018/11/15. // Copyright © 2018年 朱朝阳. All rights reserved. // #include <iostream> #include <vector> #include <string> using namespace std; int Split(const string& src,const string& separator, vector<int>& dest) { string str = src; int tmp; int max=0; string::size_type start = 0, index; dest.clear(); index = str.find_first_of(separator,start); do { if (index != string::npos) { tmp = atoi(str.substr(start,index-start ).c_str()); if(tmp>max) max=tmp; dest.push_back(tmp); start =index+separator.size(); index = str.find(separator,start); if (start == string::npos) break; } }while(index != string::npos); //the last part tmp = atoi(str.substr(start ).c_str()); if(tmp>max) max=tmp; dest.push_back(tmp); return max; } int main(int argc, const char * argv[]) { int max; int water = 0; vector< int > input; vector< int > temp; string str; getline(cin,str); max=Split(str,",",input); while (max>0 && input.size()>0 ) { for(int i=0 ; i<input.size() ; i++) { if(input[i] == max) { temp.push_back(i); input[i]--; } } for(int i=0 ; i<temp.size()-1; i++ ) { water+=temp[i+1]-temp[i]-1; } temp.clear(); max--; } cout<<water; return 0; }
true
8d868c6e9957d02f8ce83fc7e827ead069790623
C++
bennycooly/school-projects
/EE_379K_EPL/students/byf69/Project3b/Valarray_PhaseB_unittests.cpp
UTF-8
7,780
2.875
3
[]
no_license
/* * valarray_PhaseB_unittests.cpp * EPL - Spring 2015 */ #include <chrono> #include <complex> #include <cstdint> #include <future> #include <iostream> #include <stdexcept> #include "InstanceCounter.h" #include "Valarray.h" #include "gtest/gtest.h" using std::cout; using std::endl; using std::string; using std::complex; using namespace epl; template <typename X, typename Y> bool match(X x, Y y) { double d = x - y; if (d < 0) { d = -d; } return d < 1.0e-9; // not really machine epsilon, but close enough } /*********************************************************************/ // Phase B Tests /*********************************************************************/ #if defined(PHASE_B0_0) | defined(PHASE_B) TEST(PhaseB, BasicOperation) { valarray<int> x(10); valarray<int> y(20); for (int i = 0; i < 10; i++) { x.push_back(1); } for (int i = 0; i < 5; i++) { x.pop_back(); } x = x + y; for (int i = 0; i < 10; i++) { EXPECT_EQ(0, x[i]); } for (int i = 10; i < 15; i++) { EXPECT_EQ(1, x[i]); } ////////////// std::cout << x << std::endl; ////////////// valarray<int> v1(20), v2(20), v3(20), v4(20), v5(20), v6(20), v7(20), v8(20); for (int i = 0; i<20; ++i) { v1[i] = i; v2[i] = i + 1; v3[i] = i * 2; v4[i] = i * 2 + 1; } v5 = v1 + v2; v6 = v3 - v4; v7 = v1 * v3; v8 = v4 / v2; for (int i = 0; i<20; ++i) { EXPECT_EQ(v5[i], v1[i] + v2[i]); EXPECT_EQ(v6[i], v3[i] - v4[i]); EXPECT_EQ(v7[i], v1[i] * v3[i]); EXPECT_EQ(v8[i], v4[i] / v2[i]); } // Differing sizes valarray<int> v9(10), v10(10), v11(10), v12(10); for (int i = 0; i<10; ++i) { v9[i] = v2[i]; v10[i] = v4[i]; } v5 = v1 + v9; v6 = v3 - v10; v7 = v1 * v9; v8 = v10 / v4; for (int i = 0; i<10; ++i) { EXPECT_EQ(v5[i], v1[i] + v9[i]); EXPECT_EQ(v6[i], v3[i] - v10[i]); EXPECT_EQ(v7[i], v1[i] * v9[i]); EXPECT_EQ(v8[i], v10[i] / v4[i]); } } #endif #if defined(PHASE_B0_1) | defined(PHASE_B) TEST(PhaseB, Lazy) { { valarray <double> v1, v2, v3, v4; for (int i = 0; i<10; ++i) { v1.push_back(1.0); v2.push_back(1.0); v3.push_back(1.0); v4.push_back(1.0); } int cnt = InstanceCounter::counter; v1 + v2 - (v3 * v4); EXPECT_EQ(cnt, InstanceCounter::counter); valarray<double> ans(10); ans = v1 + v2 - (v3*v4); EXPECT_TRUE(match(ans[3], (v1[3] + v2[3] - (v3[3] * v4[3])))); } { valarray<int> v1(5); v1 = 4 + v1; int cnt = InstanceCounter::counter; v1 * ((-((v1 * 4).sqrt())) + v1) / v1; EXPECT_EQ(cnt, InstanceCounter::counter); valarray<int> v2 = -((v1 * 4).sqrt()); for (int i = 0; i < v2.size(); ++i) { EXPECT_EQ(-4, v2[i]); } EXPECT_EQ(cnt + 1, InstanceCounter::counter); valarray<int> v3 = v1 * ((-((v1 * 4).sqrt())) + v1) / v1; for (int i = 0; i < v3.size(); ++i) { EXPECT_EQ(0, v3[i]); } EXPECT_EQ(cnt + 2, InstanceCounter::counter); } { valarray<int> v1(5); valarray<int> v2 = 4 + v1; for (int i = 0; i < 5; ++i) { v1[i] = i; } int cnt = InstanceCounter::counter; int sum = v1.sum(); EXPECT_EQ(10, sum); EXPECT_EQ(cnt, InstanceCounter::counter); sum = (v1 + v2).sum(); EXPECT_EQ(30, sum); EXPECT_EQ(cnt, InstanceCounter::counter); } { valarray<int> v1(5); v1 = 4 + v1; int cnt = InstanceCounter::counter; v1.sqrt(); EXPECT_EQ(cnt, InstanceCounter::counter); valarray<int> v2 = v1.sqrt(); for (int i = 0; i < v2.size(); ++i) { EXPECT_EQ(2, v2[i]); } EXPECT_EQ(cnt + 1, InstanceCounter::counter); } } #endif #if defined(PHASE_B0_2) | defined(PHASE_B) TEST(PhaseB, ValarrayToScalarOp) { { valarray<int> x(0); for (int i = 0; i < 10; i++) { x.push_back(1); } valarray<int> y = x + 1; for (int i = 0; i < 10; i++) { EXPECT_EQ(2, y[i]); } y = x - 1; for (int i = 0; i < 10; i++) { EXPECT_EQ(0, y[i]); } y = x * 1; for (int i = 0; i < 10; i++) { EXPECT_EQ(1, y[i]); } y = x / 1; for (int i = 0; i < 10; i++) { EXPECT_EQ(1, y[i]); } } { valarray<int> x(0); for (int i = 0; i < 10; i++) { x.push_back(1); } valarray<int> y = 1 + x; for (int i = 0; i < 10; i++) { EXPECT_EQ(2, y[i]); } y = 1 - x; for (int i = 0; i < 10; i++) { EXPECT_EQ(0, y[i]); } y = 1 * x; for (int i = 0; i < 10; i++) { EXPECT_EQ(1, y[i]); } y = 1 / x; for (int i = 0; i < 10; i++) { EXPECT_EQ(1, y[i]); } } } #endif #if defined(PHASE_B1_0) | defined(PHASE_B) TEST(PhaseB1, Sqrt) { valarray<int> v1(10); valarray<int> v4 = 4 + v1; valarray<float> v5 = v4.sqrt(); for (uint64_t i = 0; i<10; i++) { EXPECT_EQ(2.0, v5[i]); } } #endif #if defined(PHASE_B1_1) | defined(PHASE_B) TEST(PhaseB1, Apply) { valarray<int> v1(10); valarray<int> v4 = 4 + v1; valarray<int> v7 = v4.apply(std::negate<int>()); EXPECT_EQ(10, v7.size()); for (uint64_t i = 0; i<10; i++) { EXPECT_EQ(-4, v7[i]); } } #endif #if defined(PHASE_B1_2) | defined(PHASE_B) TEST(PhaseB1, Accumulate) { valarray<int> v1{1, 2, 3, 4, 5}; int sum = v1.accumulate(std::plus<int>()); int product = v1.accumulate(std::multiplies<int>()); EXPECT_EQ(15, sum); EXPECT_EQ(120, product); } #endif #if defined(PHASE_B1_3) | defined(PHASE_B) TEST(PhaseB1, Iterator) { valarray<int> x(10); for (auto yi : x) { EXPECT_EQ(0, yi); } valarray<int>::iterator ite = x.begin(); for (; ite != x.end(); ++ite) { EXPECT_EQ(0, *ite); } } #endif #if defined(PHASE_B1_4) | defined(PHASE_B) template <typename T> struct MultVal { T _val; using result_type = T; using argument_type = T; MultVal(T val) : _val(val) {} result_type operator()(T val) const { return val * _val; } }; TEST(PhaseB1, ApplyAccumulate) { { valarray<int> v1(10); valarray<int> v4 = 4 + v1; valarray<float> v5 = v4.sqrt(); for (uint64_t i = 0; i<10; i++) { EXPECT_EQ(2.0, v5[i]); } } { valarray<int> v1(10); valarray<int> v4 = 4 + v1; valarray<int> v7 = v4.apply(std::negate<int>()); EXPECT_EQ(v7.size(), 10); for (uint64_t i = 0; i<10; i++) { EXPECT_EQ(-4, v7[i]); } } { valarray<int> v1{1, 2, 3, 4, 5}; int sum = v1.accumulate(std::plus<int>()); int product = v1.accumulate(std::multiplies<int>()); EXPECT_EQ(15, sum); EXPECT_EQ(120, product); valarray<int> v2{ }; sum = v2.accumulate(std::plus<int>()); product = v2.accumulate(std::multiplies<int>()); EXPECT_EQ(0, sum); EXPECT_EQ(0, product); } { valarray<int> v1(10); valarray<int> v2 = 4 + v1; int cnt = InstanceCounter::counter; v2.apply(MultVal<int>(-2)); EXPECT_EQ(cnt, InstanceCounter::counter); valarray<int> v3 = v2.apply(MultVal<int>(-2)); EXPECT_EQ(cnt + 1, InstanceCounter::counter); EXPECT_EQ(10, v3.size()); for (uint64_t i = 0; i < 10; ++i) { EXPECT_EQ(-8, v3[i]); } } } #endif
true
40e5ee011fa6ea6ecee6aacd154cd62666e20c02
C++
lawtonsclass/f20-code-from-class
/csci40/lec17/ptrsAndClasses.cpp
UTF-8
260
3.46875
3
[]
no_license
#include <iostream> #include <string> using namespace std; int main() { string s = "abcd"; string* sp = &s; // sp isn't a string, but *sp is! cout << (*sp).size() << endl; cout << sp->size() << endl; // equivalent to the above line return 0; }
true
e97cf67990cd99c752e05d83266626f2558cc02e
C++
jonggeunpark/selfstudy
/baekjoon/cpp/math 2/BOJ_4948.cpp
UHC
641
3.0625
3
[]
no_license
//Baekjoon online judge //4948 //Ʈ #include <iostream> #include <math.h> using namespace std; #define SIZE 246912 void setArr(bool arr[]) { fill_n(arr, SIZE + 2, true); arr[1] = false; for (int i = 2; i <= sqrt(SIZE); i++) { if (arr[i] == true) { for (int j = i * 2; j <= SIZE; j++) { if (j%i == 0) { arr[j] = false; } } } } } int main() { int n; int count; bool arr[SIZE + 2]; setArr(arr); while (1) { count = 0; cin >> n; if (n == 0) break; for (int i = n+1; i <= 2*n; i++) { if (arr[i] == true) count++; } cout << count << endl; } return 0; }
true
12b5e8579f9eeb944013fc4350c66dba4f2cbe31
C++
marinelns/cpp
/TP3/src/GerstnerWave.h
UTF-8
953
3.109375
3
[]
no_license
#ifndef GerstnerWaveH #define GerstnerWaveH #include "Dvector.h" #include <cmath> //classe dont chaque instance contient la definition d'une onde differente class GerstnerWave{ protected : double _amplitude; double _phase; Dvector _directionOnde; double _frequence; public : /*constructeur par défaut*/ GerstnerWave(); /*constructeur avec initialisation des paramètres*/ GerstnerWave(double ampl, double phas, Dvector dir, double freq); /*constructeur par copie*/ GerstnerWave(const GerstnerWave& g); /*destructeur*/ ~GerstnerWave(); /*accesseurs*/ double getAmplitude() const; double getPhase() const; Dvector getDirection() const; double getFrequence() const; /*operateur d'affectation*/ GerstnerWave& operator = (const GerstnerWave& g); /*operateur permettant d'acceder a la classe comme un foncteur*/ double operator()(Dvector point, double t); }; #endif
true
69895d01bffa07ca91a0561212eff3d6b7933ed3
C++
lumip/computegraphlib
/cglib/src/nodes/VariableNode.cpp
UTF-8
1,118
2.65625
3
[ "MIT" ]
permissive
#include "nodes/VariableNode.hpp" #include "CompilationMemoryMap.hpp" #include "GraphCompilationPlatform.hpp" VariableNode::VariableNode(std::string name) : Node(true, true) , _name(name) , _input(nullptr) { } VariableNode::~VariableNode() {} void VariableNode::SetInput(const NodePtr inputNode) { if (_input != nullptr) { this->UnsubscribeFrom(_input); } _input = inputNode; if (_input != nullptr) { this->SubscribeTo(_input); } } Node::ConstNodeList VariableNode::GetInputs() const { if (_input != nullptr) { return ConstNodeList({ _input }); } return ConstNodeList{}; } std::string VariableNode::ToString() const { return "<VariableNode " + _name + ">"; } void VariableNode::Compile(GraphCompilationPlatform& platform) const { platform.CompileVariableNode(this); } void VariableNode::GetMemoryDimensions(CompilationMemoryMap& memoryMap) const { const MemoryDimensions initDim = memoryMap.GetInputDimensions(_name); memoryMap.RegisterNodeMemory(this, initDim); memoryMap.RegisterVariableNode(_name, this); }
true
8d1c8d00ceee46c9c393624883ad792f0fcfca2f
C++
sanjusss/leetcode-cpp
/1000/1600/1650/1658.cpp
UTF-8
852
2.65625
3
[]
no_license
/* * @Author: sanjusss * @Date: 2023-01-07 15:17:01 * @LastEditors: sanjusss * @LastEditTime: 2023-01-07 15:25:02 * @FilePath: \1000\1600\1650\1658.cpp */ #include "leetcode.h" class Solution { public: int minOperations(vector<int>& nums, int x) { int sum = accumulate(nums.begin(), nums.end(), 0); int target = sum - x; if (target < 0) { return -1; } int n = nums.size(); int ans = INT_MAX; int left = 0; int right = 0; int cur = 0; while (left < n) { while (right < n && cur < target) { cur += nums[right++]; } if (cur == target) { ans = min(ans, n - (right - left)); } cur -= nums[left++]; } return ans == INT_MAX ? -1 : ans; } };
true
37d339c019d73d338ba6b5c261bafdcf554e0e3e
C++
biheng/hana
/include/boost/hana/fwd/type.hpp
UTF-8
20,808
2.890625
3
[ "LicenseRef-scancode-unknown-license-reference", "BSL-1.0" ]
permissive
/*! @file Forward declares `boost::hana::Type` and `boost::hana::Metafunction`. @copyright Louis Dionne 2015 Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) */ #ifndef BOOST_HANA_FWD_TYPE_HPP #define BOOST_HANA_FWD_TYPE_HPP namespace boost { namespace hana { //! @ingroup group-datatypes //! Tag representing a C++ type in value-level representation. //! //! A `Type` is a special kind of object representing a C++ type like //! `int`, `void`, `std::vector<float>` or anything else you can imagine. //! //! This page explains how `Type`s work at a low level. To gain intuition //! about type-level metaprogramming in Hana, you should read the //! [tutorial section](@ref tutorial-type) on type-level computations. //! //! //! The actual representation of a Type //! ----------------------------------- //! For subtle reasons having to do with ADL, the actual type of the //! `type<T>` expression is not `_type<T>`. It is a dependent type //! which inherits `_type<T>`. Hence, you should never rely on the //! fact that `type<T>` is of type `_type<T>`, but you can rely on //! the fact that it inherits it, which is different in some contexts, //! e.g. for template specialization. //! //! //! Lvalues and rvalues //! ------------------- //! When storing `Type`s in heterogeneous containers, some algorithms will //! return references to those objects. Since we are primarily interested //! in accessing their nested `::type`, receiving a reference is //! undesirable; we would end up trying to fetch the nested `::type` //! inside a reference type, which is a compilation error: //! @code //! auto ts = make_tuple(type<int>, type<char>); //! using T = decltype(ts[0_c])::type; // error: 'ts[0_c]' is a reference! //! @endcode //! //! For this reason, `Type`s provide an overload of the unary `+` operator //! that can be used to turn a lvalue into a rvalue. So when using a result //! which might be a reference to a `Type` object, one can use `+` to make //! sure a rvalue is obtained before fetching its nested `::type`: //! @code //! auto ts = make_tuple(type<int>, type<char>); //! using T = decltype(+ts[0_c])::type; // ok: '+ts[0_c]' is an rvalue //! @endcode //! //! //! Modeled concepts //! ---------------- //! 1. `Comparable`\n //! Two `Type`s are equal if and only if they represent the same C++ type. //! Hence, equality is equivalent to the `std::is_same` type trait. //! @include example/type/comparable.cpp struct Type { }; //! Creates an object representing the C++ type `T`. //! @relates Type #ifdef BOOST_HANA_DOXYGEN_INVOKED template <typename T> constexpr unspecified-type type{}; #else template <typename T> struct _type { struct _; }; template <typename T> constexpr typename _type<T>::_ type{}; #endif namespace gcc_wknd { template <typename T> constexpr auto mktype() { return type<T>; } } //! `decltype` keyword, lifted to Hana. //! @relates Type //! //! `decltype_` is somewhat equivalent to `decltype` in that it returns //! the type of an object, except it returns it as a `Type` object which //! is a first-class citizen of Hana instead of a raw C++ type. //! Specifically, given an object `x`, `decltype_` satisfies //! @code //! decltype_(x) == type<decltype(x) with references stripped> //! @endcode //! //! As you can see, `decltype_` will strip any reference from the //! object's actual type. The reason for doing so is explained below. //! However, any `cv`-qualifiers will be retained. Also, when given a //! `Type` object, `decltype_` is just the identity function. Hence, for //! any C++ type `T`, //! @code //! decltype_(type<T>) == type<T> //! @endcode //! //! In conjunction with the way `metafunction` & al. are specified, this //! behavior makes it easier to interact with both types and values at //! the same time. However, it does make it impossible to create a Type //! containing a Type with `decltype_`. In other words, it is not possible //! to create a `type<decltype(type<T>)>` with this utility, because //! `decltype_(type<T>)` would be just `type<T>` instead of //! `type<decltype(type<T>)>`. This use case is assumed to be //! rare and a hand-coded function can be used if this is needed. //! //! //! ### Rationale for stripping the references //! The rules for template argument deduction are such that a perfect //! solution that always matches `decltype` is impossible. Hence, we //! have to settle on a solution that's good and and consistent enough //! for our needs. One case where matching `decltype`'s behavior is //! impossible is when the argument is a plain, unparenthesized variable //! or function parameter. In that case, `decltype_`'s argument will be //! deduced as a reference to that variable, but `decltype` would have //! given us the actual type of that variable, without references. Also, //! given the current definition of `metafunction` & al., it would be //! mostly useless if `decltype_` could return a reference, because it //! is unlikely that `F` expects a reference in its simplest use case: //! @code //! int i = 0; //! auto result = metafunction<F>(i); //! @endcode //! //! Hence, always discarding references seems to be the least painful //! solution. //! //! //! Example //! ------- //! @include example/type/decltype.cpp #ifdef BOOST_HANA_DOXYGEN_INVOKED constexpr auto decltype_ = see documentation; #else struct decltype_t { template <typename T> constexpr auto operator()(T&&) const; }; constexpr decltype_t decltype_{}; #endif #ifdef BOOST_HANA_DOXYGEN_INVOKED //! Equivalent to `decltype_`, provided for convenience. //! @relates Type //! //! //! Example //! ------- //! @include example/type/make.cpp template <> constexpr auto make<Type> = decltype_; #endif //! `sizeof` keyword, lifted to Hana. //! @relates Type //! //! `sizeof_` is somewhat equivalent to `sizeof` in that it returns the //! size of an expression or type, but it takes an arbitrary expression //! or a Type object and returns its size as an IntegralConstant. //! Specifically, given an expression `expr`, `sizeof_` satisfies //! @code //! sizeof_(expr) == size_t<sizeof(decltype(expr) with references stripped)> //! @endcode //! //! However, given a Type object, `sizeof_` will simply fetch the size //! of the C++ type represented by that object. In other words, //! @code //! sizeof_(type<T>) == size_t<sizeof(T)> //! @endcode //! //! The behavior of `sizeof_` is consistent with that of `decltype_`. //! In particular, see `decltype_`'s documentation to understand why //! references are always stripped by `sizeof_`. //! //! //! Example //! ------- //! @include example/type/sizeof.cpp #ifdef BOOST_HANA_DOXYGEN_INVOKED constexpr auto sizeof_ = [](auto&& x) { using T = typename decltype(hana::decltype_(x))::type; return hana::size_t<sizeof(T)>; }; #else struct sizeof_t { template <typename T> constexpr auto operator()(T&&) const; }; constexpr sizeof_t sizeof_{}; #endif //! `alignof` keyword, lifted to Hana. //! @relates Type //! //! `alignof_` is somewhat equivalent to `alignof` in that it returns the //! alignment required by any instance of a type, but it takes a Type //! object and returns its alignment as an IntegralConstant. Like `sizeof` //! which works for expressions and type-ids, `alignof_` can also be //! called on an arbitrary expression. Specifically, given an expression //! `expr` and a C++ type `T`, `alignof_` satisfies //! @code //! alignof_(expr) == size_t<alignof(decltype(expr) with references stripped)> //! alignof_(type<T>) == size_t<alignof(T)> //! @endcode //! //! The behavior of `alignof_` is consistent with that of `decltype_`. //! In particular, see `decltype_`'s documentation to understand why //! references are always stripped by `alignof_`. //! //! //! Example //! ------- //! @include example/type/alignof.cpp #ifdef BOOST_HANA_DOXYGEN_INVOKED constexpr auto alignof_ = [](auto&& x) { using T = typename decltype(decltype_(x))::type; return size_t<alignof(T)>; }; #else struct alignof_t { template <typename T> constexpr auto operator()(T&&) const; }; constexpr alignof_t alignof_{}; #endif //! Checks whether a SFINAE-friendly expression is valid. //! @relates Type //! //! Given a SFINAE-friendly function, `is_valid` returns whether the //! function call is valid with the given arguments. Specifically, given //! a function `f` and arguments `args...`, //! @code //! is_valid(f, args...) == whether f(args...) is valid //! @endcode //! //! The result is returned as a compile-time `Logical`. Furthermore, //! `is_valid` can be used in curried form as follows: //! @code //! is_valid(f)(args...) //! @endcode //! //! This syntax makes it easy to create functions that check the validity //! of a generic expression on any given argument(s). //! //! @warning //! To check whether calling a nullary function `f` is valid, one should //! use the `is_valid(f)()` syntax. Indeed, `is_valid(f /* no args */)` //! will be interpreted as the currying of `is_valid` to `f` rather than //! the application of `is_valid` to `f` and no arguments. //! //! //! Example //! ------- //! @include example/type/is_valid.cpp #ifdef BOOST_HANA_DOXYGEN_INVOKED constexpr auto is_valid = [](auto&& f) { return [](auto&& ...args) { return whether f(args...) is a valid expression; }; }; #else struct is_valid_t { template <typename F> constexpr auto operator()(F&&) const; template <typename F, typename ...Args> constexpr auto operator()(F&&, Args&&...) const; }; constexpr is_valid_t is_valid{}; #endif //! @ingroup group-datatypes //! A `Metafunction` is a function that takes `Type`s as inputs and //! gives a `Type` as output. //! //! Hana provides adapters for representing several different kinds of //! metafunctions in a unified way, as normal C++ functions. The general //! process is always essentially the same. For example, given a MPL //! metafunction, we can create a normal C++ function that takes `Type` //! objects and returns a `Type` object containing the result of that //! metafunction: //! @code //! template <template <typename ...> class F> //! struct _metafunction { //! template <typename ...T> //! constexpr auto operator()(_type<T> const& ...) const { //! return hana::type<typename F<T...>::type>; //! } //! }; //! //! template <template <typename ...> class F> //! constexpr _metafunction<F> metafunction{}; //! @endcode //! //! The variable template is just for convenience, so we can write //! `metafunction<F>` instead of `_metafunction<F>{}`, but they are //! otherwise equivalent. With the above construct, it becomes possible //! to perform type computations with the usual function call syntax, by //! simply wrapping our classic metafunctions into a `metafunction` object: //! @code //! constexpr auto add_pointer = metafunction<std::add_pointer>; //! static_assert(add_pointer(type<int>) == type<int*>, ""); //! @endcode //! //! While this covers only classical MPL-style metafunctions, Hana //! provides wrappers for several constructs that are commonly used //! to embed type computations: template aliases and MPL-style //! metafunction classes. A type computation wrapped into such a //! construct is what Hana calls a `Metafunction`. However, note that //! not all metafunctions can be lifted this way. For example, //! `std::aligned_storage` can't be lifted because it requires non-type //! template parameters. Since there is no uniform way of dealing with //! non-type template parameters, one must resort to using e.g. an //! inline lambda to "lift" those metafunctions. In practice, however, //! this should not be a problem. //! //! __Example of a non-liftable metafunction__ //! @snippet example/type/non_liftable_metafunction.cpp extent //! //! //! In addition to being Callable, `Metafunction`s provide a nested `apply` //! template which allows performing the same type-level computation as //! is done by the call operator. In Boost.MPL parlance, a `Metafunction` //! `F` is also a Boost.MPL MetafunctionClass in addition to being a //! function on `Type`s. In other words again, a `Metafunction` `f` will //! satisfy: //! @code //! f(type<T>...) == type<decltype(f)::apply<T...>::type> //! @endcode //! //! But that is not all. To ease the inter-operation of values and types, //! `Metafunction`s also allow being called with arguments that are not //! `Type`s. In that case, the result is equivalent to calling the //! metafunction on the result of `decltype_`ing the arguments. //! Specifically, given a `Metafunction` `f` and arbitrary (`Type` or //! non-`Type`) objects `x...`, //! @code //! f(x...) == f(decltype_(x)...) //! @endcode //! //! So `f` is called with the type of its arguments, but since `decltype_` //! is just the identity for `Type`s, only non-`Type`s are lifted to the //! `Type` level. //! //! //! Rationale: Why aren't `Metafunction`s `Comparable`? //! --------------------------------------------------- //! When seeing `hana::template_`, a question that naturally arises is //! whether `Metafunction`s should be made `Comparable`. Indeed, it would //! seem to make sense to compare two templates `F` and `G` with //! `template_<F> == template_<G>`. However, in the case where `F` and/or //! `G` are alias templates, it makes sense to talk about two types of //! comparisons. The first one is _shallow_ comparison, and it determines //! that two alias templates are equal if they are the same alias template. //! The second one is _deep_ comparison, and it determines that two template //! aliases are equal if they alias the same type for any template argument. //! For example, given `F` and `G` defined as //! @code //! template <typename T> //! using F = void; //! //! template <typename T> //! using G = void; //! @endcode //! //! shallow comparison would determine that `F` and `G` are different //! because they are two different template aliases, while deep comparison //! would determine that `F` and `G` are equal because they always //! expand to the same type, `void`. Unfortunately, deep comparison is //! impossible to implement because one would have to check `F` and `G` //! on all possible types. On the other hand, shallow comparison is not //! satisfactory because `Metafunction`s are nothing but functions on //! `Type`s, and the equality of two functions is normally defined with //! deep comparison. Hence, we adopt a conservative stance and avoid //! providing comparison for `Metafunction`s. struct Metafunction { }; //! Lift a template to a Metafunction. //! @relates Metafunction //! //! Given a template class or template alias `f`, `template_<f>` is a //! `Metafunction` satisfying //! @code //! template_<f>(type<x>...) == type<f<x...>> //! decltype(template_<f>)::apply<x...>::type == f<x...> //! @endcode //! //! @note //! `template_` can't be SFINAE-friendly right now because of //! [Core issue 1430][1]. //! //! //! Example //! ------- //! @include example/type/template.cpp //! //! [1]: http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1430 #ifdef BOOST_HANA_DOXYGEN_INVOKED template <template <typename ...> class F> constexpr auto template_ = [](_type<T>-or-T ...) { return type<F<T...>>; }; #else template <template <typename ...> class F> struct template_t; template <template <typename ...> class F> constexpr template_t<F> template_{}; #endif //! Lift a MPL-style metafunction to a function on `Type`s. //! @relates Metafunction //! //! Given a MPL-style metafunction, `metafunction<f>` is a `Metafunction` //! satisfying //! @code //! metafunction<f>(type<x>...) == type<f<x...>::type> //! decltype(metafunction<f>)::apply<x...>::type == f<x...>::type //! @endcode //! //! //! Example //! ------- //! @include example/type/metafunction.cpp #ifdef BOOST_HANA_DOXYGEN_INVOKED template <template <typename ...> class F> constexpr auto metafunction = [](_type<T>-or-T ...) { return type<typename F<T...>::type>; }; #else template <template <typename ...> class f> struct metafunction_t; template <template <typename ...> class f> constexpr metafunction_t<f> metafunction{}; #endif //! Lift a MPL-style metafunction class to a function on `Type`s. //! @relates Metafunction //! //! Given a MPL-style metafunction class, `metafunction_class<f>` is a //! `Metafunction` satisfying //! @code //! metafunction_class<f>(type<x>...) == type<f::apply<x...>::type> //! decltype(metafunction_class<f>)::apply<x...>::type == f::apply<x...>::type //! @endcode //! //! //! Example //! ------- //! @include example/type/metafunction_class.cpp #ifdef BOOST_HANA_DOXYGEN_INVOKED template <typename F> constexpr auto metafunction_class = [](_type<T>-or-T ...) { return type<typename F::template apply<T...>::type>; }; #else template <typename F> struct metafunction_class_t : metafunction_t<F::template apply> { }; template <typename F> constexpr metafunction_class_t<F> metafunction_class{}; #endif //! Turn a `Metafunction` into a function taking `Type`s and returning a //! default-constructed object. //! @relates Metafunction //! //! Given a `Metafunction` `f`, `integral` returns a new `Metafunction` //! that default-constructs an object of the type returned by `f`. More //! specifically, the following holds: //! @code //! integral(f)(t...) == decltype(f(t...))::type{} //! @endcode //! //! The principal use case for `integral` is to transform `Metafunction`s //! returning a type that inherits from a meaningful base like //! `std::integral_constant` into functions returning e.g. an //! `IntegralConstant`. //! //! @note //! - This is not a `Metafunction` because it does not return a `Type`. //! As such, it would not make sense to make `decltype(integral(f))` //! a MPL metafunction class like the usual `Metafunction`s are. //! //! - When using `integral` with metafunctions returning //! `std::integral_constant`s, don't forget to include the //! boost/hana/ext/std/integral_constant.hpp header to ensure //! Hana can interoperate with the result. //! //! //! Example //! ------- //! @include example/type/integral.cpp #ifdef BOOST_HANA_DOXYGEN_INVOKED constexpr auto integral = [](auto f) { return [](_type<T>-or-T ...) { return decltype(f)::apply<T...>::type{}; }; }; #else template <typename F> struct integral_t; struct make_integral_t { template <typename F> constexpr integral_t<F> operator()(F const&) const { return {}; } }; constexpr make_integral_t integral{}; #endif //! Alias to `integral(metafunction<F>)`, provided for convenience. //! @relates Metafunction //! //! //! Example //! ------- //! @include example/type/trait.cpp template <template <typename ...> class F> constexpr auto trait = integral(metafunction<F>); }} // end namespace boost::hana #endif // !BOOST_HANA_FWD_TYPE_HPP
true
890166deb2ab686a96155827b015595280aee510
C++
vivekgopalshetty/code
/dp/topdown/zero_one_knapsnack.cpp
UTF-8
871
2.640625
3
[]
no_license
#include<bits/stdc++.h> using namespace std; int zero_one(int weights[],int profits[],int dp[100][100],int start,int capacity,int n) { if(capacity<0 || start>=n) { return 0; } if(dp[start][capacity]!=0) { return dp[start][capacity]; } int x1=0; if(capacity>=weights[start]) { x1=profits[start]+zero_one(weights,profits,dp,start+1,capacity-weights[start],n); } int x2=zero_one(weights,profits,dp,start+1,capacity,n); dp[start][capacity]=max(x1,x2); return dp[start][capacity]; } int main() { int n; cin>> n; int weights[n]; int profits[n]; for(int i=0;i<n;i++) { cin >> weights[i]; } for(int i=0;i<n;i++) { cin >> profits[i]; } int x; cin >> x; int dp[100][100]={}; cout << zero_one(weights,profits,dp,0,x,n); }
true
26df482767359fa1deaac4c49dfafebe0df88233
C++
azujuuuuuun/kyoupro
/AtCoder/ABC/087/c.cpp
UTF-8
462
2.671875
3
[]
no_license
#include <iostream> using namespace std; const int N_MAX = 100; int main (void) { int n; int a[2][N_MAX]; cin >> n; for (int i = 0; i < 2; i++) { for (int j = 0; j < n; j++) { cin >> a[i][j]; } } for (int i = 1; i < n; i++) a[0][i] += a[0][i - 1]; a[1][0] += a[0][0]; for (int i = 1; i < n; i++) { a[1][i] += max(a[0][i], a[1][i - 1]); } cout << a[1][n - 1] << endl; return 0; }
true
0e7f091d1be2474e83b2d1cde57584b81db3b077
C++
shuxiangguo/sxg_leetcode
/575.分糖果.cpp
UTF-8
1,719
3.609375
4
[]
no_license
/* * @lc app=leetcode.cn id=575 lang=cpp * * [575] 分糖果 * * https://leetcode-cn.com/problems/distribute-candies/description/ * * algorithms * Easy (63.88%) * Likes: 47 * Dislikes: 0 * Total Accepted: 13.3K * Total Submissions: 20.5K * Testcase Example: '[1,1,2,2,3,3]' * * * 给定一个偶数长度的数组,其中不同的数字代表着不同种类的糖果,每一个数字代表一个糖果。你需要把这些糖果平均分给一个弟弟和一个妹妹。返回妹妹可以获得的最大糖果的种类数。 * * 示例 1: * * * 输入: candies = [1,1,2,2,3,3] * 输出: 3 * 解析: 一共有三种种类的糖果,每一种都有两个。 * ⁠ 最优分配方案:妹妹获得[1,2,3],弟弟也获得[1,2,3]。这样使妹妹获得糖果的种类数最多。 * * * 示例 2 : * * * 输入: candies = [1,1,2,3] * 输出: 2 * 解析: 妹妹获得糖果[2,3],弟弟获得糖果[1,1],妹妹有两种不同的糖果,弟弟只有一种。这样使得妹妹可以获得的糖果种类数最多。 * * * 注意: * * * 数组的长度为[2, 10,000],并且确定为偶数。 * 数组中数字的大小在范围[-100,000, 100,000]内。 * * * * * */ // @lc code=start #include<iostream> #include<vector> #include<set> using namespace std; class Solution { public: int distributeCandies(vector<int>& candies) { set<int> my_set; for (auto& candy : candies) { my_set.insert(candy); } int set_size = my_set.size(); if (set_size <= candies.size() / 2) { return set_size; } else { return candies.size() / 2; } } }; // @lc code=end
true
b7d73ee74508874c7f3a3a0c4cc381a0cb246239
C++
fja0kl/LeetCode-Path
/CodingInterviews/栈的压入弹出序列/solution.cpp
UTF-8
580
3.0625
3
[]
no_license
class Solution { public: bool IsPopOrder(vector<int> pushV,vector<int> popV) { if (pushV.empty() || popV.empty()) return false; if (pushV.size() != popV.size()) return false; stack<int> dataStack; for (int i=0, j=0; i<pushV.size();){ dataStack.push(pushV[i++]);//入栈 // 如果栈顶元素和当前pop序列头元素相同,弹出 while (j<popV.size() && dataStack.top() == popV[j]){ dataStack.pop(); j++; } } return dataStack.empty(); } };
true
f58d63383f3334567a565a761c26e57c5395206e
C++
lucas54neves/gcc224-ialg
/Lista de estruturas de repetição/Questão 20 - Cálculo de PI/exercicio20.cpp
UTF-8
301
2.8125
3
[]
no_license
#include <iostream> #include <math.h> using namespace std; int main () { int nTermos, n; double valorPi, a1; cin >> nTermos; valorPi = 1; a1 = 0; n = 1; while (n <= nTermos) { a1 = sqrt(a1+2); valorPi *= a1/2; n++; } valorPi = pow(valorPi/2, -1); cout << valorPi << endl; return 0; }
true