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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
8add3014a00d917ced540869982bea0038c329aa | C++ | 404845560/Code | /HeapSort/HeapSort.cpp | GB18030 | 1,173 | 3.4375 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <vector>
using namespace std;
template<class T>
void AdjustDown(vector<T> &vec, int k, int len){
//kԪµ
vec[0] = vec[k]; //ݴ
int i;
for (i = 2*k; i <= len; i*=2)
{
if (i < len&&vec[i] < vec[i + 1]) i++; //ȡkeyϴӽڵ±
if (vec[0] >= vec[i]) break; //ɸѡ
else{
vec[k] = vec[i];
k = i;
}
}
vec[k] = vec[0];//ɸѡڵֵλ
}
template<class T>
void BuildMaxHeap(vector<T> &vec,int len){
//
int i;
//int len = vec.size()-1;
for (i = len / 2; i > 0; i--){ //n/2~1
AdjustDown(vec,i,len);
}
}
template<class T>
void Swap(T &a, T &b){
a = a + b;
b = a - b;
a = a - b;
}
template<class T>
void HeapSort(vector<T> &vec){
//0Ԫز
int i,len = vec.size()-1;
BuildMaxHeap(vec,len);
for (i = len; i > 1; i--){
Swap(vec[1],vec[i]);
AdjustDown(vec,1,i-1);
}
}
int main(){
float array[] = { 1, 2.4, 8.8, 4, 1, 4, 6, 8 };
vector<float> vec(array, array + 8);
HeapSort(vec);
for each (float var in vec)
{
cout << var << endl;
}
return 0;
} | true |
0b4ebe7da7d7bd99ab8fa5bc27d9b730d261f48a | C++ | Aria-K-Alethia/Sudoku | /SE-Single-Project[测试用]/Output.cpp | UTF-8 | 834 | 2.9375 | 3 | [] | no_license | #include "stdafx.h"
#include "iostream"
#include "Output.h"
using namespace std;
/*
@overview:this file implement the class Output in Output.h
*/
Output::Output()
{
}
void Output::error(int code)
{
/*
@overview:showing error info on screen corresponding to the code.
*/
if (code == 1) cout << "Error code 1:bad number of parameters." << endl;
else if (code == 2) cout << "Error code 2:bad instruction.expect -c or -s" << endl;
else if (code == 3) cout << "Error code 3:bad number of instruction -c" << endl;
else if (code == 4) cout << "Error code 4:bad file name" << endl;
else if (code == 5) cout << "Error code 5:bad file format" << endl;
else if (code == 6) cout << "Error code 6:bad file.can not solve the sudoku"<<endl;
else if (code == 7) cout << "Error code 7:bad generating of sudoku" << endl;
exit(-1);
}
| true |
b4a732125d4d4296b830fa5e976d2b6b7c1fd749 | C++ | SOFTK2765/PS | /BOJ/2596.cpp | UTF-8 | 1,423 | 2.578125 | 3 | [] | no_license | #include <stdio.h>
#include <string.h>
int main()
{
int n, tf=0;
scanf("%d", &n);
char a[61], t[61], p[11];
memset(a, 0, sizeof(a));
memset(p, 0, sizeof(p));
scanf("%s", a);
int l=strlen(a);
for(int i=0;i<l/6;i++)
{
strncpy(t, a+i*6, 6);
if(strcmp(t, "000000")==0) p[i]='A';
else if(strcmp(t, "001111")==0) p[i]='B';
else if(strcmp(t, "010011")==0) p[i]='C';
else if(strcmp(t, "011100")==0) p[i]='D';
else if(strcmp(t, "100110")==0) p[i]='E';
else if(strcmp(t, "101001")==0) p[i]='F';
else if(strcmp(t, "110101")==0) p[i]='G';
else if(strcmp(t, "111010")==0) p[i]='H';
else
{
for(int j=0;j<6;j++)
{
t[j]=(t[j]=='0')?'1':'0';
if(strcmp(t, "000000")==0)
{
p[i]='A';
break;
}
else if(strcmp(t, "001111")==0)
{
p[i]='B';
break;
}
else if(strcmp(t, "010011")==0)
{
p[i]='C';
break;
}
else if(strcmp(t, "011100")==0)
{
p[i]='D';
break;
}
else if(strcmp(t, "100110")==0)
{
p[i]='E';
break;
}
else if(strcmp(t, "101001")==0)
{
p[i]='F';
break;
}
else if(strcmp(t, "110101")==0)
{
p[i]='G';
break;
}
else if(strcmp(t, "111010")==0)
{
p[i]='H';
break;
}
t[j]=(t[j]=='0')?'1':'0';
if(j==5) tf++;
}
if(tf==1)
{
printf("%d", i+1);
break;
}
}
}
if(tf!=1) printf("%s", p);
return 0;
}
| true |
b7c4512cf8205c0db45fffd09e85f6331eb483f0 | C++ | rathoresrikant/HacktoberFestContribute | /rmvowel.cpp | UTF-8 | 407 | 3.25 | 3 | [
"MIT"
] | permissive | #include <bits/stdc++.h>
using namespace std;
bool is_vow(char c)
{
return (c == 'a') || (c == 'e') ||
(c == 'i') || (c == 'o') ||
(c == 'u');
}
void removeVowels(string str)
{
printf("%c", str[0]);
for (int i = 1; str[i]; i++)
if ((!is_vow(str[i - 1])) ||
(!is_vow(str[i])))
printf("%c", str[i]);
}
int main()
{
char str[] = " boom is boom";
removeVowels(str);
}
| true |
54fb31f29f164ce5397bb36ea1f0b9838ee8734e | C++ | johan-bjareholt/cpp-playground | /DV1537/Inlämningar/Inlämning IA/CellularPhone.cpp | UTF-8 | 1,868 | 3.390625 | 3 | [] | no_license | #include <sstream>
#include "CellularPhone.h"
CellularPhone::CellularPhone(string model, int price, string color, int amount){
this->model = model;
this->color = color;
this->price = price;
this->stock = amount;
}
CellularPhone::CellularPhone(CellularPhone& origin){
this->model = origin.getModel();
this->color = origin.getColor();
this->price = origin.getPrice();
this->stock = origin.getStock();
}
CellularPhone::~CellularPhone(){
}
const bool CellularPhone::operator==(CellularPhone& other){
// If modelname and color are equal
if (this->getModel()==other.getModel() && this->getColor()==other.getColor()){
return true;
}
return false;
}
void CellularPhone::operator=(CellularPhone& other){
this->model = other.getModel();
this->color = other.getColor();
this->stock = other.getStock();
}
const bool CellularPhone::operator<(CellularPhone& other){
if (this->getStock() < other.getStock())
return true;
else
return false;
}
const string CellularPhone::getModel(){
return this->model;
}
void CellularPhone::setModel(string model){
this->model = model;
}
const string CellularPhone::getColor(){
return this->color;
}
void CellularPhone::setColor(string color){
this->color = color;
}
const int CellularPhone::getPrice(){
return this->price;
}
void CellularPhone::setPrice(int price){
this->price = price;
}
const int CellularPhone::getStock(){
return this->stock;
}
void CellularPhone::setStock(int stock){
this->stock = stock;
}
void CellularPhone::addToStock(int amount){
this->stock+=amount;
}
void CellularPhone::removeFromStock(int amount){
this->stock-=amount;
}
const string CellularPhone::getInfo(){
stringstream ss;
ss << this->getModel() << endl
<< "\tFärg: " << this->getColor() << endl
<< "\tPris: " << this->getPrice() << "kr" << endl
<< "\tAntal på lager: " << this->getStock();
return ss.str();
} | true |
134a68b489dbd2d7d46cf5ea17da09fbc4628dfa | C++ | honda2017/LeetCode | /Reverse Linked List.cpp | UTF-8 | 1,027 | 3.34375 | 3 | [] | no_license | //
// main.cpp
// Reverse Linked List
//
// Created by 唧唧歪歪 on 15/5/17.
// Copyright (c) 2015年 唧唧歪歪. All rights reserved.
//
#include<iostream>
#include<vector>
using namespace std;
//结构体;
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution
{
public:
ListNode* reverseList(ListNode * head)
{
ListNode * tt=NULL;
if(head==NULL)
return tt;
tt=head;//赋予头指针;
ListNode * temp=NULL;
ListNode * list=NULL;
while(tt!=NULL)
{
temp=new ListNode(tt->val);
list=Insert(list,temp);
tt=tt->next;
}
delete head;
head=list;
return head;
}
//向链表中插入结点元素temp;
ListNode * Insert(ListNode * head,ListNode * temp)
{
if(head==NULL)
return temp;
temp->next=head;
head=temp;
return head;
}
};
int main()
{
}
| true |
533a17490bdcb37316e09bc7b7f7ce6c9ee9885d | C++ | ljalmanzar/cs480Almanzar | /PA11/src/gameDriver.cpp | UTF-8 | 6,716 | 2.578125 | 3 | [] | no_license | #ifndef __GAMEDRIVER_CPP_
#define __GAMEDRIVER_CPP_
#include "gameDriver.h"
GameDriver::GameDriver(){
//constructor
}
GameDriver::~GameDriver(){
//deconstructor
//destroy everything
for( unsigned int i = 0; i < _mazes.size(); i++ ){
delete _mazes[i];
}
for( unsigned int i = 0; i < _balls.size(); i++ ){
delete _balls[i];
}
}
void GameDriver::initGame( btDiscreteDynamicsWorld * incomingWorld ){
//set incoming variables
_world = incomingWorld;
_difficulty = EASY;
//declare helper variables
glm::mat4 transformation;
RoundType tempRound;
//initialize the mazes
//_maze_index = 0;
vector<string> files = {
"../bin/maze_easy.obj"
,"../bin/maze_interm_1.obj"
,"../bin/maze_crazyhard.obj"
};
for( unsigned int i = 0; i < files.size(); i++ ){
GLD * temp = new GLD;
temp->initialize( files[i], "../bin/deathStar.jpg", true, TRIMESH, KINEMATIC );
_mazes.push_back( temp );
}
//add the default ball
addBall();
_xwing.initialize( "../bin/xwing.obj", "../bin/WINGTOP.jpg" );
//initialize the world
_backGround.initialize("../bin/planet.obj", "../bin/star_map.jpg");
//make this guy really big
transformation = glm::scale(
_backGround.getModel(),
glm::vec3( 100.0, 100.0, 100.0 )
);
_backGround.setModel( transformation );
//initialize the static object
_casket.initialize("../bin/casket.obj", "../bin/deathStar2.jpg");//, true, TRIMESH, KINEMATIC );
_casket.translate(glm::vec3(0,-1.25,0));
//set all the appropriate pointers
_allObjects.push_back( &_casket );
_allObjects.push_back( &_backGround );
//set the master transformation
_empty = glm::mat4(1.0f);
//set the starting time
gettimeofday( &_startingTime, NULL );
}
void GameDriver::addBall(){
//creating a new ball
GLD * temp = new GLD;
temp->initialize( "../bin/planet.obj", "../bin/ice.jpg", true, SPHERE, DYNAMIC );
//setting initial position
temp->translate(glm::vec3(-1,10,5));
glm::mat4 translation = glm::scale( temp->getModel(), glm::vec3(.0001, .0001, .0001) );
temp->setModel( translation );
//temp->setShape(SPHERE);
temp->addPhysics();
//add it to the correct places
_balls.push_back( temp );
}
void GameDriver::printTimeElapsed() {
//declare variables
char buffer[100];
int cursor = 0;
//get the new time
gettimeofday( &_endingTime, NULL );
int seconds = _endingTime.tv_sec - _startingTime.tv_sec;
int microseconds = _endingTime.tv_usec - _startingTime.tv_usec;
if( microseconds < 0 ){
microseconds += 1000000;
seconds--;
}
microseconds /= 10000;
//make the string
snprintf( buffer, 100, "Player Score: %4i.%.2i",
seconds, microseconds );
string tempStr( buffer );
//print the amount of time it's taken
//no program for printing
glUseProgram(0);
glColor3f(1,1,0);
glRasterPos2f( -.95, .95 );
while( tempStr[cursor] ){
glutBitmapCharacter( GLUT_BITMAP_HELVETICA_18, tempStr[cursor++] );
}
cursor = 0;
string rpgText = "Deliver your photon torpedo into that exaust port to blow up the Death Star!";
glRasterPos2f( -.3, -.85 );
while( rpgText[cursor] ){
glutBitmapCharacter( GLUT_BITMAP_HELVETICA_18, rpgText[cursor++] );
}
cursor = 0;
}
void GameDriver::resetGame(){
//reset the time
gettimeofday( &_startingTime, NULL );
//flush out all of the balls and start over
for( unsigned int i = 0; i < _balls.size(); i++ ){
//how many balls?
//remove the rigid body
_world->removeRigidBody( _balls[i]->getRigidBody() );
delete _balls[i];
}
//clear out everything in that array
_balls.clear();
//set the empty back to normal
_empty = glm::mat4(1.0f);
//put in the default ball
addBall();
//add in the new rigid body
_world->addRigidBody( _balls[0]->getRigidBody() );
}
glm::vec3 GameDriver::tiltOnX( float angle ){
//angle is given in degrees
_empty = glm::rotate(
_empty,
angle/90.0f,
glm::vec3(1.0,0.0,0.0)
);
glm::mat3 rotationMatrix( _empty );
/*
//tilt the mazes accordingly
for( unsigned int i = 0; i < _mazes.size(); i++ ){
btTransform trans;
trans.setFromOpenGLMatrix( glm::value_ptr(_empty) );
//trans set origin
//trans set orientation
_mazes[i]->getRigidBody()->setWorldTransform(trans);
cout << "debug" << endl;
// _mazes[i]->getRigidBody()->getMotionState()->getWorldTransform(trans);
}
*/
//use newGravity to update shit
return rotationMatrix * glm::vec3(0.0, -9.81, 0.0);
}
glm::vec3 GameDriver::tiltOnZ( float angle ){
//angle is given in degrees
_empty = glm::rotate(
_empty,
angle/90.0f,
glm::vec3(0.0,0.0,1.0)
);
glm::mat3 rotationMatrix( _empty );
//use newGravity to update shit
return rotationMatrix * glm::vec3(0.0, -9.81, 0.0);
}
bool GameDriver::checkForWin(){
if( _balls.size() == 1 && _balls[0]->getModel()[3][1] < -2 ){
//if it is, reset the positions
return true;
}
return false;
}
bool GameDriver::checkIfBallOK(){
//is the balls position too low?
if( _balls.size() == 1 && _balls[0]->getModel()[3][1] > -5 ){
//if it is, reset the positions
resetGame();
}
return false;
}
void GameDriver::pickLevel(Difficulty difficulty){
switch(difficulty){
case EASY:
_difficulty = EASY;
break;
case MEDIUM:
_difficulty = MEDIUM;
break;
case HARD:
_difficulty = HARD;
break;
}
}
std::vector<GLD*> GameDriver::getAllObjects(){
//update all of the GLD
//keep static stuff static
std::vector<GLD*> temp = _allObjects;
glm::vec3 hide(0,1000,0);
glm::vec3 show(0,0,0);
switch(_difficulty){
case EASY:
_mazes[0]->translate(show);
_mazes[1]->translate(hide);
_mazes[2]->translate(hide);
break;
case MEDIUM:
_mazes[0]->translate(hide);
_mazes[1]->translate(show);
_mazes[2]->translate(hide);
break;
case HARD:
_mazes[0]->translate(hide);
_mazes[1]->translate(hide);
_mazes[2]->translate(show);
break;
}
temp.push_back(_mazes[0]);
temp.push_back(_mazes[1]);
temp.push_back(_mazes[2]);
temp.insert( temp.end(), _balls.begin(), _balls.end() );
glm::mat4 ballpos = glm::scale( _balls[0]->getModel(), glm::vec3(.75f) );
glm::mat4 newpos = glm::mat4(1.0f);
newpos[3] = ballpos[3];
newpos[3][1] += 5.0f;
_xwing.setModel( newpos );
temp.push_back( &_xwing );
return temp;
}
glm::mat4 GameDriver::getMasterTransform(){
return _empty;
}
std::string GameDriver::getFinalTime(){
//declare variables
char buffer[100];
//get the new time
gettimeofday( &_endingTime, NULL );
int seconds = _endingTime.tv_sec - _startingTime.tv_sec;
int microseconds = _endingTime.tv_usec - _startingTime.tv_usec;
if( microseconds < 0 ){
microseconds += 1000000;
seconds--;
}
microseconds /= 10000;
//make the string
snprintf( buffer, 100, "%4i.%.2i",
seconds, microseconds );
string tempStr( buffer );
return tempStr;
}
#endif | true |
254ee71694cbf0982b2085af5d4d362f11ddcba7 | C++ | Dgut/converter3d | /converter.cpp | UTF-8 | 4,634 | 2.71875 | 3 | [] | no_license | #include "converter.h"
#include "general.h"
#include "modifier.h"
#include <array>
#include <glm/gtc/constants.hpp>
namespace Converter3D
{
// tokenizer
char* gettoken(char** str, const char* delim)
{
char* token = *str + strspn(*str, delim);
*str = *str + strcspn(*str, delim);
if (**str)
*(*str)++ = 0;
return token;
}
// file helper - automatically closes the file
class File
{
FILE* stream;
public:
File(const char* name, const char* mode) : stream(nullptr) { fopen_s(&stream, name, mode); }
~File() { if (stream)fclose(stream); }
operator FILE*() const { return stream; }
};
void ObjImporter::ReadFloats(char** data, std::vector<Float>& floats, size_t number)
{
while (number--)
{
char* token = gettoken(data, " \t");
floats.push_back(token ? static_cast<float>(atof(token)) : 0.f);
}
}
unsigned ObjImporter::ReadIndices(char** data, int* indices, size_t number)
{
unsigned result = 0;
char* token = gettoken(data, " \t");
for (size_t i = 0; *token && i < number; i++)
{
char* index = gettoken(&token, "/");
if (*index)
{
result |= 1 << i;
indices[i] = atoi(index);
}
}
return result;
}
Error ObjImporter::Import(IMesh* mesh, std::string path)
{
File file(path.c_str(), "rt");
if (!file)
return Errors::CannotOpenFile; // not found
std::shared_ptr<AttributeBuffer<Float>> attributes[] =
{
std::make_shared<AttributeBuffer<Float>>(3),
std::make_shared<AttributeBuffer<Float>>(3),
std::make_shared<AttributeBuffer<Float>>(3),
};
auto faces = std::make_shared<FaceBuffer<Uint>>();
std::vector<char> line(16 * 1024); // we assume that no one has written very long comments/faces
while (fgets(line.data(), static_cast<int>(line.size()), file))
{
char* data = line.data(); // raw pointers for fast parsing
char* comment = strchr(data, '#');
if (comment)
*comment = 0; // deleting comments
char* element = gettoken(&data, " \t");
if (!strcmp(element, "v"))
ReadFloats(&data, *attributes[static_cast<size_t>(Attribute::Position)], 3);
else if(!strcmp(element, "vn"))
ReadFloats(&data, *attributes[static_cast<size_t>(Attribute::Normal)], 3);
else if (!strcmp(element, "vt"))
ReadFloats(&data, *attributes[static_cast<size_t>(Attribute::Texture)], 3);
else if (!strcmp(element, "f"))
{
unsigned face_format = 0;
std::string index;
Face<Uint>& face = faces->emplace_back(Face<Uint>());
std::array<int, 3> offset = { 0, 0, 0 };
unsigned format;
while (format = ReadIndices(&data, offset.data(), offset.size()))
{
if (!face_format)
face_format = format;
else if(face_format != format)
return Errors::WrongFileFormat; // not consistent face format
for (size_t i = 0; i < offset.size(); i++)
if (face_format & (1 << i))
face[i].push_back(offset[i] > 0 ? static_cast<Uint>(offset[i] - 1) : static_cast<Uint>(attributes[i]->GetSize() + offset[i]));
}
if (face.GetSize() < 3)
return Errors::WrongFileFormat; // not enough vertices
}
}
for (int i = 0; i < 3; i++)
{
if (attributes[i]->GetSize())
mesh->SetAttribute(static_cast<Attribute>(i), attributes[i]);
}
mesh->SetFaces(faces);
auto rotation = TransformModifier(); // 3d modelling tools usually rotate obj files so we will do the same
rotation.Rotate(glm::half_pi<float>(), glm::vec3(1.f, 0.f, 0.f));
rotation.Modify(mesh);
return Errors::Success;
}
Error StlExporter::Export(const IMesh* mesh, std::string path)
{
auto attribute = mesh->GetAttribute(Attribute::Position);
auto faces = mesh->GetFaces();
if (attribute && attribute->GetDimension() != 3)
return Errors::WrongMeshFormat; // unsuitable mesh format
File file(path.c_str(), "wb"); // C i/o is faster
if (!file)
return Errors::CannotOpenFile; // cannot be opened for writing
uint32_t num_triangles = 0;
uint16_t zero_attribute = 0;
const size_t HeaderSize = 80;
fseek(file, HeaderSize + sizeof(num_triangles), SEEK_SET); // skip header and triangles number
Mesh::ForEachTriangle(*mesh, [&](auto a, auto b, auto c)
{
auto normal = glm::normalize(glm::cross(c - b, a - b));
fwrite(&normal, sizeof(float), 3, file);
fwrite(&a, sizeof(float), 3, file);
fwrite(&b, sizeof(float), 3, file);
fwrite(&c, sizeof(float), 3, file);
fwrite(&zero_attribute, sizeof(zero_attribute), 1, file);
num_triangles++;
});
fseek(file, HeaderSize, SEEK_SET); // write triangles number
fwrite(&num_triangles, sizeof(num_triangles), 1, file);
fclose(file);
return Errors::Success;
}
}
| true |
8dc9d2277c159e1ef34e60247d96064ed7ef6cbf | C++ | ryanbujnowicz/mem | /src/lib/mem/regionReporter.h | UTF-8 | 1,049 | 2.703125 | 3 | [] | no_license | #ifndef MEM_REGIONREPORTER_H
#define MEM_REGIONREPORTER_H
#include <sstream>
#include "mem/tracking.h"
namespace {
std::string makeMemoryLeakSection(const mem::NoTracking& tracker)
{
return "";
}
std::string makeMemoryLeakSection(const mem::CountTracking& tracker)
{
std::stringstream ss;
ss << "\tUnreleased Memory Allocations: "
<< tracker.getAllocationCount() " allocs "
<< "(" << tracker.getAllocatedSize() << " bytes)\n";
return ss.str();
}
std::string makeMemoryLeakSection(const mem::SourceTracking& tracker)
{
return "\tSource Tracking\n";
}
std::string makeMemoryLeakSection(const mem::CallStackTracking& tracker)
{
return "\tCall stack Tracking\n";
}
}
namespace mem {
template <class Region>
std::string makeRegionReport(const std::string& name, const Region& region)
{
std::stringstream ss;
ss << "Region " << name << " report:\n";
ss << makeStatsSection();
ss << makeMemoryLeakSection(region.getTrackerPolicy());
return ss.str();
}
} // namespace mem
#endif
| true |
00da8d58d16501ee1fa647ee9ee1d4a89a93c3cf | C++ | ericPrince/Probotics | /libraries/PID/PID.h | UTF-8 | 633 | 2.671875 | 3 | [] | no_license | /*
--Probotics, Princeton University--
PID.h: used for standard PID control
the main method is compute() which should
be called every time loop() runs
made for arduino 1.5.1 on Feb 4, 2013
*/
#ifndef PID_h
#define PID_h
#include <Arduino.h>
const double PWM_MAX=255;
class PID{
public:
PID(double p,double i,double d,double lo,double hi);
PID(double p,double i,double d);
double compute(double input, double setPoint);
void reset();
void setConstants(double p,double i,double d);
private:
double kp,ki,kd, outMin,outMax;
double iTerm;
unsigned long lastT;
double lastInput;
};
#endif | true |
f460e209e9c2c955ae316f427357755f1b893c4c | C++ | Aragorn9756/CodePortfolio | /CPP/HW2 Singly Linked Lists/HW2 Singly Linked Lists/SinglyLinkedListSource.cpp | UTF-8 | 21,570 | 3.515625 | 4 | [] | no_license | //Copyright 2017, Bradley Peterson, Weber State University, All rights reserved.
#include <sstream>
#include <map>
#include <chrono>
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
using std::string;
using std::stringstream;
//************************************************************************
//A class I designed to help keep track of how much memory you allocate
//Do not modify, this is not part of your assignment, it just helps test it.
//For this to work, a class needs to inherit off of this one.
//Then this does the rest of the work, since it
//overloads new, new[], delete, and delete[].
//************************************************************************
class ManageMemory {
public:
static std::size_t getTotalSize() {
std::size_t total = 0;
std::map<void *, std::size_t>::iterator iter;
for (iter = mapOfAllocations.begin(); iter != mapOfAllocations.end(); ++iter) {
total += iter->second;
}
return total;
}
//I overloaded the new and delete keywords so I could manually track allocated memory.
void* operator new(std::size_t x) {
void *ptr = ::operator new(x);
mapOfAllocations[ptr] = x;
return ptr;
}
void* operator new[](std::size_t x) {
void *ptr = ::operator new[](x);
mapOfAllocations[ptr] = x;
return ptr;
}
void operator delete(void* x) {
mapOfAllocations.erase(x);
::operator delete(x);
}
void operator delete[](void* x) {
mapOfAllocations.erase(x);
::operator delete[](x);
}
private:
static std::map<void *, std::size_t> mapOfAllocations;
};
std::map<void *, std::size_t> ManageMemory::mapOfAllocations;
//******************
//The node class
//******************
template <typename T>
class Node : public ManageMemory {
public:
T data;
Node *link{ nullptr };
};
//******************
//The linked list base class
//This contains within it a class declaration for an iterator
//******************
template <typename T>
class SinglyLinkedList : public ManageMemory {
public:
//public members of the SinglyLinkedList class
~SinglyLinkedList();
string getStringFromList();
void insertFront(const T&);
void insertBack(const T&);
T getAtIndex(const unsigned int index) const; //For your assignment
T& operator[](const unsigned int index); //For your assignment
void insertAtIndex(const unsigned int index, const T& value); //For your assignment
void deleteAtIndex(const unsigned int index); //For your assignment
void deleteAllInstances(const T& value); //For your assignment
protected:
Node<T> *front{ nullptr };
Node<T> *back{ nullptr };
int count{ 0 };
};
template <typename T>// destructor
SinglyLinkedList<T>::~SinglyLinkedList() {
Node<T> *temp;
while (front != nullptr) {
temp = front;
front = front->link;
delete temp;
}
back = nullptr;
count = 0;
}
template <typename T>
void SinglyLinkedList<T>::insertFront(const T& value) {
Node<T> *temp = new Node<T>();
temp->data = value;
//empty list scenario
if (front == nullptr) {
back = temp;
}
else {
temp->link = front;
}
front = temp;
count++;
}
template <typename T>
void SinglyLinkedList<T>::insertBack(const T& value) {
Node<T> *temp = new Node<T>;
temp->data = value;
if (front == nullptr) {
front = temp;
}
else {
//put it on
back->link = temp;
}
back = temp;
count++;
}
template <typename T>
T SinglyLinkedList<T>::getAtIndex(const unsigned int index) const
{
//create item to hold data. this method passes variable, not a pointer
T item;
//Empty List
if(front == nullptr) {//if the list is empty, first won't point to anything
cout << "Umm.... There's nothing there... I can't check an empty list..." << endl;
throw 1;
}
//Index not within bounds
else if (index < 0 || index >= count){
//^^^^
//if index value is == to count, the index value is too big
//because we start the index at 0 and the size at one.
cout << "You don't even have that many items on your list bro!\n"
<< "Did you remember that index values start at 0?" << endl;
throw 1;
}
//all running smoothly
else {
//create temp pointer to keep track of place on the list
Node<T> * curr = front;
for (int i = 0; i < index; i++) {
curr = curr->link;
}
item = curr->data;
}
return item;
}
template <typename T>
T& SinglyLinkedList<T>::operator[](const unsigned int index)
{
//create temp pointer to keep track of place on the list
Node<T> * curr = front;
//Empty List
if (front == nullptr) {//if the list is empty, first won't point to anything
cout << "Umm.... There's nothing there... I can't check an empty list..." << endl;
throw 1;
}
//Index not within bounds
else if (index < 0 || index >= count) {
//^^^^
//if index value is == to count, the index value is too big
//because we start the index at 0 and the size at one.
cout << "You don't even have that many items on your list bro!\n"
<< "Did you remember that index values start at 0?" << endl;
throw 1;
}
//all running smoothly
else {
for (int i = 0; i < index; i++) {
curr = curr->link;
}
}//end else
return curr->data;
}
//TODO: Complete this method
template <typename T>
void SinglyLinkedList<T>::insertAtIndex(const unsigned int index, const T& value)
{
//Empty List
if(count == 0 && index != 0) {
cout << "You've got an empty list dude. Try putting stuff in here before you\n"
<< "insert at that index" << endl;
}
//Out of bounds(negative or over count)
else if (index < 0 || index > count) {
cout << "*nasally voice*\nUm... Excuse me sir... Um, That index doesn't exist.\n"
<< "Yeah, you can't do that sir. (or ma'am if you're female)";
}
//Before First
else if (index == 0) {
Node<T> * temp = new Node<T>;
temp->data = value;
temp->link = front;
front = temp;
//if empty
if (count == 0) {
back = temp;
}
count++;
}
//After Last
else if (index == count) {
Node<T> * temp = new Node<T>;
temp->data = value;
temp->link = nullptr;
back->link = temp;
back = temp;
count++;
}
//if valid index
else if (index > 0 && index < count) {
Node<T> * temp = new Node<T>;
Node<T> * placeholder = front;
//find requested index
for (int i = 1; i < index; i++) {
placeholder = placeholder->link;
}
//insert new node
temp->data = value;
temp->link = placeholder->link;
placeholder->link = temp;
count++;
}
//just in case something falls through the cracks.
else {
cout << "Stephen, you missed something. This is in the insertAtIndex method" << endl;
}
return;
}
template <typename T>
void SinglyLinkedList<T>::deleteAtIndex(const unsigned int index)
{
//empty list
if (front == nullptr) {
cout << "You can't delete from an empty list, man. I think you're seeing things." << endl;
}
//out of bounds
else if (index < 0 || index >= count) {
cout << "There's nothing at that index. Do you need new glasses?" << endl;
}
//single node
else if (front == back && index == 0) {
delete back;
front = nullptr;
back = nullptr;
count--;
}
//delete front
else if (index == 0) {
Node<T> * temp{ front };
front = front->link;
delete temp;
count--;
}
//delete back
else if (index == count - 1) {
Node<T> * temp{ front };
//find second to last node
while (temp->link != back) {
temp = temp->link;
}
delete back;
back = temp;
back->link = nullptr;
count--;
}
//delete in middle
else if (index > 0 && index < count - 1) {
Node<T> * temp{ front };
//another for the node before index to be deleted
Node<T> * temp2{ front };
//find requested index
for (int i = 0; i < index; i++) {
temp = temp->link;
//keep temp2 a node behind temp
if (i > 0) {
temp2 = temp2->link;
}
}
//bypass temp, so it can be deleted
temp2->link = temp->link;
delete temp;
count--;
}
//just in case something falls through the cracks.
else {
cout << "Stephen, you missed something. This is in the deleteAtIndex method" << endl;
}
return;
}
//TODO: Complete this method
template <typename T>
void SinglyLinkedList<T>::deleteAllInstances(const T& value)
{
//empty list
if (front == nullptr) {
cout << "You can't delete from an empty list, man. I think you're seeing things." << endl;
}
else {
int numDeleted = 0;
int listSize = count;
Node<T> * temp{ front };
Node<T> * temp2{ nullptr };
for (int i = 0; i < listSize; i++) {
//if at the front of the list
if (temp == front) {
//check to see if deletion needed
if (temp->data == value) {
//delete front
temp = temp->link;
delete front;
front = temp;
count--;
}
//otherwise, cycle in temp2 link
else {
temp = temp->link;
temp2 = front;
}
}//end front of list if
//if in the middle of the list
else if (temp != front && temp != back) {
//check to see if deletion needed
if (temp->data == value) {
//delete node
temp2->link = temp->link;
delete temp;
temp = temp2->link;
count--;
}
//otherwise, move temp pointers forward
else {
temp = temp->link;
temp2 = temp2->link;
}
}//end middle of the list if
//if at the back of the list
else if (temp == back) {
//check to see if deletion needed
if (temp->data == value) {
delete temp;
back = temp2;
back->link = nullptr;
count--;
}
}
}//end delete instances else
}
}
//This method helps return a string representation of all nodes in the linked list, do not modify.
template <typename T>
string SinglyLinkedList<T>::getStringFromList() {
stringstream ss;
if (front == nullptr) {
ss << "The list is empty.";
}
else {
Node<T> *currentNode = front;
ss << currentNode->data;
currentNode = currentNode->link;
while (currentNode != nullptr) {
ss << " " << currentNode->data;
currentNode = currentNode->link;
};
}
return ss.str();
}
//This helps with testing, do not modify.
bool checkTest(string testName, string whatItShouldBe, string whatItIs) {
if (whatItShouldBe == whatItIs) {
cout << "Passed " << testName << endl;
return true;
}
else {
cout << "****** Failed test " << testName << " ****** " << endl << " Output was " << whatItIs << endl << " Output should have been " << whatItShouldBe << endl;
return false;
}
}
//This helps with testing, do not modify.
bool checkTest(string testName, int whatItShouldBe, int whatItIs) {
if (whatItShouldBe == whatItIs) {
cout << "Passed " << testName << endl;
return true;
}
else {
cout << "****** Failed test " << testName << " ****** " << endl << " Output was " << whatItIs << endl << " Output should have been " << whatItShouldBe << endl;
return false;
}
}
//This helps with testing, do not modify.
bool checkTestMemory(string testName, int whatItShouldBe, int whatItIs) {
if (whatItShouldBe == whatItIs) {
cout << "Passed " << testName << endl;
return true;
}
else {
cout << "***Failed test " << testName << " *** " << endl << " You lost track of " << whatItIs << " bytes in memory!" << endl;
return false;
}
}
//This helps with testing, do not modify.
void testGetAtIndex() {
SinglyLinkedList<int> *d = new SinglyLinkedList<int>;
for (int i = 10; i < 20; i++) {
d->insertBack(i);
}
//Test just to make sure the data went in the list.
checkTest("testGetAtIndex #1", "10 11 12 13 14 15 16 17 18 19", d->getStringFromList());
//Test retrieving items.
int item = d->getAtIndex(0);
checkTest("testGetAtIndex #2", 10, item);
item = d->getAtIndex(5);
checkTest("testGetAtIndex #3", 15, item);
item = d->getAtIndex(9);
checkTest("testGetAtIndex #4", 19, item);
//Make sure the list was undisturbed during this time
checkTest("testGetAtIndex #5", "10 11 12 13 14 15 16 17 18 19", d->getStringFromList());
//Try to access out of bounds.
string caughtError = "";
try {
int item = d->getAtIndex(-1);
}
catch (int error) {
caughtError = "caught";
}
checkTest("testGetAtIndex #6", "caught", caughtError);
try {
int item = d->getAtIndex(100);
}
catch (int error) {
caughtError = "caught";
}
checkTest("testGetAtIndex #7", "caught", caughtError);
delete d;
d = new SinglyLinkedList<int>;
d->insertBack(18);
item = d->getAtIndex(0);
checkTest("testGetAtIndex #8", 18, item);
delete d;
}
//This helps with testing, do not modify.
void testSquareBrackets() {
SinglyLinkedList<int> d;
for (int i = 10; i < 20; i++) {
d.insertBack(i);
}
//Test just to make sure the data went in the list.
checkTest("testSquareBrackets #1", "10 11 12 13 14 15 16 17 18 19", d.getStringFromList());
//Test retrieving items.
int item = d[0];
checkTest("testSquareBrackets #2", 10, item);
item = d[5];
checkTest("testSquareBrackets #3", 15, item);
item = d[9];
checkTest("testSquareBrackets #4", 19, item);
//Make sure the list was undisturbed during this time
checkTest("testSquareBrackets #5", "10 11 12 13 14 15 16 17 18 19", d.getStringFromList());
//now test the return by reference
d[1] = 1000;
checkTest("testSquareBrackets #6", "10 1000 12 13 14 15 16 17 18 19", d.getStringFromList());
//Try to access out of bounds.
string caughtError = "";
try {
int item = d[-1];
}
catch (int error) {
caughtError = "caught";
}
checkTest("testSquareBrackets #7", "caught", caughtError);
try {
int item = d[100];
}
catch (int error) {
caughtError = "caught";
}
checkTest("testSquareBrackets #8", "caught", caughtError);
}
//This helps with testing, do not modify.
void testInsertAtIndex() {
SinglyLinkedList<int> *s = new SinglyLinkedList<int>;
for (int i = 10; i < 20; i++) {
s->insertBack(i);
}
//Test just to make sure the data went in the list.
checkTest("testInsertAtIndex #1", "10 11 12 13 14 15 16 17 18 19", s->getStringFromList());
s->insertAtIndex(3, 33);
checkTest("testInsertAtIndex #2", "10 11 12 33 13 14 15 16 17 18 19", s->getStringFromList());
s->insertAtIndex(0, 9);
checkTest("testInsertAtIndex #3", "9 10 11 12 33 13 14 15 16 17 18 19", s->getStringFromList());
s->insertAtIndex(12, 20);
checkTest("testInsertAtIndex #4", "9 10 11 12 33 13 14 15 16 17 18 19 20", s->getStringFromList());
delete s;
s = new SinglyLinkedList<int>;
s->insertAtIndex(0, 42);
checkTest("testInsertAtIndex #5", "42", s->getStringFromList());
s->insertAtIndex(1, 82);
checkTest("testInsertAtIndex #6", "42 82", s->getStringFromList());
delete s;
}
//This helps with testing, do not modify.
void testDeleteAtIndex() {
SinglyLinkedList<int> *d = new SinglyLinkedList<int>;
for (int i = 10; i < 17; i++) {
d->insertBack(i);
}
//Test just to make sure the data went in the list.
checkTest("testDeleteAtIndex #1", "10 11 12 13 14 15 16", d->getStringFromList());
//Test deleting front items.
d->deleteAtIndex(0);
checkTest("testDeleteAtIndex #2", "11 12 13 14 15 16", d->getStringFromList());
d->deleteAtIndex(0);
checkTest("testDeleteAtIndex #3", "12 13 14 15 16", d->getStringFromList());
//Test deleting a middle item
d->deleteAtIndex(2);
checkTest("testDeleteAtIndex #4", "12 13 15 16", d->getStringFromList());
//Test deleting back itmes
d->deleteAtIndex(3);
checkTest("testDeleteAtIndex #5", "12 13 15", d->getStringFromList());
d->deleteAtIndex(2);
checkTest("testDeleteAtIndex #6", "12 13", d->getStringFromList());
//Test deleting a Kth element that doesn't exist.
d->deleteAtIndex(500);
checkTest("testDeleteAtIndex #7", "12 13", d->getStringFromList());
//Test deleting a back item
d->deleteAtIndex(1);
checkTest("testDeleteAtIndex #8", "12", d->getStringFromList());
//Test deleting item that doesn't exist
d->deleteAtIndex(1);
checkTest("testDeleteAtIndex #9", "12", d->getStringFromList());
//Test deleting item on the front
d->deleteAtIndex(0);
checkTest("testDeleteAtIndex #10", "The list is empty.", d->getStringFromList());
//Test attempting to delete from an empty list
d->deleteAtIndex(0);
checkTest("testDeleteAtIndex #11", "The list is empty.", d->getStringFromList());
delete d;
}
//This helps with testing, do not modify.
void testdeleteAllInstances() {
SinglyLinkedList<int> *d = new SinglyLinkedList<int>;
d->insertBack(4);
d->insertBack(2);
d->insertBack(6);
d->insertBack(5);
d->insertBack(6);
d->insertBack(9);
//Do a delete, test it.
d->deleteAllInstances(6);
checkTest("testdeleteAllInstances #1", "4 2 5 9", d->getStringFromList());
delete d;
d = new SinglyLinkedList<int>;
d->insertBack(4);
d->insertBack(2);
d->insertBack(3);
d->insertBack(4);
d->insertBack(4);
d->insertBack(4);
d->insertBack(9);
d->deleteAllInstances(4);
checkTest("testdeleteAllInstances #2", "2 3 9", d->getStringFromList());
delete d;
d = new SinglyLinkedList<int>;
d->insertBack(3);
d->insertBack(3);
d->insertBack(3);
d->insertBack(8);
d->insertBack(2);
d->insertBack(3);
d->insertBack(3);
d->insertBack(3);
d->deleteAllInstances(3);
checkTest("testdeleteAllInstances #3", "8 2", d->getStringFromList());
delete d;
d = new SinglyLinkedList<int>;
d->insertBack(9);
d->insertBack(9);
d->insertBack(4);
d->insertBack(2);
d->insertBack(9);
d->insertBack(9);
d->insertBack(5);
d->insertBack(1);
d->insertBack(9);
d->insertBack(2);
d->insertBack(9);
d->insertBack(9);
//Do a delete, test it.
d->deleteAllInstances(9);
checkTest("testdeleteAllInstances #4", "4 2 5 1 2", d->getStringFromList());
//Test deleting something that doesn't exist
d->deleteAllInstances(7);
checkTest("testdeleteAllInstances #5", "4 2 5 1 2", d->getStringFromList());
//A few more tests
d->deleteAllInstances(2);
checkTest("testdeleteAllInstances #6", "4 5 1", d->getStringFromList());
d->deleteAllInstances(4);
checkTest("testdeleteAllInstances #7", "5 1", d->getStringFromList());
d->deleteAllInstances(5);
checkTest("testdeleteAllInstances #8", "1", d->getStringFromList());
d->deleteAllInstances(1);
checkTest("testdeleteAllInstances #9", "The list is empty.", d->getStringFromList());
//retest deleting something that doesn't exist.
d->deleteAllInstances(7);
checkTest("testdeleteAllInstances #10", "The list is empty.", d->getStringFromList());
delete d;
//Now ramp it up and do some huge tests. Start by timing how long a smaller approach takes.
d = new SinglyLinkedList<int>;
//Fill the list with a pattern of
//1 2 2 3 3 3 4 4 4 4 1 2 2 3 3 3 4 4 4 4 ...
cout << endl << "Preparing for testdeleteAllInstances #11, placing 75,000 numbers into the linked list to see how long things take." << endl;
for (int i = 0; i < 30000; i++) {
for (int j = 0; j < i % 4 + 1; j++) {
d->insertBack(i % 4 + 1);
}
}
cout << " Calling deleteAllInstances to remove 22,500 3s in the list." << endl;
//delete all the 3s.
auto start = std::chrono::high_resolution_clock::now();
d->deleteAllInstances(3);
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double, std::micro> diff = end - start;
double benchmarkTime = diff.count() / 1000.0;
cout << " Removing 22,500 3s took " << benchmarkTime << " milliseconds." << endl;
cout << " So we will assume removing 45,000 3s then should be double that..." << endl;
cout << " about " << benchmarkTime << " * 2 = " << (benchmarkTime * 2) << " milliseconds if done correctly." << endl;
delete d;
cout << "Starting testdeleteAllInstances #11, filling in 150,000 numbers into the linked list to get it started." << endl;
d = new SinglyLinkedList<int>;
//Fill the list with a pattern of
//1 2 2 3 3 3 4 4 4 4 1 2 2 3 3 3 4 4 4 4 ...
for (int i = 0; i < 60000; i++) {
for (int j = 0; j < i % 4 + 1; j++) {
d->insertBack(i % 4 + 1);
}
}
cout << " Finished inserting 150,000 numbers." << endl;
cout << " Calling deleteAllInstances to remove 45,000 3s. This should take about " << (benchmarkTime * 2) << " milliseconds." << endl;
//delete all the 3s.
start = std::chrono::high_resolution_clock::now();
d->deleteAllInstances(3);
end = std::chrono::high_resolution_clock::now();
diff = end - start;
double actualTime = diff.count() / 1000.0;
if (actualTime < (benchmarkTime * 2 * 1.5)) { //The 1.5 gives an extra 50% wiggle room
cout << "Passed testdeleteAllInstances #11, completed deleteAllInstances in " << actualTime << " milliseconds." << endl;
}
else {
cout << "*** Failed testdeleteAllInstances #11, deleteAllInstances took " << actualTime
<< " milliseconds." << endl;
cout << "*** This which is much worse than the expected " << (benchmarkTime * 2) << " milliseconds." << endl;
}
delete d;
}
void pressAnyKeyToContinue() {
cout << "Press enter to continue...";
//Linux and Mac users with g++ don't need this
//But everyone else will see this message.
cin.get();
}
int main() {
//Each of these checks how many bytes you have used.
checkTestMemory("Memory Leak/Allocation Test #1", 0, ManageMemory::getTotalSize());
//For your assignment, write the code to make these three methods work
//You should not modify the code here in main.
testGetAtIndex();
checkTestMemory("Memory Leak/Allocation Test #2", 0, ManageMemory::getTotalSize());
testSquareBrackets();
checkTestMemory("Memory Leak/Allocation Test #3", 0, ManageMemory::getTotalSize());
testInsertAtIndex();
checkTestMemory("Memory Leak/Allocation Test #4", 0, ManageMemory::getTotalSize());
testDeleteAtIndex();
checkTestMemory("Memory Leak/Allocation Test #5", 0, ManageMemory::getTotalSize());
testdeleteAllInstances();
checkTestMemory("Memory Leak/Allocation Test #6", 0, ManageMemory::getTotalSize());
pressAnyKeyToContinue();
return 0;
} | true |
bfff899a126bfb82ffd6e1ddf8853af73d44995c | C++ | LathaDurai/Code | /programs/binary/num_words.cpp | UTF-8 | 1,416 | 3.296875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | #include<iostream>
#include<vector>
#include<cmath>
using namespace std;
int main() {
int n;
string res ;
cin>> n;
if(n < 0 || n>9999) {
cout<<"please enter number between 0-9999\n";
exit(1);
}
string singles[] = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
string doubles[] = { "ten", "eleven", "twelve", "thirteen", "fourteen", "fivteen", "sixteen", "sevteen", "eighteen", "ninteen", "twenty"};
string doub[] = {"","", "twenty", "thirty", "fourty", "fivty", "sixty", "seventy", "eighty", "ninty", "Hundered"};
if(n <= 9) {
cout<<singles[n]<<"\n";
}
if(n > 9 && n <= 20) {
cout<<doubles[n-10]<<"\n";
}
if(n>20 && n <=99) {
cout<<doub[n/10]<<" ";
if(n%10!=0) {
cout<<singles[n%10]<<" ";
}
}
if(n>99 && n <=999) {
cout<<singles[n/100]<<" hundered ";
if(n%100!=0) {
int temp = n%100;
cout<<"and "<<doub[temp/10]<<" ";
if(temp%10!=0) {
cout<<singles[n%10]<<" ";
}
}
}
if(n>999 && n <=9999) {
cout<<singles[n/1000]<<" thousand ";
if(n%1000 != 0) {
int tt = n%1000;
cout<<"and "<<singles[tt/100]<<" hundered ";
if(n%100!=0) {
int temp = n%100;
cout<<"and "<<doub[temp/10]<<" ";
if(temp%10!=0) {
cout<<singles[n%10]<<" ";
}
}
}
}
cout<<"\n";
return 0;
}
| true |
93fccf9b8d1144aa161c0d2c9e961ffc3c45c825 | C++ | govg/Machine-Learning | /Random Forests/src/tree.cpp | UTF-8 | 9,263 | 2.890625 | 3 | [] | no_license | /*
This contains the definitions of all the class variables and the functions for
the class of the Tree datatype.
*/
#include "tree.hpp"
#include "typedef.hpp"
#include "splitCriterion.hpp"
#include <queue>
#include <vector>
#include <iostream>
#include <cmath>
#define DATA_MIN 3
#define NUM_CHECKS 5
// The definitions of the functions used in the Tree class.
Tree::Tree(int d)
{
Node n;
depth = d;
nodes.push_back(n);
}
// The crux of the entire library, this contains the part that trains
// each tree.
void Tree::trainTree(const MatrixReal& featMat, const VectorInteger& labels)
{
// We work with a queue of nodes, initially containing only the root node.
// We process the queue until it becomes empty.
std::queue<int> toTrain;
int size,numClasses,numVars,dims;
size = labels.size();
dims = featMat.cols();
numClasses = labels.maxCoeff();
classWts = VectorReal::Zero(numClasses+1);
for(int i = 0; i < labels.size(); ++i)
classWts(labels(i)) += 1.0;
classWts /= size;
for(int i = 0; i < size; ++i)
nodeix.push_back(i);
std::cout<<"Training tree, dimensions set\n";
numVars = (int)((double)sqrt((double)dims)) + 1;
int cur;
// The relevant indices for the root node is the entire set of training data
nodes[0].start = 0;
nodes[0].end = size-1;
// Initialise the queue with just the root node
toTrain.push(0);
// Stores the relevant features.
VectorReal relFeat;
// Resize our boolean array, more on this later.
indices.resize(size);
std::cout<<"Starting the queue\n";
int lpoints,rpoints;
// While the queue isn't empty, continue processing.
while(!toTrain.empty())
{
int featNum;
double threshold;
lpoints = rpoints = 0;
cur = toTrain.front();
// std::cout<<"In queue, node being processed is d :"<<cur.depth<<"\n";
// There are two ways for a node to get out of the queue trivially,
// a) it doesn't have enough data to be a non-trivial split, or
// b) it has hit the maximum permissible depth
if((nodes[cur].end - nodes[cur].start < DATA_MIN) || (nodes[cur].depth == depth))
{
// Tell ourselves that this is a leaf node, and remove the node
// from the queue.
// std::cout<<"Popping a leaf node\n";
nodes[cur].setType(true);
// Initialize the histogram and set it to zero
nodes[cur].hist = VectorReal::Zero(numClasses+1);
// The below code should give the histogram of all the elements
for(int i = nodes[cur].start; i <= nodes[cur].end; ++i)
{
nodes[cur].hist[labels(nodeix[i])] += 1.0;
}
for(int i = 0 ; i < classWts.size(); ++i)
nodes[cur].hist[i] = nodes[cur].hist[i] / classWts[i];
toTrain.pop();
continue;
}
double infoGain(-100.0);
relFeat.resize(size);
// In case this isn't a trivial node, we need to process it.
for(int i = 0; i < numVars; ++i)
{
// std::cout<<"Choosing a random variable\n";
// Randomly select a feature
featNum = rand()%dims;
// std::cout<<"Feat: "<<featNum<<std::endl;
// Extract the relevant feature set from the training data
relFeat = featMat.col(featNum);
double tmax,tmin,curInfo;
tmax = relFeat.maxCoeff();
tmin = relFeat.minCoeff();
// infoGain = -100;
//std::cout<<"Min "<<tmin<<"Max: "<<tmax<<std::endl;
// NUM_CHECKS is a macro defined at the start
for(int j = 0; j < NUM_CHECKS; ++j)
{
// std::cout<<"Choosing a random threshold\n";
// Generate a random threshold
threshold = ((rand()%100)/100.0)*(tmax - tmin) + tmin;
//std::cout<<"Thresh: "<<threshold<<std::endl;
for(int k = nodes[cur].start; k <= nodes[cur].end ; ++k)
indices[k] = (relFeat(k) < threshold);
// Check if we have enough information gain
curInfo = informationGain(nodes[cur].start,nodes[cur].end, labels);
// std::cout<<"Info gain : "<<curInfo<<"\n";
// curInfo = (double) ((rand()%10)/10.0);
if(curInfo > infoGain)
{
infoGain = curInfo;
nodes[cur].x = featNum;
nodes[cur].threshold = threshold;
}
}
}
// We have selected a feature and a threshold for it that maximises the information gain.
relFeat = featMat.col(nodes[cur].x);
// We just set the indices depending on whether the features are greater or lesser.
// Conventions followed : greater goes to the right.
for(int k = nodes[cur].start; k <= nodes[cur].end; ++k)
{
// If relfeat is lesser, indices[k] will be true, which will put it in the
// left side of the partition.
indices[k] = relFeat(k) < nodes[cur].threshold;
// indices[k] = (bool)(rand()%2);
if(indices[k])
lpoints++;
else
rpoints++;
}
if( (lpoints < DATA_MIN) || (rpoints < DATA_MIN) )
{
// Tell ourselves that this is a leaf node, and remove the node
// from the queue.
// std::cout<<"Popping a leaf node\n";
nodes[cur].setType(true);
// Initialize the histogram and set it to zero
nodes[cur].hist.resize(numClasses+1);
nodes[cur].hist = VectorReal::Zero(numClasses+1);
// The below code should give the histogram of all the elements
for(int i = nodes[cur].start; i <= nodes[cur].end; ++i)
{
nodes[cur].hist[labels(nodeix[i])] += 1.0;
}
toTrain.pop();
continue;
}
int part;
// Use the prebuilt function to linearly partition our data
part = partition(nodes[cur].start,nodes[cur].end);
Node right, left;
// Increase the depth of the children
right.depth = left.depth = nodes[cur].depth + 1;
// Correctly assign the partitions
left.start = nodes[cur].start;
left.end = part -1;
// Push back into the relevant places and also link the parent and the child
nodes.push_back(left);
nodes[cur].leftChild = nodes.size()-1;
toTrain.push(nodes[cur].leftChild);
// Ditto with the right node.
right.start = part;
right.end = nodes[cur].end;
nodes.push_back(right);
nodes[cur].rightChild = nodes.size()-1;
toTrain.push(nodes[cur].rightChild);
// Finally remove our node from the queue.
toTrain.pop();
}
}
VectorReal Tree::testTree(const VectorReal& feat)
{
int cur;
cur = 0;
while(!nodes[cur].isType())
{
// std::cout<<"Right now at node no : "<<cur<<"\n";
// std::cout<<"Node variables : x,t "<<nodes[cur].x<<"\t"<<nodes[cur].threshold<<"\n";
// std::cout<<"The feature value is "<<feat(nodes[cur].x)<<"\n";
if(nodes[cur].threshold < feat(nodes[cur].x))
cur = nodes[cur].rightChild;
else
cur = nodes[cur].leftChild;
}
// std::cout<<"Right now at node no : "<<cur<<"\n";
// for(int i = 0; i < nodes[cur].hist.size(); ++i)
// std::cout<<nodes[cur].hist(i)<<"\t";
return nodes[cur].hist;
}
double Tree::informationGain(int i, int j, const VectorInteger& labels)
{
VectorInteger l,r,t;
int ctr(0);
for(int k = i; k <= j; ++k)
ctr += ((indices[k])?1:0);
l.resize(ctr);
r.resize(j+1-i-ctr);
t.resize(j-i+1);
l = VectorInteger::Zero(ctr);
r = VectorInteger::Zero(j+1-i-ctr);
t = VectorInteger::Zero(j-i+1);
for(int k = i, m=0, n=0; k <= j; ++k)
{
if(indices[k])
l(m++) = labels[k];
else
r(n++) = labels[k];
t(k-i) = labels[k];
}
double h,hl,hr;
h = entr(t);
hl = entr(l);
hr = entr(r);
// std::cout<<"\n"<<h<<"\t"<<hl<<"\t"<<hr<<"\n";
return h - ((l.size()*hl)+(r.size()*hr))/(double)labels.size();
}
int Tree::partition(int l, int r)
{
int temp;
bool temp2;
while ( l <= r)
{
if(!indices[l])
{
temp = nodeix[l];
nodeix[l] = nodeix[r];
nodeix[r] = temp;
temp2 = indices[l];
indices[l] = indices[r];
indices[r] = temp2;
r--;
}
else
l++;
}
return r+1;
/*
while(1)
{
while(r && !indices[--r]);
while(indices[++k]);
if(k<r)
{
temp = nodeix[r];
nodeix[r] = nodeix[k];
nodeix[k] = temp;
temp2 = indices[r];
indices[r] = indices[k];
indices[k] = temp2;
k--;
}
else break;
}
if(r == 0)
return 0;
return k;
*/
}
void Tree::treeHist()
{
for(unsigned int i = 0; i < nodes.size(); ++i)
{
if(nodes[i].isType())
{
std::cout<<"\nNode number "<<i<<"\n";
for(signed int j = 0; j < nodes[i].hist.size(); ++j)
std::cout<<nodes[i].hist(j)<<"\t";
}
else
{
std::cout<<"\nNode number "<<i<<"\n";
std::cout<<"X : "<<nodes[i].x<<" thres : "<<nodes[i].threshold<<"\n";
}
}
}
bool Tree::isTrivial(int i, const VectorInteger& labels)
{
//This part checks for triviality of the node
//The three ways a node can be trivial are
//a) it has too little elements,
//b) it has the same class elements as before
//c) it has hit the max depth
if(nodes[i].rightChild - nodes[i].leftChild < DATA_MIN)
nodes[i].setType(true);
if(nodes[i].depth == depth)
nodes[i].setType(true);
VectorReal hist;
hist = VectorReal::Zero(labels.maxCoeff()+1);
for(int k = nodes[i].start; k <= nodes[i].end; ++k)
hist(labels(nodeix[k])) += 1.0;
hist = hist/hist.sum();
if(hist.maxCoeff()>.99)
nodes[i].setType(true);
return nodes[i].isType();
}
| true |
84dbc7076a35ab8beafedc1bc60e74e56535b580 | C++ | AlexP97/Juego-EDA | /AIru_6.cc | UTF-8 | 5,852 | 2.53125 | 3 | [] | no_license | #include "Player.hh"
#include <limits>
/**
* Write the name of your player and save this file
* with the same name and .cc extension.
*/
#define PLAYER_NAME ru_6
struct PLAYER_NAME : public Player {
/**
* Factory: returns a new instance of this class.
* Do not modify this function.
*/
static Player* factory () {
return new PLAYER_NAME;
}
/**
* Types and attributes for your player can be defined here.
*/
struct index {
bool v;
int d;
Dir mov;
};
typedef vector<int> VE;
typedef vector<VE> VVE;
typedef vector<index> VB;
typedef vector<VB> VVB;
bool es_ok_f(Pos p, bool primer) {
Cell c = cell(p);
return ( (primer and c.type == Empty and c.id == -1 and not c.haunted) or (not primer and c.type == Empty and not c.haunted));
}
bool es_ok_k(Pos p, Unit m_a, bool& enemic) {
Cell c = cell(p);
if (c.id != -1) {
Unit m = unit(c.id);
enemic = true;
return (c.type == Empty and m.player != 0 and not c.haunted and m.type != Witch);
}
else return (c.type == Empty and not c.haunted);
}
bool es_ok_w(Pos p, bool& enemic) {
Cell c = cell(p);
if (c.id != -1) {
Unit m = unit(c.id);
enemic = true;
return (c.type == Empty and m.player != 0 and m.type == Knight );
}
else return (c.type == Empty);
}
Dir cerca_bfs_w(Pos a, VVE& marcats) {
VVB vist(37, VB(37));
for (int i = 0; i < 37; i++)
for (int j = 0; j < 37; j++)
{
vist[i][j].v = false;
vist[i][j].d = numeric_limits<int>::max();
vist[i][j].mov = None;
}
vist[a.i][a.j].v= true; vist[a.i][a.j].d = 0;
queue<Pos> cua;
cua.push(a);
bool trobat = false;
bool primer = true;
bool enemic = false;
VE direccions(4);
for (int i = 0; i < 4; i++)
direccions[i] = (i*2);
VE perm = random_permutation(4);
while (not cua.empty() and not trobat) {
Pos u = cua.front(); cua.pop();
for (int it = 0; it < 4 and not trobat; it++) {
Pos u_2 = u + Dir(perm[it]*2);
if ( not trobat and es_ok_w(u_2, enemic) and not vist[u_2.i][u_2.j].v ) {
cua.push(u_2);
vist[u_2.i][u_2.j].v = true;
vist[u_2.i][u_2.j].d = vist[u.i][u.j].d + 1;
if (primer) vist[u_2.i][u_2.j].mov = Dir(perm[it]*2);
else vist[u_2.i][u_2.j].mov = vist[u.i][u.j].mov;
if (enemic and marcats[u_2.i][u_2.j] != 1) {
trobat = true;
marcats[u_2.i][u_2.j] = 1;
}
}
enemic = false;
}
primer = false;
}
if (trobat) {
Pos t = cua.back();
return vist[t.i][t.j].mov;
}
return None;
}
Dir cerca_bfs_k(Pos a, Unit m_a) {
VVB vist(37, VB(37));
for (int i = 0; i < 37; i++)
for (int j = 0; j < 37; j++)
{ vist[i][j].v = false;
vist[i][j].d = numeric_limits<int>::max();
vist[i][j].mov = None;
}
vist[a.i][a.j].v= true;
vist[a.i][a.j].d = 0;
queue<Pos> cua;
cua.push(a);
bool trobat = false;
bool primer = true;
bool enemic = false;
while (not cua.empty() and not trobat) {
Pos u = cua.front(); cua.pop();
VE perm = random_permutation(8);
for (int it = 0; it < 8 and not trobat; it++) {
Pos u_2 = u + Dir(perm[it]);
if ( not trobat and es_ok_k(u_2, m_a, enemic) and not vist[u_2.i][u_2.j].v ) {
cua.push(u_2);
vist[u_2.i][u_2.j].v = true; vist[u_2.i][u_2.j].d = vist[u.i][u.j].d + 1;
if (primer) vist[u_2.i][u_2.j].mov = Dir(perm[it]);
else vist[u_2.i][u_2.j].mov = vist[u.i][u.j].mov;
if (enemic) { trobat = true; }
}
enemic = false;
}
primer = false;
}
if (trobat) {
Pos t = cua.back();
return vist[t.i][t.j].mov;
}
return None;
}
Dir cerca_bfs_f(Pos a, VVE& marcats) {
VVB vist(37, VB(37));
for (int i = 0; i < 37; i++)
for (int j = 0; j < 37; j++)
{
vist[i][j].v = false;
vist[i][j].d = numeric_limits<int>::max();
vist[i][j].mov = None;}
vist[a.i][a.j].v= true; vist[a.i][a.j].d = 0;
queue<Pos> cua;
cua.push(a);
bool trobat = false;
bool primer = true;
VE direccions(4);
for (int i = 0; i < 4; i++)
direccions[i] = (i*2);
while (not cua.empty() and not trobat) {
Pos u = cua.front(); cua.pop();
for (int it = 0; it < 4 and not trobat; it++) {
Pos u_2 = u + Dir(direccions[it]);
if ( not trobat and es_ok_f(u_2, primer) and not vist[u_2.i][u_2.j].v ) {
cua.push(u_2);
vist[u_2.i][u_2.j].v = true; vist[u_2.i][u_2.j].d = vist[u.i][u.j].d + 1;
if (primer) vist[u_2.i][u_2.j].mov = Dir(direccions[it]);
else vist[u_2.i][u_2.j].mov = vist[u.i][u.j].mov;
if (cell(u_2).owner != 0 and marcats[u_2.i][u_2.j] != 1) {
trobat = true;
marcats[u_2.i][u_2.j] = 1;
}
}
}
primer = false;
}
if (trobat) {
Pos t = cua.back();
return vist[t.i][t.j].mov;
}
return None;
}
/**
* Play method, invoked once per each round.
*/
virtual void play () {
Pos actual;
VVE marcats(37, VE(37, 0));
VE f = farmers(0);
for (int unsigned i = 0; i < f.size(); ++i) {
actual = unit(f[i]).pos;
Dir executar = cerca_bfs_f(actual, marcats);
command(f[i], executar);
}
VE k = knights(0);
for (int unsigned i = 0; i < k.size(); ++i) {
actual = unit(k[i]).pos;
Dir executar = cerca_bfs_k(actual, unit(k[i]));
command(k[i], executar);
}
marcats = VVE (37, VE(37, 0));
VE w = witches(0);
actual = unit(w[0]).pos;
Dir executar = cerca_bfs_w(actual, marcats);
command(w[0], executar);
actual = unit(w[1]).pos;
executar = cerca_bfs_w(actual, marcats);
command(w[1], executar);
}
};
/**
* Do not modify the following line.
*/
RegisterPlayer(PLAYER_NAME);
| true |
b431c043dbf50225fb9d421b2eb4e3657ba27280 | C++ | timhang/Summer2018 | /car.h | UTF-8 | 528 | 2.734375 | 3 | [] | no_license | #ifndef CAR_H
#define CAR_H
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <cstdlib>
#include <set>
class car{
public:
car(std::string make,std::string model,unsigned int year, std::string color);
~car();
const std::string get_promo() const;
private:
void add_promo(std::string auth, std::string promo);
std::set<std::string> authorization;
std::string promo_info;
std::string car_make;
std::string car_model;
unsigned int car_year;
std::string car_color;
};
#endif | true |
f22d4ec4da1c540693e3085eb768e61eb11496c7 | C++ | jtahstu/iCode | /workspace/nyoj/src/1127.cpp | GB18030 | 3,448 | 3.03125 | 3 | [] | no_license | /**
* Project Name: nyoj
* File Name: 1127.cpp
* Created on: 2015717 8:29:02 last modify by 2015/7/20 3:12
* Author: jtahstu
* QQ: 1373758426 E-mail:1373758426@qq.com
* Copyright (c) 2015, jtahstu , All Rights Reserved.
*/
//#include<iostream>
//#include<cstdio>
//#include<cmath>
//#include<cstdlib>
//#include<algorithm>
//#include<string>
//#include<cstring>
//using namespace std;
//int a[315];
//int main() {
// int t, count = 0;
// cin >> t;
// while (t--) {
// memset(a, 0, sizeof(a));
// int n;
// cin >> n;
// for (int i = 1; i <= n; i++)
// cin >> a[i];
// n++; //Ҫ+1Ϊһ
// sort(a + 1, a + n);
// int x = (int) ceil(0.1 * n);
// int y = (int) ceil(0.2 * n);
// int z = (int) ceil(0.3 * n);
// cout << "Case #" << ++count << ": " << a[x] - 1 << " " << a[x + y] - 1
// << " " << a[x + y + z] - 1 << endl;
// }
// return 0;
//}
//#include <iostream>
//#include <cstdio>
//#include <cmath>
//#include <algorithm>
//
//using namespace std;
//
//int main2() {
// int penalty[320];
// int n, icase = 1, t;
// scanf("%d", &t);
// while (t--) {
// scanf("%d", &n);
// for (int i = 1; i <= n; ++i) {
// scanf("%d", &penalty[i]);
// }
// n++;
// sort(penalty + 1, penalty + n);
// int p1 = (int) ceil(n * 0.1), p2 = p1 + (int) ceil(n * 0.2), p3 = p2
// + (int) ceil(n * 0.3);
// printf("Case #%d: %d %d %d\n", icase++, penalty[p1] - 1,
// penalty[p2] - 1, penalty[p3] - 1);
// }
// return 0;
//}
//Penalty
//ʱƣ1000 ms | ڴƣ65535 KB
//Ѷȣ2
//
// As is known to us, the penalty is vitally important to competitors in the programming contest! After participating in the 2014 ACM-ICPC Asia Xian Regional Contest, LYH have a deep understanding about the importance of penalty. If some teams have solved same problem, the less penalty, the top rank.
// According to the rules of the competition, among all the teams, 10% will win a gold medal, 20% will win a silver medal, 30% will win a bronze medal. If it is not an integer, we will take the integer which not less than the real number as the number of the corresponding medal. For example, if the number of gold medal is 2.3, then we consider the number of gold medal is 3.
// For the sake of simpleness, suppose that the number of problems each team have solved is equal in the end of the programming contest, and we have known the penalty of each team. As a competitor , LYH want to know what is the maximum penalty will be if he wants to win a gold medala silver medala bronze medal.
//
//The first line of the input gives the number of test cases, T. T test cases follow.
//For each test case, the first line contains an integer n(5n310), the number of the team except LYH'team, the second line contains n distinct integers a(500a5500), the ith integer represents the penalty of the ith team except his team.
//
//For each test case, output one line Case #x: G S B, where x is the case number(starting from 1), G is the maximum penalty if he wants to win a gold medal, S is the maximum penalty if he wants to win a silver medal, B is the maximum penalty if he wants to win a bronze medal.
//
//2
//9
//500 550 600 650 700 750 800 850 900
//10
//500 511 522 533 544 555 566 577 588 599
//
//Case #1: 499 599 749
//Case #2: 510 543 587
| true |
61003bc507d1ffae6b57fc23dd2d582f823ba895 | C++ | luanics/cpp-illustrated | /luanics/logging/SimpleSource.hpp | UTF-8 | 1,181 | 2.796875 | 3 | [
"MIT"
] | permissive | #pragma once
#include "luanics/logging/Filter.hpp"
#include "luanics/logging/Record.hpp"
#include "luanics/logging/Sink.hpp"
#include "luanics/logging/Source.hpp"
#include <iostream>
#include <memory>
namespace luanics::logging {
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///
/// @class SimpleSource
///
/// @brief Logging Source suitable for single-threaded applications.
///
/// All Records submitted are immediately handed off to Sink in same thread.
///
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
class SimpleSource : public Source {
public:
SimpleSource(); ///< Installs NoFilter and SimpleSink
virtual void submit(std::unique_ptr<Record> record) override final;
virtual void setFilter(std::unique_ptr<Filter> filter) override final;
virtual void setSink(std::unique_ptr<Sink> sink) override final;
private:
std::unique_ptr<Filter> _filter;
std::unique_ptr<Sink> _sink;
}; // class SimpleSource
} // namespace luanics::logging
| true |
ebb1990288c7b70bce6957128a2151026957e8ac | C++ | captn3m0/algorithms | /sorting/merge.cpp | UTF-8 | 1,313 | 3.453125 | 3 | [] | no_license | #include <math.h>
#include <iostream>
#include "../common.h"
#include <limits.h>
#define MAX_LENGTH 12
using namespace std;
void merge(int* a,int start,int pivot,int end)
{
//create left and right arrays
int left[MAX_LENGTH], right[MAX_LENGTH],i,lp=0,rp=0;
//Copy the left and right halves of a in left/right
for(i=0;i<pivot;i++)
left[i]=a[start+i];
for(i=pivot;i<end;i++)
right[i-pivot]=a[i];
right[end-pivot]=left[pivot]=INT_MAX;//add sentinel values
//now we have copied the arrays
//There are a total of end-start elements in the complete array
for(i=start;i<end;i++)
{
if(left[lp]<=right[rp])
{
a[i]=left[lp];
lp++;
}
else
{
a[i]=right[rp];
rp++;
}
}
}
void mergeSort(int* a,int start,int end)
{
//For single element arrays, we just return it
//as it is already sorted
if(end-start==1)
return;
int pivot=floor((start+end)/2);//calculate the pivot
//call merge sort on both halves
mergeSort(a,start,pivot);//pivot is not included
mergeSort(a,pivot,end);//pivot included
//end refers to the array size
//array index goes from 0 to end-1
//Now we merge both halves
merge(a,start,pivot,end);
}
int main()
{
int arr[MAX_LENGTH]={12,11,10,9,8,7,6,5,4,3,2,1};
mergeSort(arr,0,12);
assertSorted(arr,4);
}
| true |
a2bc382993bbb3d29baa2f7ea49b3b8625bcb0b0 | C++ | Infamous999/Labisss | /YapisLaba7.cpp | UTF-8 | 1,551 | 3.4375 | 3 | [] | no_license | #include <iostream>
#include <cmath>
using namespace std;
double value();
double value_2();
class equation {
public:
double a;
double b;
double c;
};
int main() {
cout << "This program solves an equation of the form: a*sin(x) + b*cos(x) = c" << endl;
equation task;
task.a = value();
task.b = value_2();
task.c = 0;
double res_div = task.b / task.a;
cout << "Number c = 0" << endl;
cout << "equation: " << task.a << "*sin(x) + " << task.b << "*cos(x) = " << task.c << endl;
cout << "divide this equation by: cos x, we get " << task.a << "*tg(x) + " << task.b << " = 0" << endl;
cout << "divide both sides of the equation by: " << task.a << ", we get: tg(x) = " << -res_div << endl;
if (task.c == 0)
cout << "x = arctg " << -res_div << " + Pi * n" << endl;
}
double value()
{
while (true) {
double number;
cout << "Enter number a: ";
cin >> number;
if (cin.fail() || number <= 0) {
cin.clear();
cin.ignore(32767, '\n');
cout << "Error, please enter again" << endl;
}
else {
return number;
}
}
}
double value_2()
{
while (true) {
double number;
cout << "Enter number b: ";
cin >> number;
if (cin.fail() || number <= 0) {
cin.clear();
cin.ignore(32767, '\n');
cout << "Error, please enter again" << endl;
}
else {
return number;
}
}
} | true |
1ede44c54082e9fdf03dacbf3bc9140849580a95 | C++ | kumbal123/test | /god1.cpp | UTF-8 | 13,294 | 2.875 | 3 | [] | no_license | #ifndef __PROGTEST__
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <cassert>
#include <cctype>
#include <cmath>
#include <iostream>
#include <iomanip>
#include <sstream>
using namespace std;
#endif /* __PROGTEST__ */
class CTransaction{
private:
int m_Amount;
char * m_OtherID;
char * m_Sign;
char m_Mark;
public:
CTransaction(): m_Amount( 0 ),
m_OtherID( nullptr ),
m_Sign( nullptr ){}
CTransaction( int amount, const char * OtherID, const char * sign, char mark ):
m_Amount( amount ),
m_OtherID( new char[ strlen( OtherID ) + 1 ] ),
m_Sign( new char[ strlen( sign ) + 1 ] ),
m_Mark( mark )
{
memcpy( m_OtherID, OtherID, strlen( OtherID ) + 1 );
memcpy( m_Sign, sign, strlen( sign ) + 1 );
}
void deleteCTransaction(){
delete [] m_OtherID;
delete [] m_Sign;
}
int getAmount(){
return m_Amount;
}
const char * getOtherID(){
return m_OtherID;
}
const char * getSign(){
return m_Sign;
}
char getMark(){
return m_Mark;
}
};
// ------------------------------------- CAcc class --------------------------------------------------------------
class CAcc{
private:
char * m_AccID;
int m_InitialBalance;
int m_Balance;
int m_SizeTrans;
int m_MaxTrans;
CTransaction * m_Transaction;
public:
CAcc(): m_AccID( nullptr ),
m_InitialBalance( 0 ),
m_Balance( 0 ),
m_SizeTrans( 0 ),
m_MaxTrans( 0 ),
m_Transaction( nullptr ){}
CAcc( const char * accID, int initialBalance ):
m_AccID( new char[ strlen( accID ) + 1 ] ),
m_InitialBalance( initialBalance ),
m_Balance( initialBalance ),
m_SizeTrans( 0 ),
m_MaxTrans( 0 ),
m_Transaction( nullptr )
{
memcpy( m_AccID, accID, strlen( accID ) + 1 );
}
void deleteCAcc(){
delete [] m_AccID;
for( int i = 0; i < m_SizeTrans; ++i ){
m_Transaction[i].deleteCTransaction();
}
delete [] m_Transaction;
}
void TrimAcc(){
for( int i = 0; i < m_SizeTrans; ++i ){
m_Transaction[i].deleteCTransaction();
}
delete [] m_Transaction;
m_Transaction = nullptr;
m_SizeTrans = 0;
m_MaxTrans = 0;
m_InitialBalance = m_Balance;
}
const char * getAccID(){
return m_AccID;
}
int getInitialBalance(){
return m_InitialBalance;
}
int getBalance(){
return m_Balance;
}
int getSizeTrans(){
return m_SizeTrans;
}
int getMaxTrans(){
return m_MaxTrans;
}
CTransaction * getTransaction(){
return m_Transaction;
}
CTransaction getTransaction( int index ){
return m_Transaction[ index ];
}
void setTransaction( CTransaction * x ){
m_Transaction = x;
}
void newInitialBalance(){
m_InitialBalance = m_Balance;
}
void setBalance( int balance ){
m_Balance = balance;
}
void setSize( int size ){
m_SizeTrans = size;
}
void setMax( int max ){
m_MaxTrans = max;
}
int Balance(){
return m_Balance;
}
void addBalance( int amount ){
m_Balance += amount;
}
void realloc(){
if( m_SizeTrans == m_MaxTrans ){
m_MaxTrans += m_MaxTrans < 100 ? 10 : m_MaxTrans/2;
CTransaction * tmpTrans = new CTransaction[ m_MaxTrans ];
for( int j = 0; j < m_SizeTrans; ++j ){
CTransaction tmp2 = CTransaction( m_Transaction[ j ].getAmount(),
m_Transaction[ j ].getOtherID(),
m_Transaction[ j ].getSign(),
m_Transaction[ j ].getMark() );
tmpTrans[j] = tmp2;
delete [] m_Transaction[j].getOtherID();
delete [] m_Transaction[j].getSign();
}
delete [] m_Transaction;
m_Transaction = tmpTrans;
}
}
void NewTransaction( int amount, const char * OtherID, const char * sign, char mark ){
this -> realloc();
m_Transaction[ m_SizeTrans ] = CTransaction( amount, OtherID, sign, mark );
m_SizeTrans++;
}
};
// ------------------------------------- CBridge class ----------------------------------------------------------------------
class CBridge{
private:
CAcc * m_Accounts;
int m_SizeAcc;
int m_MaxAcc;
unsigned int m_SumPointer;
public:
// default constructor
CBridge(): m_Accounts( nullptr ),
m_SizeAcc( 0 ),
m_MaxAcc( 0 ),
m_SumPointer( 1 ){}
// copy constructor
CBridge( CBridge & x ): m_Accounts( x.newCopy() ),
m_SizeAcc( x.m_SizeAcc ),
m_MaxAcc( x.m_MaxAcc ),
m_SumPointer( 1 ){}
// destructor
void deleteBridge(){
for( int i = 0; i < m_SizeAcc; ++i ){
m_Accounts[i].deleteCAcc();
}
delete [] m_Accounts;
}
void realloc(){
if( m_SizeAcc == m_MaxAcc ){
m_MaxAcc += m_MaxAcc < 100 ? 10 : m_MaxAcc/2;
CAcc * tmp = new CAcc[ m_MaxAcc ];
copy( m_Accounts, m_Accounts + m_SizeAcc, tmp );
delete [] m_Accounts;
m_Accounts = tmp;
}
}
CAcc * newCopy(){
CAcc * tmpAcc = new CAcc[ m_MaxAcc ];
for( int i = 0; i < m_SizeAcc; ++i ){
CAcc tmp1 = CAcc( m_Accounts[i].getAccID(), m_Accounts[i].getInitialBalance() );
tmp1.setBalance( m_Accounts[i].getBalance() );
tmp1.setSize( m_Accounts[i].getSizeTrans() );
tmp1.setMax( m_Accounts[i].getMaxTrans() );
CTransaction * tmpTrans = new CTransaction[ m_Accounts[i].getMaxTrans() ];
for( int j = 0; j < m_Accounts[i].getSizeTrans(); ++j ){
CTransaction tmp2 = CTransaction( m_Accounts[i].getTransaction( j ).getAmount(),
m_Accounts[i].getTransaction( j ).getOtherID(),
m_Accounts[i].getTransaction( j ).getSign(),
m_Accounts[i].getTransaction( j ).getMark() );
tmpTrans[j] = tmp2;
}
tmp1.setTransaction( tmpTrans );
tmpAcc[i] = tmp1;
}
return tmpAcc;
}
// operator =
void operator = ( CBridge & x );
bool NewAccount ( const char * accID, int initialBalance );
bool Transaction ( const char * debAccID, const char * credAccID,
unsigned int amount, const char * signature );
bool TrimAccount ( const char * accID );
// Account ( accID )
CAcc & Account ( const char * accID );
friend ostream & getStream ( ostream & out, CAcc & x );
void addPointer(){
m_SumPointer++;
}
void removePointer(){
m_SumPointer--;
}
void setSizeAcc( int size ){
m_SizeAcc = size;
}
void setMaxAcc( int max ){
m_MaxAcc = max;
}
CAcc * getAccounts(){
return m_Accounts;
}
unsigned int getPointer(){
return m_SumPointer;
}
};
void CBridge::operator = ( CBridge & x ){
this -> ~CBridge();
m_SizeAcc = x.m_SizeAcc;
m_MaxAcc = x.m_MaxAcc;
m_Accounts = x.newCopy();
}
bool CBridge::NewAccount ( const char * accID, int initialBalance ){
for( int i = 0; i < m_SizeAcc; i++ ){
if( !strcmp( accID, m_Accounts[i].getAccID() ) )
return false;
}
realloc();
m_Accounts[ m_SizeAcc ] = CAcc( accID, initialBalance );
m_SizeAcc++;
return true;
}
bool CBridge::Transaction ( const char * debAccID, const char * credAccID,
unsigned int amount, const char * signature ){
if( !strcmp( debAccID, credAccID ) )
return false;
int debAccIndex = -1, credAccIndex = -1;
for( int i = 0; i < m_SizeAcc; i++ ){
if( !strcmp( debAccID, m_Accounts[i].getAccID() ) )
debAccIndex = i;
else if( !strcmp( credAccID, m_Accounts[i].getAccID() ) )
credAccIndex = i;
}
if( credAccIndex == -1 || debAccIndex == -1 )
return false;
m_Accounts[ debAccIndex ].addBalance( -1 * amount );
m_Accounts[ credAccIndex ].addBalance( amount );
m_Accounts[ debAccIndex ].NewTransaction( amount, credAccID, signature, '-' );
m_Accounts[ credAccIndex ].NewTransaction( amount, debAccID, signature, '+' );
return true;
}
bool CBridge::TrimAccount ( const char * accID ){
int accIDIndex = -1;
for( int i = 0; i < m_SizeAcc; i++ ){
if( !strcmp( accID, m_Accounts[i].getAccID() ) ){
accIDIndex = i;
break;
}
}
if( accIDIndex == -1 )
return false;
m_Accounts[ accIDIndex ].TrimAcc();
return true;
}
CAcc & CBridge::Account ( const char * accID ){
int accIDIndex = -1;
for( int i = 0; i < m_SizeAcc; i++ ){
if( !strcmp( accID, m_Accounts[i].getAccID() ) ){
accIDIndex = i;
break;
}
}
if( accIDIndex == -1 )
throw runtime_error( "no accID found " );
return m_Accounts[ accIDIndex ];
}
ostream & getSTream ( ostream & out, CAcc & x ){
out << x.getAccID() << ":\n " << x.getInitialBalance() << "\n";
for( int i = 0; i < x.getSizeTrans(); ++i ){
out << " " << x.getTransaction( i ).getMark() << " " << x.getTransaction( i ).getAmount() << ", ";
if( x.getTransaction( i ).getMark() == '+' )
out << "from: ";
else
out << "to: ";
out << x.getTransaction( i ).getOtherID() << ", sign: " << x.getTransaction( i ).getSign() << "\n";
}
out << " = " << x.getBalance() << "\n";
return out;
}
class CBank{
private:
CBridge * m_Bridge;
public:
CBank(): m_Bridge( new CBridge() ){}
CBank( CBank & x ): m_Bridge( x.m_Bridge )
{
x.m_Bridge -> addPointer();
}
// destructor
~CBank(){
if( m_Bridge -> getPointer() > 1 ){
m_Bridge -> removePointer();
m_Bridge = nullptr;
}else if( m_Bridge -> getPointer() == 1 ){
m_Bridge -> removePointer();
m_Bridge -> deleteBridge();
delete m_Bridge;
}
}
// operator =
void operator = ( CBank & x ){
this -> ~CBank();
if( x.m_Bridge )
x.m_Bridge -> addPointer();
m_Bridge = x.m_Bridge;
}
bool NewAccount ( const char * accID,
int initialBalance );
bool Transaction ( const char * debAccID,
const char * credAccID,
unsigned int amount,
const char * signature );
bool TrimAccount ( const char * accID );
CAcc & Account( const char * accID );
friend ostream & operator << ( ostream & out, CAcc & x );
};
bool CBank::NewAccount ( const char * accID, int initialBalance ){
if( !m_Bridge )
return false;
if( m_Bridge -> getPointer() > 1 ){
m_Bridge -> removePointer();
m_Bridge = new CBridge( *m_Bridge );
}
if( !m_Bridge -> NewAccount( accID, initialBalance ) )
return false;
return true;
}
bool CBank::Transaction ( const char * debAccID,
const char * credAccID,
unsigned int amount,
const char * signature ){
if( !m_Bridge )
return false;
if( m_Bridge -> getPointer() > 1 ){
m_Bridge -> removePointer();
m_Bridge = new CBridge( *m_Bridge );
}
if( !m_Bridge -> Transaction( debAccID, credAccID, amount, signature ) )
return false;
return true;
}
bool CBank::TrimAccount ( const char * accID ){
if( !m_Bridge )
return false;
if( m_Bridge -> getPointer() > 1 ){
m_Bridge -> removePointer();
m_Bridge = new CBridge( *m_Bridge );
}
if( !m_Bridge -> TrimAccount( accID ) )
return false;
return true;
}
CAcc & CBank::Account( const char * accID ){
return m_Bridge -> Account( accID );
}
ostream & operator << ( ostream & out, CAcc & x ){
return getSTream( out, x );
}
//------------------------------------------------------ main -------------------------------------------------------------------
#ifndef __PROGTEST__
int main ( void )
{
int x;
x = 5 + 6;
cout << "x: " << x << endl;
cout << "--------------------------------------- done ---------------------------------------------" << endl;
cout << "--------------------------------------- done ---------------------------------------------" << endl;
cout << "--------------------------------------- done ---------------------------------------------" << endl;
return 0;
}
#endif /* __PROGTEST__ */
| true |
d6e11a14b1065eb377fad2d05c483bb5d3e4249f | C++ | ss9036726/Programs | /selection.cpp | UTF-8 | 2,163 | 3.640625 | 4 | [] | no_license | #include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
struct node{
int data;
node *singlelink;
};
node *head; //head pointer used to store address of first node
node *q;//back tacking pointer during creation of Single linked list
void SelectionSort(node *head); //passing head node
void add(int save);
void Display(node *head); //passing head node
int main(){
int value;
int maxsize;
srand(time(0)); // this is to generate different numbers at every runtime
cout<<"How many numbers, you want to sort : ";
cin>>maxsize; // number of digits to be generated
cout<<endl;
for(int i=0;i < maxsize;i++)
{
cin>>value; // generate random numbers (data sets will change depends on fraction
add(value);
}
cout<<"Initial single link list : ";
Display(head);
cout<<endl;
SelectionSort(head);
cout<<endl<<endl<<"After Applying selection Sort...."<<endl;
cout<<endl;
Display(head);
}
void SelectionSort(node *r){ //r is the pointer to the first node
while(r != NULL){
node *p=NULL;
node *q=r;
int temp=r->data;
while(q!= NULL){
if( temp > q->data){
p=q; //p points to the smallest element in the list
temp=q->data;
}
q=q->singlelink; //q goes to the next node
}
if(p!=NULL)
swap( p->data,r->data);
r=r->singlelink; //r goes to the next node
Display(head);
}
}
void add(int save){
node *newNode=new node;
if(head==NULL){
newNode->data=save;
head=newNode;
q=newNode; //back tracking for further insertion in list
newNode->singlelink=NULL;
}
else{
newNode->data=save;
q->singlelink=newNode;
q=newNode; //update q to the current node
newNode->singlelink=NULL;
}
}
void Display(node *head){
while(head!=NULL){
cout<<head->data<<" ";
head=head->singlelink; //head goes to the next node
}
cout<<endl;
} | true |
6f8ce750493fb0bb2f12aad352f881ab666aabbe | C++ | NathanCoxson/ASCII-Scrabble-Game | /210CT Task/210CT Task/Square.cpp | UTF-8 | 1,925 | 3.203125 | 3 | [] | no_license | #include "Square.h"
Square::Square() { square_type = 0; tile.letter = '_'; tile.blank = true; }
Square::Square(int type) { square_type = type; tile.letter = '_'; tile.blank = true; }
Square::Square(char currentLetter) { tile.letter = currentLetter; square_type = 0; tile.blank = false; }
Square::Square(char currentLetter, int type) { tile.letter = currentLetter; square_type = type; tile.blank = false; }
int Square::Value()
{
switch (square_type)
{
case SquareType::eNormal: return LetterPointCalculator(tile.letter);
case SquareType::eDoubleLetter: return LetterPointCalculator(tile.letter) * 2;
case SquareType::eTripleLetter: return LetterPointCalculator(tile.letter) * 3;
case SquareType::eDoubleWord: return LetterPointCalculator(tile.letter);
case SquareType::eTripleWord: return LetterPointCalculator(tile.letter);
}
}
int Square::NormalValue() { return LetterPointCalculator(tile.letter); }
int Square::WordMultiplier()
{
switch (square_type)
{
case SquareType::eNormal: return 1;
case SquareType::eDoubleLetter: return 1;
case SquareType::eTripleLetter: return 1;
case SquareType::eDoubleWord: return 2;
case SquareType::eTripleWord: return 3;
}
}
int Square::LetterMultiplier()
{
switch (square_type)
{
case SquareType::eNormal: return 1;
case SquareType::eDoubleLetter: return 2;
case SquareType::eTripleLetter: return 3;
case SquareType::eDoubleWord: return 1;
case SquareType::eTripleWord: return 1;
}
}
string Square::ReturnLetter()
{
switch (square_type)
{
case SquareType::eNormal: return reset + char(toupper(tile.letter));
case SquareType::eDoubleLetter: return bright_cyan + char(toupper(tile.letter)) + reset;
case SquareType::eTripleLetter: return blue + char(toupper(tile.letter)) + reset;
case SquareType::eDoubleWord: return bright_magenta + char(toupper(tile.letter)) + reset;
case SquareType::eTripleWord: return red + char(toupper(tile.letter)) + reset;
}
}
| true |
a399caba281473cd97fe4c2de5b94eb696cdf997 | C++ | PoplarZhaoYang/Algorithm_problem | /game_theory/poj2484.cpp | UTF-8 | 273 | 3 | 3 | [] | no_license | #include <iostream>
class solve
{
public:
int n;
public:
void run(void){
while (std::cin >> n) {
if (!n) return;
std::cout << (n <= 2 ? "Alice" : "Bob") << std::endl;
}
}
}ac;
int main()
{
ac.run();
return 0;
}
| true |
eb04dbccc0c9600bfb8473f709fdccce896ca212 | C++ | sauloantuness/maratona | /uri2/1050.cpp | UTF-8 | 573 | 3.15625 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main(){
int d;
while(cin >> d){
switch(d){
case 61 : cout << "Brasilia" << endl; break;
case 71 : cout << "Salvador" << endl; break;
case 11 : cout << "Sao Paulo" << endl; break;
case 21 : cout << "Rio de Janeiro" << endl; break;
case 32 : cout << "Juiz de Fora" << endl; break;
case 19 : cout << "Campinas" << endl; break;
case 27 : cout << "Vitoria" << endl; break;
case 31 : cout << "Belo Horizonte" << endl; break;
default: cout << "DDD nao cadastrado" << endl;
}
}
} | true |
aff3fc44e9f908d7a6ccce267ac2d84a1c175f9a | C++ | Asionsolver/C-Note | /FunctionOverloading.cc | UTF-8 | 1,846 | 4.0625 | 4 | [] | no_license | /*
Function Overloading in C++
-->Function overloading is a feature of object oriented programming where two or more functions can have the same name but
different parameters.
-->When a function name is overloaded with different jobs it is called Function Overloading.
-->In Function Overloading “Function” name should be the same and the arguments should be different.
-->Function overloading can be considered as an example of polymorphism feature in C++.
Following is a simple C++ example to demonstrate function overloading.
How Function Overloading works?
Exact match:- (Function name and Parameter)
If a not exact match is found:–
->Char, Unsigned char, and short are promoted to an int.
->Float is promoted to double
If no match found:
->C++ tries to find a match through the standard conversion.
ELSE ERROR 🙁
*/
#include<bits/stdc++.h>
using namespace std;
void print(int i) {
cout << "Here is int " << i << endl;
}
void print(double f) {
cout << "Here is float " << f << endl;
}
void print(char const *c) {
cout << "Here is char* " << c << endl;
}
int add(int a, int b){
cout<<" using function with two arguments: ";
return a+b;
}
int add(int a, int b, int c){
cout<<" using function with three arguments: ";
return a+b+c;
}
int add(int a, int b, int c, int d){
cout<<" using function with four arguments: ";
return a+b+c+d;
}
int main(){
print(10);
print(10.10);
print("ten");
cout<<endl<<endl;
cout<<"This code is Function overloading."<<endl;
cout<<"The sum of two number"<<add(4,6)<<endl;
cout<<"The sum of three number"<<add(4,6,4)<<endl;
cout<<"The sum of four number"<<add(4,6,4,6)<<endl;
return 0;
} | true |
f2063e6758f61473e7bfb42c7dbadc6ea9f812bf | C++ | KingBing/arduino-dev | /libs/SerialFlow/SerialFlow.cpp | UTF-8 | 2,285 | 2.890625 | 3 | [] | no_license | /*
SerialFlow.cpp - Communication library with packages of values.
Created by Oleg Evsegneev, September 11, 2012.
Released into the public domain.
*/
#include "SerialFlow.h"
SerialFlow::SerialFlow(int tx, int rx): _serial(tx, rx) {
_escape = 0;
_collecting = 0;
}
void SerialFlow::begin(int baud_rate) {
_serial.begin(baud_rate);
}
void SerialFlow::setPacketFormat(DataFormat p_format, byte v_length, byte p_size) {
_p_format = p_format;
_p_size = p_size;
_v_length = v_length;
_vs_idx = 0;
_vr_idx = 0;
}
void SerialFlow::setPacketValue(short value) {
if( _vs_idx < _p_size ){
_vs[_vs_idx++] = value;
}
}
void SerialFlow::sendPacket() {
byte v;
_serial.write( 0x12 );
for( byte i=0; i<_vs_idx; i++ ){
// low byte
v = _vs[i] & 0xFF;
if( v==0x12 || v==0x13 || v==0x7D || v==0x10 )
_serial.write( 0x7D );
_serial.write( v );
// high byte
v = (_vs[i]>>8) & 0xFF;
if( v==0x12 || v==0x13 || v==0x7D || v==0x10 )
_serial.write( 0x7D );
_serial.write( v );
// separate values
if( i < _vs_idx-1 )
_serial.write(0x10);
}
_serial.write( 0x13 );
_vs_idx = 0;
}
bool SerialFlow::receivePacket() {
byte c;
while( _serial.available() ){
c = _serial.read();
if( _collecting )
if( _escape ){
_vr_val[_cr_idx++] = c;
_escape = 0;
}
// escape
else if( c == 0x7D ){
_escape = 1;
}
// value separator
else if( c == 0x10 ){
_vr[_vr_idx++] = _vr_val[0] | (_vr_val[1] << 8);
_cr_idx = 0;
}
// end
else if( c == 0x13 ){
_vr[_vr_idx++] = _vr_val[0] | (_vr_val[1] << 8);
_collecting = 0;
return 1;
}
else{
_vr_val[_cr_idx++] = c;
}
// begin
else if( c == 0x12 ){
_collecting = 1;
_cr_idx = 0;
_vr_idx = 0;
}
}
return 0;
}
short SerialFlow::getPacket( byte idx ) {
return _vr[idx];
}
| true |
94d2b1c2c05942e60a29fd5d833ef9169f484edc | C++ | Matthew-Haddad/Comp252_Final_Project | /Order_System.h | UTF-8 | 3,769 | 2.671875 | 3 | [] | no_license | #pragma once
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#include <chrono>
#include <ctime>
#include "ClassTypes.h"
int userChoice;
int tableCounter = 1;
/*PROTOTYPES*/
/*************************************************************************************************************************************************************/
/*VIEW OPTIONS SECTION*/
void viewActiveSubOrder(); /*view active sub order*/
void viewAllSubOrders(); /*view the status of all active suborders*/
void viewActiveMenu(); /*only view the active menu*/
void viewTransactionList();
/*PRINT OPTIONS SECTION*/
void printFinalReceipts(); /*print customer receipts on order completion*/
/**************************************************************************************************************************************************************/
/********************************************************************VIEW SECTION******************************************************************************/
void viewActiveSubOrder()
{
std::cout << "------------------------------------------------------------------------------------------------------------------------------\n";
std::cout << "|" << std::setw(62) << "CURRENT ORDERS" << std::setw(63) << "|" << "\n";
std::cout << "------------------------------------------------------------------------------------------------------------------------------\n";
std::cout << "NAME" << std::setw(40) << "UNIT COST" << std::setw(24) << "PRICE" << std::setw(25) << "COOK TIME" << std::setw(25) << "TABLE" << "\n";
}
void viewActiveMenu() // SHOWS A STATIC MENU
{
std::cout << "------------------------------------------------------------------------------------------------------\n";
std::cout << "|" << std::setw(50) << "MENU" << std::setw(51) << "|" << "\n";
std::cout << "------------------------------------------------------------------------------------------------------\n";
std::cout << "NAME" << std::setw(40) << "UNIT COST" << std::setw(24) << "PRICE" << std::setw(25) << "COOK TIME" << std::setw(25) << "\n";
}
void viewAllSubOrders() // USED TO VIEW ALL SUBORDERS
{
std::cout << "-------------------------------------------------------------------------------------------------------------\n";
std::cout << "|" << std::setw(65) << "ACTIVE ORDERS" << std::setw(43) << "|" << "\n";
std::cout << "-------------------------------------------------------------------------------------------------------------\n";
std::cout << "NAME" << std::setw(40) << "UNIT COST" << std::setw(24) << "PRICE" << std::setw(25) << "COOK TIME" << "\n";
}
void viewTransactionList()
{
std::cout << "************************************************************************************\n";
std::cout << "*" << std::setw(50) << "TRANSACTION LIST ORDERS" << std::setw(28) << "*\n";
std::cout << "************************************************************************************\n";
std::cout << "NAME" << std::setw(40) << "UNIT COST" << std::setw(24) << "PRICE" << "\n";
}
/********************************************************************PRINT SECTION*******************************************************************************/
void printFinalReceipts() /*print customer receipts on order completion*/
{
std::cout << "******************************************\n";
std::cout << "*" << std::setw(25) << "FINAL RECEIPT" << std::setw(17) << "*\n";
std::cout << "******************************************\n";
std::cout << "\n";
std::cout << "NAME" << std::setw(35) << "SUB TOTAL\n";
}
| true |
ba040083058718a1f6a841312151784bf7212fdc | C++ | ncahill-wegfliegen/gemeinsam | /uom/puom_ratio.h | UTF-8 | 5,031 | 2.9375 | 3 | [] | no_license | #pragma once
#include "puom.h"
#include "prefix.h"
#include "../utility/object.h"
#include <string>
#include <sstream>
#include <type_traits>
namespace nhill
{
namespace uom
{
template<typename Uom_numerator, typename Uom_denominator>
class Prefixed_uom_ratio : public virtual nhill::Object
{
public:
static_assert(std::is_enum_v<Uom_numerator >, "The template parameter for the numerator must be a stronly typed enumeration.");
static_assert(std::is_enum_v<Uom_denominator>, "The template parameter for the demoniator must be a stronly typed enumeration.");
using puom_num = Prefixed_uom<Uom_numerator>;
using puom_den = Prefixed_uom<Uom_denominator>;
Prefixed_uom_ratio();
Prefixed_uom_ratio( const puom_num& num, const puom_den& den );
Prefixed_uom_ratio( Prefix prefix_num, Uom_numerator uom_num, Prefix prefix_den, Uom_denominator uom_den );
Prefixed_uom_ratio( const Prefixed_uom_ratio& src );
Prefixed_uom_ratio& operator=( const Prefixed_uom_ratio& src ) = delete;
Prefixed_uom_ratio( Prefixed_uom_ratio&& src );
Prefixed_uom_ratio& operator=( Prefixed_uom_ratio&& src ) = delete;
virtual ~Prefixed_uom_ratio();
puom_num & numerator();
const puom_num& numerator() const;
void numerator( const puom_num& value );
puom_den& denominator();
const puom_den& denominator() const;
void denominator( const puom_den& value );
bool operator==( const Prefixed_uom_ratio& rhs ) const;
bool operator!=( const Prefixed_uom_ratio& rhs ) const;
virtual std::string to_string() const override;
private:
puom_num num;
puom_den den;
};
namespace ratio
{
template<typename Uom_numerator, typename Uom_denominator>
using puom = Prefixed_uom_ratio<Uom_numerator, Uom_denominator>;
}
}
}
#pragma region Definitions
template<typename Uom_numerator, typename Uom_denominator>
nhill::uom::Prefixed_uom_ratio<Uom_numerator, Uom_denominator>::Prefixed_uom_ratio()
: num{ Prefix::none, Uom_numerator::none }
, den( Prefix::none, Uom_denominator::none )
{
}
template<typename Uom_numerator, typename Uom_denominator>
nhill::uom::Prefixed_uom_ratio<Uom_numerator, Uom_denominator>::Prefixed_uom_ratio( const puom_num& num, const puom_den& den )
: num( num )
, den( den )
{
}
template<typename Uom_numerator, typename Uom_denominator>
nhill::uom::Prefixed_uom_ratio<Uom_numerator, Uom_denominator>::Prefixed_uom_ratio( Prefix prefix_num, Uom_numerator uom_num, Prefix prefix_den, Uom_denominator uom_den )
: num( prefix_num, uom_num )
, den( prefix_den, uom_den )
{
}
template<typename Uom_numerator, typename Uom_denominator>
nhill::uom::Prefixed_uom_ratio<Uom_numerator, Uom_denominator>::Prefixed_uom_ratio( const Prefixed_uom_ratio& src )
: num( src.num )
, den( src.den )
{
}
template<typename Uom_numerator, typename Uom_denominator>
nhill::uom::Prefixed_uom_ratio<Uom_numerator, Uom_denominator>::Prefixed_uom_ratio( Prefixed_uom_ratio&& src )
: num( src.num )
, den( src.den )
{
}
template<typename Uom_numerator, typename Uom_denominator>
nhill::uom::Prefixed_uom_ratio<Uom_numerator, Uom_denominator>::~Prefixed_uom_ratio()
{
}
template<typename Uom_numerator, typename Uom_denominator>
auto nhill::uom::Prefixed_uom_ratio<Uom_numerator, Uom_denominator>::numerator()->puom_num &
{
return num;
}
template<typename Uom_numerator, typename Uom_denominator>
auto nhill::uom::Prefixed_uom_ratio<Uom_numerator, Uom_denominator>::numerator() const->const puom_num&
{
return num;
}
template<typename Uom_numerator, typename Uom_denominator>
void nhill::uom::Prefixed_uom_ratio<Uom_numerator, Uom_denominator>::numerator( const puom_num& value )
{
num = value;
}
template<typename Uom_numerator, typename Uom_denominator>
auto nhill::uom::Prefixed_uom_ratio<Uom_numerator, Uom_denominator>::denominator()->puom_den&
{
return den;
}
template<typename Uom_numerator, typename Uom_denominator>
auto nhill::uom::Prefixed_uom_ratio<Uom_numerator, Uom_denominator>::denominator() const->const puom_den&
{
return den;
}
template<typename Uom_numerator, typename Uom_denominator>
void nhill::uom::Prefixed_uom_ratio<Uom_numerator, Uom_denominator>::denominator( const puom_den& value )
{
den = value;
}
template<typename Uom_numerator, typename Uom_denominator>
bool nhill::uom::Prefixed_uom_ratio<Uom_numerator, Uom_denominator>::operator==( const Prefixed_uom_ratio& rhs ) const
{
return(numerator() == rhs.numerator()) && (denominator() == rhs.denominator());
}
template<typename Uom_numerator, typename Uom_denominator>
bool nhill::uom::Prefixed_uom_ratio<Uom_numerator, Uom_denominator>::operator!=( const Prefixed_uom_ratio& rhs ) const
{
return(numerator() != rhs.numerator()) || (denominator() != rhs.denominator());
}
template<typename Uom_numerator, typename Uom_denominator>
std::string nhill::uom::Prefixed_uom_ratio<Uom_numerator, Uom_denominator>::to_string() const
{
std::ostringstream oss;
oss << numerator().to_string() << '/' << denominator().to_string();
return oss.str();
}
#pragma endregion
| true |
fc7d566a5f05f32cc2bd343241d29b6f0b595bb7 | C++ | kohn/kohn-zoj-sol | /zoj-1879.cpp | UTF-8 | 703 | 2.921875 | 3 | [] | no_license | #include <iostream>
#include <string.h>
#include <string>
#include <math.h>
#include <vector>
#include <map>
#include <queue>
#include <algorithm>
#include <stdio.h>
using namespace std;
bool fun(int a[3001],int n)
{
bool flag[3002];
for(int i=0;i<n;i++)
flag[i]=false;
for(int i=1;i<n;i++)
{
int t=abs(a[i]-a[i-1]);
if(t>n-1)
return false;
else
{
if(flag[t]==true)
return false;
flag[t]=true;
}
}
return true;
}
int main()
{
int n;
while(cin>>n)
{
int a[3001];
for(int i=0;i<n;i++)
cin>>a[i];
if(fun(a,n))
cout<<"Jolly"<<endl;
else
cout<<"Not jolly"<<endl;
}
return 0;
}
| true |
2bae90fc502a36b800081b59ac164378ca4c7adf | C++ | koalaink/hdoj | /hdoj/1716.cpp | UTF-8 | 1,094 | 2.515625 | 3 | [] | no_license | #include<iostream>
#include<stdio.h>
#include<set>
using namespace std;
int card[6];
bool used[6],flag;
set<int>s;
void dfs(int num,int index){
if(index==4){
s.insert(num);
return ;
}
for(int i=1;i<=4;i++){
if(!used[i]){
used[i]=true;
dfs(num*10+card[i],index+1);
used[i]=false;
}
}
return ;
}
int main(){
int a,b;
bool n_first_t=false,n_first_c=false;
while(scanf("%d%d%d%d",card+1,card+2,card+3,card+4),card[1]||card[2]||card[3]||card[4]){
if(n_first_t) printf("\n");
n_first_t=true;
s.clear();
for(int i=1;i<=4;i++){
used[i]=true;
dfs(card[i],1);
used[i]=false;
}
set<int>::iterator it=s.begin();
while(*it<1000 && it!=s.end() ) it++;
printf("%d",*it);
a=*it/1000;
it++;
for(;it!=s.end();it++){
if(*it/1000!=a){
a=*it/1000;
printf("\n%d",*it);
}else printf(" %d",*it);
}
printf("\n");
}
} | true |
4420efe7922794a05da1f26750cbc4beb950f061 | C++ | avs13/alarma- | /sensor/sensor.ino | UTF-8 | 1,608 | 2.625 | 3 | [] | no_license | #include <SPI.h>
#include <RF24.h>
#include "ultrasonico.h"
#include <EEPROM.h>
#define echo 3
#define triger 2
#define CE_PIN 9
#define CSN_PIN 10
#define PIR 4
byte direccion[5] = {1,1,1,1,1};
RF24 radio(CE_PIN,CSN_PIN);
int datos[2];
float distancia = EEPROM.read(0);
boolean stateAlarm = 0;
int distanciaU = 0;
Ultrasonic ultrasonic;
void setup(){
pinMode(echo,INPUT);
pinMode(triger,OUTPUT);
pinMode(PIR,INPUT);
radio.begin();
radio.openReadingPipe(1, direccion);
radio.startListening();
}
void loop(){
receiveData();
alarma();
}
void alarma(){
if(stateAlarm == HIGH){
distanciaU = ultrasonic.distance();
Serial.println(distancia);
if(distanciaU > distancia){
if(PIR == HIGH){
sendData();
stateAlarm == 0;
}
}
}
}
void sendData(){
radio.stopListening();
radio.openwritingPipe(direccion);
dato[0] == 5;
while(1){
bool ok = radio.write(datos, sizeof(datos));
if(ok){
break;
}
delay(20);
}
}
void receiveData(){
if (radio.available()){
radio.read(datos,sizeof(datos));
switch(datos[0]){
case 0:
stateAlarm == 0;
break;
case 1:
stateAlarm == 1;
autocalibrado();
datos[1] = 0;
break;
case 2:
autocalibrado();
datos[0] == 0;
stateAlarm == 0;
sendData();
break;
case 3:
distancia = datos[1];
break;
}
}
}
void autocalibrado(){
distancia = ultrasonic.distance();
EEPROM.write(0,distancia - 10);
distanciaU = EEPROM.read(0);
}
| true |
fcdaac04ed129a8bd7421ed564d3a8df383d514c | C++ | MohamedLEGH/SimuElections | /media.hh | UTF-8 | 757 | 2.96875 | 3 | [] | no_license | #pragma once
#include <iostream>
#include "electeur.hh"
#include "candidat.hh"
class Candidat;
class Media
{
public:
Media(std::string name, int influence)
:_nom(name),
_influence(influence)
{
}; //
~Media()
{
} // destructeur
std::string get_name() const
{
return _nom;
}
int get_influence() const
{
return _influence;
};
//virtual void infos(Electeur e) = 0; // les electeurs consultent les informations -> DISPARAIT CAR IMPLEMENTE DANS ELECTEUR ET SOUS CLASSES ASSOCIEES
virtual void interview(Candidat c) = 0; // un candidat est interviewé par un média (TV, Radio, Journal)
protected:
std::string _nom; // ne change pas
int _influence; // faible[0 3], moyenne [4 7], forte [8 10], ne change pas
};
| true |
1ed60c73973bec50474c56c92f770cc11ce7a271 | C++ | strymj/sylib_ros | /include/sylib_ros/MoveBaseGoal.h | UTF-8 | 1,498 | 2.640625 | 3 | [] | no_license | /**
* @file MoveBaseGoal.h
* @brief sending ROS move_base library
* @author strymj
* @date 2017.05
*/
#ifndef MOVEBASEGOAL_H_
#define MOVEBASEGOAL_H_
#include <ros/ros.h>
#include <move_base_msgs/MoveBaseAction.h>
#include <move_base_msgs/MoveBaseActionResult.h>
#include <geometry_msgs/Pose2D.h>
#include <tf/transform_listener.h>
/** @brief sylib namespace */
namespace sy
{
/** @brief move_base goal class */
class MoveBaseGoal
{
public:
MoveBaseGoal();
MoveBaseGoal(std::string csv_path);
/** @brief structure for move_base goal. */
struct Goal
{/*{{{*/
std::string goal_id; /**< goal id */
std::string frame_id; /**< frame id */
geometry_msgs::Pose2D pose2d; /**< goal pose */
Goal();
Goal(std::string tag, std::string frame, geometry_msgs::Pose2D& pos);
Goal(std::string tag, std::string frame, double x, double y, double theta);
};/*}}}*/
void loadCsvGoal(std::string csv_path);
void setGoal(std::string tag, std::string frame, geometry_msgs::Pose2D& pos);
void setGoal(std::string tag, std::string frame, double x, double y, double theta);
bool makeNextGoal(move_base_msgs::MoveBaseGoal& move_base_goal);
std::string getGoalID();
double getGoalDistance(tf::StampedTransform& st);
private:
/** @brief goal list. goals are called from this list. */
std::vector<Goal> goal_list;
/** @brief now goal number */
int now_goal_num;
}; // class MoveBaseGoal
} // namespace sy
#endif
| true |
65c6a96d1ccb1d944a0ba7dda80d9431500d8b2e | C++ | PoundKey/Algorithms | /LintCode/388. Permutation Sequence.cpp | UTF-8 | 773 | 3.359375 | 3 | [] | no_license | class Solution {
public:
/**
* @param n: n
* @param k: the k th permutation
* @return: return the k-th permutation
*/
string getPermutation(int n, int k) {
vector<bool> visited(n + 1, false);
string sol;
Permutation(n, k, sol, visited);
return sol;
}
void Permutation(int n, int& k, string& sol, vector<bool>& visited)
{
if (sol.size() == n) --k;
if (k == 0) return;
for (int i = 1; i <= n; i++)
{
if (visited[i]) continue;
sol += to_string(i);
visited[i] = true;
Permutation(n, k, sol, visited);
if (k == 0) break;
sol.pop_back();
visited[i] = false;
}
}
};
| true |
4e4ab613e57ddfde31eb4036eb29090dbc34306a | C++ | vugartaghiyev/e-olymp-cplus | /8532.cpp | UTF-8 | 236 | 2.734375 | 3 | [] | no_license | #include<iostream>
#include<cmath>
using namespace std;
int main(){
long long n,m;
cin>>n>>m;
for(int i=n;i<=m;i++){
cout<<(long long)pow(i,2)<<" ";
}
cout<<endl;
for(;m>=n;m--){
cout<<(unsigned long long)pow(m,3)<<" ";
}
}
| true |
91cf507c92d47511ccff0c0c74db0e7fad098547 | C++ | JayTheCoder-page/PracticeProjects | /RaoListing9p3_Constructor/RaoListing9p3_Constructor.cpp | UTF-8 | 2,981 | 4.0625 | 4 | [] | no_license | /*
* File: main.cpp
* Author: Joshua
*
* Created on June 29, 2020, 1:04 PM
*/
#include <cstdlib>
#include <iostream>
using namespace std;
void Constructor(); //Using Constructors to Initialize Class Member Variables
class Human
{
private:
string name;
int age;
public:
Human() //constructor
{
age = 1;
cout<<"Constructed an instance of class Human"<<endl;
}
void SetName (string humansName)
{
name = humansName;
}
void SetAge(int humansAge)
{
age = humansAge;
}
void IntroduceSelf()
{
cout<<"I am " + name <<" and am ";
cout<<age<<" years old"<<endl;
}
};
void PreviousLessons();
void PassingPointersToFunctions();
void CalculateArea(const float* const,
const float* const,
float* const);
void ArrayVariablePointer();
void AccessElementInArray();
void SaferPointer();
int main(int argc, char** argv) {
Constructor();
//PreviousLessons(); //extra practice
return 0;
}
void Constructor()
{
Human firstWoman;
firstWoman.SetName("Eve");
firstWoman.SetAge(28);
firstWoman.IntroduceSelf();
}
void PreviousLessons()
{
PassingPointersToFunctions();
//ArrayVariablePointer();
//AccessElementInArray();
//SaferPointer();
}
void PassingPointersToFunctions()
{
float Pi = 3.1416;
cout<<"Enter the radius: ";
float radius = 0;
cin>>radius;
float area = 0;
CalculateArea(&Pi, &radius, &area);
cout<<"Area = "<<area<<endl;
}
void CalculateArea(const float* const ptrPi, const float* const ptrR, float* const ptrArea)
{
if(ptrArea && ptrPi && ptrR)
{
*ptrArea = (*ptrR) * (*ptrR) * (*ptrPi);
}
}
void ArrayVariablePointer()
{
int myNum[4];
int* pointsToInt = myNum;
cout<<"pointsToInt = "<<hex<<pointsToInt<<endl;
cout<<"&myNum[0] = "<<hex<<&myNum[0]<<endl;
}
void AccessElementInArray()
{
const int size = 5;
int array[size] = {1, -2, 3, -4, 5};
int* pointsToArray = array;
cout<<"Display array (pointer syntax), operator*"<<endl;
for(int index = 0; index < size; ++index)
{
cout<<"Element "<<index<<" = ";
cout<<*(array + index)<<endl;
}
cout<<"Display array (array syntax), operator[]"<<endl;
for(int index = 0; index < size; ++index)
{
cout<<"Element "<<index<<" = "<<pointsToArray[index];
cout<<" "<<endl;
}
}
void SaferPointer()
{
cout<<"Is it sunny (y/n)"<<endl;
char userInput = 'n';
cin>>userInput;
bool* const isSunny = new bool;
*isSunny = true;
if(userInput == 'n')
{
*isSunny = false;
}
cout<<"Boolean flag isSunny says: "<<*isSunny<<endl;
delete isSunny;
}
| true |
3003533f4fa31e8aea37dd29313bcc9219870d34 | C++ | axshivam/AlgoRithm | /code/Palindromic_String.cpp | UTF-8 | 677 | 2.859375 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main()
{
string str;
getline(cin,str);
int n=str.size();
if(n%2==0)
{
int count=0;
if(n==2)
{
if(str[0]==str[1])
cout<<"YES"<<endl;
else
cout<<"NO"<<endl;
}
else
{
for(int i=0;i<=(n/2);i++)
{
if(str[i]==str[n-i-1])
{
count++;
}
}
if(count==(n/2))
{
cout<<"YES"<<endl;
}
else
{
cout<<"NO"<<endl;
}
}
}
else
{
int count=0;
if(n==1)
{
cout<<"YES"<<endl;
}
else
{
for(int i=0;i<(n/2);i++)
{
if(str[i]==str[n-i-1])
{
count++;
}
}
if(count==(n/2))
{
cout<<"YES"<<endl;
}
else
{
cout<<"NO"<<endl;
}
}
}
}
| true |
be7f87e04e73c47dc4f55873920be14ae8b2c93f | C++ | adiletabs/Algos | /DataStructures/Advanced/BST.cpp | UTF-8 | 4,121 | 3.40625 | 3 | [
"MIT"
] | permissive | #include <bits/stdc++.h>
using namespace std;
template<typename T>
class Node {
public:
Node* left;
Node* right;
T value;
int level;
int height;
int cnt;
int subtree_size;
Node (T x = 0, int _level = 0) {
value = x;
level = _level;
height = 1;
cnt = 0;
subtree_size = 1;
left = nullptr;
right = nullptr;
}
void increaseCounter() { cnt++; }
void updSubtreeSize() {
int size = 1;
if (this->left)
size += this->left->subtree_size;
if (this->right)
size += this->right->subtree_size;
this->subtree_size = size;
}
void updHeight() {
if (this->left)
height = max(height, this->left->height + 1);
if (this->right)
height = max(height, this->right->height + 1);
}
};
template<typename T>
class BST {
public:
Node<T>* root;
int height;
int size;
BST() {
root = nullptr;
height = 0;
size = 0;
}
Node<T>* insert(T x, Node<T>* node, int level = 1) {
if (!node) {
node = new Node<T>(x, level);
size++;
node->increaseCounter();
height = max(height, level);
} else {
if (x < node->value)
node->left = insert(x, node->left, level + 1);
else if (x > node->value)
node->right = insert(x, node->right, level + 1);
}
node->updHeight();
node->updSubtreeSize();
return node;
}
void insert(T value) { root = insert(value, root); }
int getHeight() { return height; }
int getSize() { return size; }
Node<T>* getKth(int k, Node<T>* node) {
int size_left = node->left ? node->left->subtree_size : 0;
if (size_left == k - 1)
return node;
return k <= size_left ? getKth(k, node->left) : getKth(k - size_left - 1, node->right);
}
int getKth(int k) {
Node<T>* node = getKth(k, root);
return node->value;
}
bool isLeaf(T x, Node<T>* node) {
if (node->value == x)
return !node->left && !node->right;
if (x < node->value)
return node->left ? isLeaf(x, node->left) : false;
else if (x > node->value)
return node->right ? isLeaf(x, node->right) : false;
}
bool isLeaf(Node<T>* node) { return isLeaf(node->value, root); }
bool isLeaf(T x) { return isLeaf(x, root); }
bool isBalanced(Node<T>* node) {
if (!node) return true;
int height_left = node->left ? node->left->height : 0;
int height_right = node->right ? node->right->height : 0;
if (abs(height_left - height_right) > 1)
return false;
return isBalanced(node->left) && isBalanced(node->right);
}
bool isBalanced() { return isBalanced(root); }
void printBranches(Node<T>* node) {
if (node->left) printBranches(node->left);
if ((bool)node->left ^ (bool)node->right) cout << node->value << '\n';
if (node->right) printBranches(node->right);
}
void printLeaves(Node<T>* node) {
if (node->left) printLeaves(node->left);
if (!node->left && !node->right) cout << node->value << '\n';
if (node->right) printLeaves(node->right);
}
void printJunctions(Node<T>* node) {
if (node->left) printJunctions(node->left);
if (node->left && node->right) cout << node->value << '\n';
if (node->right) printJunctions(node->right);
}
void inOrder(Node<T>* node) {
if (node->left) inOrder(node->left);
cout << node->value << '\n';
if (node->right) inOrder(node->right);
}
void preOrder(Node<T>* node) {
cout << node->value << '\n';
if (node->left) inOrder(node->left);
if (node->right) inOrder(node->right);
}
void postOrder(Node<T>* node) {
if (node->left) inOrder(node->left);
if (node->right) inOrder(node->right);
cout << node->value << '\n';
}
void print(string mode) {
for (int i = 0; i < (int)mode.size(); i++)
mode[i] = tolower(mode[i]);
if (mode == "branches")
printBranches(root);
else if (mode == "leaves")
printLeaves(root);
else if (mode == "junctions")
printJunctions(root);
else if (mode == "inorder" || mode == "asc")
inOrder(root);
else if (mode == "preorder")
preOrder(root);
else if (mode == "postorder")
postOrder(root);
}
};
int main() {
BST<int> tree;
int T;
while (T--) {
int x;
cin >> x;
tree.insert(x);
}
cout << tree.getSize() << '\n';
tree.print("ASC");
}
| true |
5b5fd649b9c467082f3608bc48182b7b8daf1e3b | C++ | jjzhang166/GameEngine-2 | /game/game/src/Renderer/PPE/GaussianSinglePassBlur.t.h | UTF-8 | 1,336 | 2.546875 | 3 | [] | no_license | #pragma once
#include "GaussianSinglePassBlur.h"
#include "Renderer/GlMacros.h"
template<BlurAxis A>
GaussianAxisBlur<A>::GaussianAxisBlur(unsigned int width, unsigned int height)
: shader(),
fbo(), depthStencilRbo(),
colorBuffer(width, height, true)
{
shader.bind();
shader.u_ScreenSampler.uncheckedSet(0);
shader.u_PixelDensity.uncheckedSet(1.0f / (A == BlurAxis::HORIZONTAL ? width : height));
fbo.bind();
colorBuffer.unbind();
fbo.addAttachment(GL_COLOR_ATTACHMENT0, colorBuffer);
depthStencilRbo.bind();
depthStencilRbo.setStorage(GL_DEPTH24_STENCIL8, width, height);
depthStencilRbo.unbind();
fbo.addRenderbuffer(depthStencilRbo, GL_DEPTH_STENCIL_ATTACHMENT);
fbo.checkStatus();
fbo.unbind();
}
template<BlurAxis T>
void GaussianAxisBlur<T>::start() const
{
fbo.bind();
GlCall(glClearColor(0.1f, 0.1f, 0.1f, 1.0f));
GlCall(glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT));
GlCall(glEnable(GL_DEPTH_TEST));
}
template<BlurAxis T>
void GaussianAxisBlur<T>::stop() const
{
fbo.unbind();
}
template<BlurAxis T>
void GaussianAxisBlur<T>::renderQuad(const VertexArray& quadVao) const
{
GlCall(glClearColor(1.f, 0.f, 1.f, 1.f));
GlCall(glClear(GL_COLOR_BUFFER_BIT));
shader.bind();
quadVao.bind();
GlCall(glDisable(GL_DEPTH_TEST));
colorBuffer.bind(0);
GlCall(glDrawArrays(GL_TRIANGLES, 0, 6));
}
| true |
172409d16625fbb3c59210a6ffc95f4c85d743b1 | C++ | sgumhold/cgv | /cgv/media/illum/obj_material.hh | UTF-8 | 4,404 | 2.578125 | 3 | [] | permissive | #pragma once
#include <cgv/media/illum/phong_material.hh> //@<
#include "lib_begin.h" //@<
namespace cgv { //@<
namespace media { //@<
namespace illum { //@<
///@>extension of a phong material with support for texture mapped color channels
class CGV_API obj_material : public phong_material
{
protected: //@<
///@> name of material
std::string name;
///@> opacity value
float opacity;
///@> file name of ambient texture
std::string ambient_texture_name;
///@> file name of diffuse texture
std::string diffuse_texture_name;
///@> file name of opacity texture
std::string opacity_texture_name;
///@> file name of specular texture
std::string specular_texture_name;
///@> file name of emission texture
std::string emission_texture_name;
///@> scaling factor for bump map
float bump_scale;
///@> file name of bump map texture
std::string bump_texture_name;
public: //@<
///@> different types of textures
enum TextureType {
TT_AMBIENT_TEXTURE = 1,
TT_DIFFUSE_TEXTURE = 2,
TT_OPACITY_TEXTURE = 4,
TT_SPECULAR_TEXTURE = 8,
TT_EMISSION_TEXTURE = 16,
TT_BUMP_TEXTURE = 32,
TT_ALL_TEXTURES = 63
};
/// define default material
obj_material() : name("default"), opacity(1), bump_scale(1) {}
/// set opacity value
void set_opacity(float o) { opacity = o; }
/// return opacity value
float get_opacity() const { return opacity; }
/// return reference to opacity value
float& ref_opacity() { return opacity; }
/// set name value
void set_name(std::string o) { name = o; }
/// return name value
const std::string& get_name() const { return name; }
/// return reference to name value
std::string& ref_name() { return name; }
/// set ambient_texture_name value
virtual void set_ambient_texture_name(std::string o) { ambient_texture_name = o; }
/// return ambient_texture_name value
const std::string& get_ambient_texture_name() const { return ambient_texture_name; }
/// return reference to ambient_texture_name value
std::string& ref_ambient_texture_name() { return ambient_texture_name; }
/// set diffuse_texture_name value
virtual void set_diffuse_texture_name(std::string o) { diffuse_texture_name = o; }
/// return diffuse_texture_name value
const std::string& get_diffuse_texture_name() const { return diffuse_texture_name; }
/// return reference to diffuse_texture_name value
std::string& ref_diffuse_texture_name() { return diffuse_texture_name; }
/// set opacity_texture_name value
virtual void set_opacity_texture_name(std::string o) { opacity_texture_name = o; }
/// return opacity_texture_name value
const std::string& get_opacity_texture_name() const { return opacity_texture_name; }
/// return reference to opacity_texture_name value
std::string& ref_opacity_texture_name() { return opacity_texture_name; }
/// set specular_texture_name value
virtual void set_specular_texture_name(std::string o) { specular_texture_name = o; }
/// return specular_texture_name value
const std::string& get_specular_texture_name() const { return specular_texture_name; }
/// return reference to specular_texture_name value
std::string& ref_specular_texture_name() { return specular_texture_name; }
/// set emission_texture_name value
virtual void set_emission_texture_name(std::string o) { emission_texture_name = o; }
/// return emission_texture_name value
const std::string& get_emission_texture_name() const { return emission_texture_name; }
/// return reference to emission_texture_name value
std::string& ref_emission_texture_name() { return emission_texture_name; }
/// set bump_texture_name value
virtual void set_bump_texture_name(std::string b) { bump_texture_name = b; }
/// return bump_texture_name value
const std::string& get_bump_texture_name() const { return bump_texture_name; }
/// return reference to bump_texture_name value
std::string& ref_bump_texture_name() { return bump_texture_name; }
/// set scale of bumps
void set_bump_scale(float bs) { bump_scale = bs; }
/// return bump scale
float get_bump_scale() const { return bump_scale; }
/// return reference to bump scale
float& ref_bump_scale() { return bump_scale; }
};
}
}
}
#include <cgv/config/lib_end.h> //@< | true |
caa21d0add131db6c938a3c00e5973e306304972 | C++ | aneury1/AHTTPServer2 | /src/DocumentBuilder.h | UTF-8 | 395 | 2.765625 | 3 | [] | no_license | #pragma once
#include <string>
#include <sstream>
#include <vector>
#include <unordered_map>
struct DocumentParameter {
std::unordered_map<std::string, std::string> values;
std::string toString() {
std::stringstream stream;
for (auto iter : values) {
stream << iter.first;
if (iter.second.size() > 0)
stream << "= \"" << iter.second << "\"";
}
return stream.str();
}
}; | true |
99e92270e75d0d7f6847a9f7ee3de06a5868ca4f | C++ | AishikBarua/3rd-year-2nd-semester | /Operating System Lab/online 7(disk algo-fcfs+sstf+cscan)/cscan.cpp | UTF-8 | 1,041 | 2.578125 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int main()
{
int heads,totalCylinderMoves=0,headPos;
cout<<"Enter number of heads:"<<endl;
cin>>heads;
cout<<"Enter initial position of head:"<<endl;
cin>>headPos;
int cylinderReq[]= {98, 183, 37, 122, 14, 124, 65, 67};
int n=8;
sort(cylinderReq,cylinderReq+n);
bool ar[heads];
for(int i=0; i<heads; i++)
ar[i]=false;
for(int i=0; i<n; i++)
{
ar[cylinderReq[i]]=true;
}
int cnt=0;
int prevpos=headPos;
while(cnt!=n)
{
for(int i=prevpos; i<heads; i++,totalCylinderMoves++)
{
if(ar[i])
{
cout<<"currently serving:"<<i<<endl;
ar[i]=false;
cnt++;
if(cnt==n)
break;
}
if(i==heads-1)
{
i=0;
totalCylinderMoves+=heads;
}
}
}
cout<<"\nTotal cylinder moves:"<<totalCylinderMoves<<endl;
return 0;
}
| true |
473fd36405f8e39146ecb457f4346cffddbaffff | C++ | AnibalSiguenza/effectiveModernCppNotes | /item27.cpp | UTF-8 | 1,654 | 3.671875 | 4 | [] | no_license | // this item talks about the solution for the problem presented in item26 which
// is the inability to averload a universal reference function
#include <bits/stdc++.h>
// one alternative is to use tag dispath /////////////////////////////////////
template <class T> void uniRefFuncImpl(T &&x, std::false_type) {
std::cout << "everything else implementation" << std::endl;
}
template <class T> void uniRefFuncImpl(T &&x, std::true_type) {
std::cout << "int implementation" << std::endl;
}
template <class T> void uniRefFunc(T &&x) {
uniRefFuncImpl(std::forward<T>(x),
std::is_integral<std::remove_reference_t<T>>());
}
/////////////////////////////////////////////////////////////////////////////
// for class costructures this one can constrain the templates ignore the
// template for element of the class and subclasses ///
class Foo {
private:
std::string name;
public:
// note: this is one of the ugliest codes your eyes will see hahaha
template <typename T, typename = std::enable_if_t<
!std::is_base_of<Foo, std::decay_t<T>>::value &&
!std::is_integral<std::remove_reference_t<T>>()>>
explicit Foo(T &&name) : name(std::forward<T>(name)) {
std::cout << "universal reference constructor" << std::endl;
};
explicit Foo(int) { std::cout << "int constructor" << std::endl; };
};
int main(int argc, char *argv[]) {
uniRefFunc("asd");
uniRefFunc(2.3123);
uniRefFunc(2);
Foo obj1("Hola");
Foo obj2(13);
auto obj3(obj1); // now the copy works without trouble since it is not
// replacing any copy constructor
return 0;
} | true |
9ac0a0010fef54f121e6ab42070eae6ba058bd2a | C++ | quocdoan419/Server | /testpoint/Mojing3DHelper.h | UTF-8 | 742 | 2.84375 | 3 | [] | no_license | #include <math.h>
#include "vec.h"
typedef android::vec3_t Point3f;
typedef android::vec2_t Point2f;
typedef android::vec3_t Vector3f;
class Plane
{
private:
float a;
float b;
float c;
float d;
float m_width;
float m_height;
Point3f m_topLeft;
Point3f m_topRight;
Point3f m_bottomLeft;
Vector3f m_xAxis;
Vector3f m_yAxis;
public:
Plane(Point3f topLeft, Point3f topRight, Point3f bottomLeft);
float Distance(Point3f pt);
bool Intersection(Vector3f light, Point2f &position);
bool IntersectTriangle(const Vector3f orig, const Vector3f dir,
Vector3f v0, Vector3f v1, Vector3f v2,
float* t, float* u, float* v);
};
| true |
2ea2dc075cd98c0e6c828e4be2ecc2f261fe6645 | C++ | jhomble/redis | /lib_acl_cpp/samples/db/mysql_query/main.cpp | GB18030 | 5,668 | 2.765625 | 3 | [] | no_license | // mysql.cpp : ̨Ӧóڵ㡣
//
#include "acl_cpp/lib_acl.hpp"
const char* CREATE_TBL =
"create table group_tbl\r\n"
"(\r\n"
"group_name varchar(128) not null,\r\n"
"uvip_tbl varchar(32) not null default 'uvip_tbl',\r\n"
"access_tbl varchar(32) not null default 'access_tbl',\r\n"
"access_week_tbl varchar(32) not null default 'access_week_tbl',\r\n"
"access_month_tbl varchar(32) not null default 'access_month_tbl',\r\n"
"update_date date not null default '1970-1-1',\r\n"
"disable integer not null default 0,\r\n"
"add_by_hand integer not null default 0,\r\n"
"class_level integer not null default 0,\r\n"
"primary key(group_name, class_level)\r\n"
")";
static bool tbl_create(acl::db_handle& db)
{
if (db.tbl_exists("group_tbl"))
{
printf("table exist\r\n");
return (true);
}
else if (db.sql_update(CREATE_TBL) == false)
{
printf("sql error\r\n");
return (false);
}
else
{
printf("create table ok\r\n");
return (true);
}
}
// ӱ
static bool tbl_insert(acl::db_handle& db, int n)
{
const char* sql_fmt = "insert into group_tbl(group_name, uvip_tbl,"
" update_date) values(:group, :test, :date)";
acl::query query;
query.create_sql(sql_fmt)
.set_format("group", "group:%d", n)
.set_parameter("test", "test")
.set_date("date", time(NULL), "%Y-%m-%d");
if (db.exec_update(query) == false)
return (false);
const acl::db_rows* result = db.get_result();
if (result)
{
const std::vector<acl::db_row*>& rows = result->get_rows();
for (size_t i = 0; i < rows.size(); i++)
{
const acl::db_row* row = rows[i];
for (size_t j = 0; j < row->length(); j++)
printf("%s, ", (*row)[j]);
printf("\r\n");
}
}
db.free_result();
return (true);
}
// ѯ
static int tbl_select(acl::db_handle& db, int n)
{
const char* sql_fmt = "select * from group_tbl where"
" group_name=:group and uvip_tbl=:test";
acl::query query;
query.create_sql(sql_fmt)
.set_format("group", "group:%d", n)
.set_format("test", "test");
if (db.exec_select(query) == false)
{
printf("select sql error\r\n");
return (-1);
}
printf("\r\n---------------------------------------------------\r\n");
// гѯһ
const acl::db_rows* result = db.get_result();
if (result)
{
const std::vector<acl::db_row*>& rows = result->get_rows();
for (size_t i = 0; i < rows.size(); i++)
{
if (n > 100)
continue;
const acl::db_row* row = rows[i];
for (size_t j = 0; j < row->length(); j++)
printf("%s, ", (*row)[j]);
printf("\r\n");
}
}
// гѯ
for (size_t i = 0; i < db.length(); i++)
{
if (n > 100)
continue;
const acl::db_row* row = db[i];
// ȡм¼ijֶεֵ
const char* ptr = (*row)["group_name"];
if (ptr == NULL)
{
printf("error, no group name\r\n");
continue;
}
printf("group_name=%s: ", ptr);
for (size_t j = 0; j < row->length(); j++)
printf("%s, ", (*row)[j]);
printf("\r\n");
}
// гѯ
const std::vector<acl::db_row*>* rows = db.get_rows();
if (rows)
{
std::vector<acl::db_row*>::const_iterator cit = rows->begin();
for (; cit != rows->end(); cit++)
{
if (n > 100)
continue;
const acl::db_row* row = *cit;
for (size_t j = 0; j < row->length(); j++)
printf("%s, ", (*row)[j]);
printf("\r\n");
}
}
int ret = (int) db.length();
// ͷŲѯ
db.free_result();
return (ret);
}
// ɾ
static bool tbl_delete(acl::db_handle& db, int n)
{
const char* sql_fmt = "delete from group_tbl where group_name=:group";
acl::query query;
query.create_sql(sql_fmt).set_format("group", "group-%d", n);
if (db.exec_update(query) == false)
{
printf("delete sql error\r\n");
return (false);
}
for (size_t i = 0; i < db.length(); i++)
{
const acl::db_row* row = db[i];
for (size_t j = 0; j < row->length(); j++)
printf("%s, ", (*row)[j]);
printf("\r\n");
}
// ͷŲѯ
db.free_result();
return (true);
}
int main(void)
{
const char* dbaddr = "127.0.0.1:3306";
const char* dbname = "acl_test_db";
const char* dbuser = "root", *dbpass = "111111";
acl::db_mysql db(dbaddr, dbname, dbuser, dbpass);
int max = 100;
// ־Ļ
acl::log::stdout_open(true);
// ȴݿ
if (db.open() == false)
{
printf("open db(%s) error\r\n", dbname);
getchar();
return 1;
}
printf("open db %s ok\r\n", dbname);
// ݱʱ
if (tbl_create(db) == false)
{
printf("create table error\r\n");
getchar();
return 1;
}
//
for (int i = 0; i < max; i++)
{
bool ret = tbl_insert(db, i);
if (ret)
printf(">>insert ok: i=%d, affected: %d\r",
i, db.affect_count());
else
printf(">>insert error: i = %d\r\n", i);
}
printf("\r\n");
int n = 0;
// ѯ
for (int i = 0; i < max; i++)
{
int ret = tbl_select(db, i);
if (ret >= 0)
{
n += ret;
printf(">>select ok: i=%d, ret=%d\r", i, ret);
}
else
printf(">>select error: i = %d\r\n", i);
}
printf("\r\n");
printf(">>select total: %d\r\n", n);
// ɾ
for (int i = 0; i < max; i++)
{
bool ret = tbl_delete(db, i);
if (ret)
printf(">>delete ok: %d, affected: %d\r",
i, (int) db.affect_count());
else
printf(">>delete error: i = %d\r\n", i);
}
printf("\r\n");
#ifndef WIN32
// mysql_server_end();
// mysql_thread_end();
#endif
printf("mysqlclient lib's version: %ld, info: %s\r\n",
db.mysql_libversion(), db.mysql_client_info());
printf("Enter any key to exit.\r\n");
getchar();
return 0;
}
| true |
3d65e0cd2234e5daff257194c8fe1e5a12f83b15 | C++ | GUET-ACM-FRESHMEN-TRAINING/10.13-18-TASK | /李明智/05分数线划定.cpp | UTF-8 | 671 | 2.796875 | 3 | [] | no_license | #include <cstdio>
#include<algorithm>
using namespace std;
struct People{
int hs;
int cj;
}people[5000];
int cmp(const People &a,const People &b)
{
if(a.cj!=b.cj)
return a.cj>b.cj;
else
return a.hs<b.hs;
}
int main()
{
int n,m,i,a,lqx,sjrs=0;
scanf("%d %d",&n,&m);
for(i=0;i<n;i++)
{
scanf("%d %d",&people[i].hs,&people[i].cj);
}
sort(people,people+n,cmp);
a=m*1.5;
lqx=people[a-1].cj;
for(i=0;people[i].cj>=lqx;i++)
sjrs++;
printf("%d %d\n",lqx,sjrs);
for(i=0;i<sjrs;i++)
printf("%d %d\n",people[i].hs,people[i].cj);
return 0;
} | true |
d7da56f65b54becf87f0d1c953a3c41397899f99 | C++ | szkutek/uni | /sem2/cpp2017/prac10/units.h | UTF-8 | 2,999 | 3.46875 | 3 | [] | no_license |
#ifndef UNITS_INCLUDED
#define UNITS_INCLUDED 1
#include <iostream>
// I would have preferred to use 'Coulomb' instead of
// 'Ampere', but 'Coulomb' is not a basic SI-unit.
// Mass/Length/Time/Current.
// kg/m/sec/ampere.
template<int M, int L, int T = 0, int I = 0>
struct si {
double val;
explicit si(double val)
: val{val} {
}
};
// Specialization for <0,0,0,0> has implicit conversion to double:
// This solves the problem of 1.0_kg / 2.0_kg + 2.0, which otherwise
// will not compile:
template<>
struct si<0, 0, 0, 0> {
double val;
// Constructor can be implicit:
si(double val)
: val{val} {}
// Conversion operator to double:
operator double() const { return val; }
};
std::string units(int Q, std::string unit) {
switch (Q) {
case 0:
break;
case 1:
return unit;
default:
return unit + "^{" + std::to_string(Q) + "}";
}
return "";
}
template<int M, int L, int T, int I>
std::ostream &operator<<(std::ostream &out, si<M, L, T, I> quant) {
// If you want, you can catch special cases, like Newton/Watt.
out << quant.val;
out << units(M, "kg");
out << units(L, "m");
out << units(T, "s");
out << units(I, "A");
return out;
}
// Physical Quantities:
namespace quantity {
using length = si<0, 1, 0, 0>;
using speed = si<0, 1, -1, 0>;
using mass = si<1, 0, 0, 0>;
using time = si<0, 0, 1, 0>;
using force = si<1, 1, -2, 0>;
using charge = si<0, 0, 1, 1>;
using current = si<0, 0, 0, 1>;
using voltage = si<1, 2, -3, -1>;
using energy = si<1, 2, -2, 0>;
using power = si<1, 2, -3, 0>;
}
// Some common units, feel free to add more.
inline quantity::mass operator "" _kg(long double x) {
return quantity::mass(x);
}
inline quantity::length operator "" _m(long double x) {
return quantity::length(x);
}
inline quantity::time operator "" _sec(long double x) {
return quantity::time(x);
}
inline quantity::energy operator "" _joule(long double x) {
return quantity::energy(x);
}
inline quantity::power operator "" _watt(long double x) {
return quantity::power(x);
}
inline quantity::force operator "" _newton(long double x) {
return quantity::force(x);
}
inline quantity::time operator "" _min(long double x) {
return quantity::time(60.0 * x);
}
inline quantity::time operator "" _hr(long double x) {
return quantity::time(3600.0 * x);
}
inline quantity::voltage operator "" _V(long double x) {
return quantity::voltage(x);
}
inline quantity::current operator "" _A(long double x) {
return quantity::current(x);
}
inline quantity::speed operator "" _mps(long double v) {
return quantity::speed(v);
}
inline quantity::speed operator "" _kmh(long double v) {
return quantity::speed(v / 3.6);
}
inline quantity::speed operator "" _knot(long double v) {
return quantity::speed(v * 0.51444444444444444444444);
}
#endif
| true |
3f43da439b667400a1a90436fd91ad171e4b5106 | C++ | alexfp95/Advanced-Algorithms-and-Data-Structures | /Templates and Exceptions/real.cpp | UTF-8 | 1,303 | 3.53125 | 4 | [] | no_license | #include "real.h"
Real::Real (float x)
{
numero_ = x;
}
Real::~Real (void){}
float Real::get_numero (void) const
{
return numero_;
}
void Real::set_numero (float dato)
{
numero_ = dato;
}
Real operator+(const Real& n1, const Real& n2)
{
return Real (n1.numero_ + n2.numero_);
}
Real operator-(const Real& n1, const Real& n2)
{
return Real (n1.numero_ - n2.numero_);
}
Real operator*(const Real& n1, const Real& n2)
{
return Real (n1.numero_ * n2.numero_);
}
Real operator/(const Real& n1, const Real& n2)
{
try
{
if(n2.numero_ == 0)
throw 0;
}
catch (int e)
{
cout << "Excepcion: Division por 0" << endl;
throw;
}
return Real (n1.numero_ / n2.numero_);
}
bool operator==(const Real& n1, const Real& n2)
{
return (n1.numero_ == n2.numero_);
}
bool operator<(const Real& n1, const Real& n2)
{
return (n1.numero_ < n2.numero_);
}
bool operator>(const Real& n1, const Real& n2)
{
return (n1.numero_ > n2.numero_);
}
ostream& operator<<(ostream& os, const Real& n1)
{
os << n1.numero_;
return os;
}
istream& operator>>(istream& is, Real& n1)
{
is >> n1.numero_;
return is;
}
ostream& Real::toStream (ostream& sout) const
{
sout << numero_;
return sout;
}
istream& Real::fromStream (istream& sin)
{
sin >> numero_;
return sin;
} | true |
8557b7404e7cff6d3bb18234b70f1bffccabfb89 | C++ | CyberTaoFlow/telepath | /engine/Action.h | UTF-8 | 1,783 | 3.125 | 3 | [] | no_license | #define MAX_VALUE 512
using namespace std;
// Get a vector of numbers and put them in a string sperate by commas.
void unicodeParser(vector <unsigned int> & shortVec,string & str){
size_t sizeV = shortVec.size();
size_t length = 0;
unsigned int len;
size_t i;
if(sizeV > MAX_VALUE){
sizeV = MAX_VALUE;
}
char buffer[sizeV * 12+1];
char * tmp = buffer;
for( i=0 ; i<sizeV ;i++){
if(i != sizeV-1 ){
len = itoa(shortVec[i],tmp);
tmp[len++] =',';
tmp[len] ='\0';
}else{
len = itoa(shortVec[i],tmp);
}
length+=len;
tmp+=len;
}
buffer[length]='\0';
str = buffer;
}
class ActionPages{
public:
unsigned int pageID;
boost::unordered_map <unsigned int,string> params;
ActionPages(){}
void clean(){
this->pageID=0;
this->params.clear();
}
};
class Action{
public:
unsigned int action_id;
string action_name;
string domain;
bool logout;
vector <ActionPages> pages;
Action(){}
void clean(){
this->action_id=0;
this->action_name.clear();
this->pages.clear();
}
};
class ActionParams{
public:
unsigned int numOfPages;
unsigned int action_id;
string action_name;
bool logout;
boost::unordered_map <unsigned int,string> params;
ActionParams(boost::unordered_map <unsigned int,string> & params,int unsigned action_id,string & action_name,int unsigned numOfPages,bool logout){
this->params = params;
this->action_id = action_id;
this->action_name = action_name;
this->numOfPages = numOfPages;
this->logout = logout;
}
};
class ActionState{
public:
unsigned int Sid;
unsigned int action_id;
string action_name;
ActionState(){}
ActionState(unsigned int Sid,unsigned int action_id,string & action_name){
this->Sid = Sid;
this->action_id = action_id;
this->action_name = action_name;
}
};
| true |
1f8390b0c4f2909074e81cffe38290831402e6ac | C++ | haoofXu/Cpp_EasyX_exploreMaze | /exploreMaze/main/main/Maze.cpp | GB18030 | 12,556 | 2.625 | 3 | [] | no_license |
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <graphics.h>
#include <conio.h>
using namespace std;
int* readMaze(char maze[100][100]) {
ifstream in("e:\\maze.txt");
if (!in) {
cout << "ܴļ" << endl;
return 0;
}
int raw = 0;
int column = 0;
int flag = 0;
int length = 0;
char a;
a = in.get();
bool find = false;
while (a != EOF) {
if (a == '\n' || a == '\r') {
if (!find) {
length = raw;
find = true;
}
raw = 0;
column++;
//cout << '1';
}
else if (a == '$') {
maze[raw][column] = a;
raw++;
//cout << '2';
}
else if (a == '+') {
maze[raw][column] = a;
raw++;
//cout << '3';
}
else {
maze[raw][column] = a;
raw++;
//cout << '4';
}
//cout << a;
a = in.get();
}
int* size = new int[2];
size[0] = length;
size[1] = column;
return size;
}
int GetDirection()
{
int ret = 6;
do
{
int ch = _getch();
cout << ch;
if (isascii(ch))
continue;
ch = _getch();
cout << ch;
switch (ch)
{
case 81:
ret = -1;
break;
case 72:
ret = 0; // top
break;
case 75:
ret = 2; // left
break;
case 77:
ret = 3; // right
break;
case 80:
ret = 1; // down
break;
case 82:
ret = 4; //Ins
break;
case 73:
/*cout << "B";*/
ret = 5; //PU
break;
default:
break;
}
} while (ret == 6);
return ret;
}
int main()
{
IMAGE img, playerp,end;
loadimage(&img, L"enemy.jpg", 20, 20, true);//ȰͼƬڹĿ£ʹL+"·"
loadimage(&playerp, L"player.jpg", 20, 20, true);//ȰͼƬڹĿ£ʹL+"·"
loadimage(&end, L"end.jpg", 20, 20, true);//ȰͼƬڹĿ£ʹL+"·"
//while (true)
//{
// GetDirection();
//}
char maze[100][100] = { '0' };
int mazeInt[100][100] = { 0 };
int* col = readMaze(maze);
initgraph(col[0]*20, col[1]*20);
setbkcolor(BLACK);
cleardevice();
int player[2] = { 0 };
int enemy[2] = { 0 };
int exit[2] = { 0 };
setcolor(BLACK);
setfillcolor(0x5454);
for (int i = 0; i < col[1]; i++) {
for (int j = 0; j < 100; j++) {
if (maze[j][i] == '#') {
fillrectangle(j * 20, i * 20, (j + 1) * 20, (i + 1) * 20);
}
else if (maze[j][i] == '~') {
setfillcolor(WHITE);
fillrectangle(j * 20, i * 20, (j + 1) * 20, (i + 1) * 20);
setfillcolor(0x5454);
}
else if (maze[j][i] == '+') {
player[0] = j;
player[1] = i;
int x = j * 20;
int y = i * 20;
mazeInt[j][i] = 1;
putimage(x, y, &playerp);//ʾͼƬ
/*setfillcolor(GREEN);
fillrectangle(j * 20, i * 20, (j + 1) * 20, (i + 1) * 20);
setfillcolor(0x5454);*/
}
else if (maze[j][i] == 'E') {
enemy[0] = j;
enemy[1] = i;
int x = j * 20;
int y = i * 20 ;
putimage(x, y, &img);
/*setfillcolor(YELLOW);
fillrectangle(j * 20, i * 20, (j + 1) * 20, (i + 1) * 20);
setfillcolor(0x5454);*/
}
else if (maze[j][i] == '$') {
exit[0] = j;
exit[1] = i;
int x = j * 20;
int y = i * 20;
putimage(x, y, &end);
/*setfillcolor(RED);
fillrectangle(j * 20, i * 20, (j + 1) * 20, (i + 1) * 20);
setfillcolor(0x5454);*/
}
}
}
while (true)
{
bool cantGo = false;
int dir = GetDirection();
if (dir == -1) { break; }
if (dir == 0) {
if (player[1] >= 1) {
if (maze[player[0]][player[1] - 1] != '#') {
maze[player[0]][player[1] - 1] = '+';
maze[player[0]][player[1]] = '~';
player[1] --;
mazeInt[player[0]][player[1]] = 1;
}
}
}
else if (dir == 1) {
if (player[1] < col[1]) {
if (maze[player[0]][player[1] + 1] != '#' ) {
maze[player[0]][player[1] + 1] = '+';
maze[player[0]][player[1]] = '~';
player[1] ++;
mazeInt[player[0]][player[1]] = 1;
}
}
}
else if (dir == 2) {
if (player[0] >= 1) {
if (maze[player[0] - 1][player[1]] != '#') {
maze[player[0] - 1][player[1]] = '+';
maze[player[0]][player[1]] = '~';
player[0] --;
mazeInt[player[0]][player[1]] = 1;
}
}
}
else if (dir == 3) {
if (player[0] < col[0]) {
if (maze[player[0]+1][player[1]] != '#') {
maze[player[0]+1][player[1]] = '+';
maze[player[0]][player[1]] = '~';
player[0] ++;
mazeInt[player[0]][player[1]] = 1;
}
}
}
else if (dir == 4) {
while (true)
{
int dir = (int)rand() % 4;
int dir2 = (int)rand() % 4;
int x = player[0];
int y = player[1];
if (dir == 0) {
if (player[1] >= 1) {
if (maze[player[0]][player[1] - 1] != '#'
&& mazeInt[player[0]][player[1] - 1] == 0) {
maze[player[0]][player[1] - 1] = '+';
maze[player[0]][player[1]] = '~';
player[1] --;
}
else {
if (player[0] == x && player[1] == y && maze[player[0]][player[1] - 1] != '#') {
cantGo = true;
}
if (cantGo) {
if (maze[player[0]][player[1] - 1] != '#') {
maze[player[0]][player[1] - 1] = '+';
maze[player[0]][player[1]] = '~';
player[1] --;
}
}
}
}
else {
continue;
}
}
else if (dir == 1) {
if (player[1] < col[1]) {
if (maze[player[0]][player[1] + 1] != '#'
&& mazeInt[player[0]][player[1] + 1] == 0 ) {
maze[player[0]][player[1] + 1] = '+';
maze[player[0]][player[1]] = '~';
player[1] ++;
}
else {
if (player[0] == x && player[1] == y && maze[player[0]][player[1] + 1] != '#') {
cantGo = true;
}
if (cantGo && maze[player[0]][player[1] + 1] != '#') {
maze[player[0]][player[1] + 1] = '+';
maze[player[0]][player[1]] = '~';
player[1] ++;
}
}
}
else {
continue;
}
}
else if (dir == 2) {
if (player[0] >= 1) {
if (maze[player[0] - 1][player[1]] != '#'
&& mazeInt[player[0] - 1][player[1]] == 0) {
maze[player[0] - 1][player[1]] = '+';
maze[player[0]][player[1]] = '~';
player[0] --;
}
else {
if (player[0] == x && player[1] == y && maze[player[0] - 1][player[1]] != '#') {
cantGo = true;
}
if (cantGo && maze[player[0] - 1][player[1]] != '#') {
maze[player[0] - 1][player[1]] = '+';
maze[player[0]][player[1]] = '~';
player[0] --;
}
}
}
else {
continue;
}
}
else if (dir == 3) {
if (player[0] < col[0]) {
if (maze[player[0] + 1][player[1]] != '#'
&& mazeInt[player[0] + 1][player[1]] == 0) {
maze[player[0] + 1][player[1]] = '+';
maze[player[0]][player[1]] = '~';
player[0] ++;
}
else {
if (player[0] == x && player[1] == y && maze[player[0] +1][player[1]] != '#') {
cantGo = true;
}
if (cantGo && maze[player[0] + 1][player[1]] != '#') {
maze[player[0] + 1][player[1]] = '+';
maze[player[0]][player[1]] = '~';
player[0] ++;
}
}
}
else {
continue;
}
}
mazeInt[player[0]][player[1]] = 1;
if (dir2 == 0) {
if (enemy[1] >= 1) {
if (maze[enemy[0]][enemy[1] - 1] != '#') {
maze[enemy[0]][enemy[1] - 1] = 'E';
maze[enemy[0]][enemy[1]] = '~';
enemy[1] --;
}
else {
continue;
}
}
else {
continue;
}
}
else if (dir2 == 1) {
if (enemy[1] < col[1]) {
if (maze[enemy[0]][enemy[1] + 1] != '#') {
maze[enemy[0]][enemy[1] + 1] = 'E';
maze[enemy[0]][enemy[1]] = '~';
enemy[1] ++;
}
else {
continue;
}
}
else {
continue;
}
}
else if (dir2 == 2) {
if (enemy[0] >= 1) {
if (maze[enemy[0] - 1][enemy[1]] != '#') {
maze[enemy[0] - 1][enemy[1]] = 'E';
maze[enemy[0]][enemy[1]] = '~';
enemy[0] --;
}
else {
continue;
}
}
else {
continue;
}
}
else if (dir2 == 3) {
if (enemy[0] < col[0]) {
if (maze[enemy[0] + 1][enemy[1]] != '#') {
maze[enemy[0] + 1][enemy[1]] = 'E';
maze[enemy[0]][enemy[1]] = '~';
enemy[0] ++;
}
else {
continue;
}
}
else {
continue;
}
}
cleardevice();
setcolor(BLACK);
setfillcolor(0x5454);
for (int i = 0; i < col[1]; i++) {
for (int j = 0; j < 100; j++) {
if (maze[j][i] == '#') {
fillrectangle(j * 20, i * 20, (j + 1) * 20, (i + 1) * 20);
}
else if (maze[j][i] == '~') {
setfillcolor(WHITE);
fillrectangle(j * 20, i * 20, (j + 1) * 20, (i + 1) * 20);
setfillcolor(0x5454);
}
else if (maze[j][i] == '+') {
player[0] = j;
player[1] = i;
int x = j * 20;
int y = i * 20;
putimage(x, y, &playerp);//ʾͼƬ
/*
setfillcolor(GREEN);
fillrectangle(j * 20, i * 20, (j + 1) * 20, (i + 1) * 20);
setfillcolor(0x5454);*/
}
else if (maze[j][i] == 'E') {
enemy[0] = j;
enemy[1] = i;
int x = j * 20;
int y = i * 20;
putimage(x, y, &img);
/*setfillcolor(YELLOW);
fillrectangle(j * 20, i * 20, (j + 1) * 20, (i + 1) * 20);
setfillcolor(0x5454);*/
}
else if (maze[j][i] == '$') {
exit[0] = j;
exit[1] = i;
int x = j * 20;
int y = i * 20;
putimage(x, y, &end);
/*
setfillcolor(RED);
fillrectangle(j * 20, i * 20, (j + 1) * 20, (i + 1) * 20);
setfillcolor(0x5454);*/
}
}
}
Sleep(500);
}
}
else if(dir==5)
{
for (int i = 0; i < 100; i++) {
for (int j = 0; j < 100; j++) {
if (maze[j][i] == '+') {
if (mazeInt[j - 1][i] == 1) {
maze[player[0] - 1][player[1]] = '+';
maze[player[0]][player[1]] = '~';
player[0] --;
}
else if (mazeInt[j + 1][i] == 1) {
maze[player[0] + 1][player[1]] = '+';
maze[player[0]][player[1]] = '~';
player[0] ++;
}
else if (mazeInt[j][i - 1] == 1) {
maze[player[0]][player[1] - 1] = '+';
maze[player[0]][player[1]] = '~';
player[1] --;
}
else if (mazeInt[j][i + 1] == 1) {
maze[player[0]][player[1] + 1] = '+';
maze[player[0]][player[1]] = '~';
player[1] ++;
}
mazeInt[j][i] = 0;
}
}
}
}
cleardevice();
setcolor(BLACK);
setfillcolor(0x5454);
for (int i = 0; i < col[1]; i++) {
for (int j = 0; j < 100; j++) {
if (maze[j][i] == '#') {
fillrectangle(j * 20, i * 20, (j + 1) * 20, (i + 1) * 20);
}
else if (maze[j][i] == '~') {
setfillcolor(WHITE);
fillrectangle(j * 20, i * 20, (j + 1) * 20, (i + 1) * 20);
setfillcolor(0x5454);
}
else if (maze[j][i] == '+') {
player[0] = j;
player[1] = i;
int x = j * 20;
int y = i * 20;
putimage(x, y, &playerp);//ʾͼƬ
/*setfillcolor(GREEN);
fillrectangle(j * 20, i * 20, (j + 1) * 20, (i + 1) * 20);
setfillcolor(0x5454);*/
}
else if (maze[j][i] == 'E') {
enemy[0] = j;
enemy[1] = i;
int x = j * 20;
int y = i * 20;
putimage(x, y, &img);//ʾͼƬ
/*setfillcolor(YELLOW);
fillrectangle(j * 20, i * 20, (j + 1) * 20, (i + 1) * 20);
setfillcolor(0x5454);*/
}
else if (maze[j][i] == '$') {
exit[0] = j;
exit[1] = i;
int x = j * 20;
int y = i * 20;
putimage(x, y, &end);
/* setfillcolor(RED);
fillrectangle(j * 20, i * 20, (j + 1) * 20, (i + 1) * 20);
setfillcolor(0x5454);*/
}
}
}
if (player[0] == exit[0] && player[1] == exit[1]) {
for (int i = 0; i < col[1]; i++) {
for (int j = 0; j < 100; j++) {
if (mazeInt[j][i] == 1) {
setfillcolor(YELLOW);
fillrectangle(j * 20, i * 20, (j + 1) * 20, (i + 1) * 20);
setfillcolor(0x5454);
}
}
}
}
}
_getch();
closegraph();
} | true |
fdce5b75121c5681bc54fff503e991709f2b5bf2 | C++ | brokenlanceorg/owlsong | /code/cc/Matc/Domain.hpp | UTF-8 | 2,053 | 2.75 | 3 | [] | no_license | //**************************************************************************
// File : Domain.hpp
// Purpose : Declares the DomaiN class
//**************************************************************************
#ifndef __DOMAIN_HPP
#define __DOMAIN_HPP
#include"Mathmatc.hpp"
//**************************************************************************
// Class : DomaiN
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Purpose : Declares the DomaiN class, which encapsulates domain
// : information pertinent to mathematical operations.
//**************************************************************************
class DomaiN
{
protected:
MatriX* mTheDomains; // the matrix to store our domain info
long double ldLengthX; // contains the length in the x direction
long double ldLengthY; // contains the length in the y direction
long double ldMidPointX;// holds the midpoint for the x direction
long double ldMidPointY;// holds the midpoint for the y direction
void Setup();
int iNum_Axes; // a quick reference to number of variables
void CalcInterval();
public:
DomaiN();
~DomaiN();
DomaiN(int);
DomaiN(long double, long double);
DomaiN(long double, long double, long double, long double);
inline long double GetLengthX() {return ldLengthX;}
inline long double GetLengthY() {return ldLengthY;}
inline long double GetMidPointX() {return ldMidPointX;}
inline long double GetMidPointY() {return ldMidPointY;}
inline long double GetFirstX() {return mTheDomains->pCol[0][0];}
inline long double GetFirstY() {return mTheDomains->pCol[1][0];}
inline long double GetLastX() {return mTheDomains->pCol[0][1];}
inline long double GetLastY() {return mTheDomains->pCol[1][1];}
void SetXInterval(long double, long double);
void SetYInterval(long double, long double);
void SetSpecificInterval(int, long double, long double);
}; // end Domain declaration
#endif
| true |
ffd198d651e53893577c2f2df68b5d55aadb67ef | C++ | Alex-zs/c-plus | /ClassExperiment/12/Array.h | UTF-8 | 1,833 | 3.390625 | 3 | [] | no_license | #ifndef Array_h
#define Array_h
#include<cassert>
template<class T>
class Array{
private:
T * list;
int size;
public:
Array(int sz=50);
Array(const Array<T> &a);
~Array();
Array<T>& operator = (const Array<T> &rhs);
T & operator [] (int i);
const T & operator [] (int i) const;
operator T * ();
operator const T*() const;
int getSize() const;
void resize(int sz);
};
template<class T>
Array<T>::Array(int sz){
assert(sz >=0);
size = sz;
list = new T [size];
}
template<class T>
Array<T>::~Array(){
delete []list;
}
template<class T>
Array<T>::Array(const Array<T>&a) {
size = a.size;
list = new T[size];
for(int i = 0; i < size; i++){
list[i] = a.list[i];
}
}
template<class T>
Array<T>&Array<T>::operator=(const Array<T> &rhs) {
if(&rhs != this) {
if (size != rhs.size) {
delete [] list;
size = rhs.size;
list = new T[size];
}
for(int i = 0; i < size; i++)
list[i] = rhs.list[i];
}
return * this;
}
template<class T>
T &Array<T>::operator[] (int n) {
assert(n >= 0 && n < size);
return list[n];
}
template<class T>
const T &Array<T>::operator[] (int n) const {
assert(n >= 0 && n < size);
return list[n];
}
template<class T>
Array<T>::operator T* (){
return list;
}
template<class T>
Array<T>::operator const T* () const {
return list;
}
template<class T>
int Array<T>::getSize() const {
return size;
}
template<class T>
void Array<T>::resize(int sz) {
assert(sz >= 0);
if(sz == size)
return;
T * newList = new T[sz];
int n = (sz<size) ? sz :size;
for(int i = 0; i < n; i++) {
newList[i] = list[i];
}
delete [] list;
list = newList;
size = sz;
}
#endif /* Array_h */
| true |
391e626da7d7ae48b07355f38897fe896530a925 | C++ | Git-HF/Algorithm-Notebook | /LeetCode/Source/mergeKLists.h | UTF-8 | 1,468 | 3.59375 | 4 | [] | no_license | /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
return process(lists, 0, lists.size()-1);
}
ListNode* process(vector<ListNode*>&lists, int left, int right)
{
if(left > right)
return NULL;
else if(left == right)
return lists[left];
int mid = (left + right) / 2;
return merge(process(lists, left, mid), process(lists, mid+1, right));
}
ListNode* merge(ListNode* head1, ListNode* head2)
{
if(!head1)
return head2;
else if(!head2)
return head1;
ListNode dummy;
ListNode* res = &dummy;
while(head1 && head2)
{
if(head1->val < head2->val)
{
ListNode* tmp = head1->next;
res->next = head1;
res = res->next;
head1 = tmp;
}
else
{
ListNode* tmp = head2->next;
res->next = head2;
res = res->next;
head2 = tmp;
}
}
if(head1)
{
res->next = head1;
}
if(head2)
{
res->next = head2;
}
return dummy.next;
}
}; | true |
9c54c0bd49d835d7f1892e6e0c1e7d507df50fae | C++ | oddity1427/learning_cplusplus | /book/Chapter 10 - References/test10_func.cpp | UTF-8 | 4,434 | 3.53125 | 4 | [] | no_license | //Updates from last chapter:
//updated read_double_vector to work with references and output to more appropriate places
//Because of the way I wrote most of the sorting functions to all use iterators, I don't think It's going to be that useful to try and work references into those functions
#include "test10.hpp"
#include <iterator>
//need to add string now that its not in the header
#include <string>
//being able to call on "stream" makes everything look alot cleaner in addition to being faster as a reference to cin
//also nice that we do not have to call on cout really anymore
std::vector<double> read_double_vector(std::istream& stream){
std::vector<double> input;
double x;
while(stream >> x){
input.push_back(x);
}
if(!stream.eof()){
stream.clear();
std::string s;
std::getline(stream,s);
//no longer need to just print to console, we have a place for that now.
std::cerr << "Error, following input not processed: " << s << "\n";
}
//clear the stream so this function can be called multiple times
std::cin.clear();
std::cin.ignore(10000,'\n');
return input;
}
//basically just takes the vector input and breaks it into iterators for the actual sorting
std::vector<double> mergesort(std::vector<double> v){
iterator start = v.begin();
iterator end = v.end();
while(!isSorted(start, end)){
sort_implementation(start, end);
}
return v;
}
//takes two iterators to sort between
//slight inefficiency in checking if it is sorted each time
//works through and determines next 1 or two runs and merges them together until a pass has been completed between the beginning and end iterator
//not really a very good sort as implemented, worst case is basically an insertion sort
//only doing it this way because the obvious example of quicksort is taken and this should be reasonably complex
void sort_implementation(iterator start, iterator end){
//turns out you need to call a method you actually wrote
if(isSorted(start, end)){
return;
}
bool savedRun = false;
iterator nextEnd;
iterator lastStart;
iterator lastEnd;
lastEnd = start;
while(true){
nextEnd = run_end(lastEnd, end);
//It turns out that this will be true whether or not there is a previously saved run.
//If there is only 1 run, the vector is sorted and this will not be called so this will only ever be called with lastStart, LastEnd already defined if there are an odd number of runs
if(end == nextEnd){
sort_merging(lastStart, lastEnd, nextEnd);
return;
}
//This is the meat of taking the identified runs and merging them if necessary
if(!savedRun){
lastStart = lastEnd;
lastEnd = nextEnd;
savedRun = true;
}else{
sort_merging(lastStart, lastEnd, nextEnd);
lastStart = lastEnd;
lastEnd = nextEnd;
savedRun = false;
}
}
}
//actually does the merging algorithm between two contiguous runs noted by 3 iterators
//this is where this becomes a bit weird, as I have to sort into a vector and then copy back to the original with the iterators
//There is definitely a way to use this to also check if the vector is sorted using the number of runs, If I was actually going to use this I would remove that inefficiency
void sort_merging(iterator start, iterator mid, iterator end){
iterator vec1Itr = start;
iterator vec2Itr = mid;
std::vector<double> sorted;
while(sorted.size() < end - start){ //not all of the elements are merged yet
if(vec1Itr == mid){ //if one of the merge halfs is already exhausted, push the other one
sorted.push_back(*vec2Itr);
vec2Itr++;
}else if(vec2Itr == end){
sorted.push_back(*vec1Itr);
vec1Itr++;
}
else if(*vec1Itr < *vec2Itr){ //push from the half which has a lower value at the head
sorted.push_back(*vec1Itr);
vec1Itr++;
}else{
sorted.push_back(*vec2Itr);
vec2Itr++;
}
}
for(double d : sorted){
*start = d;
start++;
}
}
//helps sort_implementation, makes the code cleaner
bool isSorted(iterator start, iterator end){
if(end-start == 1){
return true;
}
start++;
bool to_return = true;
while(end != start ){
if(*start < *(start - 1)){
to_return = false;
}
start++;
}
return to_return;
}
//finds the end of the next run, is called a lot so separating to make cleaner
iterator run_end(iterator start, iterator end_itr){
while(true){
if( start + 1 == end_itr || *(start+1) < *start){
return start + 1;
}
start++;
}
return start;
}
| true |
c3d3b5a1e0bcb9725195a3df5c433d6b039ba1d1 | C++ | ZetcH93/DV-ALG-labb2-Sorting | /labb2/Main.cpp | UTF-8 | 1,563 | 3.8125 | 4 | [] | no_license | #include <fstream>
#include <vector>
#include <string>
#include <iostream>
#include <chrono>
#include "SortingFunctions.hpp"
vector<long int> ReadValuesFromFile(const std::string& filepath)
{
std::ifstream file(filepath);
long int number;
std::vector<long int> numbers;
while (file >> number)
numbers.push_back(number);
return numbers;
}
void WriteValuesToFile(const std::vector<long int>& numbers, const std::string& filepath = "Output.txt")
{
std::ofstream file(filepath);
for (std::vector<long int>::size_type i = 0; i < numbers.size() - 1; ++i)
file << numbers[i] << std::endl;
file << numbers.back();
}
int main(long int argc, char** argv)
{
if (argc < 4)
{
std::cout << "To few arguments" << std::endl;
return -1;
}
vector<long int> numbers = ReadValuesFromFile(argv[1]);
long int left = 0;
long int right = (numbers.size() - 1);
auto start = std::chrono::steady_clock::now();
switch (argv[2][0])
{
case '1':
cout << "mergesort" << endl;
mergeSort(numbers);
break;
case '2':
cout << "heapsort" << endl;
heapSort(numbers);
break;
case '3':
cout << "quicksort" << endl;
quickSort(numbers, left, right);
break;
default:
std::cout << "Incorrect argument for choosing the sorting algorithm!" << std::endl;
std::cout << "Aborting process!" << std::endl;
return -1;
}
auto end = chrono::steady_clock::now();
chrono::duration<double> elapsed_seconds = end - start;
cout << "Sorting took: " << elapsed_seconds.count() << " seconds" << std::endl;
WriteValuesToFile(numbers, argv[3]);
return 0;
} | true |
6c455a40dba75cd052dd1bf3e1814df4a3c52b86 | C++ | gilbertoamarcon/ply | /src/H5-utils.cpp | UTF-8 | 2,136 | 2.671875 | 3 | [] | no_license | #include "H5-utils.hpp"
// H5G_LINK 0 Object is a symbolic link.
// H5G_GROUP 1 Object is a group.
// H5G_DATASET 2 Object is a dataset.
// H5G_TYPE 3 Object is a named datatype.
herr_t H5utils::load_datasets(hid_t loc_id, const char *name, void *opdata){
std::pair<Node*,H5::H5File*> *pair=(std::pair<Node*,H5::H5File*> *)opdata;
Node *node = new Node();
node->addr = pair->first->addr+name;
pair->first->children[std::string(name)] = node;
if(H5Gget_objtype_by_idx(loc_id,0) == H5G_GROUP){
node->addr+="/";
std::pair<Node*,H5::H5File*> aux(node,pair->second);
pair->second->iterateElems(node->addr, NULL, H5utils::load_datasets, &aux);
}
if(H5Gget_objtype_by_idx(loc_id,0) == H5G_DATASET){
H5::DataSet dataset = pair->second->openDataSet(node->addr);
H5::DataSpace dataspace = dataset.getSpace();
int rank = dataspace.getSimpleExtentNdims();
hsize_t *dims_out = new hsize_t[rank];
dataspace.getSimpleExtentDims(dims_out, NULL);
node->data.resize(dims_out[0]);
dataset.read((void*)(&(node->data[0])), dataset.getDataType());
dataset.close();
}
return 0;
}
H5utils::H5utils(char *filename){
H5::H5File *file = new H5::H5File(filename, H5F_ACC_RDONLY);
this->node = new Node();
std::pair<Node*,H5::H5File*> aux(this->node,file);
file->iterateElems("/", NULL, H5utils::load_datasets, &aux);
file->close();
}
std::vector<double>& H5utils::get(std::string type, std::string name, std::string variable){
return this->node->children[type]->children[name]->children[variable]->data;
}
std::vector<std::string> H5utils::get(std::string type, std::string name){
std::vector<std::string> names;
for(auto const& imap:this->node->children[type]->children[name]->children)
names.push_back(imap.first);
return names;
}
std::vector<std::string> H5utils::get(std::string type){
std::vector<std::string> names;
for(auto const& imap:this->node->children[type]->children)
names.push_back(imap.first);
return names;
}
std::vector<std::string> H5utils::get(){
std::vector<std::string> names;
for(auto const& imap:this->node->children)
names.push_back(imap.first);
return names;
} | true |
06334e82348097ae0e8e98babaa977f868dd7bee | C++ | c0508383/Battle-Simulator | /wizard.h | UTF-8 | 613 | 3.03125 | 3 | [] | no_license | #ifndef WIZARD_H
#define WIZARD_H
#include "character.h"
#include <string>
#include <iostream>
using namespace std;
struct spell{
string name;
int mana_cost, damage;
};
class Wizard : public Character{
private:
int mana, numOfSpells;
spell spells[10];
public:
Wizard(string n, string r, int l, int h, int m);
~Wizard();
int getMana() const;
void SetMana(int m);
int AddSpell(string n, int d, int m);
void Attack(Character *target);
void Attack(Character *target, int spell_num);
void Print();
};
#endif | true |
987415c6deedb871d4d4a17e00f52d424ea05c6a | C++ | trnthsn/VongLapPractice | /bai22.cpp | UTF-8 | 388 | 3.03125 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <iomanip>
using namespace std;
int main()
{
float n = 3;
vector <float> point;
while (true)
{
cin >> n;
if (n >= 0 && n <= 10)
point.push_back(n);
if (n < 0)
break;
}
float sum;
int m = point.size();
for (int i = 0; i < m; i++)
{
sum += point[i];
}
cout << fixed << showpoint << setprecision(2);
cout << sum / m;
} | true |
77227bb1e7a0ad4074359e306a4215b953538714 | C++ | pradyuman-verma/CodeForcesProblems | /C/C_A_B_Palindrome.cpp | UTF-8 | 3,332 | 2.546875 | 3 | [] | no_license | //pradyuman_verma
/* When you hit a roadblock, remember to rethink the solution ground up, not just try hacky fixes */
#include<bits/stdc++.h>
using namespace std;
#define int long long
#define mod 1000000007
#define ps(x, y) fixed << setprecision(y) << x
#define w(x) int x; cin >> x; while(x --)
#define gcd(x, y) __gcd(x, y)
#define lcm(a,b) ((a)*(b)) / gcd((a),(b))
#define endl "\n"
#define print(x) cout << (x ? "YES" : "NO") << endl
#define for0(i, n) for (int i = 0; i < (int)(n); i ++) //0 based indexing
#define for1(i, n) for (int i = 1; i <= (int)(n); i ++) // 1 based indexing
#define forr0(i, n) for (int i = (int)(n) - 1; i >= 0; --i) // reverse 0 based.
#define forr1(i, n) for (int i = (int)(n); i >= 1; --i) // reverse 1 base
#define debug(x) cout << "debug : " << x << endl //debug tools
//short for common types
typedef vector<int> vi;
typedef pair<int, int> ii;
//short hand for usual tokens
#define pb push_back
#define fi first
#define se second
// to be used with algorithms that processes a container Eg: find(all(c),42)
#define all(x) (x).begin(), (x).end() //Forward traversal
#define rall(x) (x).rbegin(), (x).rend() //reverse traversal
// code here
class Solution{
public :
void Solve(){
int a, b, n, cnt;
string s;
cin >> a >> b >> s;
n = s.length();
for0(j, 2){
for(int i = 0; i < n; i ++){
if(s[i] != '?'){
if(s[n - (i + 1)] == '?')
s[n - (i + 1)] = s[i];
else if(s[i] != s[n - (i + 1)]){
out();
return;
}
}
}
reverse(all(s));
}
a -= count(all(s), '0');
b -= count(all(s), '1');
cnt = count(all(s), '?');
bool help = (n & 1 && s[n / 2] == '?');
if(a < 0 || b < 0 || a + b != cnt || (help && a % 2 == 0 && b % 2 == 0)){
out();
return;
}
if(a & 1 || b & 1){
if(s[n / 2] != '?'){
out();
return;
}
s[n / 2] = (a & 1 ? '0' : '1');
if(a & 1) a -= 1;
else b -= 1;
}
if(a & 1 || b & 1){
out();
return;
}
for0(i, n){
if(s[i] == '?'){
if(a > 0){
a -= 2;
s[i] = s[n - (i + 1)] = '0';
}else{
b -= 2;
s[i] = s[n - (i + 1)] = '1';
}
}
}
cout << s << endl;
}
static void out(){
cout << -1 << endl;
}
};
signed main(){
ios_base::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
w(x){
Solution ob;
ob.Solve();
}
return 0;
}
// 4 + 3 + 7 + 6 + 3 | true |
1f86a81ed9858ba8cd72583a61bdf62d01356ff1 | C++ | chenyangchenyang/ptcx | /image.h | UTF-8 | 5,258 | 2.5625 | 3 | [
"BSD-2-Clause"
] | permissive |
/*
// Copyright (c) 2002-2014 Joe Bertolami. All Right Reserved.
//
// image.h
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Additional Information:
//
// For more information, visit http://www.bertolami.com.
*/
#ifndef __IMAGE_H__
#define __IMAGE_H__
#include "base.h"
namespace imagine {
using namespace base;
enum IGN_IMAGE_FORMAT
{
IGN_IMAGE_FORMAT_NONE = 0,
IGN_IMAGE_FORMAT_R8G8B8, // RGB, 8 bits per channel
};
class image
{
friend status create_image(IGN_IMAGE_FORMAT format, uint32 width, uint32 height, image *output);
friend status create_image(IGN_IMAGE_FORMAT format, void *image_data, uint32 width, uint32 height, image *output);
friend status destroy_image(image *input);
private:
IGN_IMAGE_FORMAT image_format;
bool placement_allocation;
uint32 width_in_pixels;
uint32 height_in_pixels;
uint32 bits_per_pixel;
uint8 channel_count;
uint8 *data_buffer;
private:
/*
// Allocation management
//
// The following methods should not be used for placement allocated images. For
// non-placement images, deallocate must be called prior to destruction.
*/
status allocate(uint32 size);
void deallocate();
/*
// An image is considered uninitialized if its format field is set to zero
// (no format). Images must have an empty data buffer in this scenario.
*/
status set_image_format(IGN_IMAGE_FORMAT format);
/*
// set_dimension will automatically manage the memory of the object. This is the
// primary interface that should be used for reserving memory for the image. Note
// that the image must contain a valid format prior to calling SetDimension.
*/
status set_dimension(uint32 width, uint32 height);
/*
// placement_allocation identifies whether the image owns its backing storage or
// whether the memory was provided by the caller.
*/
status set_placement(void *data);
public:
image();
virtual ~image();
/*
// Image dimensions are always specified in pixels. Note that compressed image
// formats may not store their image data as a contiguous set of pixels.
*/
uint32 query_width() const;
uint32 query_height() const;
uint8 *query_data() const;
uint8 query_bits_per_pixel() const;
uint8 query_channel_count() const;
IGN_IMAGE_FORMAT query_image_format() const;
/*
// Row Pitch
//
// row pitch is the byte delta between two adjacent rows of pixels in the image.
// This function takes alignment into consideration and may provide a value that
// is greater than the byte width of the visible image.
*/
uint32 query_row_pitch() const;
/*
// Slice Pitch
//
// SlicePitch is the byte size of the entire image. This size may extend beyond the
// edge of the last row and column of the image, due to alignment and tiling
// requirements on certain platforms.
*/
uint32 query_slice_pitch() const;
/*
// Block Offset
//
// Block offset returns the byte offset from the start of the image to pixel (i,j).
// Formats are required to use byte aligned pixel rates, so this function will always
// point to the start of a pixel block.
*/
uint32 query_block_offset(uint32 i, uint32 j) const;
};
/*
// image management
//
// create_image must be called prior to using an image object, and destroy_image should always
// be called on images prior to their destruction. We use this factory-like interface in order
// to hide the details of the underlying image implementation.
*/
status create_image(IGN_IMAGE_FORMAT format, uint32 width, uint32 height, image *output);
status create_image(IGN_IMAGE_FORMAT format, void *image_data, uint32 width, uint32 height, image *output);
status destroy_image(image *input);
} // namespace imagine
#endif // __IMAGE_H__
| true |
0fbf40f618fc600444170977e4dd358133b6f1a1 | C++ | muin99/codeforces-c-plus-plus | /50A Domino piling.cpp | UTF-8 | 231 | 2.953125 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main(){
int m, n;
cin >> m>>n;
if(m*n % 2 == 0){
cout << m*n/2;
}
else{
int value;
value = (m-1)*n/2 + (n-1)/2;
cout << value;
}
}
| true |
609e11274c8839991efc8bcd2c8ed293b8b72a88 | C++ | manthenasirisha/allpractice | /PSP2 Assignment 1/psp2AssignementMain/psp2AssignementMain/psp2AssignmentSource.cpp | UTF-8 | 2,911 | 3.46875 | 3 | [] | no_license | #include "pch.h"
#include <iostream>
#include <string>
#include "psp2AssignmentHeader.h"
using namespace std;
struct TimeTableCell
{
string subject;
string lecturer;
string roomNumber;
// flag to represent if a cell is free
bool isFree = true;
};
TimeTableCell timeTable[5][9];
//--------------------------------------------------------
// Function name: clearTimetableTerm
// clears the all time table form all terms.
//--------------------------------------------------------
void clearTimetable() {
for (int i = 0; i <= 4; i++) {
for (int j = 0; j <= 8; j++) {
timeTable[i][j].lecturer = "";
timeTable[i][j].roomNumber = "";
timeTable[i][j].subject = "";
timeTable[i][j].isFree = true;
}
}
}
//--------------------------------------------------------
// Function name: insertTimeTable
// input parameters
// @parm2: day
// @parm3: hour
// @parm4: subject
// @parm5: lecturer
// @parm6: roomNumber
//--------------------------------------------------------
void insertTimeTable(int day, int hour, string subject, string lecturer, string roomNumber) {
timeTable[day][hour].lecturer = lecturer;
timeTable[day][hour].roomNumber = roomNumber;
timeTable[day][hour].subject = subject;
timeTable[day][hour].isFree = false;
}
//--------------------------------------------------------
// Function name:showTimeTable
// input parameters
// @parm2: day
// @parm2: hour
//--------------------------------------------------------
void showTimeTable(int day, int hour) {
cout << hour + 9 << ", " << timeTable[day][hour].subject << ", " << timeTable[day][hour].lecturer << ", " << timeTable[day][hour].roomNumber;
}
//--------------------------------------------------------
// Function name:showEntireTimetable
//--------------------------------------------------------
void showEntireTimetable() {
string day;
for (int i = 0; i <= 4; i++) {
cout << "-----------------" << endl;
if (i == 0) {
day = "monday";
}
else if (i == 1) {
day = "tuesday";
}
else if (i == 2) {
day = "wednesday";
}
else if (i == 3) {
day = "thrusday";
}
else if (i == 4) {
day = "friday";
}
cout << day << endl;
for (int j = 0; j <= 8; j++) {
showTimeTable(i, j);
cout << endl;
}
}
}
//--------------------------------------------------------
// Function name: showfreeHoursTerms
//--------------------------------------------------------
void showFreeHours() {
string day;
for (int i = 0; i <= 4; i++) {
for (int j = 0; j <= 8; j++) {
cout << "-----------------" << endl;
if (timeTable[i][j].isFree == true) {
if (i == 0) {
day = "monday";
}
else if (i == 1) {
day = "tuesday";
}
else if (i == 2) {
day = "wednesday";
}
else if (i == 3) {
day = "thrusday";
}
else if (i == 4) {
day = "friday";
}
cout << j + 9 << " hour of " << day << " is free" ;
}
}
}
} | true |
c7cf36a2a1a2cf0d7bd0391be75876a8c9a44394 | C++ | Wqxleo/C_plus | /作业1.C整数的封装.cpp | GB18030 | 1,566 | 3.546875 | 4 | [] | no_license | #include <iostream>
#include <iomanip>
#include <cstring>
using namespace std;
class Integer
{
public:
//Ƚϼʱ
Integer(int data)
{
m_data = data;
}
Integer(char*, int);
int getValue()
{
return m_data;
}
private:
char m_str[100];
int m_data,m_radix;
};
//ȽϸʱҪ
Integer::Integer(char *str, int radix)
{
//һдһ
int l;
int i;
int flag = 1;
int sum = 0;
strcpy(m_str,str);
m_radix = radix;
l = strlen(m_str);
for(i = l-1; i >= 0; i--)
{
if(m_str[i] >= '0' && m_str[i] <= '9')
{
m_str[i] = m_str[i] - '0';
}
else
{
if(m_str[i] >= 'A' && m_str[i] <= 'Z')
{
m_str[i] = m_str[i] - 'A' + 'a' + 10;
}
else
m_str[i] = m_str[i] - 'a' + 10;
}
sum += m_str[i]*flag;
flag *= m_radix;
}
m_data = sum;
}
int main()
{
char str[100];
int numOfData, numOfStr;
int data, i, radix;
cin>>numOfData;
for (i = 0; i < numOfData; i++)
{
cin>>data;
Integer anInteger(data);
cout<<anInteger.getValue()<<endl;
}
cin>>numOfStr;
for (i = 0; i < numOfStr; i++)
{
cin>>str>>radix;
Integer anInteger(str,radix);
cout<<anInteger.getValue()<<endl;
}
return 0;
}
| true |
a69bf70f69b2532babb78c220c095a046ef00405 | C++ | hrishi3390/DesginPattersInCPP | /decorator/main.cpp | UTF-8 | 1,657 | 3.765625 | 4 | [] | no_license | //
// main.cpp
// decorator
//
// Created by Hrishikesh Chaudhari on 01/01/19.
// Copyright © 2019 Hrishikesh Chaudhari. All rights reserved.
//
/*
This is the pattern where you could augement the functionlity of a class. This pattern would require you to have access to source code and then we dont modify the original class to add the functionlity. Instead we use the referrence of the object in derived class and augment its functonality.
*/
#include <iostream>
#include <sstream>
using namespace std;
struct Shape
{
virtual string str() const = 0;
};
struct Circle : Shape {
float radius;
Circle(float radius): radius(radius){}
Circle(){}
void resize(float factor){
radius *= factor;
}
string str() const override {
ostringstream oss;
oss<<"This is a circle of radius "<<radius;
return oss.str();
}
};
struct Square : Shape {
float side;
Square(float side): side(side){}
Square(){}
string str() const override{
ostringstream oss;
oss<<"This is a square of size "<<side;
return oss.str();
}
};
struct ColoredShape : Shape {
Shape& shape;
string color;
ColoredShape(Shape &shape, const string color): shape(shape),color(color){}
string str() const override {
ostringstream oss;
oss<<shape.str()<<" has the color "<<color;
return oss.str();
}
};
int main(int argc, const char * argv[]) {
Circle c(5);
Square s(10);
ColoredShape colorCircle(s,"red");
cout<<colorCircle.str()<<endl;
//cout<<c.str()<<endl;
return 0;
}
| true |
3bcacb9fc2911ceeb9449aa887123072a0d1724c | C++ | Darling1116/Darling_1116 | /lesson_8_16/Offer_6/test_1.h | GB18030 | 1,085 | 3.734375 | 4 | [] | no_license | #pragma once
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
//1.
//1
int FindGreatestSumOfSubArray_1(vector<int> array){
if (array.empty())
return 0;
vector<int> sum;
sum.resize(array.size()); //ʼʱҪvectorʼ
sum[0] = array[0];
int max_num = sum[0];
for (int i = 1; i < array.size(); i++){
sum[i] = max(sum[i - 1] + array[i], array[i]);
if (max_num < sum[i])
max_num = sum[i];
}
return max_num;
}
//2Ƚ
int FindGreatestSumOfSubArray_2(vector<int> array){
if (array.empty())
return 0;
int total = array[0];
int max = total;
for (int i = 1; i < array.size(); i++){
if (total < 0){
total = array[i];
}
else{
total += array[i];
}
if (total > max)
max = total;
}
return max;
}
void test1_1(){
vector<int> v = { 1, -2, 3, 10, -4, 7, 2, -5 };
int ret = FindGreatestSumOfSubArray_1(v);
cout << ret << endl;
int ret2 = FindGreatestSumOfSubArray_2(v);
cout << ret2 << endl;
} | true |
e114e97f10c28a53c2c8e7064230c42741a25f93 | C++ | sarroutbi/pexpupm | /klondike/src/OptionResetGameText.cpp | UTF-8 | 598 | 2.515625 | 3 | [] | no_license | #include <iostream>
#include "OptionResetGameText.h"
#include "LanguageMap.h"
#include "LanguageHandler.h"
#include "ActionReset.h"
OptionResetGameText::OptionResetGameText(const std::string& text,
const uint8_t& pos) : OptionText(text, pos)
{
;
}
OptionResetGameText::~OptionResetGameText()
{
;
}
void OptionResetGameText::Display()
{
std::cout << std::to_string(m_pos) << ":" << m_text << std::endl;
}
GameAction* OptionResetGameText::GetGameAction()
{
char option = 0;
if(IsUserSecure()) {
return new ActionReset;
}
return NULL;
}
| true |
e5a563fab930bf3c6439152651661baa67fd0146 | C++ | damengzai/damengzai | /cpp/2second/infloat/infloat.cpp | UTF-8 | 284 | 3.109375 | 3 | [] | no_license | #include<iostream>
#include<string>
#include<vector>
using namespace std;
int main(){
vector<float> v;
for (int i = 0 ; i < 5 ; i++){
float f;
cout << "please inpute a num:" << endl;
cin >> f;
v.push_back(f);
}
for (int j = 0 ; j < 5 ; j++){
cout << v[j] << endl;
}
} | true |
07b4cdaa18ae60c7cd60a6c08f01e12a154baf86 | C++ | sanlf/Super-tic-tac-toe | /src/TicTacToe.cpp | UTF-8 | 17,434 | 2.703125 | 3 | [] | no_license | #include "../include/TicTacToe.h"
/**************************************************************************************************/
TicTacToe::TicTacToe(ALLEGRO_DISPLAY* display,
ALLEGRO_EVENT_QUEUE* eventQueue,
ALLEGRO_TIMER* timer,
GameFonts fonts,
ALLEGRO_DISPLAY_MODE dispdata):
m_display(display),
m_eventQueue(eventQueue),
m_timer(timer),
m_fonts(fonts),
m_dispdata(dispdata),
m_cursor(m_bboard),
m_winner(NO_WINNER),
m_bboard(Point(0,0),
Point(dispdata.width,
0.8*dispdata.height)),
m_currboardidx(Position::NONE),
m_player1("J1", "X",
Type::HUMAN,
m_bboard,
COLOR.CURSOR_P1),
m_player2("J2", "O",
Type::HUMAN,
m_bboard,
COLOR.CURSOR_P2)
{
m_turn = &m_player1;
reset("JUGADOR1", "X", "JUGADOR2", "O");
}
/**************************************************************************************************/
void TicTacToe::play()
{
bool redraw = true;
ALLEGRO_EVENT ev;
//this lambda tells wheter escape was pressed or not
auto closegame = [](ALLEGRO_EVENT e){return e.type == ALLEGRO_EVENT_KEY_UP &&
e.keyboard.keycode == ALLEGRO_KEY_ESCAPE;};
al_start_timer(m_timer);
while(m_winner == NO_WINNER && !closegame(ev)){
al_wait_for_event(m_eventQueue, &ev);
if(ev.type == ALLEGRO_EVENT_TIMER)
redraw = true;
if(redraw && al_is_event_queue_empty(m_eventQueue)){
redraw = false;
draw();
}
if(m_turn->getType() == Type::HUMAN){
handleUserInput(&ev);
}else{
std::pair<Position, Position> aiPlay;
aiPlay = m_turn->agentDecision(m_currboardidx);
if(m_currboardidx == Position::NONE){
selectBoard(aiPlay.first);
}
selectCell(aiPlay.second);
}
}
endgame();
al_flush_event_queue(m_eventQueue); //clean the event queue after playing
}
/**************************************************************************************************/
void TicTacToe::endgame()
{
if(m_winner != NO_WINNER){
draw();
if(m_winner != TIE){
std::string msg = ", ganaste!";
Player* winner = m_player1.getPiece() == m_winner ? &m_player1 : &m_player2;
al_show_native_message_box(m_display,
"Felicidades!",
"Felicidades!",
(winner->getName() + msg).c_str(),
nullptr, ALLEGRO_MESSAGEBOX_OK_CANCEL );
}else{
std::string msg = "El juego terminó en empate";
al_show_native_message_box(m_display,
"Empate",
"Empate",
msg.c_str(),
nullptr, ALLEGRO_MESSAGEBOX_OK_CANCEL );
}
}
}
/**************************************************************************************************/
void TicTacToe::handleUserInput(ALLEGRO_EVENT* ev)
{
if(ev->type == ALLEGRO_EVENT_KEY_UP){ //handles keyboard
handleKeyboardInput(ev);
}//else if(ev->type == ALLEGRO_MOUSE_SOMETHING??)
}
/**************************************************************************************************/
void TicTacToe::handleKeyboardInput(ALLEGRO_EVENT* ev)
{
switch(ev->keyboard.keycode){
case ALLEGRO_KEY_UP:
m_cursor.move(Position::UP);
break;
case ALLEGRO_KEY_DOWN:
m_cursor.move(Position::DOWN);
break;
case ALLEGRO_KEY_LEFT:
m_cursor.move(Position::LEFT);
break;
case ALLEGRO_KEY_RIGHT:
m_cursor.move(Position::RIGHT);
break;
case ALLEGRO_KEY_ENTER:
if(m_currboardidx == Position::NONE){
if(!selectBoard(m_cursor.m_boardidx)) //if an invalid board was selected
drawCursorError();
}else{
if(!selectCell(m_cursor.m_cellidx)) //if an invalid cell was selected
drawCursorError();
}
break;
}
}
/**************************************************************************************************/
bool TicTacToe::selectBoard(int position)
{
if(m_bboard[position].getWinner() == NO_WINNER){
m_currboardidx = static_cast<Position>(position);
m_cursor.reposition(position, static_cast<int>(Position::LEFT_UP));
//put this in the stack
return true;
}
return false;
}
/**************************************************************************************************/
bool TicTacToe::selectCell(int position)
{
if(!putPiece(position))
return false;
//put play in stack
//
updateWinner();
if(m_bboard[position].getWinner() == NO_WINNER){
m_currboardidx = static_cast<Position>(position);
m_cursor.reposition(position, static_cast<int>(Position::LEFT_UP));
}else{
m_currboardidx = Position::NONE;
m_cursor.reposition(static_cast<int>(Position::LEFT_UP));
}
changeTurn();
return true;
}
/**************************************************************************************************/
bool TicTacToe::putPiece(int cellidx)
{
if(m_currboardidx == Position::NONE) //there is no board selected
return false;
if(m_bboard[m_currboardidx][cellidx].piece != EMPTY) //the cell is already ocuppied
return false;
m_bboard[m_currboardidx][cellidx].piece = m_turn->getPiece();
return true;
}
/**************************************************************************************************/
void TicTacToe::updateWinner()
{
if(m_winner != NO_WINNER) //if there is already a winner there is no reason to check
return;
m_bboard.updateWinner();
auto m_boards = m_bboard.m_boards;
//left to right diagonal
if(m_boards[Position::CENTER].m_winner != EMPTY &&
m_boards[Position::CENTER].m_winner == m_boards[Position::LEFT_UP].m_winner &&
m_boards[Position::CENTER].m_winner == m_boards[Position::RIGHT_DOWN].m_winner)
m_winner = m_boards[Position::CENTER].m_winner;
//right to left diagonal
else if(m_boards[Position::CENTER].m_winner != EMPTY &&
m_boards[Position::CENTER].m_winner == m_boards[Position::RIGHT_UP].m_winner &&
m_boards[Position::CENTER].m_winner == m_boards[Position::LEFT_DOWN].m_winner)
m_winner = m_boards[Position::CENTER].m_winner;
//horizontal center
else if(m_boards[Position::CENTER].m_winner != EMPTY &&
m_boards[Position::CENTER].m_winner == m_boards[Position::LEFT_CENTER].m_winner &&
m_boards[Position::CENTER].m_winner == m_boards[Position::RIGHT_CENTER].m_winner)
m_winner = m_boards[Position::CENTER].m_winner;
//vertical center
else if(m_boards[Position::CENTER].m_winner != EMPTY &&
m_boards[Position::CENTER].m_winner == m_boards[Position::CENTER_UP].m_winner &&
m_boards[Position::CENTER].m_winner == m_boards[Position::CENTER_DOWN].m_winner)
m_winner = m_boards[Position::CENTER].m_winner;
//horizontal up
else if(m_boards[Position::LEFT_UP].m_winner != EMPTY &&
m_boards[Position::LEFT_UP].m_winner == m_boards[Position::CENTER_UP].m_winner &&
m_boards[Position::LEFT_UP].m_winner == m_boards[Position::RIGHT_UP].m_winner)
m_winner = m_boards[Position::LEFT_UP].m_winner;
//vertical left
else if(m_boards[Position::LEFT_UP].m_winner != EMPTY &&
m_boards[Position::LEFT_UP].m_winner == m_boards[Position::LEFT_CENTER].m_winner &&
m_boards[Position::LEFT_UP].m_winner == m_boards[Position::LEFT_DOWN].m_winner)
m_winner = m_boards[Position::LEFT_UP].m_winner;
//horizontal down
else if(m_boards[Position::RIGHT_DOWN].m_winner != EMPTY &&
m_boards[Position::RIGHT_DOWN].m_winner == m_boards[Position::LEFT_DOWN].m_winner &&
m_boards[Position::RIGHT_DOWN].m_winner == m_boards[Position::CENTER_DOWN].m_winner)
m_winner = m_boards[Position::RIGHT_DOWN].m_winner;
//vertical right
else if(m_boards[Position::RIGHT_DOWN].m_winner != EMPTY &&
m_boards[Position::RIGHT_DOWN].m_winner == m_boards[Position::RIGHT_UP].m_winner &&
m_boards[Position::RIGHT_DOWN].m_winner == m_boards[Position::RIGHT_CENTER].m_winner)
m_winner = m_boards[Position::RIGHT_DOWN].m_winner;
//finally checks if there is a tie
else if(std::all_of(m_boards.begin(), m_boards.end(),
[](const auto& board){return board.getWinner() == TIE
|| board.getWinner() == "X"
|| board.getWinner() == "O";}))
m_winner = TIE;
}
/**************************************************************************************************/
void TicTacToe::draw() const
{
al_clear_to_color(COLOR.BACKGROUND);
m_bboard.draw(m_fonts.normal);
drawGameInfo();
drawBoardWinners();
//just to know the limits
////////////////////////
/*
al_draw_rectangle(m_bboard.m_p0.x, m_bboard.m_p0.y, m_bboard.m_p1.x, m_bboard.m_p1.y, COLOR.WHITE, 3);
for(const auto& board : m_bboard.m_boards)
al_draw_rectangle(board.m_p0.x, board.m_p0.y, board.m_p1.x, board.m_p1.y, COLOR.BLUE, 3);
float last = (m_dispdata.height - m_bboard.m_p1.y) * .8;
al_draw_rectangle(m_bboard.m_p0.x, m_bboard.m_p1.y + 10, m_bboard.m_p1.x, m_bboard.m_p1.y + last, COLOR.WHITE, 3);
*/
////////////////////////
if(m_turn == &m_player1)
m_cursor.draw(COLOR.CURSOR_P1);
else
m_cursor.draw(COLOR.CURSOR_P2);
al_flip_display();
}
/**************************************************************************************************/
void TicTacToe::drawGameInfo() const
{
std::string player1 = m_player1.getName() + ": " + m_player1.getPiece();
std::string player2 = m_player2.getName() + ": " + m_player2.getPiece();
std::string currentPlayer = "Turno: " + m_turn->getName();
float spaceFromBoard = 10;
al_draw_text(m_fonts.normal, m_player1.getColor(),
m_bboard.m_p0.x, m_bboard.m_p1.y + spaceFromBoard,
ALLEGRO_ALIGN_LEFT, player1.c_str());
al_draw_text(m_fonts.normal, m_player2.getColor(),
m_bboard.m_p1.x, m_bboard.m_p1.y + spaceFromBoard,
ALLEGRO_ALIGN_RIGHT, player2.c_str());
float xcenter = (m_bboard.m_p0.x + m_bboard.m_p1.x) / 2.0;
al_draw_text(m_fonts.normal, m_turn->getColor(),
xcenter, m_bboard.m_p1.y + spaceFromBoard,
ALLEGRO_ALIGN_CENTER, currentPlayer.c_str());
}
/**************************************************************************************************/
void TicTacToe::drawBoardWinners() const
{
for(const auto& board : m_bboard.m_boards)
board.drawWinner();
m_bboard.drawWinner();
}
/**************************************************************************************************/
void TicTacToe::run()
{
menu();
}
/**************************************************************************************************/
void TicTacToe::menu()
{
float width = m_dispdata.width;
float height = m_dispdata.height;
Point txtpos = Point(width/2.0, 0);
unsigned short curridx = 0;
std::array<std::string, 5> menuOption;
menuOption[0] = "Jugar: Contra Computadora";
menuOption[1] = "Jugar: Contra Otro Jugador";
menuOption[2] = "Instrucciones";
menuOption[3] = "Acerca de";
menuOption[4] = "Salir";
ALLEGRO_EVENT ev;
while(ev.type != ALLEGRO_EVENT_DISPLAY_CLOSE){
al_clear_to_color(COLOR.BACKGROUND);
//draws title
txtpos = Point(width/2.0, 0);
al_draw_text(m_fonts.title, COLOR.WHITE, txtpos.x, txtpos.y, ALLEGRO_ALIGN_CENTER, "Gato 9x9");
//draws all menu options
txtpos.y = height/3.0;
for(const auto& option : menuOption){
if(option != menuOption[curridx]){
al_draw_text(m_fonts.selection,
COLOR.WHITE, txtpos.x, txtpos.y,
ALLEGRO_ALIGN_CENTER, option.c_str());
}else{
al_draw_text(m_fonts.selection,
COLOR.GREEN, txtpos.x, txtpos.y,
ALLEGRO_ALIGN_CENTER, option.c_str());
}
txtpos.y += (3.0/4.0 - 1.0/3.0)*height/menuOption.size();
}
al_flip_display();
al_wait_for_event(m_eventQueue, &ev);
if(ev.type == ALLEGRO_EVENT_KEY_UP){
switch(ev.keyboard.keycode){
case ALLEGRO_KEY_UP:
if(curridx > 0) --curridx;
break;
case ALLEGRO_KEY_DOWN:
if(curridx < menuOption.size() - 1) ++curridx;
break;
case ALLEGRO_KEY_ENTER:
if(menuOption[curridx] == "Jugar: Contra Computadora"){
reset("JUGADOR1", "X", "JUGADOR2", "O", Type::AI);
play();
std::cout << "Se terminó juego contra computadora" << std::endl;
}
else if(menuOption[curridx] == "Jugar: Contra Otro Jugador"){
reset("JUGADOR1", "X", "JUGADOR2", "O");
play();
std::cout << "Se terminó juego contra otro jugador" << std::endl;
}
else if(menuOption[curridx] == "Instrucciones"){
displayInstructions();
}
else if(menuOption[curridx] == "Acerca de"){
displayAbout();
}
else{ //if(menuOption[curridx] == "Exit")
ev.type = ALLEGRO_EVENT_DISPLAY_CLOSE;
}
break;
case ALLEGRO_KEY_ESCAPE:
ev.type = ALLEGRO_EVENT_DISPLAY_CLOSE;
break;
}
}
}
}
/**************************************************************************************************/
void TicTacToe::displayAbout()
{
std::string about = readFile("about/about.txt");
al_clear_to_color(COLOR.BACKGROUND);
al_draw_multiline_text(m_fonts.files, COLOR.WHITE,
10, 10, m_dispdata.width - 10, m_fonts.filesSize, //10 pixel of space
ALLEGRO_ALIGN_LEFT, about.c_str());
al_flip_display();
handleReturnToMenu(m_eventQueue);
}
/**************************************************************************************************/
void TicTacToe::displayInstructions()
{
std::string instructions = readFile("man/instructions.txt");
al_clear_to_color(COLOR.BACKGROUND);
al_draw_multiline_text(m_fonts.files, COLOR.WHITE,
10, 10, m_dispdata.width - 10, m_fonts.filesSize, //10 pixel of space
ALLEGRO_ALIGN_LEFT, instructions.c_str());
al_flip_display();
handleReturnToMenu(m_eventQueue);
}
/**************************************************************************************************/
void TicTacToe::reset(std::string nameP1, std::string pieceP1, std::string nameP2, std::string pieceP2, Type typePlayerTwo /*= Type::HUMAN*/)
{
m_winner = NO_WINNER;
m_player1.setName(nameP1);
m_player1.setPiece(pieceP1);
m_player2.setName(nameP2);
m_player2.setPiece(pieceP2);
m_player2.setType(typePlayerTwo);
m_cursor.reposition(Position::LEFT_UP);
m_currboardidx = Position::NONE;
m_turn = &m_player1;
m_bboard.reset();
al_flush_event_queue(m_eventQueue); //clean the event queue before playing
//empy the stack of plays
}
/**************************************************************************************************/
void TicTacToe::drawCursorError() const
{
draw();
m_cursor.draw(COLOR.CURSOR_ERROR);
al_flip_display();
al_rest(1);
}
| true |
6b5f5cc15def81ff638cf38143105d280fd0aba6 | C++ | abnayak/brainz | /InterviewBit/BinarySearch/search2d.cpp | UTF-8 | 554 | 3.203125 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int Solution::searchMatrix(vector<vector<int> > &A, int B) {
int rowLen = A.size();;
int columnlen = A[0].size();
for (int i = 0, j=0; i < rowLen && j < columnlen; ) {
if (A[i][j] == B)
return 1;
if(B <= A[i][columnlen-1]) {
j++;
} else {
i++;
}
}
return 0;
}
int main() {
int a[7][1] = { {3} , {29}, {36}, {63}, {67}, {72},{74} };
cout << searchMatrix(a, 41) << endl;
return 0;
}
| true |
4af8d1f6816a5c4c39b014ee2369dc0cee7ef451 | C++ | zarif98sjs/Competitive-Programming | /CSES/Graph Algorithms/Flight Discount.cpp | UTF-8 | 3,491 | 2.65625 | 3 | [] | no_license |
/** Which of the favors of your Lord will you deny ? **/
#include<bits/stdc++.h>
using namespace std;
#define LL long long
#define PII pair<int,int>
#define PLL pair<LL,LL>
#define F first
#define S second
#define ALL(x) (x).begin(), (x).end()
#define READ freopen("alu.txt", "r", stdin)
#define WRITE freopen("vorta.txt", "w", stdout)
#ifndef ONLINE_JUDGE
#define DBG(x) cout << __LINE__ << " says: " << #x << " = " << (x) << endl
#else
#define DBG(x)
#define endl "\n"
#endif
template<class T1, class T2>
ostream &operator <<(ostream &os, pair<T1,T2>&p);
template <class T>
ostream &operator <<(ostream &os, vector<T>&v);
template <class T>
ostream &operator <<(ostream &os, set<T>&v);
inline void optimizeIO()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
}
const int nmax = 2e5+7;
const LL INF = 1e15;
struct Graph
{
int n;
bool dir;
vector<vector<PII>>adj;
vector<vector<LL>>dp;
Graph(int n,bool dir)
{
this->n = n;
this->dir = dir;
int len = n+1;
adj = vector<vector<PII>>(len);
dp = vector<vector<LL>>(len,vector<LL>(2,INF));
}
void add_edge(int u,int v,int c)
{
adj[u].push_back({v,c});
if(!dir) adj[v].push_back({u,c});
}
void dijkstra(int s)
{
priority_queue< PLL,vector<PLL>,greater<PLL> >PQ;
dp[s][0] = 0; /// 0 -> no coupon until now
dp[s][1] = 0; /// 1 -> used up a coupon
PQ.push({0,s});
while(!PQ.empty())
{
int u = PQ.top().S;
LL now_d = PQ.top().F;
PQ.pop();
if(now_d!=dp[u][1])
continue; /// OPTIMIZATIONNNNNNNNNNN : WOAH . DIDNT KNOW IT BEFORE
for(auto x:adj[u])
{
int v = x.F;
LL ed = x.S;
bool relax = false;
if(dp[u][0] + ed < dp[v][0]) /// haven't used coupon yet
{
dp[v][0] = dp[u][0] + ed;
relax = true;
}
if(dp[u][0] + ed/2 < dp[v][1]) /// haven't used coupon yet , using coupon in this edge
{
dp[v][1] = dp[u][0] + ed/2;
relax = true;
}
if(dp[u][1] + ed < dp[v][1]) /// already used coupon
{
dp[v][1] = dp[u][1] + ed;
relax = true;
}
if(relax)
{
PQ.push({dp[v][1],v});
}
}
}
}
void solve()
{
dijkstra(1);
cout<<dp[n][1]<<endl;
}
};
void solveTC()
{
int n,m;
cin>>n>>m;
Graph g(n,true);
for(int i=0; i<m; i++)
{
int a,b,c;
cin>>a>>b>>c;
g.add_edge(a,b,c);
}
g.solve();
}
int32_t main()
{
optimizeIO();
int tc = 1;
// cin>>tc;
while(tc--)
{
solveTC();
}
return 0;
}
/**
**/
template<class T1, class T2>
ostream &operator <<(ostream &os, pair<T1,T2>&p)
{
os<<"{"<<p.first<<", "<<p.second<<"} ";
return os;
}
template <class T>
ostream &operator <<(ostream &os, vector<T>&v)
{
os<<"[ ";
for(T i:v)
{
os<<i<<" " ;
}
os<<" ]";
return os;
}
template <class T>
ostream &operator <<(ostream &os, set<T>&v)
{
os<<"[ ";
for(T i:v)
{
os<<i<<" ";
}
os<<" ]";
return os;
}
| true |
eec6f1a50ae202387208b1d99f589c5ab4fcd012 | C++ | hntk03/atcoder | /ARC/007/A.cpp | UTF-8 | 407 | 2.625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
typedef vector<int> VI;
typedef vector<string> VS;
//container util
#define SORT(c) sort((c).begin(),(c).end())
//repetition
#define FOR(i,a,b) for(int i=(a);i<(b);++i)
#define REP(i,n) FOR(i,0,n)
int main(void){
char X; cin >> X;
string s; cin >> s;
REP(i,s.length()){
if(X == s[i]) continue;
cout << s[i];
}
cout << endl;
return 0;
}
| true |
17b051dab913d2164e8812283b2ade8a3dbd6967 | C++ | dnjp/OpenCVTrafficSim | /src/TrafficLight.cpp | UTF-8 | 2,372 | 3.28125 | 3 | [] | no_license | #include "TrafficLight.h"
#include <iostream>
#include <random>
template <typename T> T MessageQueue<T>::receive()
{
std::unique_lock<std::mutex> uLock(_mutex);
_cond.wait(uLock, [this] { return !_queue.empty(); });
T msg = std::move(_queue.back());
_queue.pop_back();
return msg;
}
template <typename T> void MessageQueue<T>::send(T&& msg)
{
std::lock_guard<std::mutex> lck(_mutex);
_queue.push_back(std::move(msg));
_cond.notify_one();
}
TrafficLight::TrafficLight() { _currentPhase = TrafficLightPhase::red; }
void TrafficLight::waitForGreen()
{
while (true) {
std::this_thread::sleep_for(std::chrono::milliseconds(1));
TrafficLightPhase tp = _mQueue.receive();
if (tp == green) {
return;
}
}
}
TrafficLightPhase TrafficLight::getCurrentPhase() { return _currentPhase; }
void TrafficLight::simulate()
{
threads.emplace_back(std::thread(&TrafficLight::cycleThroughPhases, this));
}
// virtual function which is executed in a thread
void TrafficLight::cycleThroughPhases()
{
// generates random number between 4 and 6
auto start = std::chrono::high_resolution_clock::now();
std::random_device device;
std::mt19937 engine(device());
std::uniform_int_distribution<> distribution(4, 6);
int desired_dur = distribution(engine);
while (true) {
// measures the time between two cycles
auto end = std::chrono::high_resolution_clock::now();
auto duration
= std::chrono::duration_cast<std::chrono::seconds>(end - start)
.count();
// toggles current phase of traffic light if the desired_dur is reached
if (duration >= desired_dur) {
// toggle current phase of traffic light
switch (_currentPhase) {
case red:
_currentPhase = green;
break;
case green:
_currentPhase = red;
break;
default:
_currentPhase = red;
break;
}
// send update method to message queue using move semantics
_mQueue.send(std::move(_currentPhase));
// reset clock
start = std::chrono::high_resolution_clock::now();
}
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
}
| true |
65be26d87f1c37e7043c2f6a0658509c480afbc0 | C++ | ydzh/algorithms | /src/heap_sort.cpp | UTF-8 | 1,208 | 3.828125 | 4 | [] | no_license | #include <iostream>
#include <vector>
int LeftChild(int i)
{
return i * 2 + 1;
}
void PercDown(std::vector<int> &arr, int root, int length)
{
int child;
int tmp = arr[root];
for (; LeftChild(root) < length; root = child)
{
child = LeftChild(root);
if (child + 1 < length && arr[child] < arr[child + 1])
{
child++;
}
if (tmp < arr[child])
{
arr[root] = arr[child];
}
else
{
break;
}
}
arr[root] = tmp;
}
void SwapEle(std::vector<int> &arr, int first, int second)
{
int tmp = arr[first];
arr[first] = arr[second];
arr[second] = tmp;
}
void HeapSort(std::vector<int> &arr)
{
// build heap
for (int leaf = arr.size() / 2 - 1; leaf >= 0; leaf--)
{
PercDown(arr, leaf, arr.size());
}
// sort
for (int i = arr.size() - 1; i > 0; i--)
{
SwapEle(arr, 0, i);
PercDown(arr, 0, i);
}
}
int main()
{
std::vector<int> arr = {4, 3, 8, 9, 2, 7, 8, 2, 1};
HeapSort(arr);
for (auto it = arr.begin(); it != arr.end(); it++)
{
std::cout << *it << " ";
}
std::cout << std::endl;
} | true |
b5cb313a906f8425a76f494f15883b17db7c91eb | C++ | mikechen66/CPP-Programming | /CPP-Programming-Principles/chapter14-graphics-design/ch14_tools.cpp | UTF-8 | 4,034 | 3.296875 | 3 | [] | no_license | #include "./ch14_tools.h"
#include <iostream>
#include <cmath>
// Ex 1 - Smiley, Frowny
Smiley::Smiley (Point p, int r) :
Circle {p, r},
left {Point{p.x-r/3, p.y-r/3}, r / 4},
right {Point{p.x+r/3, p.y-r/3}, r / 4},
mouth {p, r*2/3, 200, 340} { }
void Smiley::draw_lines () const
{
Circle::draw_lines();
left.draw_lines();
right.draw_lines();
mouth.draw_lines();
}
Frowny::Frowny (Point p, int r) :
Circle {p, r},
left {Point{p.x-r/3, p.y-r/3}, r / 4},
right {Point{p.x+r/3, p.y-r/3}, r / 4},
mouth {Point{p.x, p.y+r*3/4}, r*2/3, 22, 157} { }
void Frowny::draw_lines () const
{
Circle::draw_lines();
left.draw_lines();
right.draw_lines();
mouth.draw_lines();
}
Smiley_hat::Smiley_hat (Point p, int r) :
Smiley {p, r},
hat {Point{p.x-r*3/4, p.y-r*5/4}, r*3/2, r/2}
{
hat.set_fill_color(Color::black);
}
void Smiley_hat::draw_lines () const
{
Smiley::draw_lines();
hat.draw_lines();
}
Frowny_hat::Frowny_hat (Point p, int r)
: Frowny {p, r}
{
hat.add(Point{p.x-r*3/4, p.y-r*3/4});
hat.add(Point{p.x+r*3/4, p.y-r*3/4});
hat.add(Point{p.x, p.y-r*3/2});
hat.set_fill_color(Color::yellow);
}
void Frowny_hat::draw_lines () const
{
Frowny::draw_lines();
hat.draw_lines();
}
// Ex 5 - Striped_rectangle
Striped_rectangle::Striped_rectangle (Point p, int ww, int hh, int ss)
: Rectangle{p, ww, hh}, sw{ss}
{
for (int i = p.y + ss; i < p.y + hh; i += ss)
stripes.add(Point{p.x, i}, Point{p.x + ww - 1, i});
}
void Striped_rectangle::set_stripe_color(Color col)
{
stripes.set_color(col);
}
void Striped_rectangle::draw_lines () const
{
stripes.draw();
Rectangle::draw_lines();
}
// Ex 6 - Striped_circle
Striped_circle::Striped_circle(Point p, int r, int ss)
: Circle{p, r}, sw{ss}
{
for (int i = p.y - r; i < p.y + r; i += ss) {
int x_mod = sqrt(pow(r, 2) - pow(p.y - i, 2));
stripes.add(Point{p.x - x_mod, i}, Point{p.x + x_mod, i});
}
}
void Striped_circle::draw_lines() const
{
stripes.draw_lines();
Circle::draw_lines();
}
// Ex 8 - Octagon
Octagon::Octagon(Point p, int rr)
: c{p}, r{rr}
{
for (int i = 0; i < 360; i += 45) { // <= creates 9 points to
int x = p.x + cos(i*PI/180) * rr; // close the shape (bad?)
int y = p.y + sin(i*PI/180) * rr;
add(Point{x, y});
}
}
// Ex 9 - Group
void Group::move(int dx, int dy)
{
for (int i = 0; i < vr.size(); ++i)
vr[i].move(dx, dy);
}
void Group::set_color(Color col)
{
for (int i = 0; i < vr.size(); ++i)
vr[i].set_color(col);
}
void Group::set_fill_color(Color col)
{
for (int i = 0; i < vr.size(); ++i)
vr[i].set_fill_color(col);
}
void Group::set_style(Line_style sty)
{
for (int i = 0; i < vr.size(); ++i)
vr[i].set_style(sty);
}
// Ex 10 - Pseudo_window
Pseudo_window::Pseudo_window(Point p, string url) :
viewport{p, 400, 250, 5},
button{Point{p.x + 360, p.y + 30}, 40, 20, "Next"},
content{Point{p.x + 40, p.y + 40}, url},
c1 {Point{p.x + 15, p.y + 15}, 10},
c2 {Point{p.x + 45, p.y + 15}, 10},
c3 {Point{p.x + 75, p.y + 15}, 10}
{
add(Point{p.x, p.y + 30});
add(Point{p.x + 400, p.y + 30});
c1.set_color(Color::red); // these don't work..
c2.set_color(Color::yellow);
c3.set_color(Color::green);
}
void Pseudo_window::draw_lines() const
{
viewport.draw_lines();
Shape::draw_lines();
button.draw_lines();
content.draw_lines();
c1.draw_lines();
c2.draw_lines();
c3.draw_lines();
}
/*
// Ex 11 - Binary_tree
Binary_tree::Binary_tree(Point p, int levels)
: l{levels}
{
int x_max = pow(2, levels - 1) * 2.5 * r;
int x_min = p.x - x_max / 2;
int y_min = p.y;
for (int i = 0; i < pow(2, levels) - 1; ++i) {
int level = log2(i + 1);
int x = x_min + x_max /
int y = p.y + log2(i + 1) * 4 * r;
nodes.push_back(Point{x, y});
}
}
*/
| true |
bdb70dbf0a0a7344b32907c70286e9d2e6f88545 | C++ | WesBach/PhysicsSoftBodies | /FirstOpenGL/MoveToDistanceTime.h | UTF-8 | 631 | 2.53125 | 3 | [] | no_license | #ifndef _MoveToDistanceTime_HG_
#define _MoveToDistanceTime_HG_
#include "iCommand.h"
#include <glm\vec3.hpp>
class cGameObject;
//Distance over time
class MoveToDistanceTime : public iCommand
{
public:
MoveToDistanceTime(glm::vec3 pointToMoveTo, cGameObject* theObjectToMove, float timeItShouldTake);
~MoveToDistanceTime();
virtual void update(double deltaTime);
virtual bool getDone();
cGameObject* theObjectToMove;
glm::vec3 distanceBetweenSections;
glm::vec3 posToMoveTo;
float timeToMove;
float accumulatedTime;
private:
bool isDone;
int currentSectionToProcess;
double initTime;
};
#endif // !_MoveTo_HG_
| true |
e904b1aea615d6717c3ed81b6485c512f1ab4ab8 | C++ | sibashish99/Algo-in-C-Cpp | /others/allPointsInaStraightLine.cpp | UTF-8 | 4,075 | 2.921875 | 3 | [] | no_license | #include<iostream>
#include <bits/stdc++.h>
#include<math.h>
using namespace std;
//Note this solution does not work for repeated inputs... pls refer to GeeksForGeeks
int coordinate(vector<int> x_cord, vector<int> y_cord)
{
int l = x_cord.size();
unordered_map<double, unordered_map<double,int>> map;
unordered_map<double, unordered_map<double, unordered_map<int,int>>> tracker;
unordered_set<double> set;
bool repeat=false;
int repeat_count=0;
/**{
* slope{
* c1:
* c2:
* c3:}
* slope2{
* c1:
* c2:
* c3}
* */
for(int i=0;i<l-1;i++)
{
for(int j = i+1;j<l;j++)
{
int x1 = x_cord[i];
int y1 = y_cord[i];
int x2 = x_cord[j];
int y2 = y_cord[j];
if(x2-x1==0)
{
map[90][x2]++;
set.insert(90);
}
else
{
double slope = (y2-y1)/(x2-x1);
if(slope==1)
{
cout<<x1<<","<<y1<<" "<<x2<<","<<y2<<endl;
}
double y_intercept = y2 - slope*x2;
set.insert(slope);
if(x1==x2 and y1==y2)
{
map[slope][y_intercept]++;
}
if(tracker.find(slope)!=tracker.end())
{
if(tracker[slope].find(y_intercept)!=tracker[slope].end())
{
if(tracker[slope][y_intercept].find(x1) != tracker[slope][y_intercept].end())
{
if(tracker[slope][y_intercept][x1]==y1)
{
continue;
}
}
// if(tracker[slope][y_intercept].find(x2) != tracker[slope][y_intercept].end())
// {
// if(tracker[slope][y_intercept][x2]==y2)
// {
// continue;
// }
// }
}
}
map[slope][y_intercept]++;
tracker[slope][y_intercept][x1]=y1;
// tracker[slope][y_intercept][x2]=y2;
}
}
}
int max_count= 0;
for(auto it=set.begin();it!=set.end();it++)
{
double slope = *it;
unordered_map<double,int> intercepts_count = map[slope];
cout<<"SLOPE: "<<slope<<endl;
for(auto it2=intercepts_count.begin();it2!=intercepts_count.end();it2++)
{
vector<double> intercepts;
intercepts.push_back(it2->first);
cout<<"Intercept : "<<it2->first<<" COUNT : "<<it2->second<<endl;
max_count = max(max_count, it2->second);
}
}
if(x_cord.size()==2)
{
if(x_cord[0]==0 and x_cord[1]==0 and y_cord[0]==0 and y_cord[1]==0)
{
return 2;
}
}
if(map.size()==1 and map.find(90)!=map.end() and x_cord.size()>2)
{
return max_count;
}
return max_count+1;
}
int main()
{
// vector<int> x{1,3,5,4,2,1};
// vector<int> y{1,2,3,1,3,4};
// vector<int> x{1,2,3};
// vector<int> y{1,2,3};
// vector<int> x{4,4,4};
// vector<int> y{0,-1,5};
// vector<int> x{0,0};
// vector<int> y{0,1};
// vector<int> x{1,1,2};
// vector<int> y{1,1,3};
vector<int> x{1,1,2,2};
vector<int> y{1,1,2,2};
cout<<coordinate(x,y)<<endl;
return 0;
} | true |
0321ef6ee517974c31e7c05c0cb4ed6a246e9a37 | C++ | markveligod/cpp_modules | /cpp_module_04/ex02/Squad.hpp | UTF-8 | 403 | 2.859375 | 3 | [] | no_license | #pragma once
/*
**==========================
** Includes
**==========================
*/
#include "ISquad.hpp"
class Squad: public ISquad
{
private:
int count;
ISpaceMarine **units;
public:
Squad();
Squad(Squad const &other);
virtual ~Squad();
Squad &operator=(Squad const &other);
int getCount() const;
ISpaceMarine* getUnit(int number) const;
int push(ISpaceMarine* unit);
};
| true |
f5f50fb16fd27ce46d158cbbdaa565d6f319dea5 | C++ | fernandovilarino/robolab | /Hand/Hand_code_COMPLETE/Hand_code_COMPLETE.ino | UTF-8 | 17,840 | 2.625 | 3 | [] | no_license | #include <Servo.h>
Servo myservo1;
Servo myservo2;
Servo myservo3;
Servo myservo4;
Servo myservo5;
const int FLEX1_PIN = A1; // Pin connected to voltage divider output A1
const int FLEX2_PIN = A2; //
const int FLEX3_PIN = A3; //
const int FLEX4_PIN = A4; //
const int FLEX5_PIN = A5; //
int modo; //MODE CONTROL
//MODO = 0 --> MIMIC MODE
//MODO = 1 --> TRANSITION TO PAPER ROCK SCISSORS WIN MODE
//MODO = 2 --> PAPER ROCK SCISSORS WIN MODE
//MODO = 3 --> TRANSITION TO PAPER ROCK SCISSORS LOSE MODE
//MODO = 4 --> PAPER ROCK SCISSORS LOSE MODE
//MODO = 5 --> TRANSITION TO PAPER ROCK SCISSORS NORMAL MODE
//MODO = 6 --> PAPER ROCK SCISSORS NORMAL MODE
//MODO = 7 --> TRANSITION TO MIMIC MODE
int count_MODO1; // COUNT USED BY CONTROL THE MODE 1 TRANSITION START
int count_MODO3; // COUNT USED BY CONTROL THE MODE 3 TRANSITION START
int count_MODO5; // COUNT USED BY CONTROL THE MODE 5 TRANSITION START
int count_ROCK;
bool is_ROCK;
int count_PAPER;
bool is_PAPER;
int count_SCISSORS;
bool is_SCISSORS;
#define min_pos 0
#define max_pos 100
// twelve servo objects can be created on most boards
// Measure the voltage at 5V and the actual resistance of your
// 47k resistor, and enter them below:
const float VCC = 4.98; // Measured voltage of Ardunio 5V line
const float R_DIV = 20000.0; // Measured resistance of 3.3k resistor
//const float R_DIV = 20000.0;
// Upload the code, then try to adjust these values to more
// accurately calculate bend degree.
const float STRAIGHT_RESISTANCE = 2200; // resistance when straight
const float BEND_RESISTANCE = 1000; // resistance at 90 deg
int pos = 0; // variable to store the servo position
bool end_game = 0;
void setup() {
Serial.begin(9600); // serial used for testing.
myservo1.attach(4); // attaches the servo on pin 9 to the servo object
myservo2.attach(5);
myservo3.attach(7);
myservo4.attach(6);
myservo5.attach(8);
pinMode(FLEX1_PIN, INPUT);
pinMode(FLEX2_PIN, INPUT);
pinMode(FLEX3_PIN, INPUT);
pinMode(FLEX4_PIN, INPUT);
pinMode(FLEX5_PIN, INPUT);
count_MODO1 = 0;
count_MODO3 = 0;
count_MODO5 = 0;
count_ROCK;
modo = 0;
is_ROCK = false;
is_PAPER = false;
is_SCISSORS = false;
}
void loop() {
int flex1ADC = analogRead(FLEX1_PIN);
int flex2ADC = analogRead(FLEX2_PIN);
int flex3ADC = analogRead(FLEX3_PIN);
int flex4ADC = analogRead(FLEX4_PIN);
int flex5ADC = analogRead(FLEX5_PIN);
//SERVO 1
float flexV = flex1ADC * VCC / 1023.0;
float flexR = R_DIV * (VCC / flexV - 1.0);
float angle1 = map(flexR, STRAIGHT_RESISTANCE, BEND_RESISTANCE, 0, 90.0);
// SERVO 2
flexV = flex2ADC * VCC / 1023.0;
flexR = R_DIV * (VCC / flexV - 1.0);
float angle2 = map(flexR, STRAIGHT_RESISTANCE, BEND_RESISTANCE, 0, 90.0);
//SERVO 3
flexV = flex3ADC * VCC / 1023.0;
flexR = R_DIV * (VCC / flexV - 1.0);
//Serial.println(flexR);
float angle3 = map(flexR, STRAIGHT_RESISTANCE, BEND_RESISTANCE, 0, 90.0);
//SERVO 4
flexV = flex4ADC * VCC / 1023.0;
flexR = R_DIV * (VCC / flexV - 1.0);
float angle4 = map(flexR, STRAIGHT_RESISTANCE, BEND_RESISTANCE, 0, 90.0);
//SERVO 5
flexV = flex5ADC * VCC / 1023.0;
flexR = R_DIV * (VCC / flexV - 1.0);
float angle5 = map(flexR, STRAIGHT_RESISTANCE, BEND_RESISTANCE, 0, 90.0);
if (modo == -1)
{
myservo1.write(0);
delay(50);
myservo2.write(0);
delay(50);
myservo3.write(0);
delay(50);
myservo4.write(0);
delay(50);
myservo5.write(0);
delay(50);
}
////////////////////////////////////MODE 0 MIMIC MODE: THE HAND MIMICS THE GLOVE'S FINGER POSITION////////////////////////////////////////////////
if (modo == 0)
{
//ANALOG READ
if (angle1 >= 20) myservo1.write(angle1) ;
else myservo1.write(0);
delay(50);
if (angle2 >= 20) myservo2.write(angle2);
else myservo2.write(0);
delay(50);
if (angle3 >= 20) myservo3.write(angle3);
else myservo3.write(0);
delay(50);
if (angle4 >= 20) myservo4.write(angle4);
else myservo4.write(0);
delay(50);
if (angle5 >= 20) myservo5.write(angle5);
else myservo5.write(0);
delay(50);
}
////////////////////////////////////MODE 1 TRANSITION TO PAPER ROCK SCISSORS WIN MODE////////////////////////////////////////////////
if (modo == 1)
{
count_MODO1 = 0;
modo = 2;
myservo1.write(0);
delay(50);
myservo2.write(0);
delay(50);
myservo3.write(0);
delay(50);
myservo4.write(0);
delay(50);
myservo5.write(0);
delay(50);
myservo1.write(100);
delay(1000);
myservo1.write(0);
delay(1000);
myservo2.write(100);
delay(1000);
myservo2.write(0);
delay(1000);
myservo3.write(100);
delay(1000);
myservo3.write(0);
delay(1000);
myservo4.write(100);
delay(1000);
myservo4.write(0);
delay(1000);
myservo5.write(100);
delay(1000);
myservo5.write(0);
delay(2000);
is_PAPER = false;
is_ROCK = false;
is_SCISSORS = false;
}
////////////////////////////////////MODE 2 PAPER ROCK SCISSORS WIN MODE////////////////////////////////////////////////
if (modo == 2)
{
if (is_ROCK)
{ myservo1.write(0);
delay(50);
myservo2.write(0);
delay(50);
myservo3.write(0);
delay(50);
myservo4.write(0);
delay(50);
myservo5.write(0);
delay(50);
is_ROCK = false;
modo = 0;
}
if (is_PAPER)
{ myservo1.write(100);
delay(50);
myservo2.write(0);
delay(50);
myservo3.write(100);
delay(50);
myservo4.write(0);
delay(50);
myservo5.write(100);
delay(50);
delay(2000);
myservo2.write(0);
delay(50);
myservo3.write(0);
delay(50);
is_PAPER = false;
modo = 0;
}
if (is_SCISSORS)
{
myservo2.write(100);
delay(50);
myservo3.write(100);
delay(50);
myservo4.write(100);
delay(50);
myservo5.write(100);
delay(50);
myservo1.write(100);
delay(50);
delay(2000);
myservo1.write(0);
delay(50);
myservo2.write(0);
delay(50);
myservo3.write(0);
delay(50);
myservo4.write(0);
delay(50);
myservo5.write(0);
delay(50);
is_SCISSORS = false;
modo = 0;
}
}
////////////////////////////////////MODE 3 TRANSITION TO PAPER ROCK SCISSORS LOSE MODE////////////////////////////////////////////////
if (modo == 3)
{
count_MODO3 = 0;
modo = 4;
myservo5.write(0);
delay(50);
myservo4.write(0);
delay(50);
myservo3.write(0);
delay(50);
myservo2.write(0);
delay(50);
myservo1.write(0);
delay(50);
myservo5.write(100);
delay(1000);
myservo5.write(0);
delay(1000);
myservo4.write(100);
delay(1000);
myservo4.write(0);
delay(1000);
myservo3.write(100);
delay(1000);
myservo3.write(0);
delay(1000);
myservo2.write(100);
delay(1000);
myservo2.write(0);
delay(1000);
myservo1.write(100);
delay(1000);
myservo1.write(0);
is_PAPER = false;
is_ROCK = false;
is_SCISSORS = false;
}
////////////////////////////////////MODE 4 PAPER ROCK SCISSORS LOSE MODE////////////////////////////////////////////////
if (modo == 4)
{
if (is_SCISSORS)
{ myservo1.write(0);
delay(50);
myservo2.write(0);
delay(50);
myservo3.write(0);
delay(50);
myservo4.write(0);
delay(50);
myservo5.write(0);
delay(50);
is_SCISSORS = false;
modo = 0;
}
if (is_ROCK)
{ myservo1.write(0);
delay(50);
myservo2.write(100);
delay(50);
myservo3.write(0);
delay(50);
myservo4.write(100);
delay(50);
myservo5.write(0);
delay(50);
delay(2000);
myservo2.write(0);
delay(50);
myservo3.write(0);
delay(50);
is_ROCK = false;
modo = 0;
}
if (is_PAPER)
{
myservo2.write(100);
delay(50);
myservo3.write(100);
delay(50);
myservo4.write(100);
delay(50);
myservo5.write(100);
delay(50);
myservo1.write(100);
delay(50);
delay(2000);
myservo1.write(0);
delay(50);
myservo2.write(0);
delay(50);
myservo3.write(0);
delay(50);
myservo4.write(0);
delay(50);
myservo5.write(0);
delay(50);
is_PAPER = false;
modo = 0;
}
}
////////////////////////////////////MODE 5 TRANSITION TO PAPER ROCK SCISSORS NORMAL MODE////////////////////////////////////////////////
if (modo == 5)
{
count_MODO3 = 0;
modo = 6;
myservo5.write(0);
delay(50);
myservo4.write(0);
delay(50);
myservo3.write(0);
delay(50);
myservo2.write(0);
delay(50);
myservo1.write(0);
delay(50);
myservo5.write(100);
delay(1000);
myservo4.write(100);
delay(1000);
myservo5.write(0);
delay(1000);
myservo4.write(0);
delay(1000);
is_PAPER = false;
is_ROCK = false;
is_SCISSORS = false;
}
////////////////////////////////////MODE 6 PAPER ROCK SCISSORS NORMAL MODE////////////////////////////////////////////////
if (modo == 6)
{
int randpos = random(3);
Serial.println("Numero random: ");
Serial.println(randpos);
if (is_PAPER == true || is_ROCK == true || is_SCISSORS == true)
{
if (randpos == 0) //execute ROCK
{
Serial.println("Executant posicio ROCK ");
myservo1.write(100);
delay(50);
myservo2.write(100);
delay(50);
myservo3.write(100);
delay(50);
myservo4.write(100);
delay(50);
myservo5.write(100);
delay(50);
delay(2000);
Serial.println("Reiniciant posicio ");
myservo1.write(0);
delay(50);
myservo2.write(0);
delay(50);
myservo3.write(0);
delay(50);
myservo4.write(0);
delay(50);
myservo5.write(0);
delay(50);
if (is_SCISSORS==true){
Serial.println("Win");
myservo1.write(0);
delay(50);
myservo2.write(100);
delay(50);
myservo3.write(100);
delay(50);
myservo4.write(100);
delay(50);
myservo5.write(100);
delay(50);
delay(2000);
}else if(is_PAPER==true){
myservo1.write(100);
delay(50);
myservo2.write(100);
delay(50);
myservo3.write(0);
delay(50);
myservo4.write(100);
delay(50);
myservo5.write(100);
delay(50);
delay(2000);
}else{
myservo1.write(0);
delay(50);
myservo2.write(100);
delay(50);
myservo3.write(100);
delay(50);
myservo4.write(100);
delay(50);
myservo5.write(0);
delay(50);
delay(2000);
}
myservo1.write(0);
delay(50);
myservo2.write(0);
delay(50);
myservo3.write(0);
delay(50);
myservo4.write(0);
delay(50);
myservo5.write(0);
delay(50);
}
if (randpos == 1) // execute SCISSORS
{
Serial.println("Executant posicio SCISSORS ");
myservo1.write(100);
delay(50);
myservo2.write(0);
delay(50);
myservo3.write(100);
delay(50);
myservo4.write(0);
delay(50);
myservo5.write(100);
delay(50);
delay(2000);
Serial.println("Reiniciant posicio ");
myservo2.write(0);
delay(50);
myservo3.write(0);
delay(50);
if (is_PAPER==true){
Serial.println("Win");
myservo1.write(0);
delay(50);
myservo2.write(100);
delay(50);
myservo3.write(100);
delay(50);
myservo4.write(100);
delay(50);
myservo5.write(100);
delay(50);
delay(2000);
}else if(is_ROCK==true){
myservo1.write(100);
delay(50);
myservo2.write(100);
delay(50);
myservo3.write(0);
delay(50);
myservo4.write(100);
delay(50);
myservo5.write(100);
delay(50);
delay(2000);
}else{
myservo1.write(0);
delay(50);
myservo2.write(100);
delay(50);
myservo3.write(100);
delay(50);
myservo4.write(100);
delay(50);
myservo5.write(0);
delay(50);
delay(2000);
}
myservo1.write(0);
delay(50);
myservo2.write(0);
delay(50);
myservo3.write(0);
delay(50);
myservo4.write(0);
delay(50);
myservo5.write(0);
delay(50);
}
if (randpos == 2) // exeute PAPER
{
Serial.println("Executant posicio PAPER ");
myservo1.write(0);
delay(50);
myservo2.write(0);
delay(50);
myservo3.write(0);
delay(50);
myservo4.write(0);
delay(50);
myservo5.write(0);
delay(50);
delay(2000);
if (is_ROCK==true){
Serial.println("Win");
myservo1.write(0);
delay(50);
myservo2.write(100);
delay(50);
myservo3.write(100);
delay(50);
myservo4.write(100);
delay(50);
myservo5.write(100);
delay(50);
delay(2000);
}else if(is_SCISSORS==true){
myservo1.write(100);
delay(50);
myservo2.write(100);
delay(50);
myservo3.write(0);
delay(50);
myservo4.write(100);
delay(50);
myservo5.write(100);
delay(50);
delay(2000);
}else{
myservo1.write(0);
delay(50);
myservo2.write(100);
delay(50);
myservo3.write(100);
delay(50);
myservo4.write(100);
delay(50);
myservo5.write(0);
delay(50);
delay(2000);
}
myservo1.write(0);
delay(50);
myservo2.write(0);
delay(50);
myservo3.write(0);
delay(50);
myservo4.write(0);
delay(50);
myservo5.write(0);
delay(50);
}
is_SCISSORS = false;
is_ROCK = false;
is_PAPER = false;
modo = 0;
delay(2000);
}
}
////////////////////////////////////ANGLE DETECTION////////////////////////////////////////////////
//Calibration-------------------------------<<<<
//Angle1
int Max1 = 100;
int Min1 = 30;
//Angle2
int Max2 = 90;
int Min2 = 10;
//Angle3
int Max3 = 90;
int Min3 = 10;
//Angle4
int Max4 = 110;
int Min4 = 65;
//Angle5
int Max5 = 90;
int Min5 = 10;
if (angle1 > Max1 && angle2 < Min2 && angle3 < Min3 && angle4 < Min4 && angle5 < Min5 && modo != 1 && modo != 3 && modo != 5 ) count_MODO1 = count_MODO1 + 1;
else count_MODO1 = 0;
if (angle1 < Min1 && angle2 > Max2 && angle3 < Min3 && angle4 < Min4 && angle5 < Min5 && modo != 1 && modo != 3 && modo != 5) count_MODO3 = count_MODO3 + 1;
else count_MODO3 = 0;
if (angle1 < Min1 && angle2 < Min2 && angle3 > Min3 && angle4 < Min4 && angle5 < Max5 && modo != 1 && modo != 3 && modo != 5) count_MODO5 = count_MODO5 + 1;
else count_MODO5 = 0;
if (angle1 > Max1 && angle2 > Max2 && angle3 > Max3 && angle4 > Max4 && angle5 > Max5 && (modo == 2 || modo == 4 || modo == 6)) count_ROCK = count_ROCK + 1;
else count_ROCK = 0;
if (angle1 < Min1 && angle2 < Min2 && angle3 < Min3 && angle4 < Min4 && angle5 < Min5 && (modo == 2 || modo == 4 || modo == 6)) count_PAPER = count_PAPER + 1;
else count_PAPER = 0;
if (angle1 < Min1 && angle2 > Max2 && angle3 > Min3 && angle4 < Max4 && angle5 < Min5 && (modo == 2 || modo == 4 || modo == 6)) count_SCISSORS = count_SCISSORS + 1;
else count_SCISSORS = 0;
if (count_ROCK >= 20) is_ROCK = true;
if (count_PAPER >= 20) is_PAPER = true;
if (count_SCISSORS >= 20) is_SCISSORS = true;
Serial.println("executing Mode : ");
Serial.println(modo);
Serial.println(count_MODO1);
Serial.println(count_MODO3);
Serial.println(count_MODO5);
/**/
Serial.println("Figure Count : ");
Serial.println("Rock, Paper, Sissors");
Serial.println(count_ROCK);
Serial.println(count_PAPER);
Serial.println(count_SCISSORS);
Serial.println("Angle Detection : ");
Serial.print("Angulo1 = ");
Serial.println(angle1);
Serial.print("Angulo2 = ");
Serial.println(angle2);
Serial.print("Angulo3 = ");
Serial.println(angle3);
Serial.print("Angulo4 = ");
Serial.println(angle4);
Serial.print("Angulo5 = ");
Serial.println(angle5);
if (count_MODO1 >= 20) modo = 1;
if (count_MODO3 >= 20) modo = 3;
if (count_MODO5 >= 20) modo = 5;
//modo = 0;
}
| true |
e2fe6ed59ffc9e58e47a1ef5336ccc8fcf7c100b | C++ | shubhampal39/Coding-blockk-CPP | /number theory/gcd.cpp | UTF-8 | 245 | 3.09375 | 3 | [] | no_license | #include<iostream>
using namespace std;
int gcd(int a,int b)
{
if(b==0)
{
return a;
}
return gcd(b,a%b);
}
int main()
{
int a,b;
cin>>a>>b;
int n=gcd(a,b);
cout<<"gcd"<<n<<endl;
cout<<"lcm:"<<(a*b)/n<<endl;
return 0;
} | true |
18a39f125102dff29b7ad305bad314972bfb34a7 | C++ | genie97/ALGORITHM | /BOJ_ALGORITHM/15649_N과 M (1).cpp | UTF-8 | 447 | 2.796875 | 3 | [] | no_license | #include<cstdio>
#include<vector>
using namespace std;
int num[9] = {0,};
int N, M;
vector<int> vt;
void make_perm(int cnt) {
if (cnt == M) {
for (int i = 0; i < vt.size(); i++) {
printf("%d ", vt[i]);
}
printf("\n");
return;
}
for (int i = 1; i <= N; i++) {
if (num[i] == 1)continue;
vt.push_back(i);
num[i] = 1;
make_perm(cnt + 1);
num[i] = 0;
vt.pop_back();
}
}
int main() {
scanf("%d %d", &N, &M);
make_perm(0);
}
| true |
defa82e949b6318f018921308b036a4c2738c795 | C++ | Paradixes/Data_Structure_Based_on_Cpp | /Priority_Calculator/main.cpp | UTF-8 | 1,876 | 3.53125 | 4 | [] | no_license | #include "Calculator.h"
using namespace std;
bool IsExp(string& x);
bool isopt(char& x);
int main()
{
int alter = 1;
while (alter != 0)
{
system("cls");
string Exp;
cout << "Please input an expression you want to calculate:\n" << " ";
getline(cin, Exp);
if (!IsExp(Exp))
{
cerr << "Wrong Expression! Input any char to continue" << endl;
cin >> alter;
cin.ignore(numeric_limits<std::streamsize>::max(), '\n');
continue;
}
//Exp = "1 + (2 + 3 * (4 / 2 - 6)) - (2 / (3 + 4 * (32 - 7)) + 5)";
TMyExp Test(Exp);
cout << Test.Solve();
cout << "\nDo you want to continue?(0/1)\n";
cin >> alter;
cin.ignore(numeric_limits<std::streamsize>::max(), '\n');
}
return 0;
}
bool IsExp(string& x)
{
size_t x_Length = x.length();
int n = 0, m = 0;
for (int i = 0; i < x_Length; i++)
{
if (x[i] == '(')
n++;
else if (x[i] == ')')
m++;
}
if (n != m)
return false;
for (int i = 0; i < x_Length; i++)
{
if (!isopt(x[i]) && !isdigit(x[i]) && x[i] != ' ' && x[i] != '.' && x[i] != '(' && x[i] != ')')
return false;
else if (isopt(x[i]))
{
if (!isdigit(x[i + 1]) && x[i + 1] != '(' && x[i + 1] != ' ' && x[i + 1] != '.')
return false;
}
else if (x[i] == '(')
{
if (x[i + 1] != '-' && x[i + 1] != '+' && !isdigit(x[i + 1]) && x[i + 1] != ' ')
return false;
}
else if (x[i] == ')')
{
if (i < x_Length - 1)
if (!isopt(x[i + 1]) && x[i + 1] != ' ' && x[i + 1] != ')')
return false;
}
else if (isdigit(x[i]))
{
if (x[i + 1] == '(')
return false;
}
else if (x[i] == '.')
{
if (x[i + 1] == '(')
return false;
for (int j = i + 1; j < x_Length && isdigit(x[j]) || x[j] == '.'; j++)
if (x[j] == '.')
return false;
}
}
return true;
}
bool isopt(char& x)
{
switch (x)
{
case'*':
case'/':
case'+':
case'-':return true;
default:return false;
}
} | true |
c2461447b90087d7825336352e419dcb9ee77b03 | C++ | dddddhow/ResolutionAnalysis | /src/inc/sub_tools.h | UTF-8 | 2,085 | 2.59375 | 3 | [] | no_license | #pragma once
/****************************************************************************
* Filename : sub_tools.h
*
* Author : Sheng Shen
* WPI,Tongji university
*
* Copyright : 2021-
*
* Date : 2021.09.01
*
* Description:
* 程序所涉及到的一系列子函数的头文件,主要包括:
* (1) 高斯窗函数 : void shen_gauss()
* (2) Hanning窗函数 : void shen_hanning()
* (3) 高斯平滑函数 : void shen_gauss_smooth_1d()
* (4) Ricker子波函数 : shen_ricker()
*
* Last modified:
*
*****************************************************************************/
#include <iostream>
#include "TJU_SHEN_2019.h"
//---------------------------------------------------------------------------//
//gauss window function 高斯窗函数
// N : length of window [input]
// win : hanning window vector [output]
void shen_gauss(int N, float theta, arma::fvec &win);
//---------------------------------------------------------------------------//
//hanning window function Hanning窗函数
//Input :
// N : length of window [input]
// win : hanning window vector [output]
void shen_hanning(int N, arma::fvec &win);
//---------------------------------------------------------------------------//
//gauss smooth function 高斯平滑函数
// s_in : signal [input]
// N : length of window [input]
// s_out: signal [output]
//
// notice :
// shen_gauss() is needed
void shen_gauss_smooth_1d(arma::fvec &s_in, int nwin_in, arma::fvec &s_out);
//---------------------------------------------------------------------------//
//Ricker wavelet Ricker子波
// nw : length of ricker wavelet [input]
// dt : sample interval [input]
// fre: main frequency [input]
// w : ricker wavelet [output]
void shen_ricker(int nw, float dt, float fre, arma::fvec &w);
//---------------------------------------------------------------------------//
| true |
90210c31cf3e94052e893cefe8fd870b30103baf | C++ | seflopod/PBJsimple | /include/be/bed/stmt.h | UTF-8 | 2,687 | 2.578125 | 3 | [] | no_license | ///////////////////////////////////////////////////////////////////////////////
/// \file be/bed/stmt.h
/// \author Benjamin Crist
///
/// \brief be::bed::Stmt class header.
#ifndef BE_BED_STMT_H_
#define BE_BED_STMT_H_
#include "be/_be.h"
#include <glm/glm.hpp>
#include <string>
#include <memory>
#include <unordered_map>
#include <cassert>
#include <ostream>
#include "sqlite3.h"
#include "be/bed/db.h"
#include "be/id.h"
namespace be {
namespace bed {
///////////////////////////////////////////////////////////////////////////////
/// \class Stmt be/bed/stmt.h "be/bed/stmt.h"
///
/// \brief RAII wrapper for SQLite's sqlite3_stmt API.
/// \details Stmt objects are non-copyable and non-moveable and represent a
/// prepared statement -- a compiled SQL query -- along with its
/// currently bound parameters and the resultset returned when the
/// query is executed.
/// \ingroup db
class Stmt
{
public:
Stmt(Db& db, const std::string& sql);
Stmt(Db& db, const Id& id, const std::string& sql);
~Stmt();
Db& getDb();
const Id& getId() const;
const char* getSql() const;
int parameters();
int parameter(const std::string& name);
void bind();
void bind(int parameter);
void bind(int parameter, bool value);
void bind(int parameter, int value);
void bind(int parameter, unsigned int value);
void bind(int parameter, sqlite3_int64 value);
void bind(int parameter, sqlite3_uint64 value);
void bind(int parameter, double value);
void bind(int parameter, const std::string& value);
void bind(int parameter, const char* value);
void bind_s(int parameter, const char* value);
void bindBlob(int parameter, const std::string& value);
void bindBlob(int parameter, const void* value, int length);
void bindBlob_s(int parameter, const void* value, int length);
void bindColor(int parameter, const glm::vec4& color);
bool step();
void reset();
int columns();
int column(const std::string& name);
int getType(int column);
bool getBool(int column);
int getInt(int column);
unsigned int getUInt(int column);
sqlite3_int64 getInt64(int column);
sqlite3_uint64 getUInt64(int column);
double getDouble(int column);
const char* getText(int column);
std::string getBlob(int column);
int getBlob(int column, const void*& dest);
glm::vec4 getColor(int column);
private:
Db& db_;
Id id_;
sqlite3_stmt* stmt_;
std::unique_ptr<std::unordered_map<std::string, int> > col_names_;
Stmt(const Stmt&);
void operator=(const Stmt&);
};
std::ostream& operator<<(std::ostream& os, const Stmt& s);
} // namespace be::bed
} // namespace be
#endif
| true |
a4f9cd133f4c3a479b13e54de589a4718767d906 | C++ | mariyaveleva16/OOP | /HW1/3/main.cpp | UTF-8 | 588 | 3.234375 | 3 | [] | no_license | #include "Header.h"
int main()
{
int a;
std::cout << "Enter how many rectangles you want to have in the list: ";
std::cin >> a;
double b;
double* arr;
arr = new double[a + 1];
double max = -1;
int index = 0;
for (int i = 0; i < a; i++)
{
SVG p; SVG q;
p.read();
std::cout << "Rectangle " << i << " p";
p.print();
std::cout << std::endl;
q.read();
std::cout << "Rectangle " << i << " q";
q.print();
std::cout << std::endl;
b = p.s(q);
arr[i] = b;
if (max < arr[i])
{
max = arr[i];
index = i;
}
}
std::cout << "Index=" << index;
return 0;
}
| true |
7797ef60fc4ca5c8fd4803a270d4799ec59a0b3e | C++ | TheMarlboroMan/cheap-shooter | /class/aplicacion/escudo/escudo.cpp | UTF-8 | 6,701 | 2.59375 | 3 | [] | no_license | #include "escudo.h"
const float Escudo::MS_DESPLIEGUE_ESCUDO=500.0f; //Tiempo que tarda en desplegarse plenamente.
const float Escudo::GASTO_CARGA_SEG=250.0f; //Carga gastada en un segundo.
const float Escudo::RECUPERACION_CARGA_SEG=150.0f; //Carga recuperada en un segundo.
Escudo::Escudo()
:
//recurso(NULL),
angulo(0.0f), angulo_despliegue(ANGULO),
multiplicador_despliegue(0.0f),
partes_actuales(CANTIDAD_PARTES), estado(E_ACTIVO),
max_carga_escudo(MAX_CARGA_INICIAL), carga_escudo_actual(MAX_CARGA_INICIAL),
activo(false)
{
//Generar el recurso gráfico...
//this->generar_recurso_grafico();
//Construir el vector de partes.
this->construir_vector_de_partes();
this->posicion.x=0;
this->posicion.y=0;
this->posicion.w=0;
this->posicion.h=0;
}
Escudo::~Escudo()
{
this->destruir_vector_de_partes();
}
void Escudo::construir_vector_de_partes()
{
this->destruir_vector_de_partes();
unsigned int i=0;
while(i<partes_actuales)
{
this->partes.push_back(new Escudo_parte());
i++;
}
this->iterador_turno=this->partes.begin();
this->iterador_colision=this->partes.begin();
this->iterador_representacion=this->partes.begin();
this->iterador_fin=this->partes.end();
}
void Escudo::destruir_vector_de_partes()
{
//Destruir el vector de partes.
this->iterador_turno=this->partes.begin();
this->iterador_fin=this->partes.end();
while(this->iterador_turno < this->iterador_fin)
{
delete (*this->iterador_turno);
++this->iterador_turno;
}
this->partes.clear();
}
void Escudo::establecer_posicion()
{
this->posicion_desde_coordenadas_propias();
}
void Escudo::procesar_turno(float p_delta)
{
if(!this->activo)
{
if(this->carga_escudo_actual < this->max_carga_escudo)
{
this->carga_escudo_actual+=(RECUPERACION_CARGA_SEG) * p_delta;
if(this->carga_escudo_actual > this->max_carga_escudo) this->carga_escudo_actual=this->max_carga_escudo;
}
}
else
{
if(this->carga_escudo_actual <=0)
{
this->estado=E_CIERRE;
this->carga_escudo_actual=0.0f;
}
else
{
float gasto=(GASTO_CARGA_SEG) * p_delta;
this->carga_escudo_actual-=gasto;
}
//Si delta vale MS_DESPLIEGUE_ESCUDO / 1000 es que ha pasado el
//tiempo necesario para el despliegue del escudo. De ahí podemos
//sacar la norma de crecimiento.
float factor=(MS_DESPLIEGUE_ESCUDO / 100) * p_delta;
switch(this->estado)
{
case E_DESPLIEGUE:
this->multiplicador_despliegue+=factor;
if(this->multiplicador_despliegue >= 1.0f)
{
this->multiplicador_despliegue=1.0f;
this->estado=E_ACTIVO;
}
break;
case E_ACTIVO:
break;
case E_CIERRE:
this->multiplicador_despliegue-=factor;
if(this->multiplicador_despliegue <= 0.0f)
{
this->multiplicador_despliegue=0.0f;
this->estado=E_DESPLIEGUE;
this->activo=false;
this->establecer_transparencia_partes(Escudo_parte::ALPHA_INACTIVO);
}
break;
}
}
// if(this->partes.size())
// {
this->procesar_turno_escudos(p_delta);
// }
}
void Escudo::establecer_transparencia_partes(unsigned short int alpha)
{
this->iterador_turno=this->partes.begin();
while(this->iterador_turno < this->iterador_fin)
{
(*iterador_turno)->establecer_transparencia(alpha);
++this->iterador_turno;
}
}
void Escudo::procesar_turno_escudos(float p_delta)
{
this->iterador_turno=this->partes.begin();
//Si no está activo veríamos como estaría desplegado.
float multiplicador_despliegue=this->activo ? this->multiplicador_despliegue : 1;
//Se despliega de izquierda a derecha.
float mitad_angulo=this->angulo_despliegue / 2;
float angulo=this->angulo-mitad_angulo;
//Dividimos en arco en tantas partes como puntos haya menos uno, para que haya un punto en cada corte.
float salto=(this->angulo_despliegue / (this->partes_actuales-1)) * multiplicador_despliegue;
int x=0, y=0;
//Establecer la posición de cada una de las partes.
while(this->iterador_turno < this->iterador_fin)
{
x=cos(DLibH::Herramientas::grados_a_radianes(angulo))*DISTANCIA;
y=sin(DLibH::Herramientas::grados_a_radianes(angulo))*DISTANCIA;
x+=this->x-(Escudo_parte::W / 2);
y+=this->y-(Escudo_parte::H / 2);
(*iterador_turno)->ir_a(x, y);
angulo+=salto;
++this->iterador_turno;
}
}
void Escudo::establecer_posicion_y_angulo_desde_actores(const Actor& p_actor_pos, const Actor& p_actor_angulo)
{
int w=p_actor_pos.acc_w() / 2;
int h=p_actor_pos.acc_h() / 2;
this->establecer_posicion_desde_actor(p_actor_pos, w, h);
//Establecer el ángulo a partir de la posición de la mirilla...
float pos_ax=p_actor_pos.acc_x_centro();
float pos_ay=p_actor_pos.acc_y_centro();
float pos_bx=p_actor_angulo.acc_x_centro();
float pos_by=p_actor_angulo.acc_y_centro();
DLibH::Vector_2d v=DLibH::Vector_2d::obtener_para_puntos(pos_bx, pos_by, pos_ax, pos_ay);
this->angulo=DLibH::Vector_2d::obtener_angulo_para_vector_unidad_grados(v);
}
void Escudo::reiniciar_pasos_representacion()
{
this->iterador_representacion=this->partes.begin();
}
DLibV::Representacion * Escudo::acc_representacion()
{
if(this->iterador_representacion==this->iterador_fin)
{
return NULL;
}
else
{
DLibV::Representacion * resultado=(*iterador_representacion)->acc_representacion();
++iterador_representacion;
return resultado;
}
}
bool Escudo::comprobar_colision_con(const Proyectil& p_pr)
{
this->iterador_colision=this->partes.begin();
//Comprobar con cada uno de los escudos...
while(this->iterador_colision < this->iterador_fin)
{
if( (*iterador_colision)->en_colision_con(p_pr))
{
return true;
}
++this->iterador_colision;
}
return false;
}
void Escudo::reiniciar()
{
this->multiplicador_despliegue=0.0f;
this->partes_actuales=CANTIDAD_PARTES;
this->estado=E_ACTIVO;
this->max_carga_escudo=MAX_CARGA_INICIAL;
this->carga_escudo_actual=MAX_CARGA_INICIAL;
this->angulo_despliegue=ANGULO;
this->activo=false;
this->construir_vector_de_partes();
}
bool Escudo::desactivar()
{
this->estado=E_CIERRE;
return true;
}
bool Escudo::activar()
{
if(!this->es_usable())
{
this->activo=false;
return false;
}
else
{
this->activo=true;
this->estado=E_DESPLIEGUE;
this->establecer_transparencia_partes(Escudo_parte::ALPHA_ACTIVO);
return true;
}
}
bool Escudo::sumar_duracion()
{
if(this->max_carga_escudo==MAX_CARGA_AMPLIADA)
{
return false;
}
else
{
this->max_carga_escudo+=CANTIDAD_CARGA_AMPLIADA;
return true;
}
}
bool Escudo::sumar_escudos()
{
if(this->partes_actuales==MAX_CANTIDAD_PARTES)
{
return false;
}
else
{
this->partes_actuales+=CANTIDAD_PARTES_AMPLIADO;
this->angulo_despliegue+=CANTIDAD_ANGULO_AMPLIADO;
this->construir_vector_de_partes();
return true;
}
}
| true |
c5749fdb6d06e01deafe31ea075f99bf3784f447 | C++ | yhondri/EDA | /2_3/juez/2_cuatrimestre/juez39/juez39/BookShop.h | UTF-8 | 4,022 | 2.9375 | 3 | [] | no_license | //
// BookShop.h
// juez39
//
// Created by Yhondri on 24/05/2019.
// Copyright © 2019 yhondri. All rights reserved.
//
#ifndef BookShop_h
#define BookShop_h
#include <iostream>
#include <fstream>
#include <map>
#include <unordered_map>
#include <list>
#include <stdexcept>
#include <sstream> // std::stringstream
using namespace std;
using bookId = string;
struct bookInfo {
private:
bookId mBookId;
int ejemplares;
int numEjemplaresVendidos;
list<bookId>:: iterator itBook;
public:
bookInfo() = default;
bookInfo(bookId newId, int n) : mBookId(newId), ejemplares(n), numEjemplaresVendidos(0) {
}
int getEjemplares() const {
return ejemplares;
}
void setEjemplares(int n) {
this->ejemplares = n;
}
list<bookId>:: iterator getItLista() {
return itBook;
}
void setItLista(list<bookId>:: iterator it) {
this->itBook = it;
}
int getEjemplaresVendidos() const {
return numEjemplaresVendidos;
}
void annadirEjemplarVendido() {
numEjemplaresVendidos++;
}
};
class bookShop {
private:
unordered_map<bookId, bookInfo> booksMap;
// map<int, list<bookId>> ventasMap;
list<bookId> ventasList;
public:
bookShop() {};
void nuevoLibro(int ejemplares, bookId libro) {
if (booksMap.count(libro) == 0) {
// list<bookId> &lista = ventasMap[0];
// list<bookId>:: iterator insertResult = ventasList.insert(ventasList.begin(), libro);
booksMap[libro] = bookInfo(libro, ejemplares);
} else {
bookInfo &mBook = booksMap[libro];
int totalEjemplares = ejemplares + mBook.getEjemplares();
mBook.setEjemplares(totalEjemplares);
}
}
void comprar(bookId libro) {
if (booksMap.count(libro) == 0) {
throw invalid_argument("Libro no existente");
}
if (booksMap[libro].getEjemplares() == 0) {
throw out_of_range("No hay ejemplares");
}
bookInfo &book = booksMap[libro];
int totalEjemplares = book.getEjemplares() - 1;
book.setEjemplares(totalEjemplares);
// list<bookId> &listaPuntosVendidosAntes = ventasMap[book.getEjemplaresVendidos()];
// listaPuntosVendidosAntes.erase(book.getItLista());
list<bookId>:: iterator nuevaPos;
if (book.getEjemplaresVendidos() > 0) {
nuevaPos = next(book.getItLista(), 1);
ventasList.erase(book.getItLista());
} else {
nuevaPos = next(ventasList.begin(), 1);
}
book.annadirEjemplarVendido();
// list<bookId> &listaNuevosPuntos = ventasMap[book.getEjemplaresVendidos()];
book.setItLista(ventasList.insert(nuevaPos, libro));
}
bool estaLibro(bookId libro) {
return (booksMap.count(libro) > 0);
}
void elimLibro(bookId libro) {
if (booksMap.count(libro) == 0) {
return;
}
bookInfo &book = booksMap[libro];
if (book.getEjemplaresVendidos() > 0) {
ventasList.erase(book.getItLista());
}
booksMap.erase(libro);
}
int numEjemplares(bookId libro) {
if (booksMap.count(libro) == 0) {
throw invalid_argument("Libro no existente");
}
return booksMap[libro].getEjemplares();
}
list<bookId> top10() const {
// int totalLibros = 0;
// list<bookId> result;
//
// for(auto it = ventasMap.rbegin(); it != ventasMap.rend() && totalLibros < 10; ++it) {
// if (it->first > 0) {
// for(auto value : it->second) {
// result.push_back(value);
// totalLibros++;
// }
// }
// }
return ventasList;
}
};
#endif /* BookShop_h */
| true |
b6e88caa7221eb7a64e1ac8963ffd48830e1aad4 | C++ | Anmol2307/Codechef | /SeptCha2013/LEEXAMS.cpp | UTF-8 | 1,455 | 2.515625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
inline void inp(int &n ) {//fast input function
n=0;
int ch=getchar(),sign=1;
while( ch < '0' || ch > '9' ){if(ch=='-')sign=-1; ch=getchar();}
while( ch >= '0' && ch <= '9' )
n=(n<<3)+(n<<1)+ ch-'0', ch=getchar();
n=n*sign;
}
double dp[51][1<<16];
int main () {
int t;
inp(t);
while (t--) {
int n;
inp(n);
int P[n], A[n], B[n];
for (int i = 0; i < n; i++) {
inp(P[i]);inp(A[i]);inp(B[i]);
}
memset(dp,0,sizeof(dp));
dp[0][1<<(A[0]-1)] = (double)P[0]/(double)100;
dp[0][1<<(B[0]-1)] = (double)(100-P[0])/(double)100;
int index = 1<<16;
for (int i = 1; i < n; i++) {
double val = 0;
for (int j = 1; j < index; j++) {
if (dp[i-1][j] != 0 && (((1 << (A[i]-1)) & j) == 0)) {
// val = (double)dp[i-1][j]*(double)P[i]/(double)100;
dp[i][j + (1 << (A[i]-1))] += (double)dp[i-1][j]*(double)P[i]/(double)100;
}
if (dp[i-1][j] != 0 && (((1 << (B[i]-1)) & j) == 0)) {
// val = (double)dp[i-1][j]*(double)(100-P[i])/(double)100;
dp[i][j + (1 << (B[i]-1))] += (double)dp[i-1][j]*(double)(100-P[i])/(double)100;
}
}
}
// for (int i = 0; i < n; i++) {
// for (int j = 1; j < 8; j++) {
// printf("%lf ",dp[i][j]);
// }
// printf("\n");
// }
double ans = 0;
for (int i = 1; i < index; i++) {
if (dp[n-1][i] != 0){
ans += (double)dp[n-1][i];
}
}
printf("%.9lf\n",ans);
}
} | true |
b6e40700b27c46d03cb252f804c34fa67c56e6e4 | C++ | pratiksaha/practice | /array/checkRotationPalindrome.cpp | UTF-8 | 1,178 | 3.875 | 4 | [] | no_license | //to check if a string is a rotation of a palindrome
//TODO: do in O(n) time using manacher's algorithm
#include<iostream>
#include<string>
using namespace std;
bool checkPalindrome(string str) {
int l = 0;
int h = str.length() - 1;
while (l<h)
if (str[l++] != str[h--])
return false;
return true;
}
bool checkRotationPalindrome(string str) {
if (checkPalindrome(str)) {
return true;
} else {
int n = str.length();
for (int i=0; i<n-1; i++) {
string str1 = str.substr(i+1, n-i-1);
string str2 = str.substr(0, i+1);
if (checkPalindrome(str1.append(str2)))
return true;
}
return false;
}
}
int main() {
checkRotationPalindrome("aab") ? cout<<"String is a rotation of a palindrome\n" : cout<<"String is not a rotation of a palindrome\n";
checkRotationPalindrome("abcde") ? cout<<"String is a rotation of a palindrome\n" : cout<<"String is not a rotation of a palindrome\n";
checkRotationPalindrome("aaaad") ? cout<<"String is a rotation of a palindrome\n" : cout<<"String is not a rotation of a palindrome\n";
return 0;
}
| true |
6e4f683e62df840ed916338e37cb57e96c73d9e5 | C++ | jaemin2682/BAEKJOON_ONLINE_JUDGE | /17362.cpp | UTF-8 | 317 | 2.625 | 3 | [
"MIT"
] | permissive | #include <iostream>
using namespace std;
int main() {
int n, cnt=1, val=1;
bool mode = true;
cin >> n;
while(n != cnt) {
if(cnt%8==5) mode = false;
else if(cnt%8==1) mode = true;
if(mode) val++;
else val--;
cnt++;
}
cout << val;
return 0;
} | true |
ad7a72bbf9af47f98a1b6e319033600bfac05673 | C++ | AndreyStulov/VisualStudio_project | /Shapes/Source.cpp | UTF-8 | 2,515 | 3.4375 | 3 | [] | no_license | #include<iostream>
#include<math.h>
#include<time.h>
using namespace std;
class Shape
{
public:
virtual double Area() = 0;
};
class Rectangle : public Shape
{
public:
//Constructor
Rectangle()
{
this->Side_A = (rand() % 20)+1;
this->Side_B = (rand() % 20) + 1;
}
//Getters
int Get_Side_A() {return this->Side_A;}
int Get_Side_B() {return this->Side_B;}
//Formula of Area
double Area() override {return this->Side_A * this->Side_B;}
//Perimetr of rectangle 2(A+B)
double PerOfBase()
{
return (this->Get_Side_A() + this->Get_Side_B()) * 2;
}
private:
int Side_A;
int Side_B;
};
class Circle : public Shape
{
public:
const double PI = 3.14;
//Constructor
Circle() {this->radius = (rand() % 20) + 1;}
//Formula of Area
double Area() override {return PI * this->radius*this->radius;}
//Getter
int Get_Radius() { return this->radius; }
private:
int radius;
};
class Pyramid : public Rectangle
{
public:
//Constructor
Pyramid() : Rectangle()
{
this->Side_C = (rand() % 20) + 1;
this->Half_p = (Get_Side_A() + Side_C * 2) / 2;
this->TempApofem = Half_p * (Half_p - Get_Side_A())*(Half_p - Get_Side_C())*(Half_p - Get_Side_C());
if (TempApofem>0)
{
this->Apofem = (sqrt(TempApofem)) * 2 / Get_Side_A();
}
else
{
this->Apofem = 0;
}
}
//Getters
int Get_Side_C()
{ return this->Side_C; }
int Get_Apofem()
{
return this->Apofem;
}
double Area() override
{
if (Apofem!=0)
{
return 0.5 * Rectangle::PerOfBase()*Apofem + Rectangle::Area();
}
else
{
return 0;
}
}
private:
int Side_C;
double Half_p, TempApofem, Apofem;
};
int main()
{
setlocale(0, "");
srand(time(NULL));
for (int i = 0; i < 5; i++)
{
Rectangle A;
cout << "Создан новый Прямоугольник!\nСторона А = " << A.Get_Side_A()
<< "\nСторона Б = " << A.Get_Side_B()
<< "\nПлощадь = " << A.Area() << endl << endl;
Circle B;
cout << "Создан новый Круг!\nРадиус = " << B.Get_Radius() << "\nПлощадь = " << B.Area() << endl << endl;
Pyramid C;
cout << "Создана новая Пирамида!\nСторона А = " << C.Get_Side_A()
<< "\nСторона Б = " << C.Get_Side_B()
<< "\nСторона C = "<< C.Get_Side_C()
<< "\nПлощадь = " << C.Area() << endl << endl;
}
return 0;
system("pause");
}
| true |
d531252a34e2ce9dabf97f8bef6b9f8d16333c1e | C++ | geetanshatrey/Competitive-Coding | /Code Forces/TheatreSquare.cpp | UTF-8 | 371 | 2.953125 | 3 | [] | no_license | //Link to the problem: https://codeforces.com/problemset/problem/1/A
#include<iostream>
#include <cmath>
using namespace std;
int main(){
long long int a,b,c;
long long int z;
cin>>a>>b>>c;
long double x=(double)b/c;
long double y=(double)(a-c)/c;
if(y>0){
z=ceil(x)*(1+ceil(y));
}
else{
z=ceil(x);
}
cout<<z;
}
| true |
8e71dfbb572046783e8ea1cc3b94e64007eb7ca0 | C++ | KolHaj/Expression-Evaluation-Application | /src/parse.cpp | UTF-8 | 418 | 2.78125 | 3 | [
"MIT"
] | permissive | /*
* File: parse.cpp
* Author: Kolger Hajati
* Date: May 7, 2019
* Purpose: Parse variable names from input.
*/
#include <cctype>
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
#include "parse.h"
string parseName(stringstream& ss)
{
char alnum;
string name = "";
ss >> ws;
while (isalnum(ss.peek()))
{
ss >> alnum;
name += alnum;
}
return name;
}
| true |
cd716669ddde90343458be07e41dfc4028ca4f66 | C++ | Xavota/Compiladores | /Project/Compilador/Compilador/Syn_FunctionState.cpp | UTF-8 | 9,472 | 2.65625 | 3 | [] | no_license | #include "pch.h"
#include "Syn_FunctionState.h"
#include "Syn_Parameters.h"
#include "Syn_FunctionBlock.h"
namespace Compilador
{
Syn_FunctionState::Syn_FunctionState()
{
}
Syn_FunctionState::~Syn_FunctionState()
{
}
eRETURN_STATE Syn_FunctionState::Update(AnalizadorSintactico* syntactic)
{
m_hasReturn = false;
eRETURN_STATE r = GetID(syntactic);
if (r == eRETURN_STATE::FATAL)
{
return eRETURN_STATE::FATAL;
}
if (!m_hasReturn && m_type != "void")
{
std::string errorMsg = "Missing return statement on function ";
errorMsg.append(m_name);
if (!syntactic->AddError(errorMsg))
{
return eRETURN_STATE::FATAL;
}
}
return eRETURN_STATE::GOOD;
}
eRETURN_STATE Syn_FunctionState::GetID(AnalizadorSintactico* syntactic)
{
Token tok = syntactic->GetNextToken();
if (tok.GetType() == eTOKEN_TYPE::ID)
{
m_name = tok.GetLexeme();
if (syntactic->SymbolExist(m_name, "FUNCTION", ""))
{
std::string errorMsg = "ID '";
errorMsg.append(tok.GetLexeme());
errorMsg.append("' already exist in the current context. On line ");
errorMsg.append(to_string(tok.GetLine()));
if (!syntactic->AddError(errorMsg))
{
return eRETURN_STATE::FATAL;
}
syntactic->SetContext(m_name);
}
else
{
syntactic->AddSymbol(tok.GetLine(), m_name, "FUNCTION", 0, "", "int", 0);
syntactic->SetContext(m_name);
syntactic->StatementTreeStartNew(m_name);
}
return OpenParenthesis(syntactic);
}
else
{
std::string errorMsg = "Identificator expected at function declaration on line ";
errorMsg.append(to_string(tok.GetLine()));
if (!syntactic->AddError(errorMsg))
{
return eRETURN_STATE::FATAL;
}
// Panik mode
while (tok.GetLexeme() != "(" && tok.GetLexeme() != ")" && tok.GetLexeme() != "{"
&& tok.GetLexeme() != "}" && tok.GetType() != eTOKEN_TYPE::END)
{
tok = syntactic->GetNextToken();
}
if (tok.GetLexeme() == "(")
{
m_name = "F";
syntactic->AddSymbol(tok.GetLine(), m_name, "FUNCTION", 0, "", "int", 0);
syntactic->SetContext(m_name);
syntactic->StatementTreeStartNew(m_name);
SyntaxState* state = new Syn_Parameters();
eRETURN_STATE r = state->Update(syntactic);
delete state;
if (r == eRETURN_STATE::GOOD)
{
return OpenBrackets(syntactic);
}
else if (r == eRETURN_STATE::FATAL)
{
syntactic->SetContext("");
return eRETURN_STATE::FATAL;
}
else if (r == eRETURN_STATE::BAD)
{
syntactic->SetContext("");
return eRETURN_STATE::BAD;
}
}
else if (tok.GetLexeme() == ")")
{
m_name = "F";
syntactic->AddSymbol(tok.GetLine(), m_name, "FUNCTION", 0, "", "int", 0);
syntactic->SetContext(m_name);
syntactic->StatementTreeStartNew(m_name);
return OpenBrackets(syntactic);
}
if (tok.GetLexeme() == "{")
{
m_name = "F";
syntactic->AddSymbol(tok.GetLine(), m_name, "FUNCTION", 0, "", "int", 0);
syntactic->SetContext(m_name);
syntactic->StatementTreeStartNew(m_name);
SyntaxState* state = new Syn_FunctionBlock(&m_hasReturn);
eRETURN_STATE r = state->Update(syntactic);
delete state;
syntactic->SetContext("");
return r;
}
else if (tok.GetLexeme() == "}")
{
return eRETURN_STATE::GOOD;
}
else if (tok.GetType() == eTOKEN_TYPE::END)
{
return eRETURN_STATE::BAD;
}
return eRETURN_STATE::BAD;
}
return eRETURN_STATE::BAD;
}
eRETURN_STATE Syn_FunctionState::OpenParenthesis(AnalizadorSintactico* syntactic)
{
Token tok = syntactic->GetNextToken();
if (tok.GetLexeme() == "(")
{
SyntaxState* state = new Syn_Parameters();
eRETURN_STATE r = state->Update(syntactic);
delete state;
if (r == eRETURN_STATE::GOOD)
{
return OpenBrackets(syntactic);
}
else if (r == eRETURN_STATE::FATAL)
{
syntactic->SetContext("");
return eRETURN_STATE::FATAL;
}
else if (r == eRETURN_STATE::BAD)
{
syntactic->SetContext("");
return eRETURN_STATE::BAD;
}
}
else
{
std::string errorMsg = "Expected '(' after ID of function declared on line ";
errorMsg.append(to_string(tok.GetLine()));
if (!syntactic->AddError(errorMsg))
{
syntactic->SetContext("");
return eRETURN_STATE::FATAL;
}
// Panik mode
while (tok.GetLexeme() != "(" && tok.GetLexeme() != ")" && tok.GetLexeme() != "{"
&& tok.GetLexeme() != "}" && tok.GetType() != eTOKEN_TYPE::END)
{
tok = syntactic->GetNextToken();
}
if (tok.GetLexeme() == "(")
{
SyntaxState* state = new Syn_Parameters();
eRETURN_STATE r = state->Update(syntactic);
delete state;
if (r == eRETURN_STATE::GOOD)
{
return OpenBrackets(syntactic);
}
else if (r == eRETURN_STATE::FATAL)
{
syntactic->SetContext("");
return eRETURN_STATE::FATAL;
}
else if (r == eRETURN_STATE::BAD)
{
syntactic->SetContext("");
return eRETURN_STATE::BAD;
}
}
else if (tok.GetLexeme() == ")")
{
return OpenBrackets(syntactic);
}
if (tok.GetLexeme() == "{")
{
SyntaxState* state = new Syn_FunctionBlock(&m_hasReturn);
eRETURN_STATE r = state->Update(syntactic);
delete state;
syntactic->SetContext("");
return r;
}
else if (tok.GetLexeme() == "}")
{
syntactic->SetContext("");
return eRETURN_STATE::GOOD;
}
else if (tok.GetType() == eTOKEN_TYPE::END)
{
syntactic->SetContext("");
return eRETURN_STATE::BAD;
}
syntactic->SetContext("");
return eRETURN_STATE::BAD;
}
syntactic->SetContext("");
return eRETURN_STATE::BAD;
}
eRETURN_STATE Syn_FunctionState::OpenBrackets(AnalizadorSintactico* syntactic)
{
Token tok = syntactic->GetNextToken();
if (tok.GetLexeme() == ":")
{
return Colon(syntactic);
}
else
{
std::string errorMsg = "Expected ':' after parameters of function declared on line ";
errorMsg.append(to_string(tok.GetLine()));
if (!syntactic->AddError(errorMsg))
{
syntactic->SetContext("");
return eRETURN_STATE::FATAL;
}
// Panik mode
while (tok.GetLexeme() != "{" && tok.GetLexeme() != "}"
&& tok.GetType() != eTOKEN_TYPE::END)
{
tok = syntactic->GetNextToken();
}
if (tok.GetLexeme() == "{")
{
SyntaxState* state = new Syn_FunctionBlock(&m_hasReturn);
eRETURN_STATE r = state->Update(syntactic);
delete state;
syntactic->SetContext("");
return r;
}
else if (tok.GetLexeme() == "}")
{
syntactic->SetContext("");
return eRETURN_STATE::GOOD;
}
else if (tok.GetType() == eTOKEN_TYPE::END)
{
syntactic->SetContext("");
return eRETURN_STATE::BAD;
}
syntactic->SetContext("");
return eRETURN_STATE::BAD;
}
syntactic->SetContext("");
return eRETURN_STATE::BAD;
}
eRETURN_STATE Syn_FunctionState::Colon(AnalizadorSintactico* syntactic)
{
Token tok = syntactic->GetNextToken();
if (IsFunctionType(tok))
{
m_type = tok.GetLexeme();
syntactic->UpdateSymboltype(m_name, "FUNCTION", "", tok.GetLexeme());
return GetType(syntactic);
}
else
{
std::string errorMsg =
"Expected function type at the end of declaration function on line ";
errorMsg.append(to_string(tok.GetLine()));
errorMsg.append(". Asumed int");
if (!syntactic->AddError(errorMsg))
{
syntactic->SetContext("");
return eRETURN_STATE::FATAL;
}
// Panik mode
while (tok.GetLexeme() != "{" && tok.GetLexeme() != "}"
&& tok.GetType() != eTOKEN_TYPE::END)
{
tok = syntactic->GetNextToken();
}
if (tok.GetLexeme() == "{")
{
SyntaxState* state = new Syn_FunctionBlock(&m_hasReturn);
eRETURN_STATE r = state->Update(syntactic);
delete state;
syntactic->SetContext("");
return r;
}
else if (tok.GetLexeme() == "}")
{
syntactic->SetContext("");
return eRETURN_STATE::GOOD;
}
else if (tok.GetType() == eTOKEN_TYPE::END)
{
syntactic->SetContext("");
return eRETURN_STATE::BAD;
}
syntactic->SetContext("");
return eRETURN_STATE::BAD;
}
syntactic->SetContext("");
return eRETURN_STATE::BAD;
}
eRETURN_STATE Syn_FunctionState::GetType(AnalizadorSintactico* syntactic)
{
Token tok = syntactic->GetNextToken();
if (tok.GetLexeme() == "{")
{
SyntaxState* state = new Syn_FunctionBlock(&m_hasReturn);
eRETURN_STATE r = state->Update(syntactic);
delete state;
syntactic->SetContext("");
return r;
}
else
{
std::string errorMsg = "Expected '{' at the start of statements of function on line ";
errorMsg.append(to_string(tok.GetLine()));
if (!syntactic->AddError(errorMsg))
{
syntactic->SetContext("");
return eRETURN_STATE::FATAL;
}
// Panik mode
while (tok.GetLexeme() != "{" && tok.GetLexeme() != "}"
&& tok.GetType() != eTOKEN_TYPE::END)
{
tok = syntactic->GetNextToken();
}
if (tok.GetLexeme() == "{")
{
SyntaxState* state = new Syn_FunctionBlock(&m_hasReturn);
eRETURN_STATE r = state->Update(syntactic);
delete state;
syntactic->SetContext("");
return r;
}
else if (tok.GetLexeme() == "}")
{
syntactic->SetContext("");
return eRETURN_STATE::GOOD;
}
else if (tok.GetType() == eTOKEN_TYPE::END)
{
syntactic->SetContext("");
return eRETURN_STATE::BAD;
}
syntactic->SetContext("");
return eRETURN_STATE::BAD;
}
syntactic->SetContext("");
return eRETURN_STATE::BAD;
}
} | true |
70c50fb50eb8b2cc8ef515a21e9b81ee1f76d75c | C++ | nuttybamboo/Lextory | /reg_lexer.cpp | UTF-8 | 7,141 | 2.796875 | 3 | [] | no_license | #include "reg_lexer.h"
string Lexer::getAction(){
string value = "";
for(;peek != '\0'; peek = inbuf.nextChar()){
value += peek;
}
return value;
}
string Lexer::getDifiName(){
string value = "";
for(;peek != '\0';peek = inbuf.nextChar()){
if((peek <= 'Z' && peek >= 'A') || (peek <= 'z' && peek >= 'a') || (peek <= '9' && peek >= '0') || peek == '_'){
value += peek;
}
else{
break;
}
}
//cout << "after get name " << peek << endl;
return value;
}
bool Lexer::skipSpace(){
for( ; ; peek = inbuf.nextChar()){
if(peek == ' ' || peek == '\t'){
continue;
}
else if(peek == '/'){
peek = inbuf.nextChar();
if(peek == '*'){
for(peek = ' ';;){
while(peek != '*' && inbuf.nextChar() != '*');
if((peek = inbuf.nextChar()) != '/'){
;
}
else{
peek = inbuf.nextChar();
break;
}
}
}
else {
break;
}
}
else{
break;
}
}
//cout << "after space " << peek << endl;
if(peek == '\n' || peek == '\0'){
return false;
}
else {
return true;
}
}
Token* Lexer::dealChar(){
char value = 0;
switch(peek){
case '\\':
peek = inbuf.nextChar();
value = peek;
peek = inbuf.nextChar();
//cout << "peek = \\" << value << endl;
return new Symbol(value);
default :
value = peek;
peek = inbuf.nextChar();
//cout << "peek = " << value << endl;
return new Token(value);
}
}
Token* Lexer::dealString(){
string value = "";
for(peek = inbuf.nextChar();peek != '\0';peek = inbuf.nextChar()){
if(peek == '"'){
peek = inbuf.nextChar();
break;
}
if(peek == '\\'){
peek = inbuf.nextChar();
switch(peek){
case 'n' :
value += '\n';
peek = inbuf.nextChar();
break;
case 'r' :
value += '\r';
peek = inbuf.nextChar();
break;
case '0' :
value += '\0';
peek = inbuf.nextChar();
break;
case 't' :
value += '\t';
peek = inbuf.nextChar();
break;
case 'v' :
value += '\v';
peek = inbuf.nextChar();
break;
case 'b' :
value += '\b';
peek = inbuf.nextChar();
break;
case 'f' :
value += '\f';
peek = inbuf.nextChar();
break;
case 'a' :
value += '\a';
peek = inbuf.nextChar();
break;
case '\"' :
value += '\"';
peek = inbuf.nextChar();
break;
case '\'' :
value += '\'';
peek = inbuf.nextChar();
break;
case '\\' :
value += '\\';
peek = inbuf.nextChar();
break;
case '\?' :
value += '\?';
peek = inbuf.nextChar();
break;
default :
;
}
}
else{
value += peek;
}
}
return new String(value);
}
Token* Lexer::dealSet(){
set<char> value;
for(peek = inbuf.nextChar();peek != '\0';peek = inbuf.nextChar()){
if(peek == ']'){
peek = inbuf.nextChar();
break;
}
if(peek == '-'){
if(value.size() != 1){
cout << "sytax error!" << endl;
}
else{
peek = inbuf.nextChar();
if(peek > *value.begin()){
for(char c = peek; c > *value.begin(); c--){
//cout << "insert " << c << endl;
value.insert(c);
}
}
else{
cout << "sytax error!" << endl;
}
peek = inbuf.nextChar();
if(peek == ']'){
peek = inbuf.nextChar();
break;
}
else{
cout << "error !" << endl;
//break;
}
}
}
if(peek == '\\'){
peek = inbuf.nextChar();
switch(peek){
case 'n' :
value.insert('\n');
peek = inbuf.nextChar();
break;
case 'r' :
value.insert('\r');
peek = inbuf.nextChar();
break;
case '0' :
value.insert('\0');
peek = inbuf.nextChar();
break;
case 't' :
value.insert('\t');
peek = inbuf.nextChar();
break;
case 'v' :
value.insert('\v');
peek = inbuf.nextChar();
break;
case 'f' :
value.insert('\f');
peek = inbuf.nextChar();
break;
default :
value.insert(peek);
peek = inbuf.nextChar();
break;
}
}
else{
value.insert(peek);
}
}
//cout << "peek = set" << endl;
return new SymbolSet(value);
}
Token* Lexer::dealDif(){
string value = "";
for(peek = inbuf.nextChar();peek != '\0' && peek != '$';peek = inbuf.nextChar()){
if((peek <= 'Z' && peek >= 'A') || (peek <= 'z' && peek >= 'a') || (peek <= '9' && peek >= '0') || peek == '_'){
value += peek;
}
else{
break;
}
}
if(peek != '}'){
cout << "lexer get defination end peek not } : " << peek << "error!!!" << endl;
}
else{
peek = inbuf.nextChar();
}
//cout << "peek = defi" << endl;
return new Difination(value);
}
Token* Lexer::next(){
//cout << "peek = " << peek << endl;
if(peek == ' ' || peek == '\t' || peek == '\n' || peek == '\0'){
//cout << "found ' ' " <<endl;
return new Token('$');
}
//skipSpace();
if(peek == '"'){
return dealString();
}
if(peek == '['){
return dealSet();
}
if(peek == '{'){
return dealDif();
}
return dealChar();
}
| true |
46fd6668687bbe0254ae37e278c7e85146565c06 | C++ | cleancoindev/ness-engine | /examples/SpaceFighter/shot.h | UTF-8 | 828 | 2.9375 | 3 | [
"Zlib",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | #pragma once
#include <NessEngine.h>
// define the laser shot object that players can shoot
class LaserShot
{
private:
Ness::NodePtr m_parent;
Ness::SpritePtr m_shot;
Ness::Point m_direction_vector;
float m_time_to_live;
public:
// create the new shot instance
LaserShot(Ness::NodePtr& parentNode, const Ness::Point& position, float Direction, const Ness::Color& fireColor);
~LaserShot();
// return how much time this shot got left
inline float get_time_to_live() {return m_time_to_live;}
void destroy(bool withExplosion);
// return the shot direction vector
inline const Ness::Point& get_direction_vector() const {return m_direction_vector;}
// return the shot position
inline const Ness::Point& get_position() const {return m_shot->get_position();}
// move the shot and do its events
void do_events();
}; | true |
e8cbd34594d50c7ad3bb98a5aeb971c13a53ee03 | C++ | StavrosBizelis/NetworkDistributedDeferredShading | /Include/Common/RenderControl/RenderPassPipeline.h | UTF-8 | 1,357 | 3.03125 | 3 | [
"MIT"
] | permissive | #pragma once
/// Render pass pipeline - holds an internal vector of render passes - the lower the index in the vector -> the earlier the render pass is going to be done
#include <vector>
#include "Common/RenderControl/IRenderPass.h"
#include "Common/MaterialControl/IMaterialManager.h"
namespace RenderControl
{
/// a class that manages multiple render passes
class RenderPassPipeline
{
/// owns the material manager
MaterialControl::IMaterialManager* m_materialManager;
std::vector< IRenderPass* > m_passes; ///< owns these render passes
public:
RenderPassPipeline();
virtual ~RenderPassPipeline();
/// pushes this pass to the internal vector ( this pass will be render after the previously added render pass)
/// RenderPassPipeline now owns a_pass
void PushBack(IRenderPass* a_pass);
/// remove last render pass
void PopBack();
/// @return if nullptr render pass index out of bounds
IRenderPass* GetRenderPass(const unsigned int& a_index);
unsigned int GetRenderPassCount();
void RenderAll();
void Clear(); ///< clears the pipeline and invalidates the render passes
void SetMaterialManager(MaterialControl::IMaterialManager* a_materialManager); ///< transfers ownership
MaterialControl::IMaterialManager* GetMaterialManager() const; ///< valid as long as this RenderControl object is - DO NOT DELETE
};
} | true |
e96cdb76afd1d60d712d0b1e4875311e01dacf9e | C++ | roytam1/palemoon27 | /gfx/skia/skia/src/gpu/effects/GrConvolutionEffect.h | UTF-8 | 3,507 | 2.71875 | 3 | [
"BSD-3-Clause"
] | permissive | /*
* Copyright 2012 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#ifndef GrConvolutionEffect_DEFINED
#define GrConvolutionEffect_DEFINED
#include "Gr1DKernelEffect.h"
#include "GrInvariantOutput.h"
/**
* A convolution effect. The kernel is specified as an array of 2 * half-width
* + 1 weights. Each texel is multiplied by it's weight and summed to determine
* the output color. The output color is modulated by the input color.
*/
class GrConvolutionEffect : public Gr1DKernelEffect {
public:
/// Convolve with an arbitrary user-specified kernel
static GrFragmentProcessor* Create(GrTexture* tex,
Direction dir,
int halfWidth,
const float* kernel,
bool useBounds,
float bounds[2]) {
return new GrConvolutionEffect(tex, dir, halfWidth, kernel, useBounds, bounds);
}
/// Convolve with a Gaussian kernel
static GrFragmentProcessor* CreateGaussian(GrTexture* tex,
Direction dir,
int halfWidth,
float gaussianSigma,
bool useBounds,
float bounds[2]) {
return new GrConvolutionEffect(tex, dir, halfWidth, gaussianSigma, useBounds, bounds);
}
virtual ~GrConvolutionEffect();
const float* kernel() const { return fKernel; }
const float* bounds() const { return fBounds; }
bool useBounds() const { return fUseBounds; }
const char* name() const override { return "Convolution"; }
enum {
// This was decided based on the min allowed value for the max texture
// samples per fragment program run in DX9SM2 (32). A sigma param of 4.0
// on a blur filter gives a kernel width of 25 while a sigma of 5.0
// would exceed a 32 wide kernel.
kMaxKernelRadius = 12,
// With a C++11 we could have a constexpr version of WidthFromRadius()
// and not have to duplicate this calculation.
kMaxKernelWidth = 2 * kMaxKernelRadius + 1,
};
protected:
float fKernel[kMaxKernelWidth];
bool fUseBounds;
float fBounds[2];
private:
GrConvolutionEffect(GrTexture*, Direction,
int halfWidth,
const float* kernel,
bool useBounds,
float bounds[2]);
/// Convolve with a Gaussian kernel
GrConvolutionEffect(GrTexture*, Direction,
int halfWidth,
float gaussianSigma,
bool useBounds,
float bounds[2]);
GrGLSLFragmentProcessor* onCreateGLSLInstance() const override;
void onGetGLSLProcessorKey(const GrGLSLCaps&, GrProcessorKeyBuilder*) const override;
bool onIsEqual(const GrFragmentProcessor&) const override;
void onComputeInvariantOutput(GrInvariantOutput* inout) const override {
// If the texture was opaque we could know that the output color if we knew the sum of the
// kernel values.
inout->mulByUnknownFourComponents();
}
GR_DECLARE_FRAGMENT_PROCESSOR_TEST;
typedef Gr1DKernelEffect INHERITED;
};
#endif
| true |
fcdd92a7276b99173342e32fdc42b0d600126cdc | C++ | gytim/morse | /MainWindow.h | UTF-8 | 1,019 | 2.609375 | 3 | [] | no_license | #ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QObject>
#include <QQmlApplicationEngine>
class MainWindow : public QObject
{
Q_OBJECT
public:
explicit MainWindow(QQmlApplicationEngine *engine);
public slots:
void translateText(QString text); //!< Принимаем текст и отправляем обратно
void saveFile(QString path, QString text); //!< Сохраняем файл
void loadFile(QString path); //!< Загружаем файл
private:
QString translateEng(const char* chr); //!< Отправляем на перевод инглиша
QString translateMorse(const char* chr); //!< Отправляем на перевод морзе
QString engToMorse(QString str); //!< Конвертим букву инглиш в морзе
QString morseToEng(QString str); //!< Конвертим букву морзе в инглиш
private:
QQmlApplicationEngine *viewer;
};
#endif // MAINWINDOW_H
| true |
0c0f578af462493fb9085fdc925a211451d81be6 | C++ | charmdong/Algorithm_solutions_2019 | /Baekjoon/BJ16236.cpp | UHC | 2,453 | 2.921875 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <queue>
#include <cstring>
#define MAX 20
using namespace std;
int n;
int sharkSize=2, eatNum;
int dy[4] = { -1,0,0,1};
int dx[4] = { 0,-1, 1,0 };
pair<int, int> shark;
int map[MAX][MAX];
bool visited[MAX][MAX];
int bfs(int y = shark.first, int x =shark.second);
bool isInMap(int y, int x);
class fish {
public:
int y, x, d;
fish(int y=20, int x=20, int d=0) :y(y), x(x), d(d) {}
void operator=(fish &b) {
this->y = b.y;
this->x = b.x;
this->d = b.d;
}
};
int main()
{
cin >> n;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cin >> map[i][j];
if (map[i][j] == 9)
shark = { i,j };
}
}
cout << bfs() << endl;
return 0;
}
int bfs(int y, int x) { // ִ ϴ ɸ ð
int ans = 0;
while (1) {
queue<fish> q;
vector<fish> fishes;
visited[shark.first][shark.second] = true;
q.push(fish(shark.first, shark.second, 0));
int found = -1; // bfs ǥ ť ϱ , ̸ ̿ ߴ.
while (!q.empty()) {
fish now = q.front(); q.pop();
if (found == now.d) break;
for (int i = 0; i < 4; i++) {
int ny = now.y + dy[i];
int nx = now.x + dx[i];
// ִ ĭ (Ư Ÿ ̻ )
if (isInMap(ny, nx) && !visited[ny][nx] && map[ny][nx] <= sharkSize) {
visited[ny][nx] = true;
// ִ , Ÿ ִ.
if (map[ny][nx] > 0 && map[ny][nx] < sharkSize) {
found = now.d + 1;
fishes.push_back(fish(ny, nx, now.d + 1));
}
q.push(fish(ny, nx, now.d + 1));
}
}
}
fish eat;
if (found == -1) break; // ִ Ⱑ
else {
if (fishes.size() > 1) {
for (auto t : fishes) {
if (t.y < eat.y)
eat = t;
else if (t.y == eat.y) {
if (t.x < eat.x)
eat = t;
}
else continue;
}
}
else
eat = fishes[0];
}
if (found != -1) {
ans += found;
map[shark.first][shark.second] = 0;
map[eat.y][eat.x] = 9;
shark = { eat.y,eat.x };
if (sharkSize == ++eatNum) {
sharkSize++;
eatNum = 0;
}
}
memset(visited, false, sizeof(visited));
}
return ans;
}
bool isInMap(int y, int x) {
if (y > -1 && y < n)
if (x > -1 && x <n)
return true;
return false;
} | true |
35f14bbc798b2989137b923b558cb8f727fe1037 | C++ | suraj8730/coding | /q1_lab4.cpp | UTF-8 | 488 | 3.859375 | 4 | [] | no_license | # include <iostream>
using namespace std;
int main(){
//declaring the variable
float LENGTH;
cout <<"enter your length"<<endl;
//taking input
cin >>LENGTH;
//declaring variables for output
double METER;
double KILOMETER;
//doing operation
METER= LENGTH*0.01;
KILOMETER= LENGTH*0.00001;
//printing answer
cout<<"your length is "<<LENGTH<<"cm"<<endl;
cout<<"length in meter is "<<METER<<"m"<<endl;
cout<< "length in kilometer is "<<KILOMETER<<"km"<<endl;
return 0;
}
| true |