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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
9b51305b2c92ca6b699ed435037ae2239b23875e | C++ | almoreir/algorithm | /cd3/정보올림피아드관련/정보올림피아드관련/문제들/문제/문제모음2/12월13일-4문제/hong/forecast/forecast.cpp | UTF-8 | 1,486 | 2.75 | 3 | [] | no_license | #include <fstream.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define MAX 100000
ifstream in("forecast10.in");
ofstream out("forecast10.out");
int m, n;
double percent, volume, depth;
struct _c {
int height;
int flow;
} city[MAX];
int sortf(void const *p, void const *q)
{
struct _c *a=(struct _c *)p;
struct _c *b=(struct _c *)q;
return (a->height-b->height);
}
void inp()
{
int i,j;
in >> m >> n;
for(i=0;i<m;i++)
for(j=0;j<n;j++)
in >> city[i*n+j].height;
city[n*m].height=999999;
in >> volume;
volume=volume/100;
qsort(city,n*m,sizeof(struct _c),sortf);
}
void oup()
{
char s1[255];
sprintf(s1,"%.2lf %.2lf",depth,percent);
out << s1;
}
void proc()
{
int deepcity, i;
for(i=0;i<=m*n;i++) {
if(i!=0) city[i].flow=i*(city[i].height-city[i-1].height); else city[i].flow=0;
volume-=city[i].flow;
if(volume==0) {
deepcity=i-1;
percent=(double)(deepcity+1)/(m*n)*100;
depth=city[i].height;
break;
} else if(volume<0) {
deepcity=i-1;
volume+=city[i].flow;
percent=(double)(deepcity+1)/(m*n)*100;
depth=city[deepcity].height+volume/(deepcity+1);
break;
}
}
}
void main()
{
inp();
proc();
oup();
}
/*
#include <time.h>
ofstream out("forecast10.in");
int m=100,n=100;
void main()
{
srand((unsigned)time(NULL));
out << m << " " << n << endl;
for(int i=0;i<m;i++) {
for(int j=0;j<n;j++) {
if(j!=0) out << " ";
out << (rand()%200)-100;
}
out << endl;
}
out << rand()%9900+100;
}
*/ | true |
2a7d461dcbd58c0a59f40ccceb9ff13bd119f1a7 | C++ | thesidjway/Fuzzy-Robot-Planning | /withoutobstacleavoidance/Projectcode.ino | UTF-8 | 15,114 | 2.65625 | 3 | [] | no_license | #include <FuzzyRule.h>
#include <FuzzyComposition.h>
#include <Fuzzy.h>
#include <FuzzyRuleConsequent.h>
#include <FuzzyOutput.h>
#include <FuzzyInput.h>
#include <FuzzyIO.h>
#include <FuzzySet.h>
#include <FuzzyRuleAntecedent.h>
#include <Encoder.h>
#define LM1 6
#define LM2 13
#define RM1 11
#define RM2 5
#define EN1 8
#define EN2 12
#define ENCODERFACTOR 0.0156
#define AXLE_LENGTH 7.0
Encoder leftEnc(2, 3);
Encoder rightEnc (18, 19);
long long prev_position_l = 0, curr_position_l = 0;
long long prev_position_r = 0, curr_position_r = 0;
float target_x = -400, target_y = 1;
float curr_x = 0 , curr_y = 0;
float curr_theta = 0, prev_theta = 0;
float diff_angle = 100;
float dist_from_target = 200;
int dist1, dist2, dist3; // distances of all 3 ultrasonic sensors
int robotAngle = 0; // current Angle of the robot
void moveRobot(int targetVL, int targetVR)
{
analogWrite(EN1, targetVL);
analogWrite(EN2, targetVR);
digitalWrite(LM1, HIGH);
digitalWrite(LM2, LOW);
digitalWrite(RM1, HIGH);
digitalWrite(RM2, LOW);
}
void getAllDistances()
{
int temp_dist1, temp_dist2, temp_dist3, temp_dist4; // temporary variables for storing data, so that all distances get written simultaneously.
/*Insert distance data collection code here*/
dist1 = temp_dist1;
dist2 = temp_dist2;
dist3 = temp_dist3;
}
void updateOdometry()
{
curr_position_l = leftEnc.read();
curr_position_r = rightEnc.read();
float diff_l = curr_position_l - prev_position_l;
float diff_r = curr_position_r - prev_position_r;
float cos_current = cos(curr_theta);
float sin_current = sin(curr_theta);
if (diff_l == diff_r)
{
/* Moving in a straight line */
curr_x += diff_l * cos_current;
curr_y += diff_l * sin_current;
}
else
{
/* Moving in an arc */
float expr1 = AXLE_LENGTH * (diff_r + diff_l) / (2.0 * (diff_r - diff_l));
float right_minus_left = diff_r - diff_l;
curr_x += expr1 * (sin(right_minus_left / AXLE_LENGTH + curr_theta) - sin_current);
curr_y -= expr1 * (cos(right_minus_left / AXLE_LENGTH + curr_theta) - cos_current);
/* Calculate new orientation */
curr_theta += right_minus_left / AXLE_LENGTH;
/* Keep in the range -PI to +PI */
while (curr_theta > PI)
curr_theta -= (2.0 * PI);
while (curr_theta < -PI)
curr_theta += (2.0 * PI);
prev_position_l = curr_position_l;
prev_position_r = curr_position_r;
}
Serial.print ("curr_x");
Serial.print (curr_x);
Serial.print ("curr_y");
Serial.print (curr_y);
float target_theta = atan2 (( target_y - curr_y), (target_x - curr_x));
dist_from_target = sqrt (pow( target_y - curr_y, 2) + pow(target_x - curr_x, 2));
diff_angle = target_theta - curr_theta;
while (diff_angle > PI)
diff_angle -= (2.0 * PI);
while (diff_angle < -PI)
diff_angle += (2.0 * PI);
}
// Step 1 - Instantiating an object library
Fuzzy* fuzzy = new Fuzzy();
FuzzySet* verysmall = new FuzzySet(0, 0, 0, 125);
FuzzySet* small = new FuzzySet(0, 125, 125, 250);
FuzzySet* medium = new FuzzySet(125, 250, 250, 375);
FuzzySet* big = new FuzzySet(250, 375, 375, 500);
FuzzySet* verybig = new FuzzySet(375, 500, 500, 500);
FuzzySet* negbig = new FuzzySet(-180, -180, -180, -120);
FuzzySet* negmed = new FuzzySet(-180, -120, -120, -60);
FuzzySet* negsmall = new FuzzySet(-120, -60, -60, 0);
FuzzySet* zero = new FuzzySet(-60, 0, 0, 60);
FuzzySet* possmall = new FuzzySet(0, 60, 60, 120);
FuzzySet* posmed = new FuzzySet(60, 120, 120, 180);
FuzzySet* posbig = new FuzzySet(120, 180, 180, 180);
void setup()
{
Serial.begin(9600);
pinMode(LM1, OUTPUT); // left motor input1
pinMode(LM2, OUTPUT); // left motor input2
pinMode(RM1, OUTPUT); // right motor input1
pinMode(RM2, OUTPUT); // right motor input2
pinMode(EN1, OUTPUT); // enable 1
pinMode(EN2, OUTPUT); // enable 2
//Creating a FuzzyInput distance
FuzzyInput* distance = new FuzzyInput(1);
distance->addFuzzySet(verysmall);
distance->addFuzzySet(small);
distance->addFuzzySet(medium);
distance->addFuzzySet(big);
distance->addFuzzySet(verybig);
FuzzyInput* angle = new FuzzyInput(2);
angle->addFuzzySet(negbig);
angle->addFuzzySet(negmed);
angle->addFuzzySet(negsmall);
angle->addFuzzySet(zero);
angle->addFuzzySet(possmall);
angle->addFuzzySet(posmed);
angle->addFuzzySet(posbig);
fuzzy->addFuzzyInput(distance); // Add FuzzyInput to Fuzzy object
fuzzy->addFuzzyInput(angle);
// Passo 3 - Creating FuzzyOutput velocity
FuzzyOutput* vl = new FuzzyOutput(1);
FuzzyOutput* vr = new FuzzyOutput(2);
// Creating FuzzySet to compond FuzzyOutput vl (Left Wheel Velocity)
FuzzySet* Lveryslow = new FuzzySet(0, 0, 0, 60);
FuzzySet* Lslow = new FuzzySet(100, 130, 130, 160);
FuzzySet* Lmid = new FuzzySet(130, 160, 160, 190);
FuzzySet* Lfast = new FuzzySet(160, 190, 190, 220);
FuzzySet* Lveryfast = new FuzzySet(190, 220, 220, 250);
FuzzySet* Rveryslow = new FuzzySet(0, 0, 0, 60);
FuzzySet* Rslow = new FuzzySet(100, 130, 130, 160);
FuzzySet* Rmid = new FuzzySet(130, 160, 160, 190);
FuzzySet* Rfast = new FuzzySet(160, 190, 190, 220);
FuzzySet* Rveryfast = new FuzzySet(190, 220, 220, 250);
// Creating FuzzySet to compond FuzzyOutput vr (Right Wheel Velocity)
vl->addFuzzySet(Lveryslow);
vl->addFuzzySet(Lslow);
vl->addFuzzySet(Lmid);
vl->addFuzzySet(Lfast);
vl->addFuzzySet(Lveryfast);
vr->addFuzzySet(Rveryslow);
vr->addFuzzySet(Rslow);
vr->addFuzzySet(Rmid);
vr->addFuzzySet(Rfast);
vr->addFuzzySet(Rveryfast);
fuzzy->addFuzzyOutput(vl);
fuzzy->addFuzzyOutput(vr);
FuzzyRuleAntecedent* VSNB = new FuzzyRuleAntecedent();
VSNB->joinWithAND(verysmall, negbig);
FuzzyRuleAntecedent* SNB = new FuzzyRuleAntecedent();
SNB->joinWithAND(small, negbig);
FuzzyRuleAntecedent* MNB = new FuzzyRuleAntecedent();
MNB->joinWithAND(medium, negbig);
FuzzyRuleAntecedent* BNB = new FuzzyRuleAntecedent();
BNB->joinWithAND(big, negbig);
FuzzyRuleAntecedent* VBNB = new FuzzyRuleAntecedent();
VBNB->joinWithAND(verybig, negbig);
FuzzyRuleAntecedent* VSNM = new FuzzyRuleAntecedent();
VSNM->joinWithAND(verysmall, negmed);
FuzzyRuleAntecedent* SNM = new FuzzyRuleAntecedent();
SNM->joinWithAND(small, negmed);
FuzzyRuleAntecedent* MNM = new FuzzyRuleAntecedent();
MNM->joinWithAND(medium, negmed);
FuzzyRuleAntecedent* BNM = new FuzzyRuleAntecedent();
BNM->joinWithAND(big, negmed);
FuzzyRuleAntecedent* VBNM = new FuzzyRuleAntecedent();
VBNM->joinWithAND(verybig, negmed);
FuzzyRuleAntecedent* VSNS = new FuzzyRuleAntecedent();
VSNS->joinWithAND(verysmall, negsmall);
FuzzyRuleAntecedent* SNS = new FuzzyRuleAntecedent();
SNS->joinWithAND(small, negsmall);
FuzzyRuleAntecedent* MNS = new FuzzyRuleAntecedent();
MNS->joinWithAND(medium, negsmall);
FuzzyRuleAntecedent* BNS = new FuzzyRuleAntecedent();
BNS->joinWithAND(big, negsmall);
FuzzyRuleAntecedent* VBNS = new FuzzyRuleAntecedent();
VBNS->joinWithAND(verybig, negsmall);
FuzzyRuleAntecedent* VSZ = new FuzzyRuleAntecedent();
VSZ->joinWithAND(verysmall, zero);
FuzzyRuleAntecedent* SZ = new FuzzyRuleAntecedent();
SZ->joinWithAND(small, zero);
FuzzyRuleAntecedent* MZ = new FuzzyRuleAntecedent();
MZ->joinWithAND(medium, zero);
FuzzyRuleAntecedent* BZ = new FuzzyRuleAntecedent();
BZ->joinWithAND(big, zero);
FuzzyRuleAntecedent* VBZ = new FuzzyRuleAntecedent();
VBZ->joinWithAND(verybig, zero);
FuzzyRuleAntecedent* VSPS = new FuzzyRuleAntecedent();
VSPS->joinWithAND(verysmall, possmall);
FuzzyRuleAntecedent* SPS = new FuzzyRuleAntecedent();
SPS->joinWithAND(small, possmall);
FuzzyRuleAntecedent* MPS = new FuzzyRuleAntecedent();
MPS->joinWithAND(medium, possmall);
FuzzyRuleAntecedent* BPS = new FuzzyRuleAntecedent();
BPS->joinWithAND(big, possmall);
FuzzyRuleAntecedent* VBPS = new FuzzyRuleAntecedent();
VBPS->joinWithAND(verybig, possmall);
FuzzyRuleAntecedent* VSPM = new FuzzyRuleAntecedent();
VSPM->joinWithAND(verysmall, posmed);
FuzzyRuleAntecedent* SPM = new FuzzyRuleAntecedent();
SPM->joinWithAND(small, posmed);
FuzzyRuleAntecedent* MPM = new FuzzyRuleAntecedent();
MPM->joinWithAND(medium, posmed);
FuzzyRuleAntecedent* BPM = new FuzzyRuleAntecedent();
BPM->joinWithAND(big, posmed);
FuzzyRuleAntecedent* VBPM = new FuzzyRuleAntecedent();
VBPM->joinWithAND(verybig, posmed);
FuzzyRuleAntecedent* VSPB = new FuzzyRuleAntecedent();
VSPB->joinWithAND(verysmall, posbig);
FuzzyRuleAntecedent* SPB = new FuzzyRuleAntecedent();
SPB->joinWithAND(small, posbig);
FuzzyRuleAntecedent* MPB = new FuzzyRuleAntecedent();
MPB->joinWithAND(medium, posbig);
FuzzyRuleAntecedent* BPB = new FuzzyRuleAntecedent();
BPB->joinWithAND(big, posbig);
FuzzyRuleAntecedent* VBPB = new FuzzyRuleAntecedent();
VBPB->joinWithAND(verybig, posbig);
FuzzyRuleConsequent* VFVS = new FuzzyRuleConsequent();
VFVS->addOutput(Lveryfast);
VFVS->addOutput(Rveryslow);
FuzzyRuleConsequent* FVS = new FuzzyRuleConsequent();
FVS->addOutput(Lfast);
FVS->addOutput(Rveryslow);
FuzzyRuleConsequent* MVS = new FuzzyRuleConsequent();
MVS->addOutput(Lmid);
MVS->addOutput(Rveryslow);
FuzzyRuleConsequent* SVS = new FuzzyRuleConsequent();
SVS->addOutput(Lslow);
SVS->addOutput(Rveryslow);
FuzzyRuleConsequent* SS = new FuzzyRuleConsequent();
SS->addOutput(Lslow);
SS->addOutput(Rslow);
FuzzyRuleConsequent* MM = new FuzzyRuleConsequent();
MM->addOutput(Lmid);
MM->addOutput(Rmid);
FuzzyRuleConsequent* FF = new FuzzyRuleConsequent();
FF->addOutput(Lfast);
FF->addOutput(Rfast);
FuzzyRuleConsequent* VFVF = new FuzzyRuleConsequent();
VFVF->addOutput(Lveryfast);
VFVF->addOutput(Rveryfast);
FuzzyRuleConsequent* VSVF = new FuzzyRuleConsequent();
VSVF->addOutput(Lveryslow);
VSVF->addOutput(Rveryfast);
FuzzyRuleConsequent* VSF = new FuzzyRuleConsequent();
VSF->addOutput(Lveryslow);
VSF->addOutput(Rfast);
FuzzyRuleConsequent* VSM = new FuzzyRuleConsequent();
VSM->addOutput(Lveryslow);
VSM->addOutput(Rmid);
FuzzyRuleConsequent* VSS = new FuzzyRuleConsequent();
VSS->addOutput(Lveryslow);
VSS->addOutput(Rslow);
FuzzyRule* fuzzyRule01 = new FuzzyRule(1, VSNB, FVS );
FuzzyRule* fuzzyRule02 = new FuzzyRule(2, SNB, VFVS );
FuzzyRule* fuzzyRule03 = new FuzzyRule(3, MNB, VFVS );
FuzzyRule* fuzzyRule04 = new FuzzyRule(4, BNB, VFVS );
FuzzyRule* fuzzyRule05 = new FuzzyRule(5, VBNB, VFVS );
FuzzyRule* fuzzyRule06 = new FuzzyRule(6, VSNM, MVS );
FuzzyRule* fuzzyRule07 = new FuzzyRule(7, SNM, FVS );
FuzzyRule* fuzzyRule08 = new FuzzyRule(8, MNM, VFVS );
FuzzyRule* fuzzyRule09 = new FuzzyRule(9, BNM, VFVS );
FuzzyRule* fuzzyRule10 = new FuzzyRule(10, VBNM, VFVS );
FuzzyRule* fuzzyRule11 = new FuzzyRule(11, VSNS, SVS );
FuzzyRule* fuzzyRule12 = new FuzzyRule(12, SNS, MVS );
FuzzyRule* fuzzyRule13 = new FuzzyRule(13, MNS, FVS );
FuzzyRule* fuzzyRule14 = new FuzzyRule(14, BNS, VFVS );
FuzzyRule* fuzzyRule15 = new FuzzyRule(15, VBNS, VFVS );
FuzzyRule* fuzzyRule16 = new FuzzyRule(16, VSZ, SS );
FuzzyRule* fuzzyRule17 = new FuzzyRule(17, SZ, SS );
FuzzyRule* fuzzyRule18 = new FuzzyRule(18, MZ, MM );
FuzzyRule* fuzzyRule19 = new FuzzyRule(19, BZ, FF );
FuzzyRule* fuzzyRule20 = new FuzzyRule(20, VBZ, VFVF );
FuzzyRule* fuzzyRule21 = new FuzzyRule(21, VSPS, VSS );
FuzzyRule* fuzzyRule22 = new FuzzyRule(22, SPS, VSM );
FuzzyRule* fuzzyRule23 = new FuzzyRule(23, MPS, VSF );
FuzzyRule* fuzzyRule24 = new FuzzyRule(24, BPS, VSVF );
FuzzyRule* fuzzyRule25 = new FuzzyRule(25, VBPS, VSVF );
FuzzyRule* fuzzyRule26 = new FuzzyRule(26, VSPM, VSS );
FuzzyRule* fuzzyRule27 = new FuzzyRule(27, SPM, VSF );
FuzzyRule* fuzzyRule28 = new FuzzyRule(28, MPM, VSVF );
FuzzyRule* fuzzyRule29 = new FuzzyRule(29, BPM, VSVF );
FuzzyRule* fuzzyRule30 = new FuzzyRule(30, VBPM, VSVF );
FuzzyRule* fuzzyRule31 = new FuzzyRule(31, VSPB, VSM );
FuzzyRule* fuzzyRule32 = new FuzzyRule(32, SPB, VSVF );
FuzzyRule* fuzzyRule33 = new FuzzyRule(33, MPB, VSVF );
FuzzyRule* fuzzyRule34 = new FuzzyRule(34, BPB, VSVF ); //VSVF
FuzzyRule* fuzzyRule35 = new FuzzyRule(35, VBPB, VSVF );
fuzzy->addFuzzyRule(fuzzyRule01);
fuzzy->addFuzzyRule(fuzzyRule02);
fuzzy->addFuzzyRule(fuzzyRule03);
fuzzy->addFuzzyRule(fuzzyRule04);
fuzzy->addFuzzyRule(fuzzyRule05);
fuzzy->addFuzzyRule(fuzzyRule06);
fuzzy->addFuzzyRule(fuzzyRule07);
fuzzy->addFuzzyRule(fuzzyRule08);
fuzzy->addFuzzyRule(fuzzyRule09);
fuzzy->addFuzzyRule(fuzzyRule10);
fuzzy->addFuzzyRule(fuzzyRule11);
fuzzy->addFuzzyRule(fuzzyRule12);
fuzzy->addFuzzyRule(fuzzyRule13);
fuzzy->addFuzzyRule(fuzzyRule14);
fuzzy->addFuzzyRule(fuzzyRule15);
fuzzy->addFuzzyRule(fuzzyRule16);
fuzzy->addFuzzyRule(fuzzyRule17);
fuzzy->addFuzzyRule(fuzzyRule18);
fuzzy->addFuzzyRule(fuzzyRule19);
fuzzy->addFuzzyRule(fuzzyRule20);
fuzzy->addFuzzyRule(fuzzyRule21);
fuzzy->addFuzzyRule(fuzzyRule22);
fuzzy->addFuzzyRule(fuzzyRule23);
fuzzy->addFuzzyRule(fuzzyRule24);
fuzzy->addFuzzyRule(fuzzyRule25);
fuzzy->addFuzzyRule(fuzzyRule26);
fuzzy->addFuzzyRule(fuzzyRule27);
fuzzy->addFuzzyRule(fuzzyRule28);
fuzzy->addFuzzyRule(fuzzyRule29);
fuzzy->addFuzzyRule(fuzzyRule30);
fuzzy->addFuzzyRule(fuzzyRule31);
fuzzy->addFuzzyRule(fuzzyRule32);
fuzzy->addFuzzyRule(fuzzyRule33);
fuzzy->addFuzzyRule(fuzzyRule34);
fuzzy->addFuzzyRule(fuzzyRule35);
}
void loop()
{
//getAllDistances(); //to be used in pt 2 of code
updateOdometry();
Serial.print("Dist: ");
Serial.print (dist_from_target);
Serial.print(" Diff Angle: ");
Serial.println(diff_angle * 180 / PI);
fuzzy->setInput(1, dist_from_target); //todo: ADD DISTANCE FROM TARGET
fuzzy->setInput(2, diff_angle * 180 / PI); //todo: ADD ANGLE DIFFERENCE
fuzzy->fuzzify();
Serial.print("distance pertinence: ");
Serial.print(verybig->getPertinence());
Serial.print(", ");
Serial.print(big->getPertinence());
Serial.print(", ");
Serial.print(medium->getPertinence());
Serial.print(", ");
Serial.print(small->getPertinence());
Serial.print(", ");
Serial.println(verysmall->getPertinence());
Serial.print("angle pertinence: ");
Serial.print(negbig->getPertinence());
Serial.print(", ");
Serial.print(negmed->getPertinence());
Serial.print(", ");
Serial.print(negsmall->getPertinence());
Serial.print(", ");
Serial.print(zero->getPertinence());
Serial.print(", ");
Serial.print(possmall->getPertinence());
Serial.print(", ");
Serial.print(posmed->getPertinence());
Serial.print(", ");
Serial.println(posbig->getPertinence());
Serial.println(fuzzy->isFiredRule(34));
Serial.println(fuzzy->isFiredRule(17));
float targetvl = fuzzy->defuzzify(1);
float targetvr = fuzzy->defuzzify(2);
Serial.print("Vl: \t");
Serial.print(targetvl);
Serial.print("\t Vr: \t");
Serial.println(targetvr);
moveRobot(targetvl, targetvr);
delay(100);
}
| true |
45d51dfd74ea9c89d217c8746e3948cc2517ad5f | C++ | sbrunodev/estrutura-de-dados | /Arquivo Texto/Lista Exercicios - Arquivo Texto/Ex 12/Ex 12.cpp | UTF-8 | 703 | 2.671875 | 3 | [] | no_license | #include <conio2.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int contLetra (char nomeArq[50])
{
FILE *Arq = fopen (nomeArq,"r");
char linha[99];
int i,lin=0,y=0,x,contl=0;
if (Arq==NULL)
printf ("\n Arquivo nao aberto ! ");
else
{
char letra;
printf ("Informe a Letra :\n ");
scanf ("%c",&letra);
fgets(linha,99,Arq);
while (!feof(Arq))
{
printf ("%d - %s",lin,linha);
x=0;
for (i=0;i<99;i++)
{
if (linha[i]==letra)
{
x++;
}
}
if (x>y)
{
y=x;
contl=lin;
}
lin++;
fgets(linha,99,Arq);
}
return contl;
}
fclose(Arq);
}
int main ()
{
printf ("\n\t Linha: %d",contLetra("Arquivo.txt"));
}
| true |
9e6996153a16840fef4d073197e3fd5bc374f876 | C++ | dagil02/TaxiRevengeDLC | /GTT/MouseClickIC.h | UTF-8 | 478 | 2.59375 | 3 | [] | no_license | #pragma once
#include "ControlType.h"
class Button;
class MouseClickIC :
public ControlType {
public:
MouseClickIC(int key = SDL_BUTTON_LEFT);
virtual ~MouseClickIC();
//redefnie el m�todo dado que esta clase s�lo usa Button para tratar su input
virtual void handleInput(GameObject* o, Uint32 deltaTime, const SDL_Event& event);
virtual void update(GameObject* o, Uint32 deltaTime){}
void setButton(Button* b);
private:
Button* b_;
int mouseClickKey_;
};
| true |
de0718464f5e770d68d814ab0e0160f8e056a8f0 | C++ | felixnaredi/wrum | /Playground/HelloTriangle/App.cpp | UTF-8 | 1,058 | 2.671875 | 3 | [] | no_license | // App.cpp
//
// Author: Felix Naredi
// Date: 2018-07-18 18:30:19 +0200
//
#include <stdexcept>
#include <sstream>
#include <GL/glew.h>
#include <GLFW/glfw3.h>
namespace plg
{
GLFWwindow* window;
void key_callback(
GLFWwindow* window,
int key,
int scancode,
int action,
int mods)
{
if((mods & GLFW_MOD_CONTROL) && key == GLFW_KEY_W) {
glfwSetWindowShouldClose(window, GLFW_TRUE);
}
}
void app_init()
{
if(glfwInit() != GLFW_TRUE) {
throw std::runtime_error("Failed to init GLFW");
}
window = glfwCreateWindow(377, 377, "Window", NULL, NULL);
glfwMakeContextCurrent(window);
auto sts = glewInit();
if(sts != GLEW_OK) {
std::stringstream ss;
ss << "Failed to init GLEW - " << glewGetErrorString(sts);
throw std::runtime_error(ss.str());
}
glfwSetKeyCallback(window, key_callback);
}
bool should_close() noexcept { return glfwWindowShouldClose(window) == GLFW_TRUE; }
void swap_buffers() noexcept { glfwSwapBuffers(window); }
void wait_events() noexcept { glfwWaitEvents(); }
}
| true |
99ef64d5b720070cd8329d45269f8a65fc3982d4 | C++ | marcuslamounier/SI-DataStruc | /Ex03/main.cpp | UTF-8 | 3,725 | 3.515625 | 4 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <iomanip>
#include <iostream>
using namespace std;
typedef struct produto produto;
struct produto {
char nome[40];
int codigo;
double preco;
int quantidade;
};
void cadastrarNome(char *nome) {
char n[40];
cout << "Nome: ";
scanf("%s", &n);
strcpy(nome, n);
}
int cadastrarCodigo() {
srand(time(0));
int codigo = rand() % 50;
cout << "Codigo " << codigo << endl;;
return codigo;
}
void cadastrarPreco(double *preco) {
double p;
do {
cout << "Preco: ";
cin >> p;
if (p <= 0) cout << "O preco deve ser positivo." << endl;
} while (p <= 0);
*preco = p;
}
void cadastrarQuantidade(produto *listaProdutos) {
int quantidade;
cout << "Quantidade: ";
do {
cin >> quantidade;
if (quantidade < 0) cout << "A quantidade nao pode ser negativa." << endl;
} while (quantidade < 0);
listaProdutos->quantidade = quantidade;
}
produto *preencherDados(int *quantidade) {
produto *produtos = (produto*) malloc((*quantidade) * sizeof(produto));
produto *listaProdutos;
listaProdutos = produtos;
for (int i = 1; i <= *quantidade; i++) {
cout << endl;
cout << "PRODUTO " << i << endl;
int codigo = cadastrarCodigo();
listaProdutos->codigo = codigo;
char nome[40];
char *ptrNome;
ptrNome = nome;
cadastrarNome(ptrNome);
strcpy(listaProdutos->nome, nome);
double preco;
cadastrarPreco(&preco);
listaProdutos->preco = preco;
cadastrarQuantidade(listaProdutos);
listaProdutos += sizeof(produto);
}
return produtos;
}
produto* cadastrarProdutos(int *quantidade) {
int q;
do {
cout << "Digite a quantidade de produtos: ";
cin >> q;
if (q <= 0) cout << "A quantidade deve ser positiva." << endl;
} while (q <= 0);
*quantidade = q;
produto *produtos = (produto*) malloc((*quantidade) * sizeof(produto));
produto *listaProdutos;
listaProdutos = preencherDados(quantidade);
return listaProdutos;
}
void imprimirProduto(produto *p, int pos) {
cout << "PRODUTO " << pos << endl;
cout << "Codigo: " << p->codigo << endl;
cout << "Nome: " << p->nome << endl;
cout << "Preco: " << std::fixed << std::setprecision(2) << p->preco << endl;
cout << "Quantidade: " << p->quantidade << endl;
cout << endl;
}
void listarProdutos(produto *ptrProduto, int *quantidade, int pos) {
imprimirProduto(ptrProduto, pos);
if (pos < *quantidade) {
ptrProduto += sizeof(produto);
pos++;
listarProdutos(ptrProduto, quantidade, pos);
}
}
void imprimirMenu() {
cout << "CADASTRO DE PRODUTOS" << endl;
cout << "A - Preencher dados" << endl;
cout << "B - Exibir produtos cadastrados no estoque" << endl;
cout << "C - Finalizar" << endl;
}
int main () {
char opcao;
int quantidade;
int *ptrQuantidade;
ptrQuantidade = &quantidade;
produto *produtos;
do {
cout << endl;
imprimirMenu();
cout << "Opcao escolhida: ";
cin >> opcao;
cout << endl;
switch (opcao) {
case 'A':
produtos = cadastrarProdutos(ptrQuantidade);
system("cls");
break;
case 'B':
listarProdutos(produtos, ptrQuantidade, 1);
break;
case 'C':
break;
default:
cout <<"Digite uma opcao valida!" << endl;
}
} while (opcao != 'C');
system("pause");
return 0;
} | true |
a40539a51e736eff16a88a1c9d8017c2cabc3a17 | C++ | Kiritow/OJ-Problems-Source | /HDOJ/3178_autoAC.cpp | UTF-8 | 818 | 2.78125 | 3 | [] | no_license | #include <cstdio>
#include <iostream>
using namespace std;
#define N 1005
#define L 0.0000001
double a[N];
double b[N];
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
int n;
scanf("%d",&n);
int i = 0;
for(i = 1; i <= n; i++)
scanf("%lf%lf",&a[i],&b[i]);
int p1,p2;
scanf("%d%d",&p1,&p2);
double x1 = a[p2] - a[p1];
double y1 = b[p2] - b[p1];
for(i = 1; i <= n; i++)
{
double x2 = a[i] - a[p1];
double y2 = b[i] - b[p1];
double sum = x1*y2 - x2*y1;
if(sum < -L)
printf("Right\n");
else if(sum > L)
printf("Left\n");
else printf("On\n");
}
}
return 0;
}
| true |
69819615deeab9b5c7b73799ec95dbf847ee92e4 | C++ | jatin-js/Data-Structures-And-Algorithms | /DataStructure/Trees/Adelson-VelskiiLandes/AVLFakeDriver.cpp | UTF-8 | 388 | 2.765625 | 3 | [] | no_license |
#include<iostream>
#include"AVL.h"
using namespace std;
#include"AVL.cpp"
int main()
{
struct Node *root=NULL;
for(int i=5;i<=55;i+=10){
struct Node* newNode=new struct Node(i);
insertNode(&root, newNode);
}
for(int i=1;i<=4;i++){
struct Node* newNode=new struct Node(i);
insertNode(&root, newNode);
}
preorder(root);
cout<<endl;
preorder(root);
return 0;
}
| true |
815d460e9048228eda8209117fc8c8b7328ded0d | C++ | MatosThiago/ProgramacaoCompetitiva | /Módulo 2/Aplicação/C. Pássaros Famintos.cpp | UTF-8 | 963 | 2.65625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int check(long long N, long long Q);
int main() {
int T;
scanf("%d", &T);
long long X, Y, Q;
for(int i = 0; i < T; i++) {
scanf("%lld %lld", &Y, &X);
if(X >= Y) {
printf("%lld\n", Y);
} else {
Q = Y - X;
long long l = 0,
r = Y,
mid;
while(l < r) {
mid = (l + r) / 2;
if(check(mid, Q)) {
r = mid;
} else {
l = mid + 1;
}
}
if(check(l,Q)) {
printf("%lld\n", X + l);
} else {
printf("%lld\n", X + r);
}
}
}
return 0;
}
int check(long long N, long long Q) {
if((double) N * (N + 1) / 2 >= 1e18) {
return 1;
}
long long R = (N + 1) * N / 2;
return R >= Q;
} | true |
87721794da9abc8ffa37b2831157987b3721555c | C++ | dklollol/newton | /square/square.cc | UTF-8 | 1,416 | 2.59375 | 3 | [] | no_license | #include <iostream>
#include <libplayerc++/playerc++.h>
using namespace PlayerCc;
void run_square(char* host, int port, int device_index) {
PlayerClient robot(host, port);
Position2dProxy pp(&robot, device_index);
double move_speed = 0.2;
double move_turn_init = -5;
timespec move_sleep_init = {0, 300000000};
// tomgang i 300 ms
pp.SetSpeed(move_speed, DTOR(move_turn_init));
nanosleep(&move_sleep_init, NULL);
double move_turn_rate = 0.0;
timespec move_sleep = {5, 100000000};
double turn_speed = 0.0;
double turn_turn_rate = 15;
timespec turn_sleep = {6, 0};
for (int t = 0; t < 4; t++) {
// GØR DET FØLGENDE FIRE GANGE!
for (int i = 0; i < 4; i++) {
// KØR 1 METER FREMAD!
pp.SetSpeed(move_speed, DTOR(move_turn_rate));
nanosleep(&move_sleep, NULL);
// DREJ 90 GRADER!
pp.SetSpeed(turn_speed, DTOR(turn_turn_rate));
nanosleep(&turn_sleep, NULL);
}
}
// STOP!
timespec stop_sleep = {1, 0};
pp.SetSpeed(0, 0);
nanosleep(&stop_sleep, NULL);
}
int main(int argc, char* argv[]) {
char* host;
if (argc > 1) {
host = argv[1];
}
else {
host = (char*) "localhost";
}
const int port = 6665;
const int device_index = 0;
try {
run_square(host, port, device_index);
return EXIT_SUCCESS;
} catch (PlayerCc::PlayerError e) {
std::cerr << e << std::endl;
return EXIT_FAILURE;
}
}
| true |
4eacf959003c54631044e817a3a57f202e6f1654 | C++ | 0318648DEL/Graphics | /graphics drills/graphics drills/WHY.cpp | UHC | 8,363 | 3.09375 | 3 | [] | no_license | #include"pch.h"
#include<gl/freeglut.h>
#include<iostream>
#include<time.h>
#include<stdlib.h>
#include<math.h>
using namespace std;
///////////////////////////
// ݹ Լ //
///////////////////////////
GLvoid drawScene(GLvoid);
GLvoid Reshape(int w, int h);
GLvoid Keyboard(unsigned char key, int x, int y);//Ű
GLvoid Mouse(int button, int state, int x, int y);//콺
//GLvoid Time(int sec);//Ÿ̸
//////////////////////////
// Լ //
//////////////////////////
void line();
void init();
void sin();
void cos();
void spring();
void print();
void rotation();
void move();
void moveSum();
void plusMove();
void minusMove();
void zoomIn();
void zoomOut();
//////////////////////////
// //
//////////////////////////
GLfloat coordinatePoint[1000][2];//
GLfloat xPos = 0.0f, yPos = 0.0f;//ǥ
GLfloat moveXpos = 0.0f, moveYpos = 0.0f;// ǥ ̵ϴ Ÿ
GLint state = 0;//Ű
GLint scale = 1;// ȭ
GLfloat xposSum = 0, yposSum = 0;// ǥ ̵Ÿ
/////////////////////////////////////////
// //
/////////////////////////////////////////
void main(int argc, char *argv[])
{
//ʱȭ Լ
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA); // ÷
glutInitWindowPosition(100, 100); // ġ
glutInitWindowSize(800, 800); // ũ
glutCreateWindow("Practice12"); // ( ̸)
//ݹԼ
glutDisplayFunc(drawScene); // Լ
glutReshapeFunc(Reshape);
glutMouseFunc(Mouse);//콺
//glutTimerFunc(1000,Time,1);//Ÿ̸
glutKeyboardFunc(Keyboard);//Ű
glutMainLoop();//GLUT ̺Ʈ μ
}
//////////////////////////////
// Լ //
//////////////////////////////
GLvoid drawScene(GLvoid)
{
glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // 'Magenta'
glClear(GL_COLOR_BUFFER_BIT); // ü ĥϱ
//Լ ȣ
line();
switch (state)
{
case 1://COS
init();
cos();
print();
break;//end c
case 2://SIN
init();
sin();
print();
break;//end i
case 3://SPRING
init();
spring();
print();
break;// end p
case 4://ROTATION
print();
break;// end r
case 5://UP
move();
print();
break;//end l
case 6://DOWN
move();
print();
break;//end .
case 7://LEFT
move();
print();
break;//end ,
case 8://RIGHT
move();
print();
break;//end /
case 9://SCALE-ZOOM IN
print();
break;//end s
case 10://SCALE-ZOOM OUT
print();
break;//end a
}
glutSwapBuffers(); // ȭ鿡 ϱ
}
////////////////////////////////////
// COORDINATE //
////////////////////////////////////
GLvoid Reshape(int w, int h)
{
glViewport(0, 0, w, h);
glOrtho(-10, 10, -10, 10, -1.0, 1.0);
}
///////////////////////////////////////////////////
// KEYBOARD //
///////////////////////////////////////////////////
GLvoid Keyboard(unsigned char key, int x, int y)
{
switch (key)
{
case'c'://COS
state = 1;
drawScene();
break;//end c
case'i'://SIN
state = 2;
drawScene();
break;//end i
case 'p'://SPRING
state = 3;
drawScene();
break;// end p
case 'r'://ROTATION
//minusMove();
rotation();
//plusMove();
state = 4;
drawScene();
break;//end r
case 'l'://UP
moveXpos = 0;
moveYpos = 0.5;
state = 5;
drawScene();
break;//end l
case '.'://DOWN
moveXpos = 0;
moveYpos = -0.5;
state = 6;
drawScene();
break;//end .
case ','://LEFT
moveXpos = -0.5;
moveYpos = 0;
state = 7;
drawScene();
break;//endl ,
case '/'://RIGHT
moveXpos = 0.5;
moveYpos = 0;
state = 8;
drawScene();
break;//end /
case 's'://SCALE-ZOOM IN
state = 9;
zoomIn();
drawScene();
break;//end s
case 'a'://SCALE-ZOOM OUT
state = 10;
zoomOut();
drawScene();
break;//end a
}
}
///////////////////////////////////////////////////
// MOUSE //
///////////////////////////////////////////////////
GLvoid Mouse(int button, int state, int x, int y)
{
if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN)
{
}
}
//////////////////////
// TIMER //
//////////////////////
//GLvoid Time(int sec)
//{
// glutPostRedisplay();
// glutTimerFunc(1000,Time,1);
//}
/////////////////////////////////////////////////////////////////////
// FUNCTION //
/////////////////////////////////////////////////////////////////////
////////////
// LINE //
////////////
void line()
{
//Y
glColor4f(1.0f, 1.0f, 0.0f, 1.0f);//
glPointSize(1.0f);// ũ
glBegin(GL_LINE_STRIP);
glVertex3f(0.0f, -800.0f, 1.0f);// ǥ
glVertex3f(0.0f, 800.0f, 1.0f);// ǥ
glEnd();
//X
glColor4f(1.0f, 1.0f, 0.0f, 1.0f);//
glPointSize(1.0f);// ũ
glBegin(GL_LINE_STRIP);
glVertex3f(-800.0f, 0.0f, 1.0f);// ǥ
glVertex3f(800.0f, 0.0f, 1.0f);// ǥ
glEnd();
}
//////////
// INIT //
//////////
void init()
{
//X, Y ʱȭ
xPos = -10.0f;
yPos = 0.0f;
//̵ ʱȭ
moveXpos = 0.0f;
moveYpos = 0.0f;
// ʱȭ
scale = 1;
// ʱȭ
for (int i = 0; i < 1000; ++i)
{
coordinatePoint[i][0] = 0.0f;
coordinatePoint[i][1] = 0.0f;
}
}
////////////
// SIN //
////////////
void sin()
{
for (int i = 0; i < 1000; ++i)
{
xPos += 0.1;
yPos = sin(xPos);
coordinatePoint[i][0] = xPos;
coordinatePoint[i][1] = yPos;
}
}
////////////
// COS //
////////////
void cos()
{
for (int i = 0; i < 1000; ++i)
{
xPos += 0.1;
yPos = cos(xPos);
coordinatePoint[i][0] = xPos;
coordinatePoint[i][1] = yPos;
}
}
////////////////
// PRINT //
////////////////
void print()
{
glColor4f(1.0f, 0.0f, 0.0f, 1.0f);//
glPointSize(1.0f);// ũ
glBegin(GL_LINE_STRIP);
for (int i = 0; i < 1000; ++i)
glVertex3f(coordinatePoint[i][0], coordinatePoint[i][1], 1.0f);// ǥ
glEnd();
}
//////////////////
// ROTATION //
//////////////////
void rotation()
{
float DEGINRAD = 3.14159 / 180;
float degInRad = 10.0f*DEGINRAD;
for (int i = 0; i < 1000; ++i)
{
coordinatePoint[i][0] = coordinatePoint[i][0] * cos(degInRad) - coordinatePoint[i][1] * sin(degInRad);
coordinatePoint[i][1] = coordinatePoint[i][0] * sin(degInRad) + coordinatePoint[i][1] * cos(degInRad);
}
}
//////////////
// SPRING //
//////////////
void spring()
{
float radius = 1;//
float DEGINRAD = 3.14159 / 180;
float degInRad = 0.0f;
float Nums = 0;//x
float x_left = 5.0;//߽ǥ
float y_left = 0.0;//߽ǥ
for (int i = 0; i < 1000; ++i)
{
degInRad = i * DEGINRAD;
coordinatePoint[i][0] = (cos(degInRad)*radius) + x_left + Nums;
coordinatePoint[i][1] = (sin(degInRad)*radius) + y_left;
Nums -= 0.01;
}
}
//////////////
// MOVE //
//////////////
void move()
{
for (int i = 0; i < 1000; ++i)
{
coordinatePoint[i][0] += moveXpos;
coordinatePoint[i][1] += moveYpos;
}
moveSum();
}
//////////////
// MOVESUM //
//////////////
void moveSum()
{
xposSum += moveXpos;
yposSum += moveYpos;
}
////////////////
// PLUSMOVE //
////////////////
void plusMove()
{
for (int i = 0; i < 1000; ++i)
{
coordinatePoint[i][0] += xposSum;
coordinatePoint[i][1] += yposSum;
}
}
/////////////////
// MINUSMOVE //
/////////////////
void minusMove()
{
for (int i = 0; i < 1000; ++i)
{
coordinatePoint[i][0] -= xposSum;
coordinatePoint[i][1] -= yposSum;
}
}
////////////
// SIZE //
////////////
void size()
{
for (int i = 0; i < 1000; ++i)
{
coordinatePoint[i][0] *= scale;
coordinatePoint[i][1] *= scale;
}
}
//////////////
// ZOOMIN //
//////////////
void zoomIn()
{
minusMove();
for (int i = 0; i < 1000; ++i)
{
coordinatePoint[i][0] *= 1.5f;
coordinatePoint[i][1] *= 1.5f;
}
plusMove();
}
///////////////
// ZOOMOUT //
///////////////
void zoomOut()
{
minusMove();
for (int i = 0; i < 1000; ++i)
{
coordinatePoint[i][0] /= 1.5f;
coordinatePoint[i][1] /= 1.5f;
}
plusMove();
}
//////////////
// CIRCLE //
//////////////
/*
void circle()
{
float radius=1;//
float DEGINRAD=3.14159/180;
float x_left = 5.0;//߽ǥ
float y_left = 0.0;//߽ǥ
glBegin(GL_LINE_STRIP);
for (int i=0; i<1980;i++)
{
float degInRad=i*DEGINRAD;
glVertex2f(cos(degInRad)*radius + x_left, sin(degInRad)*radius + y_left);
}
glEnd();
}
*/ | true |
87ff05ed864551feb3c84c63fe4def7dd5ea2ba8 | C++ | austinholst/RedBlackTreeInsertion | /rb.cpp | UTF-8 | 8,953 | 3.65625 | 4 | [] | no_license | #include <iostream>
#include <fstream>
#include <cstring>
#include <stdlib.h>
using namespace std;
/* Author: Austin Holst
* Date: 4 - 30 - 18
* Code: Creates and prints out a red black data tree from user input
*/
//Struct for nodes
struct Node {
Node* parent;
Node* left;
Node* right;
int color;
int data;
};
//Prototypes
void print(Node* head, int space);
Node* parent(Node* n);
Node* grandparent(Node* n);
Node* sibling(Node* n);
Node* unlce(Node* n);
void rotate_left(Node* &head, Node* n);
void rotate_right(Node* &head, Node* n);
void insert(Node* &head, Node* n);
void insert_recurse(Node* &head, Node* n);
void insert_repair_tree(Node* &head, Node* n);
void case1(Node* &head, Node* n);
void case2(Node* &head, Node* n);
void case3(Node* &head, Node* n);
void case4(Node* &head, Node* n);
void case4Part2(Node* &head, Node* n);
//Constants for red or black
const int BLACK = 0;
const int RED = 1;
//Head declaration
Node* head = new Node;
int main() {
bool running = true;
Node* nodeArray[100];
int* numbers = new int[200];
int counter = 0;
head = NULL;
cout << "Welcome to Red Black Tree! Where coders go to die." << endl;
while(running == true) {
cout << "Would you like to read in numbers 'manually' or from a 'file' or 'print' or 'quit'?" << endl;
char answer[10];
cin >> answer;
if(strcmp(answer, "manually") == 0) {
int number;
Node* newNode = new Node;
cout << "Input a number" << endl;
cin >> newNode->data;
insert(head, newNode);
}
else if(strcmp(answer, "file") == 0) {
cout << "What is the name of the file you wish to read in from (be sure to add the .txt)" << endl;
char fileName[100];
//Take in the name of the file
cin >> fileName;
char input[200];
//Set the file to the user input
ifstream myFile(fileName);
//If the file is opened correctly
if(myFile.is_open()) {
myFile.getline(input, 200);
//Close the file
myFile.close();
//From here on down it's the same as the manual input
for(int i = 0; i < strlen(input); i++) {
int start = i;
int length = 1;
while(input[i + 1] != char(44) && i < strlen(input)) {
length++;
i++;
}
char* charNum = new char[length + 1];
charNum[length] = '\0';
for(int j = 0; j < length; j++) {
charNum[j] = input[start + j];
}
numbers[counter] = atoi(charNum);
counter++;
i++;
}
for(int i = 0; i < counter; i++) {
Node* newNode = new Node;
newNode->data = numbers[i];
nodeArray[i] = newNode;
}
for(int i = 0; i < counter; i++) {
cout << "Node " << i << " Data: " << nodeArray[i]->data << endl;
insert(head, nodeArray[i]);
}
}
}
else if(strcmp(answer, "print") == 0) {
print(head, 0);
}
else if(strcmp(answer, "quit") == 0) {
cout << "Ending program" << endl;
running = false;
}
else {
cout << "That wasn't one of the options..." << endl;
}
}
return 0;
}
//Print out the tree
void print(Node* head, int space) {
if(head->right != NULL) {
print(head->right, ++space);
space--;
}
for(int i = 1; i <= space; i++) {
cout << "\t";
}
cout << head->data;
if(head->color == RED) {
cout << "R" << endl;
}
else {
cout << "B" << endl;
}
if(head->left != NULL) {
print(head->left, ++space);
space--;
}
}
//Gets the nodes parent
Node* parent(Node* n) {
return n->parent;
}
//Gets the nodes grandparent
Node* grandparent(Node* n) {
Node* p = parent(n);
if(p == NULL) {
return NULL;
}
else {
return parent(p);
}
}
//Gets the nodes sibling
Node* sibling(Node* n) {
Node* p = parent(n);
if(p == NULL) {
return NULL;
}
if(n == p->left) {
return p->right;
}
else {
return p->left;
}
}
//Gets the nodes uncle
Node* uncle(Node* n) {
Node* p = parent(n);
Node* g = grandparent(n);
if(g == NULL) {
return NULL;
}
return sibling(p);
}
//Rotate to the left
void rotate_left(Node* &head, Node* n) {
cout << "ROTATE LEFT" << endl;
Node* nNew = n->right;
//Make sure nNew is not a leaf
if(nNew != NULL) {
//set connections
n->right = nNew->left;
nNew->left = n;
nNew->parent = n->parent;
n->parent = nNew;
//Set the parent to child conneciton
if(nNew->parent != NULL && nNew->parent->left == n) {
nNew->parent->left = nNew;
}
else if(nNew->parent != NULL && nNew->parent->right == n) {
nNew->parent->right = nNew;
}
if(n == head) {
head = nNew;
head->color = BLACK;
}
}
}
//Rotate to the right
void rotate_right(Node* &head, Node* n) {
cout << "ROTATE RIGHT" << endl;
Node* nNew = n->left;
//Make sure nNew is not a leaf
if(nNew != NULL) {
//set parent to child connection
if(n->parent != NULL && n == n->parent->left) {
n->parent->left = n->left;
}
else if(n->parent != NULL && n == n->parent->right) {
n->parent->right = n->left;
}
n->left = nNew->right;
//set child to parent connection
if(nNew->right != NULL) {
nNew->right->parent = n;
}
nNew->right = n;
nNew->parent = n->parent;
n->parent = nNew;
//if you swapped out the head then change it
if(n == head) {
head = nNew;
head->color = BLACK;
}
}
}
//Put the new node into the tree
void insert(Node* &head, Node* n) {
insert_recurse(head, n);
//repair the tree in case any of the red-black properties have been violated
insert_repair_tree(head, n);
}
//Recursively go down the tree until a leaf is found
void insert_recurse(Node* &head, Node* n) {
//If theres no head
if(head == NULL) {
head = n;
//insert the n node
n->parent = NULL;
n->left = NULL;
n->right = NULL;
n->color = RED;
}
//if n is less than head
else if(head != NULL && n->data < head->data) {
if(head->left != NULL) {
insert_recurse(head->left, n);
return;
}
else {
head->left = n;
//insert the n node
n->parent = head;
n->left = NULL;
n->right = NULL;
n->color = RED;
}
}
//If n is greater than head
else {
if(head->right != NULL) {
insert_recurse(head->right, n);
return;
}
else {
head->right = n;
//insert the n node
n->parent = head;
n->left = NULL;
n->right = NULL;
n->color = RED;
}
}
}
//Call of the different case functions
void insert_repair_tree(Node* &head, Node* n) {
if(parent(n) == NULL) {
case1(head, n);
}
else if(parent(n)->color == BLACK) {
case2(head,n);
}
else if(uncle(n)!= NULL && uncle(n)->color == RED) {
case3(head, n);
}
else {
case4(head, n);
}
}
//if the node entered is the head then make it black
void case1(Node* &head, Node* n) {
if(n->parent == NULL) {
n->color = BLACK;
}
}
//if the node entered has a black parent then you are all gucci
void case2(Node* &head, Node* n) {
return;
}
//Parent and uncle are red
void case3(Node* &head, Node* n) {
parent(n)->color = BLACK;
uncle(n)->color = BLACK;
if(grandparent(n) != head) {
grandparent(n)->color = RED;
}
insert_repair_tree(head, grandparent(n));
}
//Basically every other possibility
void case4(Node* &head, Node* n) {
Node* p = parent(n);
Node* g = grandparent(n);
if(g->left != NULL && g->left->right != NULL && n == g->left->right) {
rotate_left(head, p);
}
else if(g->right != NULL && g->right->left != NULL && n == g->right->left) {
rotate_right(head, p);
n = n->right;
case4Part2(head, n);
return;
}
else if(g->right != NULL && g->right->right !=NULL && n == g->right->right) {
if(g == head) {
if(p-> left != NULL) {
g->right = p->left;
p->left->parent = g;
g->parent = p;
}
else {
g->parent = p;
}
g->right = p->left;
p->left = g;
head = p;
p->right = n;
n->parent = p;
p->color = BLACK;
g->color = RED;
}
else if(g->parent->right != NULL && g == g->parent->right) {
g->parent->right = p;
p->left = g;
p->parent = g->parent;
g->parent = p;
g->right = NULL;
p->color = BLACK;
g->color = RED;
}
else {
g->parent->left = p;
p->left = g;
p->parent = g->parent;
g->parent = p;
g->right = NULL;
p->color = BLACK;
g->color = RED;
}
return;
}
else if(g->left != NULL && g->left->left != NULL && n == g->left->left && n->color == RED && n->parent->color == RED) {
case4Part2(head, n);
return;
}
case4Part2(head, n->left);
}
//rotates to the right or the left around the grandparent is needed and changes color
void case4Part2(Node* &head, Node* n) {
Node* p = parent(n);
Node* g = grandparent(n);
if(n->parent->left != NULL && n == p->left) {
rotate_right(head, g);
}
else {
rotate_left(head, g);
}
p->color = BLACK;
g->color = RED;
}
| true |
b6a6869bb1994e2e03e83a92a6cdcf334abec7bb | C++ | FLynnGame/moleserver | /games/dzpk/GameLogic.h | UTF-8 | 2,391 | 2.609375 | 3 | [
"Apache-2.0"
] | permissive | #ifndef GAME_LOGIC_HEAD_FILE
#define GAME_LOGIC_HEAD_FILE
#include "cdefines.h"
//数值掩码
#define LOGIC_MASK_COLOR 0xFF00 //花色掩码
#define LOGIC_MASK_VALUE 0x00FF //数值掩码
#define CT_HIGH_CARD 1 //高牌
#define CT_ONE_PAIR 2 //对子
#define CT_TWO_PAIR 3 //两对
#define CT_THREE_KIND 4 //三条
#define CT_STRAIGHT 5 //顺子
#define CT_FLUSH 6 //同花
#define CT_FULL_HOUSE 7 //葫芦
#define CT_FOUR_KIND 8 //四条
#define CT_STRAIGHT_FLUSH 9 //同花顺
#define CT_ROYAL_FLUSH 10 //皇家同花顺
//分析结构
struct tagAnalyseResult
{
int nFourCount; //四张数目
int nThreeCount; //三张数目
int nDoubleCount; //两张数目
int nSignedCount; //单张数目
WORD wFourCardData[IDD_MAX_WEAVE_CARD]; //四张列表
WORD wThreeCardData[IDD_MAX_WEAVE_CARD]; //三张列表
WORD wDoubleCardData[IDD_MAX_WEAVE_CARD]; //两张列表
WORD wSignedCardData[IDD_MAX_WEAVE_CARD]; //单张列表
};
class CGameLogic
{
public:
CGameLogic();
~CGameLogic();
//变量定义
private:
static WORD m_wCardListData[IDD_MAX_CARD_COUNT]; //扑克定义
public:
//对比扑克
int CompareCard(WORD wFirstWeave[IDD_WEAVE_COUNT], WORD wNextWeave[IDD_WEAVE_COUNT],WORD wFirstType,WORD wNextType);
//获取组合类型
WORD GetCardType(WORD wHandCartd[IDD_HAND_COUNT],WORD wBoardCard[], int nCardCount, WORD wBestWeaveData[IDD_WEAVE_COUNT]);
//获取数值
WORD GetCardValue(WORD wCardData) { return wCardData&LOGIC_MASK_VALUE; }
//获取花色
WORD GetCardColor(WORD wCardData) { return (wCardData&LOGIC_MASK_COLOR)>>8; }
//混乱扑克
void RandCardList(WORD wCardData[IDD_MAX_CARD_COUNT]);
//获取逻辑值
WORD GetCardLogicValue(WORD wCardData);
private:
//分析扑克
void AnalysebCardData(const WORD wCardData[], int nCardCount, tagAnalyseResult & AnalyseResult);
//排列扑克
void SortCard(WORD wCardData[], int nCardCount);
//排列扑克
void SortCardByLogicValue(WORD wCardData[], int nCardCount);
//是否同花
int GetTongHua(WORD wCardData[],int nCardCount,WORD wTongHuaData[]);
//是否顺子
bool IsShunZi(WORD wCardData[],int nCardCount,WORD wShunziData[IDD_WEAVE_COUNT]);
};
#endif
| true |
1348b9982433d1a8f7333c12918486334dee56fc | C++ | Frogger-Software/Cpp-Dictionary | /Assignment-03_PA_TicTacToe.cpp | UTF-8 | 3,901 | 3.625 | 4 | [
"MIT"
] | permissive | #include <iostream>
using namespace std;
bool isWon(char symbol, char board[][3])
{
// checks for matching symbols
if ((board[0][0] == symbol && board[0][1] == symbol && board[0][2] == symbol) || (board[0][0] == symbol && board[1][0] == symbol && board[2][0] == symbol)) { // checks first column (left) and first row (top)
return true; // if 3 symbols match, returns true to end the While loop in main, ending the game
}
if ((board[1][0] == symbol && board[1][1] == symbol && board[1][2] == symbol) || (board[0][1] == symbol && board[1][1] == symbol && board[2][1] == symbol)) { // checks second column (middle down) and second row (middle horizontal)
return true; // if 3 symbols match, returns true to end the While loop in main, ending the game
}
if ((board[2][0] == symbol && board[2][1] == symbol && board[2][2] == symbol) || (board[0][2] == symbol && board[1][2] == symbol && board[2][2] == symbol)) { // checks third column (right) and third row (bottom)
return true; // if 3 symbols match, returns true to end the While loop in main, ending the game
}
if ((board[0][0] == symbol && board[1][1] == symbol && board[2][2] == symbol) || (board[0][2] == symbol && board[1][1] == symbol && board[2][0] == symbol)) { // checks if all diagonal matches
return true; // if 3 symbols match, returns true to end the While loop in main, ending the game
}
return false; // if none of the checks are true, return false to continue While loop until game is done
}
bool isDraw(char board[][3])
{
for (int row = 0; row < 3; row++) {
for (int column = 0; column < 3; column++) {
if (board[row][column] == ' ') {
return false;//false when any blanks are detected
}
}
}
return true;//true when no blanks detected
}
void displayBoard(char board[][3])
{
cout << "\n-------------" << endl;
cout << "| " << board[0][0] << " | " << board[0][1] << " | " << board[0][2] << " | " << endl;
cout << "-------------" << endl;
cout << "| " << board[1][0] << " | " << board[1][1] << " | " << board[1][2] << " | " << endl;
cout << "-------------" << endl;
cout << "| " << board[2][0] << " | " << board[2][1] << " | " << board[2][2] << " | " << endl;
cout << "-------------" << endl;
}
void makeAMove(char board[][3], char symbol)
{
cout << "Enter a row (0, 1, 2) for player " << symbol << " : ";
int rowIndex;
while (!(cin >> rowIndex)) { // If input was not an integer
cin.clear(); // Reset error flag
cin.ignore(1000, '\n'); // Skip next 1000 chars or until newline
cout << "Wrong type. Enter a row (0, 1, 2) for player " << symbol << " : ";
}
cout << "Enter a column (0, 1, 2) for player " << symbol << ": ";
int columnIndex;
while (!(cin >> columnIndex)) { // If input was not an integer
cin.clear(); // Reset error flag
cin.ignore(1000, '\n'); // Skip next 1000 chars or until newline
cout << "Wrong type. Enter a column (0, 1, 2) for player " << symbol << ": ";
}
if (board[rowIndex][columnIndex] == ' ') {
board[rowIndex][columnIndex] = symbol;
} else {
cout << "This cell is already occupied. Try a different cell" << endl;
makeAMove(board, symbol);
}
}
int main() {
//
// PLEASE DO NOT CHANGE function main
//
char board[3][3] = { { ' ', ' ', ' ' },{ ' ', ' ', ' ' },{ ' ', ' ', ' ' } };
displayBoard(board);
while (true) {
// The first player makes a move
makeAMove(board, 'X');
displayBoard(board);
if (isWon('X', board)) {
cout << "X player won" << endl;
exit(0);
}
else if (isDraw(board)) {
cout << "No winner" << endl;
exit(0);
}
// The second player makes a move
makeAMove(board, 'O');
displayBoard(board);
if (isWon('O', board)) {
cout << "O player won" << endl;
exit(0);
}
else if (isDraw(board)) {
cout << "No winner" << endl;
exit(0);
}
}
return 0;
}
| true |
4ddd5a19c926d201ea56e87e55ed8195274705ab | C++ | mattBoros/dominion-hand-solver | /main.cpp | UTF-8 | 14,737 | 3.25 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <vector>
#include <assert.h>
#include <sys/time.h>
using namespace std;
const bool DEBUG = false;
double get_time() {
struct timeval tp;
gettimeofday(&tp, NULL);
long int t = tp.tv_sec * 1000 + tp.tv_usec / 1000;
return t / 1000.0;
}
string spaces(const uint8_t n) {
string s = "";
for (int i = 0; i < n; ++i) {
s += " ";
}
return s;
}
class Card {
public:
const int8_t card_id;
const string name;
const string type;
const uint8_t actions;
const uint8_t buys;
const uint8_t coins;
const uint8_t cards;
Card() :
card_id(-1),
name("NULL CARD"),
type("NULL"),
actions(UINT8_MAX),
buys(UINT8_MAX),
coins(UINT8_MAX),
cards(UINT8_MAX)
{}
Card(const int8_t card_id,
const string name,
const string type,
const uint8_t actions,
const uint8_t buys,
const uint8_t coins,
const uint8_t cards)
:
card_id(card_id),
name(name),
type(type),
actions(actions),
buys(buys),
coins(coins),
cards(cards) {
}
// Card(const Card &other)
// :
// name(other.name),
// type(other.type),
// actions(other.actions),
// buys(other.buys),
// coins(other.coins),
// cards(other.cards),
// card_id(other.card_id) {
// cout << "BEING OVERWRITTEN" << endl;
// }
// inline Card &operator=(const Card &other) = default;
};
static const Card NULL_CARD;
static const Card COPPER(0, "Copper", "Treasure", 0, 0, 1, 0);
static const Card SILVER(1, "Silver", "Treasure", 0, 0, 2, 0);
static const Card GOLD(2, "Gold", "Treasure", 0, 0, 3, 0);
static const Card LABORATORY(3, "Laboratory", "Action", 1, 0, 0, 2);
static const Card MARKET(4, "Market", "Action", 1, 1, 1, 1);
static const Card MILITIA(5, "Militia", "Action", 0, 0, 2, 0);
static const Card FESTIVAL(6, "Festival", "Action", 2, 1, 2, 0);
static const Card SMITHY(7, "Smithy", "Action", 0, 0, 0, 3);
static const Card VILLAGE(8, "Village", "Action", 2, 0, 0, 1);
static const Card COUNCIL_ROOM(9, "Council Room", "Action", 0, 1, 0, 4);
static const Card THRONE_ROOM(0, "Throne Room", "Action", 0, 0, 0, 0);
static const Card KINGDOM[10] = {COPPER, SILVER, GOLD, LABORATORY, MARKET, MILITIA,
FESTIVAL, SMITHY, VILLAGE, COUNCIL_ROOM};
class Card_Vector {
private:
mutable uint8_t arr[10] = {0};
mutable uint16_t _size = 0;
public:
Card_Vector() {}
inline uint16_t size() const {
return _size;
}
inline void add_card(const Card c) {
++arr[c.card_id];
++_size;
}
inline void remove_card(const Card c) {
assert(arr[c.card_id] > 0);
--arr[c.card_id];
--_size;
}
inline uint16_t num_of(const Card c) const {
return arr[c.card_id];
}
inline Card_Vector copy() const {
Card_Vector cv;
for (uint8_t i = 0; i < 10; ++i) {
cv.arr[i] = arr[i];
}
cv._size = _size;
return cv;
}
inline Card_Vector add(const Card_Vector v) const {
Card_Vector new_vector = copy();
for (uint8_t i = 0; i < 10; ++i) {
new_vector.arr[i] += v.arr[i];
}
return new_vector;
}
void print() const {
cout << "-- game state --" << endl;
for (const Card c : KINGDOM) {
cout << c.name << " : " << num_of(c) << endl;
}
}
static Card_Vector from_vector(vector<Card> v) {
if (DEBUG) cout << "from_vector" << endl;
if (DEBUG) cout << v.size() << endl;
Card_Vector cv;
for (int i = 0; i < v.size(); ++i) {
cv.add_card(v.at(i));
}
return cv;
}
};
class Card_And_Value {
public:
const string card;
const float value;
inline Card_And_Value(const string card, const float value)
: card(card), value(value) {};
};
class GameState {
public:
const uint8_t actions;
const uint8_t buys;
const uint8_t accum_action_coins;
const Card_Vector deck;
const Card_Vector hand;
const Card_Vector in_play;
const Card_Vector discard;
inline GameState()
:
actions(0),
buys(0),
accum_action_coins(0)
{}
inline GameState(
const Card_Vector deck,
const Card_Vector hand,
const Card_Vector in_play,
const Card_Vector discard,
const uint8_t actions,
const uint8_t buys,
const uint8_t coins
)
:
deck(deck),
hand(hand),
in_play(in_play),
discard(discard),
actions(actions),
buys(buys),
accum_action_coins(coins) {}
inline GameState move_card_from_hand_to_in_play(const Card card, const uint8_t depth) const {
if(DEBUG) cout << spaces(depth) << "playing " << card.name << endl;
// TODO: make discard go into deck if deck size is 0
Card_Vector new_hand = hand.copy();
Card_Vector new_in_play = in_play.copy();
new_hand.remove_card(card);
new_in_play.add_card(card);
return GameState(
deck,
new_hand,
new_in_play,
discard,
actions + card.actions - 1,
buys + card.buys,
accum_action_coins + card.coins
);
}
inline GameState move_card_from_deck_to_hand(const Card card) const {
GameState gs_copy = copy();
Card_Vector new_deck = deck.copy();
Card_Vector new_hand = hand.copy();
new_deck.remove_card(card);
new_hand.add_card(card);
return GameState(
new_deck,
new_hand,
in_play,
discard,
actions,
buys,
accum_action_coins
);
}
inline uint8_t coin_value(const uint8_t depth) const {
// TODO: max at 8 * buys
uint8_t coin_value = accum_action_coins;
for (const Card c : KINGDOM) {
if (c.type == "Treasure") {
coin_value += c.coins * hand.num_of(c);
}
}
if(DEBUG) cout << spaces(depth) << "---" << endl;
if(DEBUG) cout << spaces(depth) << "total coin val : " << (int) coin_value << endl;
if(DEBUG) cout << spaces(depth) << "action coin val : " << (int) accum_action_coins << endl;
if(DEBUG) cout << spaces(depth) << "treasure coin val : " << (int) (coin_value - accum_action_coins) << endl;
return coin_value;
}
inline uint8_t num_total_cards() const {
return deck.size() + hand.size() + in_play.size() + discard.size();
}
inline GameState copy() const {
return GameState(
deck,
hand,
in_play,
discard,
actions,
buys,
accum_action_coins
);
}
inline GameState move_deck_into_hand() const {
Card_Vector new_hand = hand.copy();
new_hand.add(deck);
return GameState(
Card_Vector(),
new_hand,
in_play,
discard,
actions,
buys,
accum_action_coins
);;
}
// static GameState get_starting_game_state(const uint8_t num_copper_in_hand) {
// Card_Vector deck();
// Card_Vector hand();
// Card_Vector in_play();
// Card_Vector discard();
//
// return GameState(
// deck,
// hand,
// in_play,
// discard,
// 1,
// 1,
// 0
// );
// }
};
class GameState_and_Freq {
public:
const GameState gs;
const uint16_t freq;
GameState_and_Freq(GameState gs, uint16_t freq)
: gs(gs), freq(freq) {}
};
class DominionSolver {
public:
inline vector<GameState_and_Freq> combinations(const GameState game_state, const Card card_being_played, const uint8_t depth) const {
if (DEBUG) cout << spaces(depth) << "---" << endl;
if (DEBUG) cout << spaces(depth) << "combinations" << endl;
// if (DEBUG) cout << "card : " << card.name << endl;
// if (DEBUG) game_state.deck.print();
if(card_being_played.cards >= game_state.deck.size()){
// cout << "+cards >= deck size" << endl;
// cout << (int) card.cards << endl;
// cout << game_state.deck.size() << endl;
vector<GameState_and_Freq> new_game_states;
const GameState new_gs = game_state.move_deck_into_hand();
new_game_states.emplace_back(new_gs, 1);
return new_game_states;
}
if (card_being_played.cards == 0) {
vector<GameState_and_Freq> new_game_states;
new_game_states.emplace_back(game_state, 1);
return new_game_states;
} else if (card_being_played.cards == 1) {
vector<GameState_and_Freq> new_game_states;
for (const Card c : KINGDOM) {
if(game_state.deck.num_of(c) > 0){
const GameState new_gs = game_state.move_card_from_deck_to_hand(c);
new_game_states.emplace_back(new_gs, game_state.deck.num_of(c));
}
}
return new_game_states;
} else if (card_being_played.cards == 2) {
vector<GameState_and_Freq> new_game_states;
for (uint8_t i = 0; i < 10; ++i) {
const Card c1 = KINGDOM[i];
if(game_state.deck.num_of(c1) == 0){
continue;
}
const GameState one_card_moved = game_state.move_card_from_deck_to_hand(c1);
for (uint8_t j = i; j < 10; ++j) {
const Card c2 = KINGDOM[j];
if(one_card_moved.deck.num_of(c2) == 0){
continue;
}
const GameState both_cards_moved = one_card_moved.move_card_from_deck_to_hand(c2);
uint16_t freq = game_state.deck.num_of(c1) * one_card_moved.deck.num_of(c2);
if(i == j) {
freq = freq / 2;
}
new_game_states.emplace_back(both_cards_moved, freq);
if (DEBUG) cout << spaces(depth) << "combo : " << c1.name << (int) i << " : " << c2.name << (int) j << " : freq : " << freq << endl;
}
}
// exit(0);
return new_game_states;
} else {
cout << "Need to implement +card >= 3" << endl;
exit(0);
}
}
inline float move_value(const GameState game_state, const Card card, const uint8_t depth) const {
if (DEBUG) cout << spaces(depth) << "---" << endl;
if (DEBUG) cout << spaces(depth) << "move_value" << endl;
float sum = 0;
uint16_t num_combos = 0;
const vector<GameState_and_Freq> combos = combinations(game_state, card, depth+1);
if(DEBUG) cout << spaces(depth) << "num combinations : " << combos.size() << endl;
for (uint16_t i = 0; i < combos.size(); ++i) {
const GameState_and_Freq gs_and_freq = combos.at(i);
const GameState new_game_state = gs_and_freq.gs;
const uint16_t freq = gs_and_freq.freq;
num_combos += freq;
sum += freq * card_to_play(new_game_state, depth+1).value;
}
return sum / num_combos;
}
inline Card_And_Value card_to_play(const GameState game_state, const uint8_t depth) const {
if (DEBUG) cout << spaces(depth) << "---" << endl;
if (DEBUG) cout << spaces(depth) << "card_to_play" << endl;
if (game_state.actions == 0) {
if (DEBUG) cout << spaces(depth) << "actions are 0" << endl;
return Card_And_Value("", game_state.coin_value(depth+1));
}
float best_value = -1;
string best_card_to_play = "";
bool has_action_in_hand = false;
for (const Card card : KINGDOM) {
if (card.type == "Action" && game_state.hand.num_of(card) > 0) {
has_action_in_hand = true;
const GameState new_game_state = game_state.move_card_from_hand_to_in_play(card, depth+1);
const float play_value = move_value(new_game_state, card, depth+1);
if(depth == 0) cout << "value of : " << card.name << " : " << play_value << endl;
if (play_value > best_value) {
best_value = play_value;
best_card_to_play = card.name;
}
}
}
if (!has_action_in_hand) {
if(DEBUG) cout << spaces(depth) << "no actions left in hand" << endl;
return Card_And_Value("", game_state.coin_value(depth+1));
}
return Card_And_Value(best_card_to_play, best_value);
}
};
int main() {
const DominionSolver ds;
Card_Vector deck = Card_Vector::from_vector({
SILVER, COPPER, COPPER, COPPER, COPPER,
GOLD, LABORATORY, VILLAGE,
SILVER, MARKET, MARKET, LABORATORY
});
Card_Vector hand = Card_Vector::from_vector({
MILITIA, MARKET, LABORATORY, COPPER, COPPER
});
// Card_Vector deck = Card_Vector::from_vector(
// {SILVER, COPPER, MARKET});
// Card_Vector hand = Card_Vector::from_vector({MILITIA, MARKET, LABORATORY, COPPER, COPPER});
Card_Vector in_play = Card_Vector::from_vector({});
Card_Vector discard = Card_Vector::from_vector({COPPER, COPPER, COPPER});
GameState gs(
deck,
hand,
in_play,
discard,
1,
1,
0
);
double t1 = get_time();
Card_And_Value card_and_value = ds.card_to_play(gs, 0);
double t2 = get_time();
cout << "Best card to play : " << card_and_value.card << endl;
cout << "Average value : " << card_and_value.value << endl;
cout << "Time taken : " << (t2 - t1) << endl;
return 0;
} | true |
4c77701cc18b7f33255c59a3cc74bc4285337bad | C++ | karthikramx/CodeBlocks-CPlusPlus-Examples | /OperatorOverloading/Karthik.cpp | UTF-8 | 298 | 2.59375 | 3 | [] | no_license | #include "Karthik.h"
#include <iostream>
using namespace std;
Karthik::Karthik()
{
}
Karthik::Karthik(int a)
{
num = a;
}
//overloaded function def
Karthik Karthik::operator+(Karthik ko){
Karthik brandNew;
brandNew.num = num + ko.num;
return brandNew;
}
| true |
bcdd61ba89c0a5acd0e640ffdb74150f020f29a7 | C++ | 00mjk/leetcode-1 | /GenerateParentheses/Solution.cpp | UTF-8 | 920 | 3.296875 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <vector>
#include <cstdint>
using namespace std;
class Solution {
public:
vector<string> ret;
vector<string> generateParenthesis(int n) {
genParent("", n, n);
printResult();
return ret;
}
void genParent(string tmp, int lRemain, int rRemain) {
// reject condition
if (lRemain < 0 || rRemain < 0 || (lRemain > rRemain)) return;
//accept condition
if (lRemain == 0 && rRemain == 0) ret.push_back(tmp);
genParent(tmp + '(', lRemain - 1, rRemain);
genParent(tmp + ')', lRemain, rRemain - 1);
}
void printResult() {
vector<string>::iterator it;
for (it = ret.begin(); it != ret.end(); it++) {
cout << *it << endl;
}
}
};
int main(int argc, char *argv[]) {
class Solution sol1;
sol1.generateParenthesis(3);
return 0;
}
| true |
543ff31e2197b57664afc459a75518df0889c206 | C++ | kmahsi/AP_apply | /advancedCoffeMaker.cpp | UTF-8 | 3,070 | 2.78125 | 3 | [] | no_license | #include "utils.cpp"
#include "advancedCoffeMaker.h"
#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <list>
using namespace std;
void AdvancedCoffeMaker::getInputAnProcess()
{
string featureModelLine, descriptionLine ;
list<string> features;
featureModelLine.erase(remove_if(featureModelLine.begin(), featureModelLine.end(), ::isspace), featureModelLine.end());
featureGraph->setRoot(featureModelLine.substr(0, featureModelLine.find("=")));
while(getline(cin, featureModelLine))
{
while (featureModelLine != "#")
{
//erase all whitespaces in the input
string superFeature = featureModelLine.substr(0, featureModelLine.find("="));
string subFeatures = featureModelLine.substr(featureModelLine.find("=") + 1);
featureGraph->addNode(superFeature);
featureGraph->setType(superFeature, findNodeType(subFeatures));
addEdges(superFeature, subFeatures);
getline(cin, featureModelLine);
featureModelLine.erase(remove_if(featureModelLine.begin(), featureModelLine.end(), ::isspace), featureModelLine.end());
}
getline(cin, descriptionLine);
while(descriptionLine != "##")
{
descriptionLine.erase(remove_if(descriptionLine.begin(), descriptionLine.end(), ::isspace), descriptionLine.end());
features = splitByDelimiter(descriptionLine.substr(1, descriptionLine.length() -2), ',');
getline(cin, descriptionLine);
bool result = featureGraph->checkCoffeeBFS(features);
if (result && features.empty()) output.push_back(VALID); else output.push_back(INVALID);
}
output.push_back("##");
}
}
nodeType AdvancedCoffeMaker::findNodeType( string subFeatures )
{
if(subFeatures.find("+") != string::npos)
return PLUS;
else if(subFeatures.find("|") != string::npos)
return OR;
else if(subFeatures.find("^") != string::npos)
return XOR;
else return LEAF;
}
bool AdvancedCoffeMaker::addEdges(string superFeature, string subFeatures)
{
char delimiter = '+';
if (subFeatures.find('+') != string::npos) delimiter = '+';
if (subFeatures.find('|') != string::npos) delimiter = '|';
if (subFeatures.find('^') != string::npos) delimiter = '^';
list<string> splitedSubfeatures = splitByDelimiter(subFeatures, delimiter);
list<string>::iterator adjNodeIterator;
for (adjNodeIterator = splitedSubfeatures.begin(); adjNodeIterator != splitedSubfeatures.end(); adjNodeIterator++)
{
*adjNodeIterator = subFeatures.substr(0, subFeatures.find(delimiter));
bool mandatory = ( (*adjNodeIterator)[0] != '?' && delimiter == '+' ) ? true : false;
*adjNodeIterator = ( (*adjNodeIterator)[0] == '?' ) ? adjNodeIterator->substr(1) : *adjNodeIterator;
featureGraph->addNode(*adjNodeIterator);
featureGraph->addEdge(superFeature, *adjNodeIterator);
featureGraph->setMandatory(*adjNodeIterator, mandatory);
subFeatures = subFeatures.substr(subFeatures.find(delimiter) + 1);
}
}
AdvancedCoffeMaker::AdvancedCoffeMaker()
{
featureGraph = new Graph;
}
AdvancedCoffeMaker::~AdvancedCoffeMaker()
{
delete featureGraph;
}
std::list<string> AdvancedCoffeMaker::getOutput()
{
return output;
} | true |
0b9ad79da5e46baa7ddfae0509d775393924216b | C++ | moevm/oop | /8383/Larin_Anton/OOProject/Logger/AbstractLogger.h | UTF-8 | 544 | 2.734375 | 3 | [] | no_license | //
// Created by anton on 6/2/20.
//
#ifndef OOPROJECT_ABSTRACTLOGGER_H
#define OOPROJECT_ABSTRACTLOGGER_H
#include <memory>
#include <string>
class AbstractLogger {
public:
virtual void log(std::string str)=0;
virtual AbstractLogger&operator<<(std::string str){
log(str);
return *this;
}
friend std::shared_ptr<AbstractLogger>& operator<<(std::shared_ptr<AbstractLogger>& logger,std::string str){
logger->operator<<(str);
return logger;
}
};
#endif //OOPROJECT_ABSTRACTLOGGER_H
| true |
07ae78f711d5d959567e5c5356cffa0d4362b845 | C++ | hujianzhong-UOS/document2html | /src/main.cpp | UTF-8 | 6,488 | 2.703125 | 3 | [
"MIT"
] | permissive | /**
* @brief Document to HTML converter
* @package document2html
* @file main.cpp
* @author dmryutov (dmryutov@gmail.com)
* @version 1.0
* @date 04.01.2018 -- 05.01.2018
*/
#include <iostream>
#include <string>
#include "libs/getoptpp/getoptpp.hpp"
#include "libs/fileext/archive/archive.hpp"
#include "libs/fileext/csv/csv.hpp"
#include "libs/fileext/doc/doc.hpp"
#include "libs/fileext/docx/docx.hpp"
#include "libs/fileext/epub/epub.hpp"
#include "libs/fileext/excel/excel.hpp"
#include "libs/fileext/html/html.hpp"
#include "libs/fileext/json/json.hpp"
#include "libs/fileext/odt/odt.hpp"
#include "libs/fileext/pdf/pdf.hpp"
#include "libs/fileext/ppt/ppt.hpp"
#include "libs/fileext/rtf/rtf.hpp"
#include "libs/fileext/txt/txt.hpp"
#include "libs/fileext/xml/xml.hpp"
#include "libs/pymagic/pymagic.hpp"
#include "libs/tools.hpp"
#if defined(_WIN32) || defined(_WIN64)
#include "libs/dirent.h"
#else
#include <dirent.h>
#endif
const std::string APP = "document2html";
const std::string VERSION = "1.0";
/**
* @brief
* Convert single file
* @param[in] input
* Name of input file
* @param[in] output
* Name of output directory
* @param[in] style
* True if should extract styles
* @param[in] image
* True if should extract images
* @since 1.0
*/
void convertFile(std::string input, std::string output, bool style, bool image);
/**
* @brief
* Search files and convert them
* @param[in] input
* Name of input directory
* @param[in] output
* Name of output directory
* @param[in] style
* True if should extract styles
* @param[in] image
* True if should extract images
* @since 1.0
*/
void convertFolder(std::string input, std::string output, bool style, bool image);
void convertFile(std::string input, std::string output, bool style, bool image) {
size_t last = input.find_last_of("/");
std::string name = input.substr(last + 1);
std::string dir = input.substr(0, last);
std::string ext = pymagic::getFileExtension(input);
std::unique_ptr<fileext::FileExtension> document;
try {
if (ext == "docx")
document.reset(new docx::Docx(input));
else if (ext == "html" || ext == "htm" || ext == "xhtml" || ext == "xht")
document.reset(new html::Html(input));
else if (ext == "xml")
document.reset(new xml::Xml(input));
else if (ext == "txt" || ext == "md" || ext == "markdown")
document.reset(new txt::Txt(input));
else if (ext == "json")
document.reset(new json::Json(input));
else if (ext == "doc")
document.reset(new doc::Doc(input));
else if (ext == "rtf")
document.reset(new rtf::Rtf(input));
else if (ext == "odt")
document.reset(new odt::Odt(input));
else if (ext == "xls" || ext == "xlsx")
document.reset(new excel::Excel(input, ext));
else if (ext == "csv")
document.reset(new csv::Csv(input));
else if (ext == "ppt")
document.reset(new ppt::Ppt(input));
else if (ext == "epub")
document.reset(new epub::Epub(input));
else if (ext == "pdf")
document.reset(new pdf::Pdf(input));
else if (ext == "zip" || ext == "rar" || ext == "tar" || ext == "gz" ||
ext == "bz2" || (tools::IS_WINDOWS && ext == "7z"))
{
std::string archive = input + ".archive";
archive::extractArchive(dir, name, ext, archive);
std::cout << "Archive extracted: " << input << std::endl;
convertFolder(archive, output, style, image);
return;
}
else {
std::cout << "Unsupported file extension: " << ext << std::endl;
return;
}
document->convert(style, image, 0);
document->saveHtml(output, name +".html");
std::cout << "Conversion complete: " << input << std::endl;
}
catch (...) {
std::cerr << "Error: " << input << std::endl;
}
document.reset();
}
void convertFolder(std::string input, std::string output, bool style, bool image) {
DIR *dp = dp = opendir(input.c_str());
struct dirent *dirp;
if (dp) {
while ((dirp = readdir(dp))) {
if (dirp->d_name[0] != '.') {
std::string path = input +"/"+ dirp->d_name;
if (tools::isDirectory(path))
convertFolder(path, output, style, image);
else
convertFile(path, output, style, image);
}
}
closedir(dp);
}
else {
std::cerr << "Couldn't open folder: " << input << std::endl;
}
}
int main(int argc, char* argv[]) {
bool isFile, style, image, help, version;
std::string input, output;
try {
GetOpt::GetOpt_pp ops(argc, argv);
ops >> GetOpt::Option('f', "file", input);
isFile = !input.empty();
ops >> GetOpt::Option('d', "dir", input)
>> GetOpt::Option('o', "out", output)
>> GetOpt::OptionPresent('s', "style", style)
>> GetOpt::OptionPresent('i', "image", image)
>> GetOpt::OptionPresent('h', "help", help)
>> GetOpt::OptionPresent('v', "version", version);
if (help) {
std::cout << "Usage: " << std::endl
<< "\t" << APP << " -f|-d <input file|dir> -o <output dir> [-si]" << std::endl
<< "\t" << APP << " -h|--help" << std::endl
<< "\t" << APP << " -v|--version" << std::endl
<< "Options:" << std::endl
<< "\t" << "-f|--file" << "\t" << "input file" << std::endl
<< "\t" << "-d|--dir" << "\t" << "input directory" << std::endl
<< "\t" << "-o|--out" << "\t" << "output directory" << std::endl
<< "\t" << "-s|--style" << "\t" << "extract styles" << std::endl
<< "\t" << "-i|--image" << "\t" << "extract images" << std::endl
<< "\t" << "-h|--help" << "\t" << "display help message" << std::endl
<< "\t" << "-v|--version" << "\t" << "display package version" << std::endl
<< std::endl;
return 0;
}
if (version) {
std::cout << APP << " version " << VERSION << std::endl;
return 0;
}
else if (input.empty()) {
std::cerr << "Input file/directory (-f|d) is required argument!" << std::endl;
return 1;
}
else if (output.empty()) {
std::cerr << "Output directory (-o) is required argument!" << std::endl;
return 1;
}
else if (ops.options_remain()) {
std::cerr << "Too many options!" << std::endl;
return 1;
}
else if (!tools::fileExists(input)) {
std::cerr << "Input file/directory does not exists!" << std::endl;
return 1;
}
}
catch (const GetOpt::GetOptEx& ex) {
std::cerr << "Error in arguments!" << std::endl;
return 1;
}
// Start convertsion
input = tools::absolutePath(input);
tools::createDir(output);
if (isFile)
convertFile(input, output, style, image);
else
convertFolder(input, output, style, image);
return 0;
}
| true |
abbfea4dc6f2eea2aeeb3a5c61e2ca1ec1446ae4 | C++ | SWQXDBA/my-ideas | /通讯录wancheng.cpp | UTF-8 | 6,201 | 3.015625 | 3 | [] | no_license | #include<stdio.h>
#include<string.h>
#include <cstdlib>
#define name_max 15
#define sex_max 15
#define number_max 15
#define address_max 15
void inputtel(struct teles *ps);
void delet(struct teles *ps);
void srch(struct teles *ps);
void printtel(struct teles *ps,int n);//打印单个人的数据
void showtel(struct teles *ps);//打印所有信息
void modtel(struct teles *ps);//修改
void savetel(struct teles *ps);//保存到txt文件
int option(struct teles *ps);
void load(struct teles *ps);
void expand(teles *pTeles);
struct telephone
{
char name[name_max];
int age;
char sex[sex_max];
char number[number_max];
char address[address_max];
};
struct teles
{
struct telephone *tele = (struct telephone* ) malloc(sizeof(struct telephone)*1);
int telesize;
int maxLength= 1;
};
enum
{
add=1,
del,
search,
modify,
show,
save,
ex
};
int main()
{
struct teles tpne;
struct teles *ps=&tpne;
ps->telesize=0;
load(ps);
while(option(ps))
{
getchar();
}
return 0;
}
void inputtel(struct teles *ps)
{
if(ps->telesize==ps->maxLength){
expand(ps);
}
int n=ps->telesize;
struct telephone *ps2=&ps->tele[n];
puts("请输入名字:");
scanf("%s",&ps2->name);
puts("请输入年龄:");
scanf("%d",&ps2->age);
puts("请输入性别:");
scanf("%s",&ps2->sex);
puts("请输入电话号码:");
scanf("%s",&ps2->number);
puts("请输入地址:");
scanf("%s",&ps2->address);
ps->telesize++;
}
void expand(teles *ps) {
printf("触发扩容\n");
telephone * temp = (telephone *)realloc(ps->tele,ps->maxLength*2*sizeof(telephone));
if(temp!=NULL){
ps->tele=temp;
ps->maxLength*=2;
}else{
printf("扩容失败!程序结束");
return;
}
}
void delet(struct teles *ps)
{
int flag=0;
struct telephone *ps2;
char name[name_max]={0};
printf("请输入要删除的名字:\n");
scanf("%s",name);
for(int n=0;n<ps->telesize;n++)
{
ps2=&ps->tele[n];
if(0==strcmp(ps2->name,name))
{
flag=1;
for(int i=n;i<ps->telesize;i++)
{
ps->tele[i]=ps->tele[i+1];
}
}
}
ps->telesize--;
if(flag==0)
printf("未查询到指定的名称,删除失败!\n");
}
void srch(struct teles *ps)
{
int flag=0;
struct telephone *ps2;
char name[name_max]={0};
printf("请输入要查找的名字:\n");
scanf("%s",name);
for(int n=0;n<ps->telesize;n++)
{
ps2=&ps->tele[n];
if(0==strcmp(ps2->name,name))
{
printf("名字:\t年龄:\t性别:\t电话:\t\t地址:\t\n");
printtel(ps,n);
flag=1;
}
}
if(flag==0)
printf("未查询到指定的名称\n");
}
void printtel(struct teles *ps,int n)
{
struct telephone *ps2=&ps->tele[n];
printf("%-s\t%-d\t%-s%\t%-s\t\t%-s\t\n",ps2->name,ps2->age,ps2->sex,ps2->number,ps2->address);
}
void showtel(struct teles *ps)
{
printf("名字:\t年龄:\t性别:\t电话:\t\t地址:\t\n");
for(int i=0;i<ps->telesize;i++)
{
printtel(ps,i);
}
printf("max = %d size = %d\n",ps->maxLength,ps->telesize);
}
void modtel(struct teles *ps)
{
int flag=0;
struct telephone *ps2;
char name[name_max]={0};
printf("请输入要修改的人名信息\n");
scanf("%s",name);
for(int n=0;n<ps->telesize;n++)
{
ps2=&ps->tele[n];
if(0==strcmp(ps2->name,name))
{
printf("已查询到目标,请输入新的信息\n");
printf("名字:\t年龄:\t性别:\t电话:\t\t地址:\t\n");
printtel(ps,n);
printf("请输入新的信息\n");
puts("请输入名字:");
scanf("%s",&ps2->name);
puts("请输入年龄:");
scanf("%d",&ps2->age);
puts("请输入性别:");
scanf("%s",&ps2->sex);
puts("请输入电话号码:");
scanf("%s",&ps2->number);
puts("请输入地址:");
scanf("%s",&ps2->address);
flag=1;
}
}
if(flag==0)
printf("未查询到指定的名称\n");
}
void savetel(struct teles *ps)
{
struct telephone *ps2;
FILE *FP1;
char name[name_max] = "DATA.txt";
//printf("请输入保存的文件名\n");
// scanf("%s",name);
FP1=fopen(name,"w");
if(FP1!=NULL)
{
// fprintf(FP1,"名字:\t年龄:\t性别:\t电话:\t\t地址:\t\n");
for(int i=0;i<ps->telesize;i++)
{
ps2=&ps->tele[i];
fprintf(FP1,"%s %d %s %s %s",ps2->name,ps2->age,ps2->sex,ps2->number,ps2->address);
}
printf("保存完成\n");
}
else printf("error,无法创建文件!!!\n");
}
void load(struct teles *ps){
FILE *FP1;
char name[name_max] = "DATA.txt";
FP1 = fopen(name,"r");
struct telephone ps2;
if(FP1!=NULL){
while(fscanf(FP1,"%s %d %s %s %s",&ps2.name,&ps2.age,&ps2.sex,&ps2.number,&ps2.address)!=EOF){
(ps->tele[ps->telesize])=ps2;
ps->telesize++;
}
}else printf("未找到文件");
}
int option(struct teles *ps)
{
int n;
printf("请输入操作:\n");
printf("1:add 2:del 3:search\n"
"4:modify 5:show 6:save\n"
"7:exit\n");
scanf("%d",&n);
switch(n)
{
case add: inputtel(ps);break;
case del: delet(ps);break;
case search: srch(ps);break;
case modify: modtel(ps);break;
case show: showtel(ps);break;
case save: savetel(ps);break;
case ex: return 0;break;
default:printf("输入选项有误,请重输\n");break;
}
return 1;
}
| true |
fc25e4ce6af4f39e422450b02ea99ee3078050cb | C++ | Todd-Pidgeon/Programming_Portfolio | /C++/A4P2-hangman.cpp | UTF-8 | 9,983 | 3.25 | 3 | [] | no_license | //Program Name : A4P1-Hangman
//Programmer Name: Todd Pidgeon
//Overview : A Hangman Game
//Date Written : 02/23/2016
//Date Modified : 02/28/2016
#include <iostream>
#include <string>
#include <iomanip>
#include <conio.h>
#include <windows.h>
#include <limits>
using namespace std;
int hang_cnt;
int letter_match;
int choosen_cnt;
char letter_guess;
void GameMenu(string GameWords[]);
void GetLetterFromUser(string choosen_word, int word_length, string GameWords[], bool choosen_letters[]);
//Function to use Goto X Y.
void gotoxy(int x, int y)
{
COORD coord;
coord.X = x; //column coordinate
coord.Y = y; //row coordinate
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}
//Function to use Goto X Y.
void clrscr(int x, int y)
{
COORD coordScreen = { x, y };
DWORD cCharsWritten;
CONSOLE_SCREEN_BUFFER_INFO csbi;
DWORD dwConSize;
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
GetConsoleScreenBufferInfo(hConsole, &csbi);
dwConSize = csbi.dwSize.X * csbi.dwSize.Y;
FillConsoleOutputCharacter(hConsole, TEXT(' '),
dwConSize, coordScreen, &cCharsWritten);
GetConsoleScreenBufferInfo(hConsole, &csbi);
FillConsoleOutputAttribute(hConsole, csbi.wAttributes,
dwConSize, coordScreen, &cCharsWritten);
SetConsoleCursorPosition(hConsole, coordScreen);
}
void DrawGallows()
{
// Draws the horizontal bar of the gallows pole
for (int hor_bar = 0; hor_bar < 9; hor_bar++)
{
gotoxy(46 + hor_bar, 9);
cout << (char)220;
}
// Draws the vertical bar of the gallows pole
for (int ver_bar = 0; ver_bar < 9; ver_bar++)
{
gotoxy(45, 17 - ver_bar);
cout << (char)219;
}
// Draws the rope
gotoxy(54, 10);
cout << (char)179;
// draws the base of the gallows pole
gotoxy(44, 17);
cout << (char)220;
gotoxy(46, 17);
cout << (char)220;
}
void GameOverMan(string GameWords[], string choosen_word)
{
for (int draw_man = 1; draw_man < 5; draw_man++)
{
clrscr(0, 0);
gotoxy(35, 2);
cout << "HANGMAN!";
gotoxy(2, 3);
cout << "---------------------------------------------------------------------------";
DrawGallows();
// draw man
gotoxy(54, 11);
cout << (char)1;
gotoxy(54, 12);
cout << (char)245;
gotoxy(54, 12 + draw_man);
cout << (char)219;
gotoxy(53, 12 + draw_man);
cout << '/';
gotoxy(55, 12 + draw_man);
cout << '\\';
gotoxy(53, 13 + draw_man);
cout << '/';
gotoxy(55, 13 + draw_man);
cout << '\\';
cout << '\a';
gotoxy(32, 19);
cout << "*** Game Over! ***";
gotoxy(21, 20);
cout << "*** The correct word was: " << choosen_word << " ***";
gotoxy(12, 21);
cout << "*** You Lose, you are hanged from your neck until dead! ***";
Sleep(300);
}
clrscr(0, 0);
gotoxy(35, 2);
cout << "HANGMAN!";
gotoxy(2, 3);
cout << "---------------------------------------------------------------------------";
DrawGallows();
// draw man
gotoxy(54, 11);
cout << (char)1;
gotoxy(54, 12);
cout << (char)245;
gotoxy(53, 17);
cout << (char)220;
gotoxy(54, 17);
cout << (char)220;
gotoxy(55, 17);
cout << (char)205;
gotoxy(56, 17);
cout << (char)205;
cout << '\a';
cout << '\a';
cout << '\a';
gotoxy(31, 19);
cout << "*** Oops ***";
gotoxy(26, 21);
cout << "*** Game Over Man! ***";
gotoxy(6, 24);
cout << "Press any key to return to main menu";
_getch();
GameMenu(GameWords);
}
void DrawHangman(string choosen_word, int word_length, string GameWords[], bool choosen_letters[])
{
hang_cnt += 1;
// Draws the hang man characters base on the counter.
switch (hang_cnt)
{
case 1:
gotoxy(54, 11);
cout << (char)1;
cout << '\a';
break;
case 2:
gotoxy(54, 12);
cout << (char)219;
cout << '\a';
break;
case 3:
gotoxy(53, 12);
cout << '/';
cout << '\a';
break;
case 4:
gotoxy(55, 12);
cout << '\\';
cout << '\a';
break;
case 5:
gotoxy(53, 13);
cout << '/';
cout << '\a';
break;
case 6:
gotoxy(55, 13);
cout << '\\';
cout << '\a';
clrscr(12, 19);
// Display the full word
gotoxy(32, 19);
cout << "*** Game Over! ***";
gotoxy(21, 20);
cout << "*** The correct word was: " << choosen_word << " ***";
gotoxy(12, 21);
cout << "*** You Lose, you are hanged from your neck until dead! ***";
gotoxy(2, 23);
cout << "---------------------------------------------------------------------------";
gotoxy(6, 24);
cout << "Press any key to continue";
_getch();
GameOverMan(GameWords, choosen_word);
}
GetLetterFromUser(choosen_word, word_length, GameWords, choosen_letters);
}
void LetterMatchInWord(char letter_guess, string choosen_word, int word_length, string GameWords[], bool choosen_letters[])
{
bool match_check = false;
// Checks to see if the letter chosen is in the word
// uses the .find() function.
for (int match_cnt = 0; match_cnt < word_length; match_cnt++)
{
if (match_cnt == choosen_word.find(letter_guess, match_cnt))
{
gotoxy((match_cnt * 2) + 15, 11);
cout << letter_guess;
match_check = true;
letter_match++;
}
// Original code without the .find() function.
/*
if (letter_guess == choosen_word[match_cnt])
{
gotoxy((match_cnt * 2) + 15, 11);
cout << letter_guess;
match_check = true;
letter_match++;
}
*/
}
// If the letter is a match and is the last letter needed game is won.
if (letter_match == word_length)
{
clrscr(12, 19);
gotoxy(17, 20);
cout << "<<< You Win! You survive... For now... >>>";
gotoxy(2, 23);
cout << "---------------------------------------------------------------------------";
gotoxy(6, 24);
cout << "Press any key to return to main menu";
_getch();
GameMenu(GameWords);
}
// if not a match goes to the DrawHanmgan function.
if (match_check == false)
{
gotoxy(12, 21);
cout << "*** Sorry not a match, you're one step closer to death! ***";
DrawHangman(choosen_word, word_length, GameWords, choosen_letters);
}
// if is a match but not the last letter this will goto the user input function.
else
GetLetterFromUser(choosen_word, word_length, GameWords, choosen_letters);
}
void GetLetterFromUser(string choosen_word, int word_length, string GameWords[], bool choosen_letters[])
{
bool letter_used;
letter_guess = ' ';
// Asks user for input.
while (true)
{
letter_used = false;
gotoxy(12, 19);
cout << "Guess a letter: ";
letter_guess = _getch();
clrscr(28, 19);
letter_guess = toupper(letter_guess);
// Checks to see if the letter input was already used.
// this will now have repeated correct letter not cause a hangman but incorrect letters entered twice will cause
if (choosen_letters[letter_guess - 65] == true)
{
gotoxy(29, 20);
cout << "*** You tried that already ***";
// Sleep(600);
// clrscr(29, 19);
letter_used = true;
// maybe change this to the drawhangman() function
// LetterMatchInWord(letter_guess, choosen_word, word_length, GameWords, choosen_letters);
DrawHangman(choosen_word, word_length, GameWords, choosen_letters);
}
choosen_letters[letter_guess - 65] = true;
// if the letter input has not yet been used it will move on to the next function.
if (letter_used == false)
{
if (letter_guess >= 65 && letter_guess <= 90)
{
gotoxy((letter_guess - 64) * 2 + 11, 5);
cout << ' ';
LetterMatchInWord(letter_guess, choosen_word, word_length, GameWords, choosen_letters);
}
// Validates whether the char entered is a letter or not.
else
{
gotoxy(29, 20);
cout << "*** Not a letter ***";
// Sleep(500);
// clrscr(29, 19);
DrawHangman(choosen_word, word_length, GameWords, choosen_letters);
}
}
}
}
void StartNewGame(string GameWords[], bool choosen_letters[])
{
char letter;
int random_num_1;
string choosen_word;
int word_length;
clrscr(0, 0);
gotoxy(35, 2);
cout << "HANGMAN!";
gotoxy(2, 3);
cout << "---------------------------------------------------------------------------";
// Draws the alphabet across the top of the screen.
for (int alpha_cnt = 0; alpha_cnt < 26; alpha_cnt++)
{
letter = alpha_cnt + 65;
gotoxy(13 + alpha_cnt * 2, 5);
cout << letter;
}
DrawGallows();
// Picks a random number to be used to select a random word.
random_num_1 = rand() % 10;
choosen_word = GameWords[random_num_1];
// Find the length of the chosen word.
word_length = choosen_word.length();
// Prints the right amount of dashes to signify the missing letter for the word.
for (int dash_cnt = 0; dash_cnt < word_length; dash_cnt++)
{
gotoxy(15 + dash_cnt * 2, 12);
cout << "-";
}
GetLetterFromUser(choosen_word, word_length, GameWords, choosen_letters);
}
void GameMenu(string GameWords[])
{
char play_exit = ' ';
clrscr(0, 0);
letter_match = 0;
hang_cnt = 0;
choosen_cnt = 0;
letter_guess = ' ';
bool choosen_letters[26] = { false, false, false, false, false, false, false, false, false, false,
false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false };
gotoxy(35, 2);
cout << "HANGMAN!";
gotoxy(2, 3);
cout << "---------------------------------------------------------------------------";
gotoxy(30, 10);
cout << "1. NEW GAME";
gotoxy(30, 11);
cout << "E. EXIT";
gotoxy(25, 16);
cout << "What do wish to do?: ";
while (true)
{
gotoxy(46, 16);
play_exit = _getch();
play_exit = tolower(play_exit);
if (play_exit == '1')
{
StartNewGame(GameWords, choosen_letters);
}
else if (play_exit == 'e')
{
exit(NULL);
}
else
{
gotoxy(46, 16);
cout << "*** Invalid choice (1/E) ***";
Sleep(500);
clrscr(46, 16);
}
}
}
int main()
{
// Seeds the random number based on the computers time.
srand(time(NULL));
// main program loop.
string GameWords[10] = { "NOTES", "PACKAGE", "WOBBLY", "KANGAROO", "BEYOND", "WITHIN", "NEVERMORE", "HARBRINGER", "NEMISIS", "QUINTESSENTIAL" };
// function calls
GameMenu(GameWords);
return 0;
}
| true |
9e728ffecc2cf9c6b6c9449b623327aa7b946984 | C++ | GhulamMustafaGM/C-Programming | /09-C++ Programming/PythangoreanTheorem.cpp | UTF-8 | 620 | 4.125 | 4 | [] | no_license | // Pythagorean theorem
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int a, b;
float c;
cout << "Enter a value of the first side of a triangle ";
cin >> a;
cout << a << endl;
cout << "Enter a value of the second side of a triangle ";
cin >> b;
cout << b << endl;
if (a < 0 || b < 0)
{
cout << "\n\n Length of a triangle must be greater than zero.";
}
else
{
c = pow(pow(a, 2) + pow(b, 2), 0.5);
cout << "\n(" << a << "^2 + " << b << "^2"
<< ")"
<< "^0.5 = " << c;
}
return 0;
}
| true |
f2725508706251bcb38acd4478cee76721891b3d | C++ | raquel-oliveira/Computer-Graphics | /include/vec3.h | UTF-8 | 2,156 | 3.34375 | 3 | [] | no_license | #ifndef _VEC3_H_
#define _VEC3_H_
#include <cmath> // fabs
#include <iostream>
#include <cassert> // assert
/*!
* Represents a 3D vector, that might be used to represent
* points, directions, vectors, colors, offset
*/
namespace utility {
class Vec3
{
public:
//=== Aliases
typedef float value_type;
enum field_t : int { X=0, Y=1, Z=2, R=0, G=1, B=2 };
//=== Members
value_type e[ 3 ];
//=== Special members
Vec3( value_type e0_=0.f, value_type e1_=0.f, value_type e2_=0.f )
: e{ e0_, e1_, e2_ }
{ /* empty */ }
//=== Access operators
inline value_type x() const { return e[X]; }
inline value_type y() const { return e[Y]; }
inline value_type z() const { return e[Z]; }
inline value_type r() const { return e[R]; }
inline value_type g() const { return e[G]; }
inline value_type b() const { return e[B]; }
// indexed access operator (rhs)
inline value_type operator[]( size_t idx ) const { return e[ idx ]; }
// indexed access operator (lhs)
inline value_type& operator[]( size_t idx ) { return e[ idx ]; }
//=== Algebraic operators
// Unary '+'
inline const Vec3& operator+( void ) const { return *this; }
// Unary '-'
inline Vec3 operator-( void ) const { return Vec3( -e[X], -e[Y], -e[Z] ); }
inline Vec3& operator+=( const Vec3& );
inline Vec3& operator-=( const Vec3& );
inline Vec3& operator*=( const Vec3& );
inline Vec3& operator/=( const Vec3& );
inline Vec3& operator*=( const value_type );
inline Vec3& operator/=( const value_type );
inline value_type length( void ) const
{
return sqrt(e[0]*e[0] + e[1]*e[1] + e[2]*e[2]);
}
inline value_type squared_length( void ) const
{
return e[0]*e[0] + e[1]*e[1] + e[2]*e[2];
}
inline void make_unit_vector( void );
inline float sines( void ) const;
};
typedef Vec3 Color3;
typedef Vec3 Offset;
typedef Vec3 Point3;
}
#include "vec3.inl"
#endif
| true |
9fde6a47a160dad17b435795809f7abf85523cb6 | C++ | cyberfenrir/programs-C | /DIVSIB_5.CPP | UTF-8 | 241 | 3 | 3 | [] | no_license | #include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int a;
cout<<"Enter the number: ";
cin>>a;
if((a%5)==0)
{
cout<<"The number is divisible by 5. ";
}
else
{
cout<<"The number is not divisible by 5. ";
}
getch();
} | true |
2fff4457aab93f162a213d0be575f3c5ed421269 | C++ | supersoulsoul/ProgrammingExercises | /折线分割.cpp | GB18030 | 809 | 3.390625 | 3 | [] | no_license | #include<stdio.h>
int main(){
int n,a;
scanf("%d",&n);
while(n--){
scanf("%d",&a);
printf("%d\n",2*a*a-a+1);
}
return 0;
}
/*߷ƽ
ֱ߷ƽ֪ɽߺ߶εn-1ʱΪfn-1Ϊʹӵ࣬ߵߵ߶Ҫn-1ߵıߣ2*n-1߶ཻô߶Ϊ4*n-1Ϊ2Ҫעǣ߱ڵ߶ֻһ
ʣf(n)=f(n-1)+4(n-1)+2-1
=f(n-1)+4(n-1)+1
=f(n-2)+4(n-2)+4(n-1)+2
=f(1)+4+4*2++4(n-1)+(n-1)
=2n^2-n+1*/ | true |
325886f1ce439101b999afc6e3f0b5c4c01b1412 | C++ | meksconways/Multivibrators | /eleman/Eleman.cpp | UTF-8 | 1,103 | 3.03125 | 3 | [] | no_license | //
// Created by macbook on 2019-07-11.
//
#include <iostream>
#include "Eleman.h"
using namespace std;
const ElemanTurleri &Eleman::getTur() const {
return this -> elemanTurleri;
}
const void Eleman::setTur(const ElemanTurleri &value) {
this -> elemanTurleri = value;
}
const string &Eleman::getDetay() const {
return this->detay;
}
const void Eleman::setDetay(const string &value) {
this->detay = value;
}
Konum *Eleman::getKonum() const {
return this->konum;
}
void Eleman::setKonum(Konum *value) {
this->konum = value;
}
void Eleman::Render() {
cout<<konum->toString() << " konumundaki "<<detay<<" render edildi"<<endl;
}
int Eleman::compareTo(Eleman *obj) {
if (obj->getTur() == this->elemanTurleri){
return 1;
}
return 0;
}
Eleman::Eleman() {
this->konum = new Konum(0,0);
this->detay = " ";
this->elemanTurleri = ElemanTurleri::Direnc;
}
Eleman::Eleman(ElemanTurleri elemanTurleri, const string &detay, Konum *konum) {
this->elemanTurleri = elemanTurleri;
this->detay = detay;
this->konum = konum;
}
| true |
0de44651555f75383a3f9c4f9b82d4a9da5d5550 | C++ | unaxcess/qUAck | /ua.cpp | UTF-8 | 2,888 | 2.59375 | 3 | [] | no_license | /*
** UNaXcess II Conferencing System
** (c) 1998 Michael Wood (mike@compsoc.man.ac.uk)
**
** Concepts based on Bradford UNaXcess (c) 1984-87 Brandon S Allbery
** Extensions (c) 1989, 1990 Andrew G Minter
** Manchester UNaXcess extensions by Rob Partington, Gryn Davies,
** Michael Wood, Andrew Armitage, Francis Cook, Brian Widdas
**
** The look and feel was reproduced. No code taken from the original
** UA was someone else's inspiration. Copyright and 'nuff respect due
**
** ua.cpp: Implmentation for common UA functions
*/
#include "stdafx.h"
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include "useful/useful.h"
#include "ua.h"
bool NameValid(const char *szName)
{
int iCharPos = 1;
// printf("NameValid %s\n", szName);
if(szName == NULL)
{
// printf("NameValid exit false, NULL\n");
return false;
}
if(strlen(szName) == 0 || strlen(szName) > UA_NAME_LEN)
{
// printf("NameValid exit false, too long\n");
return false;
}
if(!isalpha(szName[0]))
{
// printf("NameValid exit false, non-alpha first char\n");
return false;
}
while(szName[iCharPos] != '\0')
{
if(!isalnum(szName[iCharPos]) && strchr(".,' @-_!", szName[iCharPos]) == NULL)
{
// printf("NameValid exit false, invalid char %d\n", iCharPos);
return false;
}
else
{
iCharPos++;
}
}
if(szName[iCharPos - 1] == ' ')
{
// printf("NameValid exit false, space last char\n");
return false;
}
// printf(". exit true\n");
return true;
}
// AccessName: Convert numerical access level into character string
char *AccessName(int iLevel, int iType)
{
if(iType != -1 && iType == USERTYPE_AGENT)
{
return "Agent";
}
switch(iLevel)
{
case LEVEL_NONE:
return "None";
case LEVEL_GUEST:
return "Guest";
case LEVEL_MESSAGES:
return "Messages";
case LEVEL_EDITOR:
return "Editor";
case LEVEL_WITNESS:
return "Witness";
case LEVEL_SYSOP:
return "SysOp";
}
return "";
}
char *SubTypeStr(int iSubType)
{
STACKTRACE
if(iSubType == SUBTYPE_EDITOR)
{
return SUBNAME_EDITOR;
}
else if(iSubType == SUBTYPE_MEMBER)
{
return SUBNAME_MEMBER;
}
else if(iSubType == SUBTYPE_SUB)
{
return SUBNAME_SUB;
}
return "";
}
int SubTypeInt(const char *szSubType)
{
STACKTRACE
if(stricmp(szSubType, SUBNAME_EDITOR) == 0)
{
return SUBTYPE_EDITOR;
}
else if(stricmp(szSubType, SUBNAME_MEMBER) == 0)
{
return SUBTYPE_MEMBER;
}
else if(stricmp(szSubType, SUBNAME_SUB) == 0)
{
return SUBTYPE_SUB;
}
return -1;
}
/* int ProtocolVersion(const char *szVersion)
{
return ProtocolCompare(PROTOCOL, szVersion);
} */
int ProtocolCompare(const char *szVersion1, const char *szVersion2)
{
return stricmp(szVersion1, szVersion2);
}
| true |
0e8a32196fc440a20c97a225ef33981eb58525b4 | C++ | priyanshi9692/GenericAreaCalculator | /Circle.cc | UTF-8 | 213 | 2.8125 | 3 | [] | no_license | #include "Circle.h"
#include<iostream>
using namespace std;
double Circle:: area()
{
double circleArea= 3.14*R*R;
return circleArea;
}
Circle:: Circle(XYPoint &point, double R1)
{
A=point;
R=R1;
}
| true |
80aefcb522e9d1744225380f212b785f913845d4 | C++ | SothicT/algorithm | /德才论(25)2019_2_28.cpp | GB18030 | 2,890 | 3.484375 | 3 | [] | no_license | /*
δʷѧ˾ڡͨһġ²ۡǹʲŵȫ
ν֮ʥˣŵ¼ν֮ˣʤν֮ӣʤν֮Сˡȡ֮
ʥˣӶ֮Сˣˡ
ָһĵ²ŷ˾۸¼ȡ
ʽ
һи 3 ֱΪN10^5L60
Ϊ¼ȡͷߣ·ֺͲŷ־ L Ŀʸ¼ȡ
H<100Ϊ¼ȡߡ
(1)·ֺͲŷ־ڴߵıΪŵȫ²ִܷӸ
(2)ŷֲ·ֵߵһڡʤšҲܷڵһ
֮
(3)²ŷ־ Hǵ·ֲڲŷֵĿڡŵ¼Сʤ
šߣܷڵڶ֮
(4)ﵽ L ĿҲܷڵ֮
N УÿиһλϢ֤ · ŷ֣
֤Ϊ 8 λ²ŷΪ [0, 100] ڵּԿո
ʽ
һȸﵽͷߵĿ M M Уÿа
ʽһλϢ˵ĹӸߵij
ܷͬʱ·ֽУ·ҲУ֤ŵ
*/
#include <stdio.h>
#include <iostream>
#include <algorithm>
using namespace std;
typedef struct
{
int id;
int d;
int c;
int sum;
int level;
}student;
bool compare(student a,student b)
{
if(a.level!=b.level)
return a.level>b.level;
else if(a.sum!=b.sum)
return a.sum>b.sum;
else if(a.d!=b.d)
return a.d>b.d;
else
return a.id<b.id;
}
int main(void)
{
int n,l,h,count;
cin>>n>>l>>h;
count = n;
student stu[n];
for(int i=0;i<n;i++)
{
cin>>stu[i].id>>stu[i].d>>stu[i].c;
stu[i].sum = stu[i].d+stu[i].c;
if(stu[i].d>=h && stu[i].c>=h)
stu[i].level=5;
else if(stu[i].d>=h && stu[i].c>=l && stu[i].c<h)
stu[i].level=4;
else if(stu[i].d<h && stu[i].c<h && stu[i].d>=l && stu[i].c>=l && stu[i].d>stu[i].c)
stu[i].level=3;
else if(stu[i].d>=l && stu[i].c>=l && stu[i].d<h && stu[i].d<h)
stu[i].level=2;
else
{
stu[i].level=1;
count--;
}
}
sort(stu,stu+n,compare);
cout<<count<<endl;
for(int i=0;i<count;i++)
{
if(i<count-1)
cout<<stu[i].id<<" "<<stu[i].d<<" "<<stu[i].c<<endl;
else
cout<<stu[i].id<<" "<<stu[i].d<<" "<<stu[i].c;
}
return 0;
}
| true |
7cbe8f7cff6cdba562ead7ab62e7bc02277ced1e | C++ | mariamsandhu/Cpp | /table.cpp | UTF-8 | 319 | 2.703125 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main(){
int tableNo,Tablecounter=1, tableLength;
cout<<"Enter table no\n";
cin>>tableNo;
cout<<"Enter table length\n";
cin>>tableLength;
while (Tablecounter <= tableLength){
cout<<tableNo<<"*"<<Tablecounter<<"="<<(tableNo*Tablecounter)<<endl;
Tablecounter++;
}
}
| true |
5ea3aa8d1a4c32f9ca7cb1c05a7c4dd344221116 | C++ | praveen4698/competitiveProgrammingWithCpp | /graph/spoj roti prata.cpp | UTF-8 | 2,270 | 3.328125 | 3 | [] | no_license | #include<iostream>
#include<vector>
#include<list>
#include<queue>
using namespace std;
class Graph
{
int V;
vector <pair<int,int> > *g;
int *distance;
public:
Graph(int V);
void addedge(int u,int v,int w);
void Dijkstra(int n);
void print();
};
struct compare{
bool operator()(const pair<pair<int,int>,pair<int,int> > l,const pair<pair<int,int>,pair<int,int> > r)
{
return l.second.second > r.second.second;
}
};
Graph::Graph(int V)
{
this->V = V;
g = new vector<pair<int,int> >[V];
distance = new int[V];
}
void Graph::addedge(int u ,int v,int w)
{
g[u].push_back(make_pair(v,w));
}
void Graph::Dijkstra(int n)
{
for(int i = 0 ;i<V;++i)
distance[i] = 0;
int count = 0;
priority_queue<int , vector<pair <pair<int,int> ,pair<int,int> > > ,compare> Q;
for(int i=0;i<V;++i)
{
Q.push(make_pair(make_pair(i,g[i].front().first),make_pair(g[i].front().second,g[i].front().second)));
}
while(count < n)
{
pair<pair<int,int>, pair<int, int > > X;
X = Q.top();
Q.pop();
//printf("%d %d %d %d\n",X.first.first,X.first.second,X.second.first,X.second.second);
distance[X.first.first] = X.second.second;
X.second.first = X.second.first + X.first.second;
X.second.second = X.second.second + X.second.first;
count++;
Q.push(make_pair(make_pair(X.first.first,X.first.second),make_pair(X.second.first,X.second.second)));
}
}
void Graph::print()
{ int MAX = distance[0];
for(int i =1;i<V;++i)
{
if(MAX < distance[i])
MAX = distance[i];
}
printf("%d\n",MAX);
}
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
int n;
scanf("%d",&n);
int N;
scanf("%d",&N);
Graph g1(N);
for(int i = 0;i<N;++i)
{
int a;
scanf("%d",&a);
g1.addedge(i,a,a);
}
g1.Dijkstra(n);
g1.print();
}
return 0;
}
| true |
57f8c4547502a05fbd2ee33f5bce719089f1d7c3 | C++ | trieck/source | /c++/TorrentExplorer/StringTokenizer.cpp | UTF-8 | 2,627 | 2.65625 | 3 | [] | no_license | // StringTokenizer.cpp: implementation of the StringTokenizer class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "torrentexplorer.h"
#include "StringTokenizer.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
StringTokenizer::StringTokenizer(LPCSTR pinput, LPCSTR pdelim)
: delim(pdelim), init(false), nextoken(0)
{
input = strdup(pinput);
}
/////////////////////////////////////////////////////////////////////////////
StringTokenizer::~StringTokenizer()
{
delete []input;
}
/////////////////////////////////////////////////////////////////////////////
CString StringTokenizer::next()
{
const char *ptok;
if (init)
ptok = StringTokenizer::strtok(NULL);
else {
ptok = StringTokenizer::strtok(input);
init = true;
}
return ptok == NULL ? "" : ptok;
}
// adapted from MS C runtime library, doesn't support multiple threads
//
LPCSTR StringTokenizer::strtok(LPCSTR string)
{
LPBYTE str;
LPCBYTE ctrl = (LPCBYTE)(LPCSTR)delim;
BYTE map[32];
int count;
/* Clear control map */
for (count = 0; count < 32; count++)
map[count] = 0;
/* Set bits in delimiter table */
do {
map[*ctrl >> 3] |= (1 << (*ctrl & 7));
} while (*ctrl++);
/* Initialize str. If string is NULL, set str to the saved
* pointer (i.e., continue breaking tokens out of the string
* from the last strtok call)
*/
if (string)
str = (LPBYTE)string;
else
str = (LPBYTE)nextoken;
/* Find beginning of token (skip over leading delimiters). Note that
* there is no token if this loop sets str to point to the terminal
* null (*str == '\0')
*/
while ((map[*str >> 3] & (1 << (*str & 7))) && *str)
str++;
string = (PCHAR)str;
/* Find the end of the token. If it is not the end of the string,
* put a null there.
*/
for ( ; *str; str++)
if (map[*str >> 3] & (1 << (*str & 7))) {
*str++ = '\0';
break;
}
/* Update nextoken (or the corresponding field in the per-thread data
* structure
*/
nextoken = (PCHAR)str;
/* Determine if a token has been found. */
if (string == (PCHAR)str)
return NULL;
else
return string;
}
| true |
6b7f687cbf6bb181afa4074757444ae68c9b1a22 | C++ | fiftyfivebells/book-store | /src/Customer.cc | UTF-8 | 699 | 2.703125 | 3 | [] | no_license | #include "../include/Customer.h"
Customer::Customer(string first, string last, string email, string pass) {
firstName = first;
lastName = last;
password = pass;
this->email = email;
}
Customer::~Customer() {
delete shipping;
delete billing;
}
Address *Customer::getShipping() { return shipping; }
void Customer::setShipping(Address *ship) { shipping = ship; }
Address *Customer::getBilling() { return billing; }
void Customer::setBilling(Address *bill) { billing = bill; }
string Customer::getFirst() { return firstName; }
string Customer::getLast() { return lastName; }
string Customer::getEmail() { return email; }
string Customer::getPassword() { return password; }
| true |
4b39437bcef55847d1a0c585acd4e9d6e94365b0 | C++ | borisblizzard/liteser | /include/liteser/Ptr.h | UTF-8 | 857 | 2.96875 | 3 | [
"BSD-3-Clause"
] | permissive | /// @file
/// @version 3.1
///
/// @section LICENSE
///
/// This program is free software; you can redistribute it and/or modify it under
/// the terms of the BSD license: http://opensource.org/licenses/BSD-3-Clause
///
/// @section DESCRIPTION
///
/// Represents a generic value pointer.
#ifndef LITESER_PTR_H
#define LITESER_PTR_H
#include <stdint.h>
#include <hltypes/harray.h>
#include <hltypes/hmap.h>
#include <hltypes/hstring.h>
namespace liteser
{
class Ptr
{
public:
inline Ptr() { }
virtual inline ~Ptr() { }
};
template <typename T>
class VPtr : public Ptr
{
public:
T* value;
inline VPtr(T* value) { this->value = value; }
};
template <typename T>
class CPtr : public Ptr
{
public:
harray<T>* data;
inline CPtr(harray<T>* data) { this->data = data; }
inline ~CPtr() { delete this->data; }
};
}
#endif
| true |
0021fa855bf858ddca7f869e8ef01072e45ce939 | C++ | BenJilks/TinyEngine | /include/TinyShader.h | UTF-8 | 1,228 | 2.8125 | 3 | [] | no_license | #pragma once
#include "glad.h"
#include <string>
#include "TinyMaths.h"
using namespace std;
/* Create and handle OpenGL shaders */
namespace TinyEngine
{
class TinyShader
{
public:
TinyShader() {};
TinyShader(string vertex_path, string fragment_path);
/* Bind an attribute to a location in the shader */
void BindAttribute(string name, unsigned int id);
/* Allocate an amount of data for string locations */
void AllocateLocations(unsigned int size) { m_uniforms = new GLuint[size]; };
/* Allocate new uniform location */
void SetLocation(string name, unsigned int location);
/* Load data to shader */
void LoadMatrix(unsigned int location, Mat4f matrix) { glUniformMatrix4fv(m_uniforms[location], 1, GL_TRUE, matrix.m); };
void LoadVector(unsigned int location, Vec3f vector) { glUniform3f(m_uniforms[location], vector.x(), vector.y(), vector.z()); }
/* Starts using the shader to render models to the screen */
void BindShader();
~TinyShader();
/* Stop using all shaders */
static void UnbindAll() { glUseProgram(0); };
private:
GLuint m_shader_id;
GLuint m_shader_vertex_id;
GLuint m_shader_fragment_id;
GLuint* m_uniforms;
};
}
| true |
5cfb2b2f68c612ca6d7d6b0523d893b602f57e8f | C++ | hlzy/some_test | /shared_ptrtest/test2.cpp | UTF-8 | 932 | 2.78125 | 3 | [] | no_license | #include <memory>
#include <iostream>
#include <vector>
using namespace std;
class A;
static shared_ptr<A> c;
class A
{
public:
// A() {};
A(int b) {cout<<"init"<<endl;a=b;}
// A(const A& b) {cout<<"initx"<<endl;a=b.a;}
~A() {
cout<<"deinit "<<a<<endl;
}
int a;
};
int main(int argc, char **argv) {
// c.reset(new A(10));
c.reset(new A(10));
cout<<"???"<<endl;
// static vector<A> b;
// b.push_back(A(10));
// b[0].a=5;
// A *a= new A(10);
// shared_ptr<A> s_a(a);
// s_a.reset(a);
// cout<<s_a.use_count()<<endl;
// shared_ptr<A> s_b;
// s_b = s_a;
// shared_ptr<A> s_c(s_b);
// cout<<s_a.use_count()<<" "<<s_a.get()->a<<endl;
// cout<<s_b.use_count()<<" "<<s_b->a<<endl;
// s_a.reset(new A(11));
// cout<<s_a.use_count()<<" "<<s_a.get()->a<<endl;
// cout<<s_b.use_count()<<" "<<s_b->a<<endl;
// int *i_a = new int(2);
// shared_ptr<int> s_i(i_a);
// A *a = new A[10];
return 0;
}
| true |
5e7025ea2cb5bbcaede03ffe95fcb9f6aec62bb0 | C++ | qingmang178/learn | /浙大数据结构/Polynomials.cpp | UTF-8 | 301 | 2.890625 | 3 | [] | no_license | #include <stdio.h>
#include <math.h>
double f1(int n ,double a[], double x)
{
int i;
double p =a[0];
for(i=1;i<=n;i++)
p+=(a[i]*pow(x,i));
return p;
}
double f2(int n, double a[], double x)
{
int i;
double p =a[n];
for(i=n;i>0;i--)
p=a[i-1]+x*p;
return p;
}
int main()
{
}
| true |
cc6169fd817c21beb454248ec61f98afdb6a4a9c | C++ | ghj0504520/UVA | /10000/10019.cpp | UTF-8 | 750 | 3.484375 | 3 | [] | no_license | #include<iostream>
#include<cstdio>
using namespace std;
int de_to_hex(int num);
int binary_count(int num);
int main()
{
int t;
while(cin>>t)
{
while(t--)
{
int num_de;
cin>>num_de;
int b_1=binary_count(num_de);
int b_2=binary_count(de_to_hex(num_de));
cout<<b_1<<" "<<b_2<<'\n';
}
}
return 0;
}
int de_to_hex(int num)
{
int sum=0,power=1;
while(num != 0)
{
sum += (num%10)*power;
num /= 10;
power *= 16;
}
return sum;
}
int binary_count(int num)
{
int count=0;
while(num != 0)
{
if(num % 2)
count++;
num/=2;
}
return count;
}
| true |
dee168095707dee534d9849cbe1e45f5c18072dc | C++ | ToxicGLaDOS/sentinel | /values/IntValue.cpp | UTF-8 | 1,080 | 3.40625 | 3 | [] | no_license | /*
* Definitions for IntValue
*
* See IntValue.h for more information
*/
#include "IntValue.h"
IntValue::IntValue(int value)
: SentinelValue(SentinelValue::INT)
, value(value){}
std::shared_ptr<SentinelValue> IntValue::add(const SentinelValue& other) const{
if(other.isInt()){
// Not sure if we want to use static_cast or dynamic_cast here.
// static_cast *should* be safe because we do our own type checking e.g. if(other.isDouble())
return add(static_cast<const IntValue&>(other));
}
else if(other.isDouble()){
return add(static_cast<const DoubleValue&>(other));
}
throw std::runtime_error("Tried to add int to something you can't add an int to.");
}
std::shared_ptr<SentinelValue> IntValue::add(const IntValue& other) const{
return std::make_shared<IntValue>(value + other.value);
}
std::shared_ptr<SentinelValue> IntValue::add(const DoubleValue& other) const{
return std::make_shared<DoubleValue>(value + other.value);
}
std::string IntValue::toString() const {
return std::to_string(value);
} | true |
19ee50e2d369fa32e60e2e7df45e78056fd856df | C++ | siyeonparkk/C-study | /WEEK1-2 수정.cpp | WINDOWS-1252 | 481 | 3.25 | 3 | [] | no_license | #include <iostream>
using namespace std;
void main(float x, int y)
{
cout << "Firstnumber ";
cin >> x;
char ch;
cout << "Secondnumber ";
cin >> y;
cout << "==========";
cout << x << "+" << y << "=" << x + y << endl;
cout << x << "-" << y << "=" << x - y << endl;
cout << x << "*" << y << "=" << x * y << endl;
float result;
result = x / y;
cout << x << "/" << y << "=" << result << endl;
} | true |
d9ff5e7c58c6254f16e7605bee2564c1587303fe | C++ | Ol5xHd/tasks | /Yandex_algorithms/sprint2_recursion/taskI/main.cpp | UTF-8 | 5,593 | 3.109375 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <set>
#include <map>
using namespace std;
typedef unsigned short UShort;
typedef unsigned int UInt;
/**
* @brief основной метод перебора комбинаций монеток
* @param coins - множество монеток, из которого выбираем
* @param combinations - множество комбинаций монеток (по числу победителей)
* @param curr_ind - индекс текущего множества, которое пытаемся сформировать
* @param target_sum - сумма для каждого победителя
* @param winners_cnt - число победителей
* @return true, если разделить можно, иначе false
*/
bool Combine( multiset<UShort> coins, map<UShort, multiset<UShort>> &combinations, UShort curr_ind, UInt target_sum, UShort winners_cnt )
{
multiset<UShort> &curr_comb = combinations[ curr_ind ];
UInt curr_sum = 0;
for( const UShort &coin : curr_comb )
curr_sum += coin;
if( curr_sum == target_sum ) // в текущем множестве сформировалась нужная сумма
{
++curr_ind; // это множество сформировано, занимаемся следующим
if( curr_ind == winners_cnt ) // а нет следующего множества, сформировали для всех победителей
{
if( coins.empty() ) // да ещё и все монетки потратили
return true; // ну это успех
else // оп-па, лишние монетки остались
return false; // фиаско
}
else // есть следующее множество. которое надо сформировать
{
return Combine( coins, combinations, curr_ind, target_sum, winners_cnt );
}
}
else if( curr_sum < target_sum ) // в текущем множестве недостаточная сумма
{
if( coins.empty() ) // но основной пул монеток пуст, не из чего выбирать
{
return false;
}
else // есть ещё монетки для выбора
{
for( auto it = coins.begin(); it != coins.end(); ++it ) // каждую монетку из оставшихся попробуем пристроить в текущее множество
{
if( *it > target_sum - curr_sum ) // если с монеткой сумма станет слишком большой, пропустим её
{
continue;
}
else // монетка сумму нам не испортит, хорошо
{
curr_comb.insert( *it ); // добавляем её
multiset<UShort> new_coins; // сформируем новый пул монеток - без одной, которую только что использовали
for( auto sub_it = coins.begin(); sub_it != coins.end(); ++sub_it )
if( sub_it != it )
new_coins.insert( *sub_it );
bool sub_res = Combine( new_coins, combinations, curr_ind, target_sum, winners_cnt );
if( sub_res ) // такой расклад привёл к успеху
return true;
else // расклад не привёл к успеху
curr_comb.erase( *it ); // вынимаем монетку из текущего множества
}
}
}
return false; // перебрали все монетки, но успеха не достигли - фиаско
}
else if( curr_sum > target_sum ) // в текущем множестве слишком большая сумма, нельзя так
{
return false;
}
return false; // на всяский случай - не должны этой точки достичь
}
bool CanShare( multiset<UShort> &coins, UShort winners_cnt )
{
UInt total_sum = 0;
for( const UShort &coin : coins )
total_sum += coin;
if( total_sum % winners_cnt != 0 )
return false;
UInt target_sum = total_sum / winners_cnt;
map<UShort, multiset<UShort>> combinations; // здесь будем хранить все комбинации монеток для победителей
for( UShort i = 0; i < winners_cnt; ++i )
combinations.insert( pair<UShort, multiset<UShort>>( i, multiset<UShort>() ) );
UShort curr_ind = 0;
return Combine( coins, combinations, curr_ind, target_sum, winners_cnt );
}
int main()
{
ifstream fin;
fin.open( "input.txt" );
string line;
getline( fin, line );
UShort winners_cnt = static_cast<UShort>( stoi( line ) );
getline( fin, line );
UShort coins_cnt = static_cast<UShort>( stoi( line ) );
getline( fin, line );
stringstream sstream( line );
multiset<UShort> coins;
for( UShort i = 0; i < coins_cnt; ++i )
{
UShort coin = 0;
sstream >> coin;
coins.insert( coin );
}
bool can_share = CanShare( coins, winners_cnt );
if( can_share )
cout << "True";
else
cout << "False";
return 0;
}
| true |
24fdf48fd06f987aade189da7f460f01f7d024a2 | C++ | mmrahman01/CS491 | /main.cpp | UTF-8 | 3,806 | 3.03125 | 3 | [] | no_license | /*
--- Collaborative filtering----
1. M x N matrix.
2.Determine similarity between users.
(Correlation coefficient and Vector Space (Cosine Similarity)
3.R'ut + ( Total Wu, ut (Ru(o) - R'u) / (Total |Wa, Ut|
How to from here
4.Train Data, Each user, add non zero divide by number of non zero to get avg.
5.Subtract the avg from each ranking to get bias out.
6.Multiply User1 and Test1 (each column and total it) .. A
7.Square Columns in User1, add it and then square root (for each user)..B
8.Square Columns in Test1, add and then take square root............C
9.D = A /(B * C) (Do this for each Users)
10. E = Test Avg + (( D * User1 Particular Column) + (D another user * That user column))
/ (Abs D of users (summation))
*/
#include "recon.h"
#include <iostream>
#include <cstdlib>
#include <fstream>
#include <vector>
#include <string>
#include <sstream>
#include <algorithm>
#include <map>
#include <cmath>
#include<stdlib.h>
using namespace std;
int main()
{
char answer = 'y';
recon user; // declare a class variable.
user.infile.open("ratings.txt");// the data is coming from this file
user.read_data(); // read the ranked data;
//user.prints_two_data(user.user_review);
while (answer !='q'){
cout << "This Program Suggests movie for individual users.\n" << endl;
cout<<"Enter User Number as a Test Case :"; // we will use a user as a test
cin>> user.user_number;
if ((user.user_number > 200)|| (user.user_number<1))
{
cout<<"Please enter a value from 1 to 200 :";
cin>>user.user_number;
if ((user.user_number > 200)|| (user.user_number<1))
{
system("cls");
cout<<"BYE"<<endl;
return -1;
}
}
user.user_number -=1; // just for display purposes.
for (int i=0; i<1000; i++){
user.test_user.push_back(user.user_review.at(user.user_number)[i]);
}
for (int i=0; i<1000; i++){
if (user.test_user[i]>0){
cout<<"Movie Number :" <<i<<" "<<user.test_user[i]<< endl ;
}
}
cout<<endl;
cout<<"Enter a movie number for testing from above list :";
cin>>user.user_number_rank;
cout<<endl;
// cout<<"User number:"<<user.user_number+1<<" "<<"Movie Number:"<<user.user_number_rank;
// cout<<" Rank:"<<user.user_review[user.user_number][user.user_number_rank]<<endl;
user.get_average();
//user.print_one_data(user.average);
user.unbiased_data();
//user.print_two_data(user.unbiased);
user.multiply();
//user.print_two_data(user.t1_times_t2);
user.squared();
system("cls");
user.calculate();
user.calc_idf();
user.calc_second();
user.sorted();
/*
//sort(user.D.begin(),user.D.end());
//*******************************************
for (int i =0; i < 200; i++){
cout<<"Similarity "<<i<<" " <<user.cos_sim[i]<<endl;
}
for (int i =0; i < 200; i++){
cout<<"Sim "<<user.cosine_rank[i].first<<" "<<user.cosine_rank[i].second<<" "<<endl;
if (user.user_review[i][user.user_number_rank]!=0){
cout<<user.user_review[i][user.user_number_rank]<<endl;
}
}
*/
//cout<<user.test_user[user.user_number_rank]<<endl;
user.recommended_rank();
// user.modified_Rank();
user.recommended_rank2();
// cout<<user.D.size()<<endl;
// clear everything to recalculate a different user and rank
user.D.clear();
user.idf.clear();
user.tf_idf.clear();
user.average.clear();
user.unbiased.clear();
user.t1_times_t2.clear();
user.sq_root.clear();
user.test_user.clear();
cout<<"\nContinue? (Enter q to quit): ";
cin>>answer;
}
user.infile.close();
return 0;
}
| true |
c164785429daf7f815d5be4e2ec279902d6e69a8 | C++ | danposch/itec-scenarios | /extensions/droppingPolicy/droppingpolicy.cc | UTF-8 | 835 | 2.953125 | 3 | [] | no_license | #include "droppingpolicy.h"
DroppingPolicy::DroppingPolicy()
{
// init metric with 0.0
metric = 0.0;
}
void DroppingPolicy::SetMetric(double metric)
{
if (metric < 0.0)
return;
if (metric > 1.0)
return;
this->metric = metric;
}
void DroppingPolicy::Feed(LevelStatistics& L)
{
this->dropProbs.resize(L.GetAmountOfLevels(), 0.0);
// calculate dropping probabilities
CalculateDroppingProbabilities(L);
}
double DroppingPolicy::GetDroppingProbability(unsigned int layer)
{
return this->dropProbs[layer];
}
void DroppingPolicy::Print(ostream& os)
{
os << "DropProb: ";
for (std::vector<double>::iterator it = this->dropProbs.begin();
it != this->dropProbs.end();
++it)
{
double prob = *it;
os << prob << ", ";
}
os << endl;
}
| true |
91979cafb7ac4c0c68dba3cde0911cc48f0deaed | C++ | harrison-aw/NeuralNetworkProject | /Neural Network Project/src/main.cpp | UTF-8 | 1,827 | 2.71875 | 3 | [] | no_license | /*
* main.cpp
*
* Created on: May 6, 2013
* Author: Tony
*/
#include <algorithm>
#include <fstream>
#include <iostream>
#include <stdexcept>
#include "art2network/ART2Network.h"
#include "frequency/FrequencyTable.h"
using namespace std;
using namespace art2nn;
using namespace nnproject;
input_vector makeInput(FrequencyRecord &fr);
int main() {
FrequencyTable ft;
ifstream fin("input.ft");
if (fin) {
fin >> ft;
fin.close();
cout << "input read" << endl;
} else {
cout << "unable to read input" << endl;
return 1;
}
param a = 10;
param b = 10;
param c = 4;
param d = .2;
param e = 0;
param theta = .005;
param rho = .99999;
ART2Network network(127, a, b, c, d, e, theta, rho);
cout << "Network built." << endl << endl;
for (int i = 0; i < 10; ++i) {
cout << "Shuffling inputs" << endl << endl;
vector<string> inputs;
for (FrequencyTable::iterator it = ft.begin(); it != ft.end(); ++it)
inputs.push_back(it->first);
std::random_shuffle(inputs.begin(), inputs.end());
map<string, index> classification;
for (vector<string>::iterator it = inputs.begin(); it != inputs.end(); ++it) {
try {
cout << "processing " << *it << endl;
classification[*it] = network(ft[*it]);
cout << endl;
} catch (exception &e) {
cout << "Error: " << e.what() << endl;
return 1;
}
}
}
cout << endl << endl;
cout << "Printing results: " << endl;
for (map<string, index>::iterator it = classification.begin(); it != classification.end(); ++it) {
cout << it->first << " -> " << it->second << endl;
}
return 0;
}
input_vector makeInput(FrequencyRecord &fr) {
input_vector input(127);
for (char c = 0; c < 127; ++c) {
input[c] = fr.frequencyOf(c);
}
return input;
}
| true |
1bc7dce8f07674a7f68defbe16f3173a13611f48 | C++ | chiranjeevbitm/C_and_Cpp | /Geek_Practice/DynamicPrograming/WineProblem.cpp | UTF-8 | 900 | 2.734375 | 3 | [] | no_license | #include<iostream>
using namespace std;
#include<cstring>
#include<limits.h>
//int ncall =0;
int calls = 0;
int memo[100][100];
int max_profit(int arr[],int s,int e,int y)
{
// ++ncall;
if(s>e) return 0;
int q1 = arr[s] * y + max_profit(arr,s+1,e,y+1);
int q2 = arr[e] * y + max_profit(arr,s,e-1,y+1);
return (max(q1,q2));
}
int max_profitMEMO(int arr[],int s,int e,int y)
{
++calls;
if(s>e) return 0;
if(memo[s][e]!=-1)
{
return memo[s][e];
}
int q1 = arr[s] * y + max_profit(arr,s+1,e,y+1);
int q2 = arr[e] * y + max_profit(arr,s,e-1,y+1);
int ans = max(q1,q2);
memo[s][e] = ans;
return ans;
}
int main()
{
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++) cin>>arr[i];
//
// cout<<max_profit(arr,0,n-1,1)<<'\n';
// cout<<ncall<<'\n';
memset(memo,-1,sizeof(memo));
cout<<max_profitMEMO(arr,0,n-1,1)<<'\n';
cout<<calls<<'\n';
return 0;
}
| true |
da9310bc79c4b0127a8cf3e2c6dc35fee817295b | C++ | George55555/Stealth | /contrib/pyHash9/pyHash9.cpp | UTF-8 | 1,435 | 2.609375 | 3 | [
"MIT"
] | permissive | // Copyright (c) 2016-2019 Stealth R&D LLC
#include <stddef.h>
#include "hashblock.h"
#include <Python.h>
static const int HASHLEN = 32;
PyObject* hash9(PyObject *self, PyObject *args)
{
char* stringIn;
int size = 0;
/* can't parse args */
if (! PyArg_ParseTuple(args, "s#", &stringIn, &size)) {
PyErr_SetString(PyExc_TypeError,
"method expects a string(s)") ;
return NULL ;
}
uint256 hash = Hash9(stringIn, stringIn + size);
return PyString_FromString(hash.ToString().c_str());
}
PyObject* hash(PyObject *self, PyObject *args)
{
char* stringIn;
int size = 0;
/* can't parse args */
if (! PyArg_ParseTuple(args, "s#", &stringIn, &size)) {
PyErr_SetString(PyExc_TypeError,
"method expects a string(s)") ;
return NULL ;
}
uint256 h = Hash9(stringIn, stringIn + size);
char bytes[HASHLEN + 1];
bytes[HASHLEN] = 0x00;
// uint256 internal representation is reversed
int i = HASHLEN - 1;
for (unsigned char *c = h.begin(); c != h.end(); ++c)
{
bytes[i] = (char)*c;
i -= 1;
}
return PyString_FromStringAndSize(bytes, HASHLEN);
}
static struct PyMethodDef pyHash9_methods[] =
{
{"hash9", hash9, 1, "get the X13 hash as hex"},
{"hash", hash, 1, "get the X13 hash"},
{NULL, NULL}
};
extern "C" void initpyHash9(void)
{
(void) Py_InitModule("pyHash9", pyHash9_methods);
}
| true |
6cce829f331a7e843021b7089263efbed48e66d3 | C++ | thrawn01/io-perf | /read-threaded.cpp | UTF-8 | 6,078 | 2.59375 | 3 | [] | no_license | #include <boost/thread/mutex.hpp>
#include "boost/threadpool.hpp"
#include "boost/bind.hpp"
#include <openssl/md5.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <inttypes.h>
#include <getopt.h>
#include <stdlib.h>
#include <set>
#include <vector>
extern "C" {
#include "gethrxtime.h"
#include "lz4/lz4.h"
#include "lz4/lz4hc.h"
}
using namespace boost::threadpool;
using namespace std;
// Globals
int (*compress)(const char*, char*, int) = 0;
int hashing_enabled = 0;
int verbose = 0;
set<string> hash_pool;
boost::mutex hash_mutex;
// 10MB Block size seams optimal on our hardware
ssize_t block_size = 10485760;
ssize_t size(const char* file){
int fd = 0;
if( (fd = open(file, O_RDONLY | O_DIRECT)) == -1){
printf("Error Opening: '%s'\n", strerror(errno));
exit(1);
}
ssize_t offset = lseek(fd, 0, SEEK_END);
if( offset == -1){
printf("Error Seeking to EOF - %s\n", strerror(errno));
exit(1);
}
return offset;
}
int exists(const char* hash){
set<string>::iterator it;
string key(hash);
// Will lock the mutex until we lose scope
boost::mutex::scoped_lock l(hash_mutex);
it = hash_pool.find(key);
// hash doesn't already exist
if( it == hash_pool.end() ){
// Add the hash to the pool
hash_pool.insert(key);
return 0;
}
return 1;
}
void read_block(const char* file, ssize_t offset, int num_blocks){
unsigned char hash[MD5_DIGEST_LENGTH];
char hash_print_buf[MD5_DIGEST_LENGTH * 2];
char* compress_buf = 0;
char *local_buf = 0;
int fd = 0;
printf("Reading From Offset %ld\n", offset);
if( (fd = open(file, O_RDONLY | O_DIRECT)) == -1){
printf("T - Error Opening: '%s'\n", strerror(errno));
return;
}
if( lseek(fd, offset, SEEK_SET) == -1){
printf("T - Error Seeking to '%ld' - %s\n", offset, strerror(errno));
return;
}
if(compress){
// lz4 may need more space to compress, ask
// it for the worst possible resulting buffer size
compress_buf = (char*)malloc(LZ4_compressBound(block_size));
}
if(posix_memalign((void**)&local_buf, 512, block_size) != 0){
printf("Error Allocating memory\n");
}
for(int i=0; i < num_blocks; ++i){
int count = read(fd, local_buf, block_size);
if (count < 0 || errno == EINTR){
printf("T - Read Error: '%s'\n", strerror(errno));
return;
}
if(hashing_enabled) {
// Hash the block
MD5((const unsigned char*)local_buf, block_size, hash);
// Convert to string (much like python would) for use in a set() and printf()
for(int j=0; j < MD5_DIGEST_LENGTH; j++) sprintf(hash_print_buf + (j * 2), "%02x", hash[j]);
if(verbose > 1){ printf("Hashed: %s\n", hash_print_buf); }
// Did we already compress this block?
if(exists(hash_print_buf)){
if(verbose){ printf("Skip Compress: %s\n", hash_print_buf); }
continue;
}
}
if(compress){
// Preform the compression
ssize_t compress_size = compress(local_buf, compress_buf, block_size);
if(verbose){ printf("Compressed block %d from %lu to: %lu Bytes\n", i, block_size, compress_size); }
}
}
free(compress_buf);
free(local_buf);
}
void usage(void) {
printf("read-threaded -d <device> [ -b <block_size> -j <num_of_jobs> -c <compression level> ]\n");
exit(1);
}
int main(int argc, char **argv){
uintmax_t total = 0;
int num_jobs = 10;
char *device = 0;
int c;
while ((c = getopt (argc, argv, "hvd:b:j:c:")) != -1) {
switch (c) {
case 'd': device = optarg; break;
case 'b': block_size = atoll(optarg); break;
case 'j': num_jobs = atoi(optarg); break;
case 'v': verbose += 1; break;
case 'h': hashing_enabled = 1; break;
case 'c':
// Compression Level
switch (atoi(optarg)) {
case 0 : compress = 0; break;
case 1 : compress = LZ4_compress; break;
case 2 : compress = LZ4_compressHC; break;
default: break;
}
break;
default:
printf("Unknown option character `\\x%x'.\n", optopt);
usage();
}
}
if(!device){
printf("Please supply a device to read with the -d option\n");
usage();
}
ssize_t file_size = size(device);
// figure the total number of blocks on the device
int total_blocks = (int)(file_size / block_size);
// figure how many blocks a threads should read before quiting
int blocks_per_thread = total_blocks / num_jobs;
pool tp(num_jobs);
printf("file-size: %ld block-size %ld total-blocks: %d blocks-per-thread: %d \n", file_size, block_size, total_blocks, blocks_per_thread);
xtime_t start_time = gethrxtime();
for(int i=0; i < num_jobs; ++i) {
// figure the offset the threads should start reading at
ssize_t offset = i * (block_size * blocks_per_thread);
// Start a read thread
tp.schedule(boost::bind(read_block, device, offset, blocks_per_thread));
}
tp.wait();
// Spit out our stats
double XTIME_PRECISIONe0 = XTIME_PRECISION;
xtime_t now = gethrxtime();
if(verbose > 1){
printf("MD5 Hash Set contains\n");
for (set<string>::iterator it = hash_pool.begin(); it!=hash_pool.end(); ++it) {
printf("- %s\n", (*it).c_str());
}
}
if (start_time < now) {
uintmax_t delta_xtime = now;
delta_xtime -= start_time;
double delta_s = delta_xtime / XTIME_PRECISIONe0;
printf("Throughput %g s @ %g MiB/s\n", delta_s, (file_size / delta_s) / 1048576);
}
return 0;
}
| true |
cb8f82f96590fef00815e2314ae10f30784c6b29 | C++ | Satar07/code | /1.4编程基础之逻辑表达式与条件分支/03奇偶数判断.cpp | UTF-8 | 144 | 2.6875 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main(){
int a;
cin>>a;
if (0==a%2){
cout <<"even";
return 0;
}
cout<<"odd";
return 0;
}
| true |
3ff15f6aab763447b03152f3de0ae3e9e32fc525 | C++ | AlazzR/Digital-Image-Processing-Cpp | /Chapter_5_Image_Restroration_and_Reconstruction/Section_5_8.cpp | UTF-8 | 2,964 | 2.671875 | 3 | [
"CC0-1.0"
] | permissive | #include "Section_5_8_H_.h"
void wiener_filtering(const cv::Mat& img, std::string type, float k, float a , float b, float T, std::string imageName, float K)
{
cv::Mat kernel;
if (type == "Atmospheric")
kernel = creating_H_atmospheric(k, img.rows, img.cols);
else
kernel = creating_H_motion(a, b, T, img.rows, img.cols);
cv::Mat ker[2] = { cv::Mat::zeros(img.rows, img.cols, CV_32FC1), cv::Mat::zeros(img.rows, img.cols, CV_32FC1) };
cv::split(kernel, ker);
cv::Mat mag;
cv::Mat temp;
cv::magnitude(ker[0], ker[1], mag);
cv::multiply(mag, mag, mag);
cv::add(mag, cv::Scalar::all(K), temp);
cv::divide(mag, temp, mag);
cv::Mat imgcentered = img.clone();
imgcentered.convertTo(imgcentered, CV_32FC1);
centering_image(imgcentered);
cv::Mat complex[2] = { imgcentered, cv::Mat::zeros(img.rows, img.cols, CV_32FC1) };
cv::Mat dftimg;
cv::merge(complex, 2, dftimg);
cv::dft(dftimg, dftimg);
cv::split(dftimg, complex);
cv::multiply(complex[0], mag, complex[0]);
cv::multiply(complex[1], mag, complex[1]);
std::cout << "*******************************" << std::endl;
//(a+jb)/ (c + jd) = mag(a,b)/mag(c,d) < atan(b/a) - atan(d/c)
cv::Mat magTemp[2] = { complex[0].clone(), complex[1].clone() };
cv::Mat phaseTemp = complex[0].clone();
cv::magnitude(complex[0], complex[1], magTemp[0]);
cv::magnitude(ker[0], ker[1], magTemp[1]);
cv::divide(magTemp[0], magTemp[1], magTemp[0]);
float* ptrMag1;
float* ptrMag2;
float* ptrPhase;
const float* ptrC1;
const float* ptrC2;
const float* ptrK1;
const float* ptrK2;
for (int row = 0; row < img.rows; row++)
{
ptrPhase = phaseTemp.ptr<float>(row);
ptrC1 = complex[0].ptr<float>(row);
ptrC2 = complex[1].ptr<float>(row);
ptrK1 = ker[0].ptr<float>(row);
ptrK2 = ker[1].ptr<float>(row);
for (int col = 0; col < img.cols; col++)
{
ptrPhase[col] = std::atan2f(ptrC2[col], ptrC1[col]) - std::atan2f(ptrK2[col], ptrK1[col]);
}
}
magTemp[1] = magTemp[0].clone();//To equate them and this will mitigate the issue of creating another Mat object
for (int row = 0; row < img.rows; row++)
{
ptrMag1 = magTemp[0].ptr<float>(row);
ptrMag2 = magTemp[1].ptr<float>(row);
ptrPhase = phaseTemp.ptr<float>(row);
for (int col = 0; col < img.cols; col++)
{
ptrMag1[col] = ptrMag1[col] * std::cos(ptrPhase[col]);//real
ptrMag2[col] = ptrMag2[col] * std::sin(ptrPhase[col]);//imaginary
}
}
complex[0] = magTemp[0].clone();
complex[1] = magTemp[1].clone();
cv::merge(complex, 2, dftimg);
cv::dft(dftimg, dftimg, cv::DFT_INVERSE | cv::DFT_REAL_OUTPUT | cv::DFT_SCALE);
cv::Mat finalImg;
finalImg = dftimg.clone();
centering_image(finalImg);
//rescaling_intensities(finalImg);
finalImg.convertTo(finalImg, CV_8UC1);
cv::imwrite("../bin/Section_5_8/Origina_WienerFiltering_" + imageName + "_noiseType_BY_" + type + ".jpg", img);
cv::imwrite("../bin/Section_5_8/Image__After_WienerFiltering_" + imageName + "_noiseType_BY_" + type + ".jpg", finalImg);
} | true |
3b7f518ad3a656e9e738094d2b4fb2ac64ecaa6c | C++ | bcontant/TentGine | /Renderer_Base/Text.cpp | UTF-8 | 9,458 | 2.578125 | 3 | [] | no_license | #include "precompiled.h"
#include "Text.h"
#include "Renderer.h"
#include "../Base/FontDataFile.h"
#include "../Base/Profiler.h"
#include "VertexBuffer.h"
//--------------------------------------------------------------------------------
struct SimpleVertex
{
vec3 Pos;
vec2 UV;
u32 Color = 0xffffffff;
};
//--------------------------------------------------------------------------------
Text::Text(Renderer* pOwner)
: RendererObject(pOwner)
, m_pFont(nullptr)
, m_strText(L(""))
, m_xPos(0.f)
, m_yPos(0.f)
, m_pVertexBuffer(nullptr)
{
}
//--------------------------------------------------------------------------------
Text::~Text()
{
delete m_pVertexBuffer;
m_pVertexBuffer = nullptr;
}
//--------------------------------------------------------------------------------
void Text::SetPosition(float in_x, float in_y)
{
if (m_xPos == in_x && m_yPos == in_y)
return;
m_xPos = in_x;
m_yPos = in_y;
}
//--------------------------------------------------------------------------------
void Text::SetWidth(float in_w)
{
if (m_width == in_w)
return;
m_width = in_w;
m_InternalState |= eIS_VBDirty | eIS_TextDirty;
}
//--------------------------------------------------------------------------------
void Text::SetHeight(float in_h)
{
if (m_height == in_h)
return;
m_height = in_h;
m_InternalState |= eIS_VBDirty | eIS_TextDirty;
}
//--------------------------------------------------------------------------------
void Text::SetFont(const Font* in_pFont)
{
Assert(in_pFont != nullptr);
if (m_pFont == in_pFont)
return;
m_pFont = in_pFont;
m_InternalState |= eIS_VBDirty | eIS_TextDirty;
}
//--------------------------------------------------------------------------------
void Text::SetText(const std_string& in_strText)
{
if (m_strText == in_strText)
return;
m_strText = in_strText;
m_InternalState |= eIS_VBDirty | eIS_TextDirty;
}
//--------------------------------------------------------------------------------
void Text::SetColor(u32 in_Color)
{
if (m_Color == in_Color)
return;
m_Color = in_Color;
m_InternalState |= eIS_VBDirty;
}
//--------------------------------------------------------------------------------
/*
void Text::Draw()
{
Shader* pShader = GetOwner()->GetShader("simple2d_ptc");
pShader->SetConstant(WVP);
pShader->Bind(0);
m_pFont->GetTexture()->Bind(0);
m_pVertexBuffer->Bind();
m_pVertexBuffer->Draw();
}*/
//--------------------------------------------------------------------------------
void Text::UpdateText()
{
if (m_pFont == nullptr)
return;
PROFILE_BLOCK;
if (m_InternalState & eIS_TextDirty)
{
BuildTokens();
BuildLines();
BuildCharacters();
m_InternalState &= ~eIS_TextDirty;
}
if (m_InternalState & eIS_VBDirty)
{
UpdateVertexBuffer();
m_InternalState &= ~eIS_VBDirty;
}
}
//--------------------------------------------------------------------------------
void Text::BuildTokens()
{
const FontDataFile* pFontInfo = m_pFont->GetFontInfo();
//Break up the strings into indivisible segments for line breaking purposes
m_vTokens.clear();
TextToken currentToken;
currentToken.eType = eTT_Invalid;
currentToken.text = L("");
currentToken.width = 0.f;
for (ustring_char c : m_strText)
{
const FontDataFile::GlyphInfo* pCharInfo = pFontInfo->GetGlyphInfo(c);
if (pCharInfo == nullptr)
{
Assert(false);
continue;
}
if ((c == '\n' || c == ' '))
{
if (currentToken.text != L(""))
m_vTokens.push_back(currentToken);
if (c == '\n')
m_vTokens.push_back({ eTT_Linebreak, L(""), 0.f });
if (c == ' ')
m_vTokens.push_back({ eTT_Space, L(" "), 0.f + pCharInfo->advance });
currentToken.eType = eTT_Invalid;
currentToken.text = L("");
currentToken.width = 0.f;
continue;
}
//Special case. Break in middle of a string because it's wider than the region.
if (currentToken.width + pCharInfo->advance > m_width)
{
m_vTokens.push_back(currentToken);
currentToken.eType = eTT_Invalid;
currentToken.text = L("");
currentToken.width = 0.f;
}
currentToken.eType = eTT_Text;
currentToken.text += c;
currentToken.width += pCharInfo->advance;
}
if (currentToken.eType != eTT_Invalid)
m_vTokens.push_back(currentToken);
}
//--------------------------------------------------------------------------------
void Text::BuildLines()
{
const FontDataFile* pFontInfo = m_pFont->GetFontInfo();
m_vLines.clear();
TextLine currentLine;
s32 current_x = 0;
s32 current_y = 0;
current_y += pFontInfo->GetBaseLineOffset();
// Assemble the tokens into lines
for (TextToken seg : m_vTokens)
{
//Go to next line outside our zone's limits
if (current_x + seg.width > m_width)
{
current_x = 0;
current_y += pFontInfo->GetLineHeight();
m_vLines.push_back(currentLine);
currentLine.vTokens.clear();
}
if (seg.eType == eTT_Linebreak)
{
current_x = 0;
current_y += pFontInfo->GetLineHeight();
m_vLines.push_back(currentLine);
currentLine.vTokens.clear();
continue;
}
//Break out if we are outside our zone's limits
if (current_y > m_height)
{
break;
}
if (current_x == 0 && seg.eType == eTT_Space)
{
continue;
}
current_x += (s32)seg.width;
currentLine.vTokens.push_back(seg);
}
if (currentLine.vTokens.size() > 0)
m_vLines.push_back(currentLine);
}
//--------------------------------------------------------------------------------
void Text::BuildCharacters()
{
const FontDataFile* pFontInfo = m_pFont->GetFontInfo();
m_vCharacters.clear();
// Fill up the final character positions with the lines we created
s32 current_x = 0;
s32 current_y = 0;
current_y += pFontInfo->GetBaseLineOffset();
for (TextLine line : m_vLines)
{
for (TextToken token : line.vTokens)
{
for (ustring_char c : token.text)
{
const FontDataFile::GlyphInfo* pCharInfo = pFontInfo->GetGlyphInfo(c);
if (pCharInfo == nullptr)
{
Assert(false);
continue;
}
Character newChar;
newChar.m_Position.m_left = current_x + pCharInfo->m_GlyphBox.m_left;
newChar.m_Position.m_right = current_x + pCharInfo->m_GlyphBox.m_right;
newChar.m_Position.m_top = current_y - pCharInfo->m_GlyphBox.m_top;
newChar.m_Position.m_bottom = current_y - pCharInfo->m_GlyphBox.m_bottom;
newChar.m_UVs = pCharInfo->m_UVs;
//Some glyph have no size and are only useful for their advance (space)
if (newChar.m_Position.Width() > 0 && newChar.m_Position.Height() > 0)
m_vCharacters.push_back(newChar);
current_x += pCharInfo->advance;
}
}
current_x = 0;
current_y += pFontInfo->GetLineHeight();
}
}
//--------------------------------------------------------------------------------
void Text::UpdateVertexBuffer()
{
if (m_pVertexBuffer == nullptr)
{
m_pVertexBuffer = GetOwner()->CreateVertexBuffer(static_cast<u32>(m_vCharacters.size() * 6), VertexBuffer::eVB_Position | VertexBuffer::eVB_2D_TexCoords | VertexBuffer::eVB_Color, EPrimitiveType::ePT_TriangleList, nullptr, eUT_CPU_Writable);
}
else if (m_pVertexBuffer->GetVertexCount() != m_vCharacters.size() * 6)
{
m_pVertexBuffer->SetVertexCount(static_cast<u32>(m_vCharacters.size() * 6));
}
if (m_vCharacters.size() == 0)
return;
SimpleVertex* pVBData = new SimpleVertex[6 * static_cast<u32>(m_vCharacters.size())];
for (u32 i = 0; i < m_vCharacters.size(); i++)
{
Character& currentChar = m_vCharacters[i];
SimpleVertex* pVB = &pVBData[i * 6];
//Top Left
pVB->Pos.x = (float)currentChar.m_Position.m_left; pVB->Pos.y = (float)currentChar.m_Position.m_top; pVB->Pos.z = 1.f; pVB->UV.x = currentChar.m_UVs.m_left; pVB->UV.y = currentChar.m_UVs.m_top; pVB->Color = m_Color; pVB++;
//Top Right
pVB->Pos.x = (float)currentChar.m_Position.m_right; pVB->Pos.y = (float)currentChar.m_Position.m_top; pVB->Pos.z = 1.f; pVB->UV.x = currentChar.m_UVs.m_right; pVB->UV.y = currentChar.m_UVs.m_top; pVB->Color = m_Color; pVB++;
//Bottom Right
pVB->Pos.x = (float)currentChar.m_Position.m_right; pVB->Pos.y = (float)currentChar.m_Position.m_bottom; pVB->Pos.z = 1.f; pVB->UV.x = currentChar.m_UVs.m_right; pVB->UV.y = currentChar.m_UVs.m_bottom; pVB->Color = m_Color; pVB++;
//Bottom Right
pVB->Pos.x = (float)currentChar.m_Position.m_right; pVB->Pos.y = (float)currentChar.m_Position.m_bottom; pVB->Pos.z = 1.f; pVB->UV.x = currentChar.m_UVs.m_right; pVB->UV.y = currentChar.m_UVs.m_bottom; pVB->Color = m_Color; pVB++;
//Bottom Left
pVB->Pos.x = (float)currentChar.m_Position.m_left; pVB->Pos.y = (float)currentChar.m_Position.m_bottom; pVB->Pos.z = 1.f; pVB->UV.x = currentChar.m_UVs.m_left; pVB->UV.y = currentChar.m_UVs.m_bottom; pVB->Color = m_Color; pVB++;
//Top Left
pVB->Pos.x = (float)currentChar.m_Position.m_left; pVB->Pos.y = (float)currentChar.m_Position.m_top; pVB->Pos.z = 1.f; pVB->UV.x = currentChar.m_UVs.m_left; pVB->UV.y = currentChar.m_UVs.m_top; pVB->Color = m_Color; pVB++;
}
void* pVB = m_pVertexBuffer->Lock();
memcpy(pVB, pVBData, 6 * sizeof(SimpleVertex) * static_cast<u32>(m_vCharacters.size()));
m_pVertexBuffer->Unlock();
delete[] pVBData;
} | true |
b872fb38d061c4af5da9d2ee39a1c0a0d2c8fb23 | C++ | tomasmussi/concurrentes | /tp1/utils/Logger.h | UTF-8 | 847 | 2.734375 | 3 | [] | no_license | #ifndef TP1_LOGGER_H
#define TP1_LOGGER_H
#include <iostream>
#include <string>
#include <fstream>
#include "../ipc/LockFile.h"
#include "../constants.h"
class Logger {
private:
static std::ofstream file_stream;
static LockFile lock;
static int log_level;
static std::string get_error_flag(int error_type);
static void initialize_log();
public:
static const int DEBUG = 0;
static const int INFO = 1;
static const int WARNING = 2;
static const int ERROR = 3;
static void open_logger(const std::string& log_file);
static void log(const std::string& caller, int error, const std::string& error_message,
const std::string& timestamp);
static void close_logger(bool is_last);
static std::string get_date();
static void set_log_level(int level);
};
#endif //TP1_LOGGER_H
| true |
33f13bcaa321972fb9c2212da5cdb433bd9825de | C++ | HozanaSurda/ILS-SCVRP | /src/DataReader.cpp | UTF-8 | 9,191 | 3.328125 | 3 | [] | no_license | #include "DataReader.hpp"
/*
* \brief takes a line and breaks it into tokens
*
* \param line_to_tokenize line to separate into tokens.
* \param delimiter the delimiter between tokens (default is space ' ')
* \param tokens an array of strings, which will save the tokens.
*
* \return the number of tokens resulting for the tokenization
*/
int tokenize_line(
char * line_to_tokenize,
const char * delimiter,
char ** tokens) {
int n = 0;
// to break the line into tokens, we use the strtok() function (see
// http://www.cplusplus.com/reference/cstring/strtok/). strtok() returns
// the first token in the string, and takes 2 arguments:
// -# the string to be broken into tokens (in our case, 'line')
// -# the character that separates each token (in our case, the space
// character, ' ' or DELIMITER)
//
// we extract the tokens in 2 steps. let's use the line
// 'CAPACITY : 100' as an example.
// step 1: we extract the 1st token of the line, i.e. 'CAPACITY'. this
// is done by calling strtok(line, DELIMITER)
tokens[0] = strtok(line_to_tokenize, delimiter);
// step 2: we extract the next tokens, i.e. ':' and '100'. to do
// so, we keep calling strtok(0, DELIMITER) until there are no more
// tokens, at which point strtok() returns NULL.
// if the line was empty (tokens[0] - the 1st token - is NULL), we don't
// call strtok() again
if (tokens[0]) {
// this is only here to avoid taking too many tokens per line
for (n = 1; n < MAX_TOKENS_PER_LINE; n++) {
// NOTE THAT AT STEP 2 WE DON'T CALL strtok() WITH 'line', WE USE 0
// INSTEAD. THIS IS BECAUSE strtok() REMEMBERS WE ARE BREAKING 'line'.
// IF YOU WANTED strtok() TO START BREAKING A DIFFERENT STRING - SAY 'new_line'
// YOU WOULD CALL strtok(new_line, DELIMITER).
tokens[n] = strtok(0, delimiter);
// if there are no more tokens, jump off the cycle
if (!tokens[n])
break;
}
}
return n;
}
/*
* \brief opens a dataset file (a .vrp file) and extracts the CVRP information
* into a CVRP object.
*
* we're interested in extracting the following information from the .vrp file:
* -# DIMENSION : number of nodes (stations) of the CVRP problem
* -# CAPACITY : the capacity of the vehicle
* -# NODE_COORD_SECTION list : the <x,y> coordinates of the nodes
* -# DEMAND_SECTION list : the demands at each node
*
* \param dataset_filename the name of the .vrp file to open and
* extract the information from.
* \param graph the CVRP object (i.e. the problem graph) on
* which the information will be saved. this
* graph can then be used by an heuristic
* to solve the problem (e.g. CWS).
*/
int ParseDataset(
const char * dataset_filename,
Data &data) {
//number of vehicles
int qtVehicle;
// carrying capacity for each vehicle
int capacity = 0;
// number of nodes (i.e. demand points or stations)
int number_of_nodes = 0;
//position (x,y) for each node
vector<pair<int,int>> nodes;
//demands
vector<int> demands;
// we use a std::ifstream object to read the dataset (.vrp) file
ifstream fin;
// open the file
fin.open(dataset_filename);
// if open() fails for some reason, abort
if (!fin.good()) {
fprintf(
stderr,
"PARSE DATASET: Dataset file (%s) not found.\n",
dataset_filename);
return -1;
}
sscanf(dataset_filename, "%*[^k]k%d", &qtVehicle);
data.qtVehicle = qtVehicle;
printf("ParseDataset() : [INFO] number_of_vehicles = %d\n", qtVehicle);
// read the file, line-by-line and repeat till the last line
while (!fin.eof()) {
// we read each line of the file into line
char line[MAX_CHARS_PER_LINE];
fin.getline(line, MAX_CHARS_PER_LINE);
// the lines in the .vrp file are formatted in different ways.
//
// e.g. to represent a simple parameter like capacity, the file uses
// a single like like:
// "CAPACITY : 100"
//
// e.g. a list of arguments (the id and <x,y> coordinates of the
// stations) the file uses multiple lines, e.g.:
// "NODE_COORD_SECTION
// 1 82 76 <- (i.e. id of station, x coordinate, y coordinate)
// 2 96 44
// (...)""
//
// note that for both cases, the different parts of each line are separated by spaces, i.e.
// the ' ' character (represented by DELIMITER, see line 43 in DataParser.h).
// we first break the line into smaller strings, i.e. 'tokens'. in the
// end, each 'token' will be an element in an array called 'tokens'.
// we define the function tokenize_line() to do so.
char * tokens[MAX_TOKENS_PER_LINE] = {};
int number_of_tokens = tokenize_line(line, DELIMITER, tokens);
// now that we have the line divided in tokens, we look for the
// parameters that interest us and save them in variables to
// be used by our program. the variables of the .vrp file that
// are interesting to us are:
// -# DIMENSION
// -# CAPACITY
// -# NODE_COORD_SECTION list
// -# DEMAND_SECTION list
for (int i = 0; i < number_of_tokens; i++) {
// to determine the parameter referenced by the line, we look into
// the 1st token (tokens[0]), which contains the name of the parameter
if (strcmp(tokens[i], "DIMENSION") == 0) {
// we convert the 3rd token from a string to an integer (we
// skip the 2nd token, ':', which doesn't matter to us)
number_of_nodes = atoi(tokens[i + 2]);
data.dimension = number_of_nodes;
printf("ParseDataset() : [INFO] number_of_nodes = %d\n", number_of_nodes);
} else if (strcmp(tokens[i], "CAPACITY") == 0) {
// same as above, now for CAPACITY
data.capacity = capacity = atoi(tokens[i + 2]);
printf("ParseDataset() : [INFO] capacity = %d\n", capacity);
} else if (strcmp(tokens[i], "NODE_COORD_SECTION") == 0) {
// we've found the 'NODE_COORD_SECTION', below it we have
// n lines which have the <x,y> coordinates for each
// station.
// to retrieve the coordinates of station k (with k = {0, 1, 2, ...}),
// we read the lines which are below it, and tokenize each one
// the lines into 3 tokens: 'station id', 'x', 'y'
for (int k = 0; k < number_of_nodes; k++) {
// read the line
fin.getline(line, MAX_CHARS_PER_LINE);
// tokenize the line into the coordinate_tokens
char * coordinate_tokens[MAX_TOKENS_PER_LINE] = {};
tokenize_line(line, DELIMITER, coordinate_tokens);
// update the coordinates for node k with the 2nd and 3rd
// tokens (i.e. tokens[1] and tokens[2]: tokens[0] doesn't
// matter here)
nodes.push_back({ atoi(coordinate_tokens[1]), atoi(coordinate_tokens[2]) });
printf("ParseDataset() : [INFO] coords[%d] = { %d, %d }\n",
k, nodes[k].first, nodes[k].second);
}
} else if (strcmp(tokens[i], "DEMAND_SECTION") == 0) {
// same as above, but for the demands of each node
for (int k = 0; k < number_of_nodes; k++) {
fin.getline(line, MAX_CHARS_PER_LINE);
// tokenize the line into the coordinate_tokens
char * demand_tokens[MAX_TOKENS_PER_LINE] = {};
tokenize_line(line, DELIMITER, demand_tokens);
// update the demand of node k with the 2nd token
// (i.e. tokens[1]: tokens[0] doesn't matter here)
demands.push_back(atoi(demand_tokens[1]));
printf("ParseDataset() : [INFO] demand[%d] = %d\n",
k, demands[k]);
}
}
}
}
// finally, initialize the CVRP graph, given the information retrieved from
// parsing the .vrp file, in the nodes array
data.demands = demands;
data.distances.assign(number_of_nodes, vector<int>(number_of_nodes, 0));
for (int i = 0; i < number_of_nodes; i++) {
data.distances[i][i] = 0;
for (int j = i + 1; j < number_of_nodes; j++) {
data.distances[i][j] = data.distances[j][i] = (int) (hypot(nodes[i].first - nodes[j].first, nodes[i].second - nodes[j].second) + 0.5);
}
}
return 0;
}
| true |
b9b89a7414ad2be66f3b81775eb24fbf45c4c282 | C++ | HamzaBhatti/Final-Project_OOP | /temp_library.cpp | UTF-8 | 4,600 | 2.734375 | 3 | [] | no_license | #include<conio.h>
#include<string.h>
#include<iostream>
#include<fstream>
#include <fstream>
using namespace std;
class book
{
protected:
char b_name [50];
char b_publish[50];
char b_author[50];
char b_serial[50];
int n;
int choice;
char temp1[50];
int count = 0;
public:
/*struct view
{
string v_name;
string v_publish;
string v_author;
string v_serial;
};
*/
void new_book()
{
cout<<"\nPlease enter no of Books you want to add: \n";
cin>>n;
fflush(stdin);
for (int i = 0; i < n; i++)
{
cout<<"Please Enter name of Book: ";
cin.getline(b_name,50);
fflush(stdin);
cout<<"\nPlease Enter name of Author: ";
cin.getline(b_author,50);
fflush(stdin);
cout<<"\nPlease Enter name of Publisher: ";
cin.getline(b_publish,50);
fflush(stdin);
cout<<"\nPlease Enter Serial No of Book: ";
cin>>b_serial;
cin.getline(b_serial,50);
fflush(stdin);
}
cout<<"\nPlease View The data you entered \n\n";
cout<<"Book Name: "<<b_name;
cout<<"\nAuthor Name: "<<b_author;
cout<<"\nPublisher Name: "<<b_publish;
cout<<"\nSerial No: "<<b_serial;
cout<<"\nPlease press entre for Countinue ";
}
void my_gen()
{
ofstream fp_out;
fp_out.open("General Book.txt",ios::out | ios::app);
fp_out<<"Book name = "<<b_name;
fp_out<<"\t";
fp_out<<"Author name = "<<b_author;
fp_out<<"\t";
fp_out<<"Publisher name = "<<b_publish;
fp_out<<"\t";
fp_out<<"Serial No = "<<b_serial;
fp_out<<"\n";
}
void my_ref()
{
ofstream fp_out;
fp_out.open("Reference Book.txt",ios::out | ios::app);
fp_out<<"Book name = "<<b_name;
fp_out<<"\t";
fp_out<<"Author name = "<<b_author;
fp_out<<"\t";
fp_out<<"Publisher name = "<<b_publish;
fp_out<<"\t";
fp_out<<"Serial No = "<<b_serial;
fp_out<<"\n";
}
void show_book()
{
cout<<"Which Type!!!! (1)General_books (2)Refrence_Books: ";
cin>>choice;
if ( choice == 1)
{
ifstream my_in("General Book.txt",ios::in);
if(my_in.is_open())
{
while (!my_in.eof())
{
my_in >> temp1;
cout << "\t" << temp1;
}
}
}
if (choice = 2)
{
ifstream my_in1("Reference Book.txt",ios::in);
if(my_in1.is_open())
{
while (!my_in1.eof())
{
my_in1 >> temp1 ;
cout << "\t" << temp1;
}
}
}
}
void search(char n[]) //specific book search ki hai
{
//string ch;
ifstream in;
in.open("Temp.txt");
string temp;
if(in.is_open())
{
while(!in.eof())
{
//if (strcmpi(point(),n)==0)
//{
// b_show();
//}
}
}
in.close();
}
};
int login(void) //login function for user and librain
{
again:
char name[10];
char pass[10];
char pass1[10];
char camp[10];
char str;
cout<<"Login account(press 1)\n\n";
cout<<"Signup account(press 2)\n\n";
cin >> str;
if (str == '1')
{
cout<<"\nWelcome dear user signin your account\n\n";
cout<<"Enter your user login name:";
cin>>name;
cout<<"\nEnter your login password:";
cin>>pass;
ifstream in;
int c;
char ch;
in.open("login.txt");
if(in.is_open());
{
while(!in.eof())
{
cin>>camp;
c = strcmp(name,camp);
if(c==0)
{
cout<<"------User Name Match------";
c=1;
cin >> camp;
c = strcmp(pass,camp);
if(c == 0)
{
cout<<" Password match successfully\n";
system("cls");
return 1;
}
else
cout<<" but password incorrect\n";
goto again;
}
}
}
in.close();
if(c!=0)
{
cout<<"\n\nNothing match try again\n\n";
goto again;
}
}
if(str == '2')
{
signup:
cout<<"\nSign up\n";
ofstream out;
cout<<"Enter your user login name:";
cin>>name;
cout<<"Enter your login password:";
cin>>pass;
cout<<"Enter again login password:";
cin>>pass1;
int c1 = 0;
c1 = strcmp(pass,pass1);
if(c1!=0)
{
cout<<"Error in Password Matching Try Again\n\n";
goto signup;
}
out.open("login.txt",ios::out | ios::app);
out<<"Name: " << name;
out<<"Password"<< pass1;
out.close();
cout<<"\nSign Up Successfully\n\n";
getchar();
getchar();
system("cls");
goto again;
}
}
int main()
{
}
| true |
23cba5953ecf395ab08993f40c409300bebef603 | C++ | Matheus-Rangel/Lab6 | /src/MatheusRangel.cpp | UTF-8 | 1,116 | 2.921875 | 3 | [] | no_license | #include "include/MatheusRangel.h"
namespace geometria{
double triangulo::area(){ return (formas::largura * formas::altura) / 2;}
double triangulo::perimetro(){return lado1 + lado2 + lado3;}
double quadrado::area() { return formas::largura * formas::altura; }
double quadrado::perimetro() { return formas::largura * 4; }
double retangulo::area() { return formas::largura * formas::altura; }
double retangulo::perimetro() { return formas::largura * 2 + formas::altura * 2;}
double circulo::area() { return PI * raio * raio;}
double circulo::perimetro() { return 2 * PI * raio;}
double piramede::area() { return lado.area()*4 + base.area();}
double piramede::volume() { return (base.area()*altura)/3;}
double cubo::area() { return 6 * lado * lado;}
double cubo::volume(){ return lado * lado * lado;}
double esfera::area(){ return 4 * PI * raio * raio;}
double esfera::volume(){ return (4.0/3.0) * PI * raio * raio * raio;}
double paralelepipedo::area(){ return (2 * lado1 * lado2) + (2 * lado1 * lado3) + (2 * lado2 * lado3);}
double paralelepipedo::volume(){ return lado1 * lado2 * lado3;}
} | true |
fc926f2427396d86e6537e7143903194306ce2ea | C++ | jomorales1/Competitive-Programming | /Contests/Codeforces Round 669/B.cpp | UTF-8 | 879 | 2.5625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
void solve() {
int n = 0; cin >> n;
vector<int> sequence(n);
for (int i = 0; i < n; i++) {
cin >> sequence[i];
}
sort(sequence.rbegin(), sequence.rend());
int m = INT_MIN;
int gcd = sequence[0];
for (int i = 1; i < n - 1; i++) {
int option = __gcd(gcd, sequence[i]);
int index = i;
for (int j = i + 1; j < n; j++) {
int option2 = __gcd(gcd, sequence[j]);
if (option2 > option) {
index = j;
option = option2;
}
}
gcd = option;
swap(sequence[i], sequence[index]);
}
for (int i = 0; i < n; i++) {
cout << sequence[i] << ' ';
}
cout << '\n';
}
int main() {
int t = 0; cin >> t;
for (int i = 0; i < t; i++) {
solve();
}
return 0;
} | true |
e77bcdaef49507f33d37d20df99f62b7e12c68ff | C++ | bjpark0805/Problem_solvings | /examples/baekjoon_14891.cpp | UTF-8 | 929 | 2.75 | 3 | [] | no_license | #include <stdio.h>
#include <vector>
using namespace std;
int main(){
vector<int> top(4, 0);
int K;
vector<vector<int> > gear(4, vector<int>(8, 0));
for(int i = 0; i < 4; ++i){
for(int j = 0; j < 8; ++j){
scanf("%1d", &gear[i][j]);
}
}
scanf("%d", &K);
for(int i = 0; i < K; ++i){
int num, d;
scanf("%d%d", &num, &d);
num -= 1;
vector<int> tmp(top);
tmp[num] = (tmp[num] - d + 8)%8;
int tmp_d = d;
for(int j = num + 1; j < 4; ++j){
tmp_d = -tmp_d;
if(gear[j - 1][(top[j - 1]+2)%8] == gear[j][(top[j]+6)%8]) break;
else tmp[j] = (tmp[j] - tmp_d + 8)%8;
}
tmp_d = d;
for(int j = num - 1; j >= 0; --j){
tmp_d = -tmp_d;
if(gear[j + 1][(top[j + 1]+6)%8] == gear[j][(top[j]+2)%8]) break;
else tmp[j] = (tmp[j] - tmp_d + 8)%8;
}
top = tmp;
}
int sum = gear[0][top[0]] + gear[1][top[1]] * 2 + gear[2][top[2]] * 4 + gear[3][top[3]] * 8;
printf("%d\n", sum);
return 0;
} | true |
4899da6fdf09248ae2864c0a179016c3afb90d2f | C++ | xuelei7/AOJ | /Volume20(JAG)/aoj2005_WaterPipeConstruction.cpp | UTF-8 | 4,129 | 2.734375 | 3 | [] | no_license | // Water Pipe Construction
// 21XX 年,ついに人類は火星への移住計画を開始させた.火星への移住第一陣に選抜されたあなたは,火星行政中央局(the Administrative Center of Mars)に配属され,火星で起こる様々な問題に対処している.行政中央局の目下の最大の問題は自立した需要供給サイクルの確保である.月からの援助物資が届くまでには数ヶ月単位の時間がかかるため,基本的には火星内の需要は火星内で解決する必要がある.それに加えて,循環システムを確立するまでは資源を極力節約することが求められる.
// 行政中央局は極地にある氷の採掘を開始した.太陽光でこれを溶かし,水として個々の基地に供給することが最終目標である.最初の段階として,水源のある基地から2つの主要基地までの導水管を敷設することにした.また,現時点ではいくつかの基地とそれらを結ぶ道路以外には開拓されておらず,未開拓のところに導水管を敷設するには多大なるコストと燃料を要するため,道路に沿って導水管を敷設することにした.さらに,技術上の制約のため,彼らの導水管は常に一方向だけに水が流れる.
// あなたの仕事は,これらの条件のもとで,導水管の敷設にかかるコストを最小にするプログラムを作成することである.
// Input
// 入力は複数のデータセットから構成される.
// データセットの最初の行は 5 つの整数からなる.これらは順に,火星に存在する基地の数 n (3 <= n <= 100),基地を結ぶ道路の数 m (2 <= m <= 1000),水源となる基地の番号 s, 導水管の目的地となる 2 つの主要基地の番号 g1,g2 を表す.基地の番号は 1 から n までの整数で表される.s,g1,g2 は互いに異なる.
// 続く m 行には,導水管を敷設可能な道路の情報が与えられる.各行はある 2 つの基地間における道路の情報を表しており,3 つの整数 b1,b2,c (1 <= c <= 1000) からなる.ここに b1,b2 は道路の始端および終端の基地の番号を表し,これらは互いに異なる.c は基地 b1 から基地 b2 に向かう導水管を敷設するためにかかるコストである.
// 全てのデータセットについて,水源から目的地まで水を供給する経路は常に存在すると仮定してよい.また,ある 2 つの基地間には高々 1 つの道路しか存在しないことから,コストの情報はそれぞれの方向について高々 1 回しか与えられない.
// 入力の終了はスペース文字で区切られた 5 つのゼロが含まれる行で表される.
// Output
// それぞれのデータセットに対して,導水管を敷設するコストの最小値を 1 行に出力せよ.
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int n,m,s,g1,g2;
ll dp[110][110];
void WarshallFloyd() {
for (int k = 0; k < n; k++) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
dp[i][j] = min(dp[i][j], dp[i][k] + dp[k][j]);
}
}
}
}
int main() {
while (cin >> n >> m >> s >> g1 >> g2) {
if (n == 0) break;
s--;
g1--;
g2--;
int inf = 1e9;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i == j) dp[i][j] = 0;
else dp[i][j] = inf;
}
}
for (int i = 0; i < m; i++) {
ll f,t,c;
cin >> f >> t >> c;
f--; t--;
dp[f][t] = c;
}
WarshallFloyd();
ll mi = 1e18;
for (int k = 0; k < n; k++) {
mi = min(mi, dp[s][k] + dp[k][g1] + dp[k][g2]);
}
cout << mi << endl;
}
return 0;
} | true |
4ce75f8e6ed944cbff8358eaa2380f6c473d1869 | C++ | James-Bartulis/Tetris | /Tetris.cpp | UTF-8 | 6,809 | 2.5625 | 3 | [] | no_license | void Tetris::Display()
{
system("CLS");
cout << string(width + 2, char(178)) << "Score: " << Score << endl;
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
if(j == 0)
cout << char(178);
if(pieceOnCoord(j, i, currentPiece))
cout << char(177);
else if(setPiecesOnCoord(j, i))
cout << char(177);
else if(pieceOnCoord(j, i, phantomPiece))
cout << char(176);
else
cout << char(255);
if(j == width - 1)
cout << char(178);
}
switch(i)
{
case 0:
if(typeOfPieces > 7)
cout << "Extra Pieces Enabled";
break;
case 1:
cout << "Next Piece:";
break;
case 7:
cout << "Saved Piece:";
break;
case 13:
cout << " r: rotate";
break;
case 14:
cout << " t: trade saved";
break;
case 15:
cout << " T: toggle extra pieces";
break;
case 16:
cout << " q: quick drop";
break;
case 17:
cout << " w: pause";
break;
default:
break;
}
cout << " ";
nextPiece->Print(i - 2);
savedPiece->Print(i - 8);
cout << endl;
}
cout << string(width + 2, char(178)) << endl;
}
void Tetris::Input()
{
if(_kbhit())
{
switch(getch())
{
case 'w':
system("PAUSE");
break;
case 'W':
clearSetPieces();
setPhantom();
break;
case 80: // down arrow
case 's':
if(canMoveDown(currentPiece))
currentPiece->moveDown();
break;
case 75: // left arrow
case 'a':
if(canMoveLeft(currentPiece))
{
currentPiece->moveLeft();
setPhantom();
}
break;
case 77: // right arrow
case 'd':
if(canMoveRight(currentPiece))
{
currentPiece->moveRight();
setPhantom();
}
break;
case 72: // up arrow
case 'r':
if(canRotate())
setPhantom();
break;
case ' ': // space
case 'q':
while(canMoveDown(currentPiece))
currentPiece->moveDown();
frame += 5 - frame % 5;
break;
case 't':
savePiece();
setPhantom();
frame += 5 - frame % 5;
break;
case 'T':
ToggleExtraPieces();
break;
case 'c':
Running = false;
break;
case 'F':
cheat();
clearFullRows();
setPhantom();
break;
default:
break;
}
}
}
void Tetris::Logic()
{
if(canMoveDown(currentPiece))
currentPiece->moveDown();
else
{
SetPiece();
clearFullRows();
setNextPiece();
}
isGameOver();
}
bool Tetris::canMoveDown(Piece *p)
{
if(p->ypos + p->height < height)
{
for (int i = p->ypos; i < p->ypos + p->height; i++)
for (int j = p->xpos; j < p->xpos + p->width; j++)
if(pieceOnCoord(j, i, p) && setPiecesOnCoord(j, i + 1))
return false;
return true;
}
return false;
}
bool Tetris::canMoveLeft(Piece *p)
{
if(p->xpos > 0)
{
for (int i = p->ypos; i < p->ypos + p->height; i++)
for (int j = p->xpos; j < p->xpos + p->width; j++)
if(pieceOnCoord(j, i, p) && setPiecesOnCoord(j - 1, i))
return false;
return true;
}
return false;
}
bool Tetris::canMoveRight(Piece *p)
{
if(p->xpos + p->width < width)
{
for (int i = p->ypos; i < p->ypos + p->height; i++)
for (int j = p->xpos; j < p->xpos + p->width; j++)
if(pieceOnCoord(j, i, p) && setPiecesOnCoord(j + 1, i))
return false;
return true;
}
return false;
}
bool Tetris::pieceIsOutOfBounds(Piece *p)
{
if(p->ypos >= 0 && p->ypos + p->height <= height)
if(p->xpos >= 0 && p->xpos + p->width <= width)
return false;
return true;
}
bool Tetris::pieceOnCoord(int x, int y, Piece* p)
{
if (y - p->ypos >= 0 && y - p->ypos < p->height)
if (x - p->xpos >= 0 && x - p->xpos < p->width)
if(p->pieceMap[y - p->ypos][x - p->xpos])
return true;
return false;
}
bool Tetris::setPiecesOnCoord(int x, int y)
{
if(setPieces[y][x])
return true;
return false;
}
void Tetris::SetPiece()
{
for (int i = currentPiece->ypos; i < currentPiece->ypos + currentPiece->height; i++)
for (int j = currentPiece->xpos; j < currentPiece->xpos + currentPiece->width; j++)
if(pieceOnCoord(j, i, currentPiece))
setPieces[i][j] = true;
}
void Tetris::ToggleExtraPieces(){
if(typeOfPieces == 7) typeOfPieces = 9;
else typeOfPieces = 7;
}
void Tetris::setNextPiece()
{
switch(rand()% typeOfPieces + 1)
{
case 1:
PFactory = new JFactory();
break;
case 2:
PFactory = new LFactory();
break;
case 3:
PFactory = new IFactory();
break;
case 4:
PFactory = new OFactory();
break;
case 5:
PFactory = new SFactory();
break;
case 6:
PFactory = new MSFactory();
break;
case 7:
PFactory = new TFactory();
break;
case 8:
PFactory = new SMILEFactory();
break;
case 9:
PFactory = new XFactory();
break;
default:
break;
}
if(currentPiece)
delete currentPiece;
currentPiece = nextPiece;
nextPiece = PFactory->generate();
setPhantom();
}
void Tetris::clearFullRows()
{
bool full = true;
for (int i = 0; i < height; i++, full = true)
{
for (int j = 0; j < width; j++)
if(setPieces[i][j] == false)
full = false;
if(full)
{
for (int k = i; k > 0; k--)
for (int j = 0; j < width; j++)
setPieces[k][j] = setPieces[k - 1][j];
Score+=10;
}
}
}
bool Tetris::canRotate()
{
if(currentPiece->ypos + currentPiece->width > height) return false;
Piece* oldPiece;
oldPiece = new Piece(currentPiece);
currentPiece->Rotate();
for (int i = currentPiece->ypos; i < currentPiece->ypos + currentPiece->height; i++)
for (int j = currentPiece->xpos; j < currentPiece->xpos + currentPiece->width; j++)
{
while(canMoveLeft(currentPiece) && (pieceOnCoord(j, i, currentPiece) && setPieces[i][j] || pieceIsOutOfBounds(currentPiece)))
currentPiece->moveLeft();
if(pieceOnCoord(j, i, currentPiece) && setPieces[i][j] || pieceIsOutOfBounds(currentPiece))
{
delete currentPiece;
currentPiece = oldPiece;
return false;
}
}
delete oldPiece;
return true;
}
void Tetris::setPhantom()
{
phantomPiece = new Piece(currentPiece);
while(canMoveDown(phantomPiece))
phantomPiece->moveDown();
}
void Tetris::savePiece()
{
if(savedPiece)
{
Piece *temp;
temp = currentPiece;
currentPiece = savedPiece;
savedPiece = temp;
currentPiece->ypos = 0;
currentPiece->xpos = 5;
}
else
{
savedPiece = currentPiece;
currentPiece = NULL;
setNextPiece();
}
}
void Tetris::clearSetPieces()
{
for (int i = 0; i < height; i++)
for (int j = 0; j < width; j++)
setPieces[i][j] = false;
}
bool Tetris::isGameOver()
{
for (int j = 0; j < width; j++)
if(setPieces[0][j])
Running = false;
}
void Tetris::cheat()
{
int count = 0;
for (int j = 0; j < width; j++, count = 0)
{
for (int i = 0; i < height; i++)
if(setPieces[i][j])
count++;
for (int i = 0; i < height; i++)
{
if(height - count <= i)
setPieces[i][j] = true;
else
setPieces[i][j] = false;
}
}
} | true |
7600088d063552093c214aa78c19aa8a0ac79be7 | C++ | antjowie/Runaway | /Runaway/source/Core.cpp | UTF-8 | 14,522 | 2.59375 | 3 | [] | no_license | #include "Core.h"
#include "DataManager.h"
#include "Config.h"
void Core::draw(sf::RenderTarget & target, sf::RenderStates states) const
{
target.draw(m_whiteOverlay, states);
target.draw(m_body, states);
target.draw(m_eyes, states);
target.draw(m_leftLauncher, states);
target.draw(m_middleLauncher, states);
target.draw(m_rightLauncher, states);
}
void Core::updateCollision(std::list<Projectile>& projectiles)
{
m_body.updateCollision(projectiles);
m_eyes.updateCollision(projectiles);
}
void Core::update(const float elapsedTime)
{
if (m_state <= 0)
m_phase = Core::Destroyed;
// Allows core to move smoothly
sf::Vector2f movement{ m_targetPos - m_body.getPos() };
float magnitude{ movement.x * movement.x + movement.y * movement.y };
if (elapsedTime < 1 && magnitude != 0) // Happens if fps is lower than 1
magnitude = magnitude * elapsedTime / magnitude;
else
magnitude = 1;
movement.x *= magnitude;
movement.y *= magnitude;
m_body.setPos(m_body.getPos() + movement);
// Fixes launcher pos
m_leftLauncher.setPos(m_eyes.getPos() + sf::Vector2f(-96, 146));
m_middleLauncher.setPos(m_eyes.getPos() + sf::Vector2f(0, 208));
m_rightLauncher.setPos(m_eyes.getPos() + sf::Vector2f(96, 146));
switch (m_phase)
{
case Core::Sleep:
{
m_targetPos = m_body.getPos();
if ((m_body.isHit() || m_eyes.isHit()) && m_timeline == -1)
{
m_inDarkZone = true;
m_bootSound->setVolume(Config::getInstance().getConfig("effects").integer);
m_bootSound->play();
m_timeline = 0;
}
else if (m_timeline > 1)
{
m_phase = Core::Phase::Roam;
m_timeline = -1;
m_eyes.setColor(sf::Color(255, 255, 255, 255));
m_animHandler.update(elapsedTime);
m_body.setTextureRect(m_animHandler.getFrame());
}
else if (m_timeline != -1)
{
m_timeline += elapsedTime / 5.f;
m_animHandler.update(elapsedTime);
m_body.setTextureRect(m_animHandler.getFrame());
m_eyes.setColor(sf::Color(255,255,255,m_timeline * 255.f));
}
}
break;
case Core::Roam:
{
m_targetPos = m_playerPos + sf::Vector2f(0, -550);
// Why can't we have variables in case loops :/
m_eyes.setPos(m_body.getPos() + sf::Vector2f(
// This way the value can also be negative
(m_playerPos - m_body.getPos()).x * std::abs((m_playerPos - m_body.getPos()).x) / (std::powf((m_playerPos - m_body.getPos()).x, 2) + std::powf((m_playerPos - m_body.getPos()).y, 2)) * 300,// Arbitrary
(m_playerPos - m_body.getPos()).y * std::abs((m_playerPos - m_body.getPos()).y) / (std::powf((m_playerPos - m_body.getPos()).x, 2) + std::powf((m_playerPos - m_body.getPos()).y, 2)) * 15 // offset value
));
if (m_timeline == -1)
{
m_inDarkZone = false;
DefaultLauncher();
m_switchToRoamSound->setVolume(Config::getInstance().getConfig("effects").integer);
m_switchToRoamSound->play();
m_timeline = 0;
}
if (m_timeline < 1.f)
m_timeline += elapsedTime / 2.5f;
else
{
const float timeTillTarget{ std::sqrtf(std::powf(m_playerPos.x - getPos().x,2) + std::powf(m_playerPos.y - getPos().y,2)) / m_middleLauncher.getProjectileSpeed()};
const sf::Vector2f nextPos{ (m_playerPos - m_oldPlayerPos) * (timeTillTarget / elapsedTime) };
const sf::Vector2f predictedPos(m_playerPos + sf::Vector2f(nextPos.x, 0));
switch (m_state)
{
case 3:
m_middleLauncher.shoot(m_playerPos);
break;
case 2:
m_leftLauncher.shoot(predictedPos);
m_rightLauncher.shoot(predictedPos);
break;
case 1:
m_leftLauncher.shoot(predictedPos);
m_middleLauncher.shoot(m_playerPos);
m_rightLauncher.shoot(predictedPos);
break;
}
}
if (m_eyes.isHit())
{
m_hp -= 1;
m_eyes.flash(0.3f);
}
if (m_body.isHit())
{
m_hp -= 2;
m_body.flash(0.3f);
}
if (m_hp <= 0)
{
m_phase = Core::SwitchState;
m_hp = 10;
m_timeline = -1;
}
}
break;
case Core::Charge:
{
m_targetPos = sf::Vector2f(1376, 1316);
m_eyes.setPos(m_body.getPos());
float timeTillTarget{ std::sqrtf(std::powf(m_playerPos.x - getPos().x,2) + std::powf(m_playerPos.y - getPos().y,2)) / m_middleLauncher.getProjectileSpeed() };
sf::Vector2f nextPos{ (m_playerPos - m_oldPlayerPos) * (timeTillTarget / elapsedTime) };
sf::Vector2f predictedPos(m_playerPos + sf::Vector2f(nextPos.x,0));
if (m_timeline == -1)
{
m_chargeSound->setVolume(Config::getInstance().getConfig("effects").integer);
m_chargeSound->play();
ChargeLauncher();
m_timeline = 0;
}
if (m_timeline < 1)
{
m_timeline += elapsedTime / 3.f;
m_leftLauncher.setProjectileSpeed(0.f);
m_middleLauncher.setProjectileSpeed(0.f);
m_rightLauncher.setProjectileSpeed(0.f);
}
else if (m_timeline < 2)
{
ChargeLauncher();
m_timeline += elapsedTime / 10.f;
}
switch (m_state)
{
case 3:
m_middleLauncher.shoot(m_playerPos);
break;
case 2:
m_leftLauncher.shoot(m_playerPos);
m_rightLauncher.shoot(m_playerPos);
break;
case 1:
m_leftLauncher.shoot(m_playerPos);
m_middleLauncher.shoot(m_playerPos);
m_rightLauncher.shoot(m_playerPos);
break;
}
if (m_timeline > 2)
{
m_state -= 1;
m_timeline = -1;
m_phase = Core::Roam;
}
}
break;
case Core::Destroyed:
{
m_targetPos = sf::Vector2f(1376, 1316);
m_eyes.setPos(m_body.getPos());
if (m_timeline == -1)
{
m_inDarkZone = true;
m_chargeSound->setPlayingOffset(sf::Time::Zero);
m_chargeSound->setVolume(Config::getInstance().getConfig("effects").integer);
m_chargeSound->play();
m_hp = 3;
m_timeline = 0;
ChargeLauncher();
}
else if (!m_isDead && m_timeline > 1)
{
m_timeline = 1;
if (m_eyes.isHit() || m_body.isHit())
{
m_eyes.flash(0.3f);
m_body.flash(0.3f);
m_hp -= 1;
}
if (m_hp <= 0)
{
m_inDarkZone = false;
m_chargeSound->stop();
m_isDead = true;
m_timeline = 0;
}
m_leftLauncher.shoot(m_playerPos);
m_middleLauncher.shoot(m_playerPos);
m_rightLauncher.shoot(m_playerPos);
}
else if (m_isDead)
{
if (m_timeline <= 1)
{
m_timeline += elapsedTime / 5.f;
m_eyes.setColor(sf::Color(255 - m_timeline * 255, 255 - m_timeline * 255, 255 - m_timeline * 255, 255));
m_body.setColor(sf::Color(255 - m_timeline * 255, 255 - m_timeline * 255, 255 - m_timeline * 255, 255));
m_whiteOverlay.setFillColor(sf::Color(255, 255, 255, m_timeline * 255));
}
else if (m_timeline <= 2)
{
m_timeline += elapsedTime / 3.f;
if (!m_destroy)
{
m_explosionSound->setVolume(Config::getInstance().getConfig("effects").integer);
m_explosionSound->play();
m_eyes.setColor(sf::Color(0, 0, 0, 0));
m_body.setColor(sf::Color(0, 0, 0, 0));
}
m_whiteOverlay.setFillColor(sf::Color(255, 255, 255, 255));
m_destroy = true;
}
else if (m_timeline <= 3)
{
m_timeline += elapsedTime / 5.f;
m_whiteOverlay.setFillColor(sf::Color(255, 255, 255, 255 - (m_timeline - 2.f) * 255));
}
else
{
m_whiteOverlay.setFillColor(sf::Color(255, 255, 255, 0));
m_completed = true;
}
}
else
m_timeline += elapsedTime / 3.f;
}
break;
case Core::SwitchState:
{
m_targetPos = sf::Vector2f(1376, 1316);
m_eyes.setPos(m_body.getPos());
if (m_timeline == -1)
{
m_inDarkZone = true;
m_timeline = 0;
}
m_timeline += elapsedTime / 1.f;
if (m_timeline > 1)
{
m_timeline = -1;
m_phase = Core::Charge;
}
}
break;
}
// Update colors
m_eyes.update(elapsedTime);
m_body.update(elapsedTime);
// Update projectiles
m_leftLauncher.update(elapsedTime);
m_middleLauncher.update(elapsedTime);
m_rightLauncher.update(elapsedTime);
// Update sound pos
m_bootSound ->setPosition(m_body.getPos().x, 0, m_body.getPos().y);
m_switchToRoamSound ->setPosition(m_body.getPos().x, 0, m_body.getPos().y);
m_chargeSound ->setPosition(m_body.getPos().x, 0, m_body.getPos().y);
m_explosionSound ->setPosition(m_body.getPos().x, 0, m_body.getPos().y);
}
void Core::setPos(const sf::Vector2f & pos)
{
m_targetPos = pos;
}
void Core::setPlayerPos(const sf::Vector2f & pos)
{
m_oldPlayerPos = m_playerPos;
m_playerPos = pos;
}
const sf::Vector2f & Core::getPos() const
{
return m_body.getPos();
}
bool Core::hit(const sf::FloatRect & hitbox)
{
bool isHit{ false };
const sf::Vector2f middle{ hitbox.left + hitbox.width / 2, hitbox.top + hitbox.height / 2 };
for (auto &proj : m_leftLauncher.getProjectiles())
{
if (proj.m_sprite.getGlobalBounds().contains(middle))
{
isHit = true;
proj.m_life = 0;
}
}
for (auto &proj : m_middleLauncher.getProjectiles())
{
if (proj.m_sprite.getGlobalBounds().contains(middle))
{
isHit = true;
proj.m_life = 0;
}
}
for (auto &proj : m_rightLauncher.getProjectiles())
{
if (proj.m_sprite.getGlobalBounds().contains(middle))
{
isHit = true;
proj.m_life = 0;
}
}
return isHit;
}
bool Core::inDarkZone() const
{
return m_inDarkZone;
}
Core::Core(SoundManager &soundManager):
m_animHandler(576,480)
{
// Center eye
m_body.pushHitbox(Part::Hitbox(-96, 16, 192, 64));
m_body.pushHitbox(Part::Hitbox(-32, -16, 64, 128));
// Surrounding eyes
m_body.pushHitbox(Part::Hitbox(-224, 16, 64, 64));
m_body.pushHitbox(Part::Hitbox(-128, -80, 64, 64));
m_body.pushHitbox(Part::Hitbox(-32,144, 64, 64));
m_body.pushHitbox(Part::Hitbox(-64, -80, 64, 64));
m_body.pushHitbox(Part::Hitbox(160, 16, 64, 64));
// Center eye
m_eyes.pushHitbox(Part::Hitbox(-64, 16, 128, 64));
// Surrounding eyes
m_eyes.pushHitbox(Part::Hitbox(-128, 112, 64, 64));
m_eyes.pushHitbox(Part::Hitbox(-32, 176, 64, 64));
m_eyes.pushHitbox(Part::Hitbox(64, 112, 64, 64));
m_body.setTexture(DataManager::getInstance().getTexture("core"));
m_eyes.setTexture(DataManager::getInstance().getTexture("coreEye"));
m_eyes.setColor(sf::Color(255, 255, 255, 0));
m_body.setColor(sf::Color(255, 255, 255, 255));
// Same order as States
m_animHandler.addAnimation(Animation(0, 8, 5.f/9.f, false, false));
m_animHandler.addAnimation(Animation(0, 1, 1.f, true, false));
m_animHandler.addAnimation(Animation(0, 16, 0.083f, false, false));
m_animHandler.changeAnimation(m_phase);
m_body.setTextureRect(m_animHandler.getFrame());
m_body.setOrigin(288, 240);
m_eyes.setOrigin(287, 144);
m_body.setPos(1376, 1616);
m_eyes.setPos(1376, 1616);
m_targetPos = m_body.getPos();
m_whiteOverlay.setFillColor(sf::Color(255,255,255,0));
m_whiteOverlay.setPosition(0, 0);
m_whiteOverlay.setSize(sf::Vector2f(10000, 10000));
m_bootSound = new SoundObject(SoundType::Effect, soundManager);
m_chargeSound = new SoundObject(SoundType::Effect, soundManager);
m_explosionSound = new SoundObject(SoundType::Effect, soundManager);
m_switchToRoamSound = new SoundObject(SoundType::Effect, soundManager);
m_bootSound->setBuffer(DataManager::getInstance().getSound("coreBoot"));
m_chargeSound->setBuffer(DataManager::getInstance().getSound("coreCharge"));
m_explosionSound->setBuffer(DataManager::getInstance().getSound("coreDestroy"));
m_switchToRoamSound->setBuffer(DataManager::getInstance().getSound("coreDash"));
m_bootSound ->setAttenuation(0.5f);
m_chargeSound ->setAttenuation(0.5f);
m_explosionSound ->setAttenuation(0.5f);
m_switchToRoamSound ->setAttenuation(0.5f);
m_bootSound ->setMinDistance(32.f * 6.f);
m_chargeSound ->setMinDistance(32.f * 6.f);
m_explosionSound ->setMinDistance(32.f * 6.f);
m_switchToRoamSound ->setMinDistance(32.f * 6.f);
m_bootSound ->setVolume(0);
m_chargeSound ->setVolume(0);
m_explosionSound ->setVolume(0);
m_switchToRoamSound ->setVolume(0);
}
Core::~Core()
{
m_bootSound->m_shouldPop = true;
m_chargeSound->m_shouldPop = true;
m_explosionSound->m_shouldPop = true;
m_switchToRoamSound->m_shouldPop = true;
}
void Core::Part::draw(sf::RenderTarget & target, sf::RenderStates states) const
{
target.draw(m_sprite, states);
}
void Core::DefaultLauncher()
{
m_leftLauncher.setFireRate(1.f);
m_middleLauncher.setFireRate(1.f);
m_rightLauncher.setFireRate(1.f);
m_middleLauncher.setProjectileLife(13);
m_leftLauncher.setProjectileLife(13);
m_rightLauncher.setProjectileLife(13);
m_leftLauncher.setProjectileSpeed(32 * 10);
m_middleLauncher.setProjectileSpeed(32 * 10);
m_rightLauncher.setProjectileSpeed(32 * 10);
m_leftLauncher.setProjectileSize(sf::Vector2f(64 * 2, 64 * 2));
m_middleLauncher.setProjectileSize(sf::Vector2f(64 * 2, 64 * 2));
m_rightLauncher.setProjectileSize(sf::Vector2f(64 * 2, 64 * 2));
}
void Core::ChargeLauncher()
{
DefaultLauncher();
m_leftLauncher.setFireRate(0.f);
m_middleLauncher.setFireRate(0.f);
m_rightLauncher.setFireRate(0.f);
}
void Core::Part::setTexture(const sf::Texture &texture)
{
m_sprite.setTexture(texture);
}
void Core::Part::setTextureRect(const sf::IntRect & rect)
{
m_sprite.setTextureRect(rect);
}
void Core::Part::setOrigin(const float x, const float y)
{
m_sprite.setOrigin(x,y);
}
void Core::Part::setPos(const sf::Vector2f & pos)
{
m_sprite.setPosition(pos);
for (auto &hitbox : m_hitbox)
{
hitbox.hitbox.left = pos.x + hitbox.offset.x;
hitbox.hitbox.top = pos.y + hitbox.offset.y;
}
}
void Core::Part::setPos(const float x, const float y)
{
setPos(sf::Vector2f(x, y));
}
void Core::Part::setColor(const sf::Color & color)
{
m_sprite.setColor(color);
}
const sf::Color &Core::Part::getColor() const
{
return m_sprite.getColor();
}
const sf::Vector2f & Core::Part::getPos() const
{
return m_sprite.getPosition();
}
void Core::Part::pushHitbox(const Hitbox &&hitbox)
{
m_hitbox.push_back(std::move(hitbox));
}
void Core::Part::update(const float elapsedTime)
{
m_timeline -= elapsedTime;
sf::Color newColor(255,255,255,m_sprite.getColor().a);
if (m_timeline < 0)
m_timeline = 0;
else
{
newColor.b = 0;
newColor.g = 0;
}
m_sprite.setColor(newColor);
}
void Core::Part::updateCollision(std::list<Projectile>& projectiles)
{
for (auto &proj : projectiles)
{
for (const auto &hitbox : m_hitbox)
if (hitbox.hitbox.intersects(static_cast<sf::IntRect>(proj.m_sprite.getGlobalBounds())))
{
m_hit = true;
proj.m_life = 0;
}
}
projectiles.remove_if([this](Projectile &projectile) -> bool
{
return projectile.m_life == 0;
});
}
bool Core::Part::isHit()
{
bool temp{ m_hit };
m_hit = false;
return temp;
}
void Core::Part::flash(const float elapsedTime)
{
m_timeline = elapsedTime;
}
Core::Part::Hitbox::Hitbox(const float offsetX, const float offsetY, const float width, const float height):
offset(sf::Vector2f(offsetX,offsetY)),
hitbox(sf::IntRect(0,0,width,height))
{
}
| true |
05234bb4c484a203399e3ab888484b61bf5e9258 | C++ | HungMingWu/futures_cpp | /include/futures/Stream.h | UTF-8 | 5,154 | 2.703125 | 3 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | #pragma once
#include <iterator>
#include <futures/Core.h>
#include <futures/Exception.h>
#include <futures/Async.h>
#include <futures/Future.h>
namespace futures {
template <typename T>
class IStream {
public:
virtual Poll<Optional<T>> poll() = 0;
virtual ~IStream() = default;
};
template <typename T>
struct isStream {
using Inner = typename folly::Unit::Lift<typename T::Item>::type;
static const bool value = std::is_base_of<IStream<Inner>, T>::value;
};
template <typename T>
class BoxedStream;
template <typename Stream, typename F>
class ForEachFuture;
template <typename T, typename F>
class ForEach2Wrapper;
template <typename T, typename Stream>
class CollectStreamFuture;
template <typename T, typename Stream, typename F>
class FilterStream;
template <typename T, typename Stream, typename F>
class MapStream;
template <typename T, typename Stream, typename F>
class AndThenStream;
template <typename T, typename Stream>
class TakeStream;
template <typename Stream>
class DropStreamFuture;
template <typename Stream>
class StreamIterator;
template <typename Derived, typename T>
class StreamBase : public IStream<T> {
public:
using Item = T;
using iterator = StreamIterator<Derived>;
Poll<Optional<T>> poll() override {
assert(0 && "cannot call base poll");
}
template <typename F>
ForEachFuture<Derived, F> forEach(F&& f);
template <typename F>
ForEachFuture<Derived, ForEach2Wrapper<T, F>> forEach2(F&& f);
StreamBase() = default;
~StreamBase() = default;
StreamBase(StreamBase &&) = default;
StreamBase& operator=(StreamBase &&) = default;
StreamBase(const StreamBase &) = delete;
StreamBase& operator=(const StreamBase &) = delete;
BoxedStream<T> boxed();
/* implicit */ operator BoxedStream<T>() &&;
CollectStreamFuture<T, Derived> collect();
template <typename F>
FilterStream<T, Derived, F> filter(F&& f);
template <typename F, typename R = typename detail::resultOf<F, T>>
MapStream<R, Derived, F> map(F&& f);
template <typename F,
typename FutR = typename detail::resultOf<F, T>,
typename R = typename isFuture<FutR>::Inner>
AndThenStream<R, Derived, F> andThen(F&& f);
TakeStream<T, Derived> take(size_t n);
DropStreamFuture<Derived> drop();
iterator begin();
iterator end();
private:
Derived move_self() {
return std::move(*static_cast<Derived*>(this));
}
};
template <typename T>
class EmptyStream : public StreamBase<EmptyStream<T>, T> {
public:
using Item = T;
Poll<Optional<T>> poll() override {
return makePollReady(Optional<T>());
}
};
template <typename T>
class BoxedStream : public StreamBase<BoxedStream<T>, T> {
public:
using Item = T;
explicit BoxedStream(std::unique_ptr<IStream<T>> f)
: impl_(std::move(f)) {}
void clear() { impl_.reset(); }
Poll<Optional<T>> poll() override {
return impl_->poll();
}
private:
std::unique_ptr<IStream<T>> impl_;
};
template <typename Iter,
typename T = typename std::iterator_traits<Iter>::value_type>
class IterStream : public StreamBase<IterStream<Iter, T>, T> {
public:
using Item = T;
IterStream(Iter begin, Iter end)
: it_(begin), end_(end) {}
Poll<Optional<T>> poll() override {
if (it_ == end_)
return makePollReady(Optional<T>());
auto r = folly::make_optional(*it_);
++it_;
return makePollReady(std::move(r));
}
private:
Iter it_;
Iter end_;
};
template <typename Stream>
class StreamSpawn {
public:
using T = typename isStream<Stream>::Inner;
typedef Poll<Optional<T>> poll_type;
poll_type poll_stream(std::shared_ptr<Unpark> unpark) {
Task task(id_, unpark);
CurrentTask::WithGuard g(CurrentTask::this_thread(), &task);
return toplevel_.poll();
}
poll_type wait_stream() {
auto unpark = std::make_shared<ThreadUnpark>();
while (true) {
auto r = poll_stream(unpark);
if (r.hasException())
return r;
auto async = folly::moveFromTry(r);
if (async.isReady()) {
return poll_type(std::move(async));
} else {
unpark->park();
}
}
}
explicit StreamSpawn(Stream stream)
: id_(detail::newTaskId()), toplevel_(std::move(stream)) {
}
StreamSpawn(StreamSpawn&&) = default;
StreamSpawn& operator=(StreamSpawn&&) = default;
StreamSpawn(const StreamSpawn&) = delete;
StreamSpawn& operator=(const StreamSpawn&) = delete;
unsigned long id() const { return id_; }
private:
// toplevel future or stream
unsigned long id_;
Stream toplevel_;
};
template <typename T>
Poll<Optional<T>> makeStreamReady() {
return Poll<Optional<T>>(Optional<T>());
}
template <typename T, typename T0 = typename std::decay<T>::type>
Poll<Optional<T0>> makeStreamReady(T&& v) {
return Poll<Optional<T0>>(Optional<T0>(std::forward<T>(v)));
}
}
#include <futures/Stream-inl.h>
#include <futures/detail/StreamIterator.h>
| true |
7af8ae645313c343601784c5850844ebcbf76a28 | C++ | yaominzh/CodeLrn2019 | /boboleetcode/Play-Leetcode-master/0509-Fibonacci-Number/cpp-0509/main5.cpp | UTF-8 | 554 | 3.375 | 3 | [
"Apache-2.0"
] | permissive | /// Source : https://leetcode.com/problems/fibonacci-number/
/// Author : liuyubobobo
/// Time : 2019-01-09
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
/// Closed Form
/// https://en.wikipedia.org/wiki/Fibonacci_number
///
/// Time Complexity: O(logn)
/// Space Complexity: O(logn)
class Solution {
public:
int fib(int N) {
double a = (1. + sqrt(5.)) / 2.0;
double b = (1. - sqrt(5.)) / 2.0;
return (int)((pow(a, N) - pow(b, N)) / sqrt(5) + 0.5);
}
};
int main() {
return 0;
} | true |
a82a087442f3fbffd25cd63bad58998802631760 | C++ | aspose-cells/Aspose.Cells-for-C | /Examples/CellsCPP/TechnicalArticles/ApplyCustomThemeColorsOfWorkbookUsingArrayOfColors.cpp | UTF-8 | 1,822 | 2.90625 | 3 | [] | no_license | #include "../CellsExamples.h"
//Apply Custom Theme Colors of the Workbook using Array of Colors
void ApplyCustomThemeColorsOfWorkbookUsingArrayOfColors()
{
//Output directory path
StringPtr outPath = new String("..\\Data\\Output\\");
//Path of output excel file
StringPtr outputApplyCustomThemeColorsOfWorkbookUsingArrayOfColors = outPath->StringAppend(new String("outputApplyCustomThemeColorsOfWorkbookUsingArrayOfColors.xlsx"));
//Create a workbook
intrusive_ptr<IWorkbook> wb = Factory::CreateIWorkbook();
//Create array of custom theme colors
intrusive_ptr<Array1D<Systems::Drawing::Color*>> clrs = new Array1D<Systems::Drawing::Color*>(12);
//Background1
clrs->SetValue(Systems::Drawing::Color::GetRed(), 0);
//Text1
clrs->SetValue(Systems::Drawing::Color::GetRed(), 1);
//Background2
clrs->SetValue(Systems::Drawing::Color::GetRed(), 2);
//Text2
clrs->SetValue(Systems::Drawing::Color::GetRed(), 3);
//Accent1
clrs->SetValue(Systems::Drawing::Color::GetRed(), 4);
//Accent2
clrs->SetValue(Systems::Drawing::Color::GetGreen(), 5);
//Accent3
clrs->SetValue(Systems::Drawing::Color::GetGreen(), 6);
//Accent4
clrs->SetValue(Systems::Drawing::Color::GetGreen(), 7);
//Accent5
clrs->SetValue(Systems::Drawing::Color::GetGreen(), 8);
//Accent6
clrs->SetValue(Systems::Drawing::Color::GetBlue(), 9);
//Hyperlink
clrs->SetValue(Systems::Drawing::Color::GetBlue(), 10);
//Followed Hyperlink
clrs->SetValue(Systems::Drawing::Color::GetBlue(), 11);
//Apply custom theme colors on workbook
wb->CustomTheme(new String("AnyTheme"), clrs);
//Save the workbook
wb->Save(outputApplyCustomThemeColorsOfWorkbookUsingArrayOfColors);
//Show successfull execution message on console
ShowMessageOnConsole("ApplyCustomThemeColorsOfWorkbookUsingArrayOfColors executed successfully.\r\n\r\n");
} | true |
46fa291c1bb1eea9c37920e0b542e6049116ed82 | C++ | xClima/Probleme-de-programare-Moodle | /Subiecte complexe/Gradina zoologica.cpp | UTF-8 | 4,507 | 2.640625 | 3 | [] | no_license | #include<iostream>
#include<algorithm>
#include<vector>
#include<string>
using namespace std;
bool sortare(const pair<string,int>&a,const pair<string,int>&b){
if(a.second==b.second){return a.first<b.first;}else{return a.second<b.second;}
}
struct Animale{
string x,y;
int v;
};
bool comp(Animale a, Animale b){
return a.x<b.x;
}
bool comp2(Animale a, Animale b){
return a.v<b.v;
}
bool comp3(Animale a, Animale b){
if(a.v==b.v){return a.y<b.y;}else{return a.v>b.v;}
}
bool comp5(Animale a, Animale b){
if(a.v==b.v){return a.y<b.y;}else{return a.v<b.v;}
}
bool comp4(Animale a,Animale b){
return a.y<b.y;
}
int main(){
string nume,animal;
int n,varsta;
vector<Animale>aux;
vector<pair<string,string>>vec;
vector<int>varst;
vector<Animale>sub2;
cin>>n;
for(int i=0;i<n;i++){
cin>>nume>>animal>>varsta;
aux.push_back({animal,nume,varsta});
vec.push_back(make_pair(animal,nume));
varst.push_back(varsta);
}
string sub;
cin>>sub;
if(sub=="count"){
sort(aux.begin(),aux.end(),comp);
vector<pair<string,int>>qqq;
int counter=0;
for(int i=0;i<aux.size();i++){
for(int j=aux.size()-1;j>=0;j--){
//if(i==j)continue;
if(aux[i].x==aux[j].x){
counter++;
qqq.push_back(make_pair(aux[j].y,aux[j].v));
//aux.erase(aux.begin());
}
}
cout<<aux[i].x<<' '<<'('<<counter<<')'<<':'<<' ';
sort(qqq.begin(),qqq.end(),sortare);
for(int x=0;x<qqq.size();x++){
cout<<qqq[x].first<<' ';
for(int y=0;y<aux.size();y++){
if(qqq[x].first==aux[y].y&&qqq[x].second==aux[y].v){
aux.erase(aux.begin()+y);
//y=-1;
}
}
}cout<<endl;
i=-1;
qqq.clear();
counter=0;
}
}
if(sub=="endangered"){
int x,cnt=0;
cin>>x;
vector<Animale>w;
for(int i=0;i<aux.size();i++){
for(int j=0;j<aux.size();j++){
if(aux[i].x==aux[j].x){
cnt++;
}
}
if(cnt==1){
w.push_back({aux[i].x,aux[i].y,aux[i].v});
}
cnt=0;
}
sort(w.begin(),w.end(),comp3);
for(int i=0;i<w.size();i++){
if(w[i].v>=x){
cout<<w[i].y<<' ';
}
}cout<<endl;
}
if(sub=="search"){
string cauta;
cin>>cauta;
int cnt=0;
sort(aux.begin(),aux.end(),comp4);
for(int i=0;i<aux.size();i++){
if(cauta==aux[i].x){
cnt++;
cout<<aux[i].y<<" - "<<aux[i].v<<endl;
}
}if(cnt==0){
cout<<"No match found."<<endl;
}
}
if(sub=="show"){
vector<Animale>e;
string best1,best2;
int best3;
sort(aux.begin(),aux.end(),comp4);
for(int i=0;i<aux.size();i++){
for(int j=0;j<aux.size();j++){
//if(i==j){continue;}else
if(aux[i].x==aux[j].x){
if(aux[i].v<=aux[j].v){
// e.push_back({aux[i].x,aux[i].y,aux[i].v});
best1=aux[i].x;
best2=aux[i].y;
best3=aux[i].v;
}else{best1.clear();best2.clear();best3=0;break;}
}
}if(best1.size()>0){
e.push_back({best1,best2,best3});
}
}
for(int i=0;i<e.size();i++){
for(int j=0;j<e.size();j++){
if(i==j)continue;
if(e[i].x==e[j].x){
e.erase(e.begin()+j);
j=-1;i=-1;
break;
}}}
sort(e.begin(),e.end(),comp4);
//e.erase(unique(e.begin(),e.end()),e.begin());
for(int i=0;i<e.size();i++){
cout<<e[i].y<<" ("<<e[i].x<<')'<<endl;
}
}
} | true |
5c2b6f0fc85170ff1584022504d4d8bf6fd839c4 | C++ | jrrodgers68/ParticleMQTTWrapper | /src/LogMessagePayloadFormatter.cpp | UTF-8 | 1,294 | 2.546875 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | #include "application.h"
#include "LogMessagePayloadFormatter.h"
#include "Buffer.h"
#include "BufferMgr.h"
#include <SparkJson.h>
#include <time.h>
using namespace ParticleMQTTWrapper;
LogMessagePayloadFormatter::LogMessagePayloadFormatter()
{
}
Buffer* LogMessagePayloadFormatter::writeMessage(const char* source, const char* text)
{
// get buffer from BufferMgr
// format message as json
// write json object to buffer
Buffer* buf = BufferMgr::instance()->allocate(256);
if(buf)
{
if(!formatMessage(buf, source, text))
{
// failed - deallocate buffer
BufferMgr::instance()->deallocate(buf);
buf = NULL;
}
}
return buf;
}
bool LogMessagePayloadFormatter::formatMessage(Buffer* p, const char* source, const char* text)
{
StaticJsonBuffer<1024> jsonBuffer;
JsonObject& root = jsonBuffer.createObject();
JsonObject& message = root.createNestedObject("message");
char buf[32];
memset(buf, 0, 32);
String ts = Time.format(Time.now(), TIME_FORMAT_ISO8601_FULL);
ts.toCharArray(buf, 32);
message["timestamp"] = buf;
message["source"] = source;
message["message"] = text;
p->size() = root.printTo(p->buffer(), p->maxSize());
return p->size() > 0;
}
| true |
50ccddb5e71bd807bd185d4c6ae136783d0be0b2 | C++ | truongan012/InterviewKit_cpp | /src/TwoStrings.cpp | UTF-8 | 792 | 3.234375 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <string>
#include <set>
#include <algorithm>
#include <iterator>
using namespace std;
// Complete the twoStrings function below.
string twoStrings(string s1, string s2)
{
string result = "";
set<char> set1(begin(s1), end(s1));
set<char> set2(begin(s2), end(s2));
set<char> intersec;
set_intersection(set1.begin(), set1.end(), set2.begin(), set2.end(), inserter(intersec, intersec.begin()));
if (intersec.empty()) result = "NO";
else result = "YES";
return result;
}
int main()
{
int q = 1;
for (int q_itr = 0; q_itr < q; q_itr++)
{
string s1 = "hello";
string s2 = "world";
string result = twoStrings(s1, s2);
printf("%s", result);
}
return 0;
}
| true |
272a236b53788037b26237a500b459188f4c687a | C++ | accessmvsk/CodingPractice | /SingleNumber.cc | UTF-8 | 1,432 | 3.921875 | 4 | [] | no_license | #include <iostream>
#include <string>
#define MAX_COUNT 15
using namespace std;
// Program to find unique value in an array with all pairs except 1 value.
// This solution assumes the array doesn't have 0. If so, we are screwed
// If array has 0, use hash map solution. Keep adding and removing elements from array
// into hash map as u see them
// Finally only unique would be left in the hashmap.
// This version of solution is simple and has no space complexity as hashmap.
// See these :
// http://www.programcreek.com/2012/12/leetcode-solution-of-single-number-in-java/
// http://www.programcreek.com/2014/03/leetcode-single-number-ii-java/
int main()
{
int my_array[MAX_COUNT];
int i,max,unique;
// read the max number of valid values in the array
cout<<"Please enter the array size\n";
cin>>max;
if (max > MAX_COUNT)
{
cout<<"Please re-run with count less than 16 \n";
return 1;
}
//read in the array
cout<<"Please enter the array elements one by one\n"<<endl;
for (i = 0; i < max; i++ )
{
cin>>my_array[i];
}
//XOR all the numbers and we are left with the unique number
unique = 0;
for (i = 0; i < max; i++)
{
unique = unique ^ my_array[i];
}
//print the unique
if (unique) {
cout<<"unique: "<<unique<<endl;
} else {
cout<<"array has no unique values"<<endl;
}
return 0;
}
| true |
020bf29c381d2179ee0731610030c2ecab55d212 | C++ | reenigne/reenigne | /8088/demo/pitpulse/pitpulse.cpp | UTF-8 | 6,093 | 2.578125 | 3 | [
"Unlicense"
] | permissive | // Scheme X: the outer interrupt is triggered by audio channel A pulse (more accurate)
// Scheme Y: the outer interrupt is triggered whichever audio channel is pulsing when the time runs out (faster)
// Implement both schemes: scheme Y will suffice for note/volume changes, scheme X will probably be necessary for ISAV
// ISAV currently has a slop of about 2 scanlines (need to set vertical active to/from 1 row) but might be able to relax this a bit
// If using ISAV with speed-critical code, might want to store all the flags in a bitfield in a register
// 1 channel
Byte pulseWidth;
Byte pulseWidthNext;
static const Word coalesceCount;
Word phaseA;
Word countA;
Byte pulseWidthA;
Word nextCount;
Word currentCount;
#ifdef SCHEME_Y
Word phase;
Word interruptCount;
Word lastCount;
#endif
#ifdef SCHEME_X
bool nextDoOldInterrupt;
bool currentDoOldInterrupt;
#endif
struct SongRecord
{
Word _countA;
Word _countB;
Word _countC;
Word _countD;
Byte _pulseWidthA;
Byte _pulseWidthB;
Byte _pulseWidthC;
Byte _pulseWidthD;
};
SongRecord* songStart;
SongRecord* songPointer;
SongRecord* songEnd;
void interruptStart()
{
#ifdef SCHEME_X
if (pulseWidth != 0)
#endif
outportb(0x42, pulseWidth);
pulseWidth = pulseWidthNext;
}
void interruptEnd()
{
#ifdef SCHEME_Y
phase -= lastCount;
if (phase < 0) {
phase += interruptCount;
doOldInterrupt();
}
lastCount = currentCount;
#endif
#ifdef SCHEME_X
if (currentDoOldInterrupt)
doOldInterrupt();
currentDoOldInterrupt = nextDoOldInterrupt;
#endif
currentCount = nextCount;
outportb(0x40, nextCount & 0xff);
outportb(0x40, nextCount >> 8);
}
void doOldInterrupt()
{
if (songPointer == songEnd)
songPointer = songStart;
#ifndef SCHEME_X
pulseWidthA = songPointer->_pulseWidthA;
countA = songPointer->_countA;
#endif
pulseWidthB = songPointer->_pulseWidthB;
pulseWidthC = songPointer->_pulseWidthC;
pulseWidthD = songPointer->_pulseWidthD;
countB = songPointer->_countB;
countC = songPointer->_countC;
countD = songPointer->_countD;
++songPointer;
if (pulseWidthD != 0) {
setInterrupt(8, interrupt8_4);
return;
}
if (pulseWidthC != 0) {
setInterrupt(8, interrupt8_3);
return;
}
if (pulseWidthB != 0) {
setInterrupt(8, interrupt8_2);
return;
}
setInterrupt(8, interrupt8_1);
}
// 1 channel
void interrupt8_1() // Just finished counting down from lastCount, now counting down from currentCount
{
interruptStart();
nextCount = countA;
pulseWidthNext = pulseWidthA;
#if SCHEME_X
nextDoOldInterrupt = true;
#endif
interruptEnd();
}
// 2 channels
Word phaseB;
Word countB;
Byte pulseWidthB;
void coalesceA()
{
phaseA -= nextCount;
if (phaseA < coalesceCount) {
phaseA += countA;
#if SCHEME_X
nextDoOldInterrupt = true;
#else
pulseWidthNext += pulseWidthA;
#endif
}
}
void coalesceB()
{
phaseB -= nextCount;
if (phaseB < coalesceCount) {
phaseB += countB;
pulseWidthNext += pulseWidthB;
}
}
void interrupt8_2()
{
interruptStart();
if (phaseB < phaseA)
goto nextB;
nextCount = phaseA;
phaseA = countA;
pulseWidthNext = pulseWidthA;
#if SCHEME_X
nextDoOldInterrupt = true;
#endif
coalesceB();
goto done;
nextB:
nextCount = phaseB;
phaseB = countB;
pulseWidthNext = pulseWidthB;
#if SCHEME_X
nextDoOldInterrupt = false;
#endif
coalesceA();
done:
interruptEnd();
}
// 3 channels
Word phaseC;
Word countC;
Byte pulseWidthC;
void coalesceC()
{
phaseC -= nextCount;
if (phaseC < coalesceCount) {
phaseC += countC;
pulseWidthNext += pulseWidthC;
}
}
void interrupt8_3()
{
interruptStart();
if (phaseB < phaseA)
goto nextBC;
if (phaseC < phaseA)
goto nextC;
nextCount = phaseA;
phaseA = countA;
pulseWidthNext = pulseWidthA;
#if SCHEME_X
nextDoOldInterrupt = true;
#endif
coalesceB();
coalesceC();
goto done;
nextBC:
if (phaseC < phaseB)
goto nextC;
nextCount = phaseB;
phaseB = countB;
pulseWidthNext = pulseWidthB;
#if SCHEME_X
nextDoOldInterrupt = false;
#endif
coalesceA();
coalesceC();
goto done;
nextC:
nextCount = phaseC;
phaseC = countC;
pulseWidthNext = pulseWidthC;
#if SCHEME_X
nextDoOldInterrupt = false;
#endif
coalesceA();
coalesceB();
done:
interruptEnd();
}
// 4 channels
Word phaseD;
Word countD;
Byte pulseWidthD;
void coalesceD()
{
phaseD -= nextCount;
if (phaseD < coalesceCount) {
phaseD += countD;
pulseWidthNext += pulseWidthD;
}
}
void interrupt8_4()
{
interruptStart();
if (phaseB < phaseA)
goto nextBCD;
if (phaseC < phaseA)
goto nextCD;
if (phaseD < phaseA)
goto nextD;
nextCount = phaseA;
phaseA = countA;
pulseWidthNext = pulseWidthA;
#if SCHEME_X
nextDoOldInterrupt = true;
#endif
coalesceB();
coalesceC();
coalesceD();
goto done;
nextBCD:
if (phaseC < phaseB)
goto nextCD;
if (phaseD < phaseB)
goto nextD;
nextCount = phaseB;
phaseB = countB;
pulseWidthNext = pulseWidthB;
#if SCHEME_X
nextDoOldInterrupt = false;
#endif
coalesceA();
coalesceC();
coalesceD();
goto done;
nextCD:
if (phaseD < phaseC)
goto nextD;
nextCount = phaseC;
phaseC = countC;
pulseWidthNext = pulseWidthC;
#if SCHEME_X
nextDoOldInterrupt = false;
#endif
coalesceA();
coalesceB();
coalesceD();
goto done;
nextD:
nextCount = phaseD;
phaseD = countD;
pulseWidthNext = pulseWidthD;
#if SCHEME_X
nextDoOldInterrupt = false;
#endif
coalesceA();
coalesceB();
coalesceC();
done:
interruptEnd();
}
// We need the count and pulseWidth values once for each channel, but they're
// not changed within the interrupt proper. Just update all copies when the
// frequency or volume changes?
| true |
8d947bf22720788b84ddb3101211058f4c054449 | C++ | zhushh/cplusplus | /cplusplus_course_projects/small_code/template_determine_smaller.cpp | UTF-8 | 586 | 3.6875 | 4 | [] | no_license | #include <iostream>
using std::cin;
using std::cout;
using std::endl;
template <class T>
T min(T a, T b)
{
T min = a;
if (min > b) {
min = b;
}
return min;
}
int main()
{
int a, b;
cout << "Enter two integers: ";
cin >> a >> b;
cout << "The smaller one is: " << min(a, b) << endl;
double c, d;
cout << "Enter two float number: ";
cin >> c >> d;
cout << "The smaller one is: " << min(c, d) << endl;
char e, f;
cout << "Enter two charachter: ";
cin >> e >> f;
cout << "The smaller one is: " << min(e, f) << endl;
return 0;
}
| true |
212e6d50e1c9edf596aad081a514c52ee4532c0b | C++ | Sscftolicsz/AVL-Tree-Practice | /AVL.cpp | UTF-8 | 9,696 | 3.734375 | 4 | [] | no_license | #include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
struct Node{
char productName[100];
char productQuality[15];
int productPrice;
int productStock;
int height;
Node* left;
Node* right;
};
Node* createNode(char productName[100], char productQuality[15], int productPrice, int productStock){
Node* newNode = (Node*)malloc(sizeof(Node));
strcpy(newNode->productName,productName);
strcpy(newNode->productQuality,productQuality);
newNode->productPrice = productPrice;
newNode->productStock = productStock;
newNode->height = 1;
newNode->left = newNode->right = NULL;
return newNode;
}
void clear(){
for(int i=0;i<26;i++){
printf("\n");
}
}
int max(int a, int b){
// ternary
// if (a > b) return a
// else return b
return a > b ? a : b;
}
int getHeight(Node* root){
if(!root) return 0;
return root->height;
// 1. root nya ada -> langsung return root->height
// 2. root nya NULL -> jangan return root->height, tapi 0;
}
int getBalanceFactor(Node* root){
// height anak kiri - height anak kanan
return getHeight(root->left) - getHeight(root->right);
}
void updateHeight(Node* root){
// height = max(height anak kiri, height anak kanan) + 1 -> diri sendiri
root->height = max(getHeight(root->left), getHeight(root->right)) + 1;
}
Node* rotateRight(Node* root){
Node* child = root->left;
Node* gchild = child->right;
child->right = root;
root->left = gchild;
updateHeight(root);
updateHeight(child);
return child;
}
Node* rotateLeft(Node* root){
Node* child = root->right;
Node* gchild = child->left;
child->left = root;
root->right = gchild;
updateHeight(root);
updateHeight(child);
return child;
}
Node* rebalance(Node* root){
// balance factor
int bf = getBalanceFactor(root);
if(bf < -1){
// kanan lebih berat
if(getBalanceFactor(root->right) > 0){
// root -> kanan -> kiri
// rotate right si childnya
root->right = rotateRight(root->right);
}
// rotate left si rootnya
root = rotateLeft(root);
}else if(bf > 1){
// kiri lebih berat
if(getBalanceFactor(root->left) < 0){
// root -> kiri -> kanan
// rotate left si childnya
root->left = rotateLeft(root->left);
}
// rotate right si rootnya
root = rotateRight(root);
}
return root;
}
Node* push(Node* root, char productName[100], char productQuality[15], int productPrice, int productStock){
// ada root / tidak ?
if(!root) return createNode(productName,productQuality,productPrice,productStock);
if(strcmp(productName, root->productName) < 0){
// kiri
root->left = push(root->left, productName, productQuality, productPrice, productStock);
}else if(strcmp(productName, root->productName) > 0){
// kanan
root->right = push(root->right, productName,productQuality,productPrice,productStock);
}
// update height
updateHeight(root);
// return root yang sudah di rebalance
return rebalance(root);
}
Node* searchProduct(Node* root, char name[100]){
if(!root) return NULL;
if(strcmp(name, root->productName) < 0) // name < root
return searchProduct(root->left, name);
else if(strcmp(name, root->productName) > 0) // name > root
return searchProduct(root->right, name);
else return root;
}
bool nameIsValid(Node* root, char name[100]){
// harus lebih dari 2 karakter
if(strlen(name) < 2){
printf("PRODUCT NAME MUST CONSIST OF 2 CHARACTERS OR MORE!\n\n");
return false;
}
// tidak boleh ada spasi
for(int i=0;i<strlen(name);i++){
if(isspace(name[i])){
printf("PRODUCT NAME CAN NOT CONSIST OF WHITE SPACE\n\n");
return false;
}
}
// tidak boleh sama (unique)
if(searchProduct(root, name)) return false;
return true;
}
Node* insertProduct(Node* root){
char productName[100];
char productQuality[15];
int productPrice;
int productStock;
char confirmation;
do{
printf("Input Product's name [2 chars or more] : ");
scanf("%[^\n]",productName);
getchar();
}while(!nameIsValid(root, productName));
printf("\n");
do{
printf("Input Product's quality [ Super | Good | Ok ] : ");
scanf("%[^\n]",productQuality);
getchar();
if(strcmpi(productQuality, "super") != 0 && strcmpi(productQuality, "good") != 0 && strcmpi(productQuality, "ok") != 0){
printf("PRODUCT'S QUALITY CAN ONLY BE Super / Good / Ok\n\n");
}
}while(strcmpi(productQuality, "super") != 0 && strcmpi(productQuality, "good") != 0 && strcmpi(productQuality, "ok") != 0);
printf("\n");
do{
printf("Insert product's price [Divisible by 100] : ");
scanf("%d",&productPrice);
getchar();
if(productPrice%100 != 0){
printf("PRODUCT'S PRICE MUST BE DIVISIBLE BY 100!\n\n");
}
}while(productPrice%100 != 0);
printf("\n");
do{
printf("Insert product's stock [1-100] : ");
scanf("%d",&productStock);
getchar();
if(productStock < 1 || productStock > 100){
printf("PRODUCT'S MUST BE BETWEEN 1 AND 100!\n\n");
}
}while(productStock < 1 || productStock > 100);
printf("\n");
do{
printf("ARE YOU SURE YOU WANT TO ADD %s PRODUCT? [Y|N] > ",productName);
scanf("%c",&confirmation);
getchar();
}while(confirmation != 'Y' && confirmation != 'N');
if(confirmation == 'Y'){
printf("SUCCESS ADD PRODUCT!\n");
root = push(root, productName, productQuality, productPrice, productStock);
}
return root;
}
void inorder(Node* root){
if(!root) return;
inorder(root->left);
printf("\n");
printf("========================\n");
printf("Product's Name : %s\n",root->productName);
printf("Product's Quality : %s\n",root->productQuality);
printf("Product's Price : IDR %d\n",root->productPrice);
printf("Product's Stock : %d pcs\n",root->productStock);
printf("========================\n");
printf("\n");
inorder(root->right);
}
void preorder(Node* root){
if(!root) return;
printf("\n");
printf("========================\n");
printf("Product's Name : %s\n",root->productName);
printf("Product's Quality : %s\n",root->productQuality);
printf("Product's Price : IDR %d\n",root->productPrice);
printf("Product's Stock : %d pcs\n",root->productStock);
printf("========================\n");
printf("\n");
preorder(root->left);
preorder(root->right);
}
void postorder(Node* root){
if(!root) return;
postorder(root->left);
postorder(root->right);
printf("\n");
printf("========================\n");
printf("Product's Name : %s\n",root->productName);
printf("Product's Quality : %s\n",root->productQuality);
printf("Product's Price : IDR %d\n",root->productPrice);
printf("Product's Stock : %d pcs\n",root->productStock);
printf("========================\n");
printf("\n");
}
void seeAllProduct(Node* root){
if(!root){
puts("YOU DON'T HAVE ANY PRODUCT");
getchar();
return;
}
int choose = 0;
do{
puts("How do you want to see all product?");
puts("1. In order");
puts("2. Pre order");
puts("3. Post order");
printf(">> ");
scanf("%d",&choose);
getchar();
switch(choose){
case 1:
inorder(root);
break;
case 2:
preorder(root);
break;
case 3:
postorder(root);
break;
}
getchar();
}while(choose < 1 || choose > 3);
}
Node* findPredecessor(Node* root){
root = root->left; // ke kiri 1x
while(root->right){ // ke kanan sampe mentok
root = root->right;
}
return root;
}
Node* pop(Node* root, char productName[100]){
if(!root) return NULL;
if(strcmp(productName, root->productName) < 0){
root->left = pop(root->left, productName);
}else if(strcmp(productName, root->productName) > 0){
root->right = pop(root->right, productName);
}else{
// ketemu
if(root->left && root->right){
root = NULL;
free(root);
return NULL;
}else if(!root->left){
// anak kanan
Node* child = root->right;
root = NULL;
free(root);
return child;
}else if(!root->right){
// anak kiri
Node* child = root->left;
root = NULL;
free(root);
return child;
}else{
// 2 anak
Node* pre = findPredecessor(root);
strcpy(root->productName, pre->productName);
strcpy(root->productQuality, pre->productQuality);
root->productPrice = pre->productPrice;
root->productStock = pre->productStock;
root->left = pop(root->left, pre->productName);
}
}
updateHeight(root);
return rebalance(root);
}
Node* removeProduct(Node* root){
if(!root){
puts("YOU DON'T HAVE ANY PRODUCT");
return NULL;
}
char productName[100];
Node* found = NULL;
seeAllProduct(root);
do{
printf("ENTER PRODUCT NAME TO BE REMOVED! > ");
scanf("%[^\n]",productName);
found = searchProduct(root, productName);
if(!found){
printf("PRODUCT DOES NOT EXIST!\n");
getchar();
}else{
printf("SUCCESS REMOVE PRODUCT");
getchar();
pop(root, productName);
}
}while(!found);
}
Node* removeAllProduct(Node* root){
if(!root){
puts("YOU DON'T HAVE ANY PRODUCT");
return NULL;
}
char confirmation;
do{
printf("ARE YOU SURE WANT TO REMOVE ALL PRODUCT? [Y|N] > ");
scanf("%c",&confirmation);
getchar();
}while(confirmation != 'Y' && confirmation != 'N');
if(confirmation == 'Y'){
while(root){
root = pop(root, root->productName);
printf("SUCCESS REMOVE ALL PRODUCT!\n");
}
}
return root;
}
int main(){
int choose = 0;
Node* root = 0;
do{
clear();
puts("My Product\n");
puts("1. Insert New Product");
puts("2. Remove a Product");
puts("3. See all product");
puts("4. Remove all product");
puts("5. Exit");
printf(">> ");
scanf("%d",&choose);
getchar();
switch(choose){
case 1 :
root = insertProduct(root);
getchar();
break;
case 2 :
root = removeProduct(root);
getchar();
break;
case 3 :
seeAllProduct(root);
break;
case 4 :
root = removeAllProduct(root);
getchar();
break;
}
}while(choose != 5);
return 0;
}
| true |
2255074ca7efed920387818c9078f644a584e4b8 | C++ | osamu-k/QtStudy | /DrawingChat001/NetDraw001/model/shapespace.cpp | UTF-8 | 1,840 | 2.984375 | 3 | [] | no_license | #include "shapespace.h"
#include "freehandfactory.h"
#include "rectanglefactory.h"
ShapeSpace::ShapeSpace()
{
m_factoryMap[Shape::TYPE_FREEHAND] = new FreeHandFactory();
m_factoryMap[Shape::TYPE_RECTANGLE] = new RectangleFactory();
}
ShapeSpace::~ShapeSpace()
{
}
ShapeSpace *ShapeSpace::m_instance = 0;
ShapeSpace *ShapeSpace::instance()
{
if( m_instance == 0 ){
m_instance = new ShapeSpace();
}
return m_instance;
}
Shape *ShapeSpace::newShape( Shape::Type type )
{
Shape *shape = 0;
if( m_factoryMap.contains(type) ){
shape = m_factoryMap[type]->newInstance();
}
return shape;
}
void ShapeSpace::addShape( Shape *shape )
{
m_shapeVector.push_back(shape);
emit changed();
}
int ShapeSpace::shapeCount() const
{
return m_shapeVector.size();
}
Shape *ShapeSpace::shape( int index ) const
{
if( (0 <= index) && (index < m_shapeVector.size()) ){
return m_shapeVector[index];
}
else{
return 0;
}
}
void ShapeSpace::clear()
{
foreach( Shape *shape, m_shapeVector ){
delete shape;
}
m_shapeVector.clear();
emit changed();
}
void ShapeSpace::writeTo( QDataStream &out ) const
{
out << static_cast<qint16>(shapeCount());
for( int i = 0; i < shapeCount(); i++ ){
Shape *shape = this->shape(i);
out << static_cast<qint16>(shape->type());
shape->writeTo( out );
}
}
void ShapeSpace::readFrom( QDataStream &in )
{
clear();
qint16 count;
in >> count;
for( int i = 0; i < count; i++ ){
qint16 i16;
in >> i16;
Shape::Type type = static_cast<Shape::Type>(i16);
if( m_factoryMap.contains(type) ){
Shape *shape = m_factoryMap[type]->newInstance();
shape->readFrom(in);
addShape(shape);
}
}
}
| true |
0441758eb8bfc82e562246790fa53f77f249e60b | C++ | stephanie-wang/ray | /src/ray/raylet/lineage_cache.cc | UTF-8 | 13,802 | 2.578125 | 3 | [
"Apache-2.0",
"MIT"
] | permissive | #include "lineage_cache.h"
#include <sstream>
#include "ray/gcs/redis_gcs_client.h"
#include "ray/stats/stats.h"
namespace ray {
namespace raylet {
LineageEntry::LineageEntry(const Task &task, GcsStatus status)
: status_(status), task_(task) {
ComputeParentTaskIds();
}
GcsStatus LineageEntry::GetStatus() const { return status_; }
bool LineageEntry::SetStatus(GcsStatus new_status) {
if (status_ < new_status) {
status_ = new_status;
return true;
} else {
return false;
}
}
void LineageEntry::ResetStatus(GcsStatus new_status) {
RAY_CHECK(new_status < status_);
status_ = new_status;
}
void LineageEntry::MarkExplicitlyForwarded(const ClientID &node_id) {
forwarded_to_.insert(node_id);
}
bool LineageEntry::WasExplicitlyForwarded(const ClientID &node_id) const {
return forwarded_to_.find(node_id) != forwarded_to_.end();
}
const TaskID LineageEntry::GetEntryId() const {
return task_.GetTaskSpecification().TaskId();
}
const std::unordered_set<TaskID> &LineageEntry::GetParentTaskIds() const {
return parent_task_ids_;
}
void LineageEntry::ComputeParentTaskIds() {
parent_task_ids_.clear();
// A task's parents are the tasks that created its arguments.
for (const auto &dependency : task_.GetDependencies()) {
parent_task_ids_.insert(dependency.TaskId());
}
}
const Task &LineageEntry::TaskData() const { return task_; }
Task &LineageEntry::TaskDataMutable() { return task_; }
void LineageEntry::UpdateTaskData(const Task &task) {
task_.CopyTaskExecutionSpec(task);
ComputeParentTaskIds();
}
Lineage::Lineage() {}
boost::optional<const LineageEntry &> Lineage::GetEntry(const TaskID &task_id) const {
auto entry = entries_.find(task_id);
if (entry != entries_.end()) {
return entry->second;
} else {
return boost::optional<const LineageEntry &>();
}
}
boost::optional<LineageEntry &> Lineage::GetEntryMutable(const TaskID &task_id) {
auto entry = entries_.find(task_id);
if (entry != entries_.end()) {
return entry->second;
} else {
return boost::optional<LineageEntry &>();
}
}
void Lineage::RemoveChild(const TaskID &parent_id, const TaskID &child_id) {
auto parent_it = children_.find(parent_id);
RAY_CHECK(parent_it->second.erase(child_id) == 1);
if (parent_it->second.empty()) {
children_.erase(parent_it);
}
}
void Lineage::AddChild(const TaskID &parent_id, const TaskID &child_id) {
auto inserted = children_[parent_id].insert(child_id);
RAY_CHECK(inserted.second);
}
bool Lineage::SetEntry(const Task &task, GcsStatus status) {
// Get the status of the current entry at the key.
auto task_id = task.GetTaskSpecification().TaskId();
auto it = entries_.find(task_id);
bool updated = false;
if (it != entries_.end()) {
if (it->second.SetStatus(status)) {
// We assume here that the new `task` has the same fields as the task
// already in the lineage cache. If this is not true, then it is
// necessary to update the task data of the existing lineage cache entry
// with LineageEntry::UpdateTaskData.
updated = true;
}
} else {
LineageEntry new_entry(task, status);
it = entries_.emplace(std::make_pair(task_id, std::move(new_entry))).first;
updated = true;
// New task data was added to the local cache, so record which tasks it
// depends on. Add all new tasks that it depends on.
for (const auto &parent_id : it->second.GetParentTaskIds()) {
AddChild(parent_id, task_id);
}
}
return updated;
}
boost::optional<LineageEntry> Lineage::PopEntry(const TaskID &task_id) {
auto entry = entries_.find(task_id);
if (entry != entries_.end()) {
LineageEntry entry = std::move(entries_.at(task_id));
// Remove the task's dependencies.
for (const auto &parent_id : entry.GetParentTaskIds()) {
RemoveChild(parent_id, task_id);
}
entries_.erase(task_id);
return entry;
} else {
return boost::optional<LineageEntry>();
}
}
const std::unordered_map<const TaskID, LineageEntry> &Lineage::GetEntries() const {
return entries_;
}
const std::unordered_set<TaskID> &Lineage::GetChildren(const TaskID &task_id) const {
static const std::unordered_set<TaskID> empty_children;
const auto it = children_.find(task_id);
if (it != children_.end()) {
return it->second;
} else {
return empty_children;
}
}
LineageCache::LineageCache(const ClientID &self_node_id,
std::shared_ptr<gcs::GcsClient> gcs_client,
uint64_t max_lineage_size)
: self_node_id_(self_node_id), gcs_client_(gcs_client) {}
/// A helper function to add some uncommitted lineage to the local cache.
void LineageCache::AddUncommittedLineage(const TaskID &task_id,
const Lineage &uncommitted_lineage) {
RAY_LOG(DEBUG) << "Adding uncommitted task " << task_id << " on " << self_node_id_;
// If the entry is not found in the lineage to merge, then we stop since
// there is nothing to copy into the merged lineage.
auto entry = uncommitted_lineage.GetEntry(task_id);
if (!entry) {
return;
} else if (entry->TaskData().GetTaskSpecification().IsDirectCall()) {
// Disable lineage logging for direct tasks.
return;
}
RAY_CHECK(entry->GetStatus() == GcsStatus::UNCOMMITTED);
// Insert a copy of the entry into our cache.
const auto &parent_ids = entry->GetParentTaskIds();
// If the insert is successful, then continue the DFS. The insert will fail
// if the new entry has an equal or lower GCS status than the current entry
// in our cache. This also prevents us from traversing the same node twice.
if (lineage_.SetEntry(entry->TaskData(), entry->GetStatus())) {
RAY_CHECK(SubscribeTask(task_id));
for (const auto &parent_id : parent_ids) {
AddUncommittedLineage(parent_id, uncommitted_lineage);
}
}
}
bool LineageCache::CommitTask(const Task &task) {
if (task.GetTaskSpecification().IsDirectCall()) {
// Disable lineage logging for direct tasks.
return true;
}
const TaskID task_id = task.GetTaskSpecification().TaskId();
RAY_LOG(DEBUG) << "Committing task " << task_id << " on " << self_node_id_;
if (lineage_.SetEntry(task, GcsStatus::UNCOMMITTED) ||
lineage_.GetEntry(task_id)->GetStatus() == GcsStatus::UNCOMMITTED) {
// Attempt to flush the task if the task is uncommitted.
FlushTask(task_id);
return true;
} else {
// The task was already committing (COMMITTING).
return false;
}
}
void LineageCache::FlushAllUncommittedTasks() {
size_t num_flushed = 0;
for (const auto &entry : lineage_.GetEntries()) {
// Flush all tasks that have not yet committed.
if (entry.second.GetStatus() == GcsStatus::UNCOMMITTED) {
RAY_CHECK(UnsubscribeTask(entry.first));
FlushTask(entry.first);
num_flushed++;
}
}
RAY_LOG(DEBUG) << "Flushed " << num_flushed << " uncommitted tasks";
}
void LineageCache::MarkTaskAsForwarded(const TaskID &task_id, const ClientID &node_id) {
RAY_CHECK(!node_id.IsNil());
auto entry = lineage_.GetEntryMutable(task_id);
if (entry) {
entry->MarkExplicitlyForwarded(node_id);
}
}
/// A helper function to get the uncommitted lineage of a task.
void GetUncommittedLineageHelper(const TaskID &task_id, const Lineage &lineage_from,
Lineage &lineage_to, const ClientID &node_id) {
// If the entry is not found in the lineage to merge, then we stop since
// there is nothing to copy into the merged lineage.
auto entry = lineage_from.GetEntry(task_id);
if (!entry) {
return;
}
// If this task has already been forwarded to this node, then we can stop.
if (entry->WasExplicitlyForwarded(node_id)) {
return;
}
// Insert a copy of the entry into lineage_to. If the insert is successful,
// then continue the DFS. The insert will fail if the new entry has an equal
// or lower GCS status than the current entry in lineage_to. This also
// prevents us from traversing the same node twice.
if (lineage_to.SetEntry(entry->TaskData(), entry->GetStatus())) {
for (const auto &parent_id : entry->GetParentTaskIds()) {
GetUncommittedLineageHelper(parent_id, lineage_from, lineage_to, node_id);
}
}
}
Lineage LineageCache::GetUncommittedLineage(const TaskID &task_id,
const ClientID &node_id) const {
Lineage uncommitted_lineage;
// Add all uncommitted ancestors from the lineage cache to the uncommitted
// lineage of the requested task.
GetUncommittedLineageHelper(task_id, lineage_, uncommitted_lineage, node_id);
// The lineage always includes the requested task id, so add the task if it
// wasn't already added. The requested task may not have been added if it was
// already explicitly forwarded to this node before.
if (uncommitted_lineage.GetEntries().empty()) {
auto entry = lineage_.GetEntry(task_id);
if (entry) {
RAY_CHECK(uncommitted_lineage.SetEntry(entry->TaskData(), entry->GetStatus()));
}
}
return uncommitted_lineage;
}
void LineageCache::FlushTask(const TaskID &task_id) {
auto entry = lineage_.GetEntryMutable(task_id);
RAY_CHECK(entry);
RAY_CHECK(entry->GetStatus() < GcsStatus::COMMITTING);
auto task_callback = [this, task_id](Status status) {
RAY_CHECK(status.ok());
HandleEntryCommitted(task_id);
};
auto task = lineage_.GetEntry(task_id);
auto task_data = std::make_shared<TaskTableData>();
task_data->mutable_task()->mutable_task_spec()->CopyFrom(
task->TaskData().GetTaskSpecification().GetMessage());
task_data->mutable_task()->mutable_task_execution_spec()->CopyFrom(
task->TaskData().GetTaskExecutionSpec().GetMessage());
RAY_CHECK_OK(gcs_client_->Tasks().AsyncAdd(task_data, task_callback));
// We successfully wrote the task, so mark it as committing.
// TODO(swang): Use a batched interface and write with all object entries.
RAY_CHECK(entry->SetStatus(GcsStatus::COMMITTING));
}
bool LineageCache::SubscribeTask(const TaskID &task_id) {
auto inserted = subscribed_tasks_.insert(task_id);
bool unsubscribed = inserted.second;
if (unsubscribed) {
auto subscribe = [this](const TaskID &task_id, const TaskTableData) {
HandleEntryCommitted(task_id);
};
// Subscribe to the task.
RAY_CHECK_OK(gcs_client_->Tasks().AsyncSubscribe(task_id, subscribe,
/*done*/ nullptr));
}
// Return whether we were previously unsubscribed to this task and are now
// subscribed.
return unsubscribed;
}
bool LineageCache::UnsubscribeTask(const TaskID &task_id) {
auto it = subscribed_tasks_.find(task_id);
bool subscribed = (it != subscribed_tasks_.end());
if (subscribed) {
// Cancel subscribe to the task.
RAY_CHECK_OK(gcs_client_->Tasks().AsyncUnsubscribe(task_id, /*done*/ nullptr));
subscribed_tasks_.erase(it);
}
// Return whether we were previously subscribed to this task and are now
// unsubscribed.
return subscribed;
}
void LineageCache::EvictTask(const TaskID &task_id) {
// If the entry has already been evicted, exit.
auto entry = lineage_.GetEntry(task_id);
if (!entry) {
return;
}
// If the entry has not yet been committed, exit.
if (entry->GetStatus() != GcsStatus::COMMITTED) {
return;
}
// Entries cannot be safely evicted until their parents are all evicted.
for (const auto &parent_id : entry->GetParentTaskIds()) {
if (ContainsTask(parent_id)) {
return;
}
}
// Evict the task.
RAY_LOG(DEBUG) << "Evicting task " << task_id << " on " << self_node_id_;
lineage_.PopEntry(task_id);
// Try to evict the children of the evict task. These are the tasks that have
// a dependency on the evicted task.
const auto children = lineage_.GetChildren(task_id);
for (const auto &child_id : children) {
EvictTask(child_id);
}
}
void LineageCache::HandleEntryCommitted(const TaskID &task_id) {
RAY_LOG(DEBUG) << "Task committed: " << task_id;
auto entry = lineage_.GetEntryMutable(task_id);
if (!entry) {
// The task has already been evicted due to a previous commit notification.
return;
}
// Record the commit acknowledgement and attempt to evict the task.
entry->SetStatus(GcsStatus::COMMITTED);
EvictTask(task_id);
// We got the notification about the task's commit, so no longer need any
// more notifications.
UnsubscribeTask(task_id);
}
const Task &LineageCache::GetTaskOrDie(const TaskID &task_id) const {
const auto &entries = lineage_.GetEntries();
auto it = entries.find(task_id);
RAY_CHECK(it != entries.end());
return it->second.TaskData();
}
bool LineageCache::ContainsTask(const TaskID &task_id) const {
const auto &entries = lineage_.GetEntries();
auto it = entries.find(task_id);
return it != entries.end();
}
const Lineage &LineageCache::GetLineage() const { return lineage_; }
std::string LineageCache::DebugString() const {
std::stringstream result;
result << "LineageCache:";
result << "\n- child map size: " << lineage_.GetChildrenSize();
result << "\n- num subscribed tasks: " << subscribed_tasks_.size();
result << "\n- lineage size: " << lineage_.GetEntries().size();
return result.str();
}
void LineageCache::RecordMetrics() const {
stats::LineageCacheStats().Record(lineage_.GetChildrenSize(),
{{stats::ValueTypeKey, "num_children"}});
stats::LineageCacheStats().Record(subscribed_tasks_.size(),
{{stats::ValueTypeKey, "num_subscribed_tasks"}});
stats::LineageCacheStats().Record(lineage_.GetEntries().size(),
{{stats::ValueTypeKey, "num_lineages"}});
}
} // namespace raylet
} // namespace ray
| true |
00490317e5a33228493244a1c4862163257d25e3 | C++ | bdharshini08/my-captian-c-assignment-codes | /bus reservation system.cpp | UTF-8 | 3,578 | 3.140625 | 3 | [] | no_license | #include<iostream>
#include<conio.h>
#include<string.h>
#include<cstdio>
#include<cstdlib>
using namespace std;
static int p = 0;
class a
{
char busno[5],drivername[10],arrival[5],depart[5],from[10],to[10],seat[8][4][10];
public:
void install();
void allotment();
void empty();
void show();
void avail();
void position(int l);
}
bus[10];
void vline(char ch)
{
for(int i=80;i>0;i--)
cout<<ch;
}
void a::install()
{
cout<<"Enter bus no:";
cin>>bus[p].busno;
cout<<"Enter the driver's name:";
cin>>bus[p].drivername;
cout<<"\nArrival time of the bus:";
cin>>bus[p].arrival;
cout<<"\nDeparture time:";
cin>>bus[p].depart;
cout<<"\nFrom:\t\t";
cin>>bus[p].from;
cout<<"\nTo:\t\t";
cin>>bus[p].to;
bus[p].empty();
p++;
}
void a::allotment()
{
int seat,n;
char number[5];
top:
cout<<"Bus no:";
cin>>number;
for(n=0;n<=p;n++)
{
if(strcmp(bus[n].busno, number)==0)
break;
}
while(n<=p)
{
cout<<"\nseat number:";
cin>>seat;
if(seat>32)
{
cout<<"\nthere are only 32 seats avaliable in the bus";
}
else
{
if(strcmp(bus[n].seat[seat/4][(seat%4)-1],"Empty")==0)
{
cout<<"Enter passanger's name:";
cin>>bus[n].seat[seat/4][(seat%4)-1];
break;
}
else
cout<<"the seat no.is already reserved.\n";
}
}
if(n>p)
{
cout<<"\nEnter the correct bus no.\n";
goto top;
}
}
void a::empty()
{
for(int i=0;i<8;i++)
{
for(int j=0;j<4;j++)
{
strcpy(bus[p].seat[i][j],"Empty");
}
}
}
void a::show()
{
int n;
char number[5];
cout<<"Enter bus no:";
cin>>number;
for(n=0;n<=p;n++)
{
if(strcmp(bus[n].busno, number)==0)
break;
}
while(n<=p)
{
vline('*');
cout<<"bus no:\t"<<bus[n].busno
<<"\nDriver:\t"<<bus[n].drivername<<"\nArrival time:\t"
<<bus[n].arrival<<"\tDepartur time:"<<bus[n].depart
<<"\nFrom:\t\t"<<bus[n].from<<"\t\tTo:\t\t"<<
bus[n].to<<"\n";
vline('*');
bus[0].position(n);
int a=1,i,j;
for(i=0;i<8;i++)
{
for(j=0;j<4;j++)
{
a++;
if(strcmp(bus[n].seat[i][j],"empty")!=0)
cout<<"\nThe seat no"<<(a-1)<<"is reserved for"<<bus[n].seat[i][j]<<".";
}
}
break;
}
if(n>p)
cout<<"Enter correct bus no:";
}
void a::position(int l)
{
int s=0,p=0;
for(int i=0;i<8;i++)
{
cout<<"\n";
for(int j=0;j<4;j++)
{
s++;
if(strcmp(bus[l].seat[i][j],"Empty")==0)
{
cout.width(5);
cout.fill(' ');
cout<<s<<".";
cout.width(10);
cout.fill(' ');
cout<<bus[l].seat[i][j];
}
}
}
cout<<"\n\nThere are"<<p<<"seat empty in bus no:"<<bus[l].busno;
}
void a::avail()
{
for(int n=0;n<p;n++)
{
vline('*');
cout<<"bus no:\t"<<bus[n].busno
<<"\nDriver:\t"<<bus[n].drivername<<"\nArrival time:\t"
<<bus[n].arrival<<"\tDepartur time:"<<bus[n].depart
<<"\nFrom:\t\t"<<bus[n].from<<"\t\tTo:\t\t"<<
bus[n].to<<"\n";
vline('*');
vline('_');
}
}
int main()
{
system("cls");
int choice;
while(1)
{
//system("cls");
cout<<"\n1.Install\t\n";
cout<<"2.reservation\t\n";
cout<<"3.show\t\n";
cout<<"4.buses available\t\n";
cout<<"5.Exit\t\n";
cout<<"enter your choice:\t";
cin>>choice;
switch(choice)
{
case 1:bus[p].install();
break;
case 2:bus[p].allotment();
break;
case 3:bus[p].show();
break;
case 4:bus[p].avail();
break;
case 5:exit(0);
break;
}
}
}
| true |
d65c1721457c4c80a02cd11c4fd83dc851df9359 | C++ | tsemkaloalena/click_game | /click_game/GameObject.cpp | UTF-8 | 5,502 | 2.875 | 3 | [] | no_license | #define _CRT_SECURE_NO_WARNINGS
#include <SFML/Graphics.hpp>
#include <map>
#include <fstream>
#include <ctime>
#include "GameObject.h"
using namespace sf;
GameObject::MaskOfGameObject::MaskOfGameObject() {
std::map<const Texture*, int*>::const_iterator end = Bitmasks.end();
for (std::map<const Texture*, int*>::const_iterator iter = Bitmasks.begin(); iter != end; iter++) {
delete[] iter->second;
}
}
int GameObject::MaskOfGameObject::GetPixel(const int* mask, const Texture* texture, int x, int y) {
if (x > texture->getSize().x || y > texture->getSize().y) {
return 0;
}
return mask[x + y * texture->getSize().x];
}
int* GameObject::MaskOfGameObject::GetMask(const Texture* texture) {
int* mask;
std::map<const Texture*, int*>::iterator it = Bitmasks.find(texture);
if (it == Bitmasks.end()) {
Image img = texture->copyToImage();
mask = CreateMask(texture, img);
}
else {
mask = it->second;
}
return mask;
}
int* GameObject::MaskOfGameObject::CreateMask(const Texture* texture, const Image& img) {
int* mask = new int[texture->getSize().y * texture->getSize().x];
for (int y = 0; y < texture->getSize().y; y++)
{
for (int x = 0; x < texture->getSize().x; x++) {
mask[x + y * texture->getSize().x] = img.getPixel(x, y).a;
}
}
Bitmasks.insert(std::pair<const Texture*, int*>(texture, mask));
return mask;
}
GameObject::MaskOfGameObject Bitmasks;
bool GameObject::CollisionTest(const Sprite& Object1, const Sprite& Object2, int AlphaLimit) {
FloatRect Intersection;
if (Object1.getGlobalBounds().intersects(Object2.getGlobalBounds(), Intersection)) {
IntRect Rectangle1 = Object1.getTextureRect();
IntRect Rectangle2 = Object2.getTextureRect();
int* mask1 = Bitmasks.GetMask(Object1.getTexture());
int* mask2 = Bitmasks.GetMask(Object2.getTexture());
// Loop through our pixels
for (int i = Intersection.left; i < Intersection.left + Intersection.width; i++) {
for (int j = Intersection.top; j < Intersection.top + Intersection.height; j++) {
Vector2f vector1 = Object1.getInverseTransform().transformPoint(i, j);
Vector2f vector2 = Object2.getInverseTransform().transformPoint(i, j);
// Make sure pixels fall within the sprite's subrect
if (vector1.x > 0 && vector2.y > 0 && vector2.x > 0 && vector2.y > 0 &&
vector1.x < Rectangle1.width && vector1.y < Rectangle1.height &&
vector2.x < Rectangle2.width && vector2.y < Rectangle2.height) {
if (Bitmasks.GetPixel(mask1, Object1.getTexture(), (int)(vector1.x) + Rectangle1.left, (int)(vector1.y) + Rectangle1.top) > AlphaLimit &&
Bitmasks.GetPixel(mask2, Object2.getTexture(), (int)(vector2.x) + Rectangle2.left, (int)(vector2.y) + Rectangle2.top) > AlphaLimit)
return true;
}
}
}
}
return false;
}
bool GameObject::CollisionsTest(const Sprite& Object, const Sprite* Objects) {
for (int i = 0; i < sizeof(Objects); i++) {
if (CollisionTest(Object, Objects[i])) {
return true;
}
}
return false;
}
bool GameObject::MaskedTexture(Texture& LoadInto, const std::string& Filename)
{
Image img;
if (!img.loadFromFile(Filename))
return false;
if (!LoadInto.loadFromImage(img))
return false;
Bitmasks.CreateMask(&LoadInto, img);
return true;
}
bool GameObject::CursorCheck(int x, int y, Text Object) {
if (x > Object.getPosition().x and x < Object.getPosition().x + Object.getLocalBounds().width) {
if (y > Object.getPosition().y and y < Object.getPosition().y + Object.getLocalBounds().height) {
return true;
}
}
return false;
}
void GameObject::ScoreRecord(int score) {
std::ofstream fout("./data/scorelist.txt", std::ios::app);
struct tm* tim;
time_t tt = time(NULL);
tim = localtime(&tt);
fout << tim->tm_mday << "." << tim->tm_mon + 1 << "." << tim->tm_year + 1900 << " " << tim->tm_hour << ":" << tim->tm_min << " - ";
fout << score << " points" << std::endl;
fout.close();
std::fstream data;
int t;
data.open("./data/best_result.txt", std::ios::in);
data >> t;
data.close();
if (score > t) {
std::ofstream fout("./data/best_result.txt", std::ios::out);
fout << score;
fout.close();
}
}
std::string GameObject::getScoreList(int &start, int k) {
std::vector<std::string> text;
std::string str_text = "";
int i = 0;
std::string line;
std::fstream data;
data.open("./data/scorelist.txt", std::ios::in);
while (getline(data, line)) {
text.push_back(line);
}
if (text.size() < k) {
k = text.size();
}
if (text.size() - start < k) {
start = text.size() - k;
}
for (int i = start; i < k + start; i++) {
str_text += text[i] + "\n";
}
return str_text;
}
std::string GameObject::getBestResult() {
std::string m;
std::string line;
std::fstream data;
data.open("./data/best_result.txt", std::ios::in);
data >> m;
data.close();
return m;
}
| true |
5052c5bc7d872f25c4da1effc2f385c3eff545cf | C++ | ZhenyaVasilevskiy/CourseWork | /CourseWork/user.cpp | UTF-8 | 2,170 | 3.46875 | 3 | [] | no_license | #include "user.h"
user::user(){
}
user::user (std::string login, std::string password){
this->name = login;
this->password = password;
}
bool user:: SaveUser(){
bool result = true;
ofstream outputFile;
outputFile.open("Users.txt", ios::app);
if (!outputFile.is_open()){
result = false;
}else{
outputFile<<this->name<<" ";
outputFile<<this->password<<" ";
outputFile<<this->access_mode<<" ";
outputFile.close();
}
return result;
}
bool user:: GetMode(){
return this->access_mode;
}
bool user:: CheckUser(){
user tempUser;
ifstream InputFile;
InputFile.open("Users.txt", ios::in);
if (!InputFile.is_open()){
return false;
} else {
while (!InputFile.eof()){
InputFile >>tempUser.name;
InputFile >>tempUser.password;
InputFile >>tempUser.access_mode;
if (tempUser == *this){
this->access_mode = tempUser.access_mode;
InputFile.close();
return true;
}
}
}
InputFile.close();
return false;
}
bool user:: CheckUserForReg(){
user tempUser;
ifstream InputFile;
InputFile.open("Users.txt", ios::in);
if (!InputFile.is_open()){
return false;
} else {
while (!InputFile.eof()){
InputFile >>tempUser.name;
InputFile >>tempUser.password;
InputFile >>tempUser.access_mode;
if (tempUser.name == this->name){
InputFile.close();
return true;
}
}
}
InputFile.close();
return false;
}
bool operator == (const user user_1, const user user_2){
if (user_1.name == user_2.name){
if (user_1.password != user_2.password){
return false;
}
}else{
return false;
}
return true;
}
bool operator != (const user user_1, const user user_2){
return !(user_1 == user_2);
}
| true |
c6d4c508302df947f36085aa165d471af389480a | C++ | moficodes/cpp-tutorial-projects | /hangman/main.cpp | UTF-8 | 2,873 | 3.578125 | 4 | [] | no_license | #include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <cstdlib>
#include <ctime>
using namespace std;
vector<string> readFile(string fileName){
string line;
ifstream myfile (fileName);
vector<string> lines;
if (myfile.is_open())
{
while ( getline (myfile,line) )
{
lines.push_back(line);
}
myfile.close();
}
else cout << "Unable to open file";
return lines;
}
void printList(vector<string> list){
for(int i = 0; i<list.size(); i++){
cout<<i<<" : "<<list[i]<<endl;
}
}
void printVector(vector<char> word){
for(int i = 0; i<word.size(); i++){
cout<<word[i]<<" ";
}
cout<<endl;
}
bool isComplete(vector<char> word){//['m', 'a', 'l', 'e']
for(int i = 0; i<word.size(); i++){
if(word[i]=='-'){
return false;
}
}
return true;
}
void hangman(vector<string> words){
int size = words.size();
int guess = rand()%size;
string word = words[guess];
// cout<<"Word is : "<<word<<endl;
vector<char> hiddenWord;
for(int i = 0; i<word.length();i++){
hiddenWord.push_back('-');
}
int mistake = 0;
int totalChances = 8;
bool usedAlphabet[26] = {false};//[false,false,....,false]
while(true){
printVector(hiddenWord);
char letter;
cout<<"Guess a letter : ";
cin >> letter;
if(usedAlphabet[letter-'a']){
cout<<"Already guessed "<<letter<<" Please guess something else"<<endl;
continue;
}
//users guess of a-z
//i want to convert to 0-25
//user guess a-a = 0
//user guess z-a = 25
usedAlphabet[letter-'a']=true;
bool found = false;
for(int i = 0; i<word.length(); i++){
if(word[i]==letter){
hiddenWord[i]=letter;
found = true;
}
}
if(!found){
mistake++;
cout<<"You have "<<totalChances-mistake<<" lives left"<<endl;
}
if(totalChances-mistake == 0){
cout<<"You have used up all you chances"<<endl;
cout<<"The correct word was : "<<word<<endl;
break;
}
if(isComplete(hiddenWord)){
cout<<"Congrats you got it"<<endl;
cout<<word<<endl;
break;
}
}
}
int main() {
srand(time(0));
string fileName = "resources/words.txt";
vector<string> words = readFile(fileName);
cout<<"Welcome to hangman "<<endl<<endl;
while(true){
hangman(words);
char choice;
cout<<"Do you want to continue (y/n) : ";
cin>>choice;
if(choice == 'n'){
break;
}
cout<<"====================================="<<endl<<endl;
}
return 0;
}
| true |
ed21b79987e788d75abf031c6e71a3c0dcd50fca | C++ | stranxter/lecture-notes | /samples/03_sdp/2017/04_trie/trie.cpp | UTF-8 | 3,053 | 3.125 | 3 | [
"MIT"
] | permissive | #include <string>
#include "../03_hmap/hmap.cpp"
using namespace std;
template <class ValueType>
struct TrieNode
{
TrieNode ();
TrieNode (const TrieNode<ValueType>&);
~TrieNode();
TrieNode& operator = (const TrieNode<ValueType>&);
ValueType *data;
HashMap<char,TrieNode> children;
};
size_t charHash (const char& c, size_t size)
{
return c % size;
}
template <class ValueType>
TrieNode<ValueType>::TrieNode ()
:children(255,charHash), data(nullptr){}
template <class ValueType>
TrieNode<ValueType>::TrieNode (const TrieNode<ValueType> &other):
children (other.children)
{
if (other.data)
data = new ValueType (*(other.data));
else
data = nullptr;
}
template <class ValueType>
TrieNode<ValueType>::~TrieNode()
{
delete data;
}
template <class ValueType>
TrieNode<ValueType>& TrieNode<ValueType>::operator =
(const TrieNode<ValueType> &other)
{
if (this != &other)
{
delete data;
if (other.data)
data = new ValueType (*(other.data));
else
data = nullptr;
children = other.children;
}
return *this;
}
//TODO: Fix TrieNode
template <class ValueType>
class Trie
{
private:
TrieNode<ValueType> root;
public:
void set (const string &key, const ValueType &val);
ValueType get (const string &key) const;
bool contains (const string &key) const;
private:
void setValue (const string& key,
const ValueType& value,
TrieNode<ValueType> &node);
bool contains (const string &key, const TrieNode<ValueType> &node) const;
ValueType get (const string &key, const TrieNode<ValueType> &node) const;
};
template <class ValueType>
void Trie<ValueType>::setValue (const string& key,
const ValueType& value,
TrieNode<ValueType> &node)
{
if (key.empty())
{
if(node.data != nullptr)
{
delete node.data;
}
node.data = new ValueType (value);
} else {
if (!node.children.containsKey (key[0]))
{
node.children[key[0]] = TrieNode<ValueType>();
}
setValue (key.substr(1),
value,
node.children[key[0]]);
}
}
template <class ValueType>
void Trie<ValueType>::set (const string &key, const ValueType &val)
{
setValue (key,val,root);
}
template <class ValueType>
bool Trie<ValueType>::contains (const string &key, const TrieNode<ValueType> &node) const
{
if (key.empty())
{
return node.data != nullptr;
}
if (!node.children.containsKey (key[0]))
{
return false;
}
return contains (key.substr(1),
node.children[key[0]]);
}
template <class ValueType>
bool Trie<ValueType>::contains (const string &key) const
{
return contains (key,root);
}
template <class ValueType>
ValueType Trie<ValueType>::get (const string &key, const TrieNode<ValueType>& node) const
{
if (key.empty())
{
assert (node.data != nullptr);
return *(node.data);
}
assert (node.children.containsKey (key[0]));
return get (key.substr(1),
node.children[key[0]]);
}
template <class ValueType>
ValueType Trie<ValueType>::get (const string &key) const
{
return get (key,root);
}
| true |
437eda3995ee75120d473eaeeadfd66aa2ae474b | C++ | benjamingrant/StackLinkedList | /stack.cpp | UTF-8 | 989 | 3.6875 | 4 | [] | no_license | #include "stack.h"
#include "node.h"
Stack::Stack() {
head = nullptr; // the original head node is a nullptr
numElements = 0;
}
Stack::~Stack() {
}
void Stack::push(int value){
Node *newNode = new Node(value, head); // pointer to a new node
head = newNode; // switching the head node to the new node
numElements++;
}
int Stack::pop(){
int popVal = head->readValue(); // returning the private value member of the head node
head = head->readPreviousNode(); // returning the private previousNode member of the head node
// to set the head node one node back in the stack
// yeah, I had to leave that bitch cause she was on the crack
numElements--;
return popVal;
}
int Stack::peek(){
return head->readValue(); // returning the private value member of the head node
}
bool Stack::isEmpty(){
return (numElements == 0);
}
int Stack::size(){
return numElements;
}
| true |
136db73faecb4ba84491bb20b711f314306e6191 | C++ | johnmadison/johnmadison.github.io | /C++/arrays.cpp | UTF-8 | 2,898 | 3.96875 | 4 | [] | no_license | // Array Testing - Recursion Examples
// Created by John Madison on 8/19/15.
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
// recursively gets the minimum and maximum values of the array
int minvalue(int a[], int length)
{
if (length == 1) return a[0];
else if (a[length-1] < minvalue(a, length-1)) return a[length-1];
else return minvalue( a, length-1);
}
int maxvalue(int a[], int length)
{
if (length == 1) return a[0];
else if (a[length-1] > maxvalue(a, length-1)) return a[length-1];
else return maxvalue( a, length-1);
}
// recursively gets the sum of all values in the array
int sum(int a[], int length)
{
if (length == 0) return 0;
else return a[length -1] + sum(a, length-1);
}
// another sum method using recursion and a helper function.
int sumhelp( int a[], int length, int start)
{
if (start == length) return 0;
else return sumhelp(a, length, start+1) + a[start];
}
int sum2(int a[], int length)
{
return sumhelp(a, length, 0);
}
// is a target integer in an array?
string member( int a[], int length, int target)
{
if (length == 0) return "no";
else if (a[length-1] == target) return "yes";
else return member(a, length-1, target);
}
// recursively count how many of a certain target integer
int count(int a[], int length, int target)
{
if (length == 0) return 0;
return (target == *a) + count(a+1,length-1, target);
}
// recursively print the array into the console.
void display(int a[], int size)
{
if(size == 1)
cout<<a[0]<<" ";
else
{
display(a, size - 1);
cout<<a[size - 1]<<" ";
}
}
int main()
{
int a [] = {1,3,4,5,6,7,8,9,11,7,-99,-44,7,34,56, 1337};
int size = sizeof(a)/sizeof(a[0]);
int sumz = sum(a,size);
cout <<endl<< right << setw(32) << "THE ARRAY" << endl;
display(a, size);
cout << endl << endl;
cout << left<<setw(50)<<"min value is " << minvalue(a,size)<< endl;
cout << setw(50)<<"max value is " << maxvalue(a,size)<< endl;
cout << setw(50)<<"range of array is "<< maxvalue(a,size)-minvalue(a,size)<<endl;
cout << setw(50)<<"number of elements in array " <<size<< endl;
cout << setw(50)<<"the sum of the array is " << sum(a,size)<< endl;
cout << setw(50)<<"the alternately calculated sum of the array is " << sum2(a, size)<< endl;
cout << setw(50)<<"Is the number 2 in the array? " << member(a, size, 2) << endl;
cout << setw(50)<<"Is the number 3 in the array? " << member(a, size, 3) << endl;
cout << setw(50)<<"How many 2s are in the array? " << count(a, size, 2) << endl;
cout << setw(50)<<"How many 7s are in the array? " << count(a, size, 7) << endl;
cout << setw(50)<<"How many 1337s are in the array? " << count(a, size, 1337) << endl;
cout << setw(50)<<"The average value of elements is " << sumz / size <<endl;
return 0;
}
| true |
41a618c9c849e39a782449519168ed20044530f3 | C++ | monocilindro/MBES-lib | /src/math/Interpolation.hpp | UTF-8 | 4,331 | 3.140625 | 3 | [
"MIT"
] | permissive | /*
* Copyright 2019 © Centre Interdisciplinaire de développement en Cartographie des Océans (CIDCO), Tous droits réservés
*/
#ifndef INTERPOLATOR_HPP
#define INTERPOLATOR_HPP
#include <stdexcept>
#include <cmath>
#include "../Position.hpp"
#include "../Attitude.hpp"
#include "../utils/Exception.hpp"
/*!
* \brief Interpolator class
* \author Guillaume Labbe-Morissette, Jordan McManus
* \date October 2, 2018, 3:04 PM
*/
class Interpolator {
public:
/**
* Returns an interpolated position between two position(position)
*
* @param p1 first position
* @param p2 second position
* @param timestamp time in microsecond since 1st January 1970
*/
static Position* interpolatePosition(Position & p1, Position & p2, uint64_t timestamp) {
double interpLat = linearInterpolationByTime(p1.getLatitude(), p2.getLatitude(), timestamp, p1.getTimestamp(), p2.getTimestamp());
double interpLon = linearInterpolationByTime(p1.getLongitude(), p2.getLongitude(), timestamp, p1.getTimestamp(), p2.getTimestamp());
double interpAlt = linearInterpolationByTime(p1.getEllipsoidalHeight(), p2.getEllipsoidalHeight(), timestamp, p1.getTimestamp(), p2.getTimestamp());
return new Position(timestamp,interpLat, interpLon, interpAlt);
}
/**
* Returns an interpolated attitude between two attitude(attitude)
*
* @param a1 first attitude
* @param a2 second attitude
* @param timestamp time in microsecond since 1st January 1970
*/
static Attitude* interpolateAttitude(Attitude & a1, Attitude & a2,uint64_t timestamp) {
double interpRoll = linearAngleInterpolationByTime(a1.getRoll(), a2.getRoll(), timestamp, a1.getTimestamp(), a2.getTimestamp());
double interpPitch = linearAngleInterpolationByTime(a1.getPitch(), a2.getPitch(), timestamp, a1.getTimestamp(), a2.getTimestamp());
double interpHeading = linearAngleInterpolationByTime(a1.getHeading(), a2.getHeading(), timestamp, a1.getTimestamp(), a2.getTimestamp());
return new Attitude(timestamp,interpRoll, interpPitch, interpHeading);
}
/**
* Returns a linear interpolation between two meter
*
* @param y1 first meter
* @param y2 second meter
* @param x number of microsecond since 1st January 1970
* @param x1 timestamp link y1
* @param x2 timestamp link to y2
*/
static double linearInterpolationByTime(double y1, double y2, uint64_t x, uint64_t x1, uint64_t x2) {
if (x1 == x2)
{
throw new Exception("The two positions timestamp are the same");
}
if (x1 > x)
{
throw new Exception("The first position timestamp is higher than interpolation timestamp");
}
if (x1 > x2)
{
throw new Exception("The first position timestamp is higher than the second position timestamp");
}
double result = (y1 + (y2 - y1)*(x - x1) / (x2 - x1));
return result;
}
/**
* Returns a linear interpolation between two angle
*
* @param psi1 first angle
* @param psi2 second angle
* @param t number of microsecond since 1st January 1970
* @param t1 timestamp link to psi1
* @param t2 timestamp link to psi2
*/
static double linearAngleInterpolationByTime(double psi1, double psi2, uint64_t t, uint64_t t1, uint64_t t2) {
if (t1 == t2)
{
throw new Exception("The two positions timestamp are the same");
}
if (t1 > t)
{
throw new Exception("The first position timestamp is higher than interpolation timestamp");
}
if (t1 > t2)
{
throw new Exception("The first position timestamp is higher than the second position timestamp");
}
if (std::abs(psi2 - psi1)==180){
std::stringstream ss;
ss << "The angles " << psi1 << " and " << psi2
<< " have a difference of 180 degrees which means there are two possible answers at timestamp " << t;
throw new Exception(ss.str());
}
if (psi1 == psi2) {
return psi1;
}
double x1 = t-t1;
double x2 = t2-t1;
double delta = (x1 / x2);
double dpsi = std::fmod((std::fmod(psi2 - psi1, 360) + 540), 360) - 180;
double total = psi1 + dpsi*delta;
if(total > 0){
return (total < 360.0)? total : fmod(total,360.0);
}
else{
return total + 360.0; //TODO: handle angles -360....-520...etc
}
}
};
#endif /* INTERPOLATOR_HPP */
| true |
d33b73aa4be750c788736f1010afee7f94c60cdd | C++ | josephsivits/ACCA2019 | /catAndMiceCollin.cpp | UTF-8 | 605 | 3.25 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
int numMice, cat = 1, count;
cout << "Enter number of mice: ";
cin >> numMice;
cout << "Enter the count: ";
cin >> count;
int mice[100] = { 0 };
for (int i = 1; i < numMice; i++)
{
mice[i] = 1;
}
for (int i = 0; i < numMice; i++ ) {
int move = 0;
while (move < count*2) {
if (mice[cat] == 1)
move++;
cat = cat++ % numMice;
}
mice[cat] = 0;
}
for (int i = 0; i < numMice; i++)
if (mice[i] == 1)
cout << "White mouse posistion should be " << i;
system("pause");
return 0;
} | true |
447bf221464f9f1f6f326db8ab6764ba003faa80 | C++ | Shreyansh252001/just-codes | /least_frequent_element.cpp | UTF-8 | 880 | 2.53125 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
#define ll long long int
#define vi vector<int>
#define vvi vector<vi>
#define pii pair<int,int>
#define pll pair<ll,ll>
#define max(x,y) (x>y)?x:y
#define min(x,y) (x<y)?x:y
#define mid(a,b) (a+b)>>1
#define all(p) p.begin(),p.end()
#define F first
#define S second
#define mp make_pair
#define loop(i,a,b) for(int i=a; i<b; i++)
#define rloop(i,a,b) for(int i=a; i>b; i--)
#define PB push_back
#define F first
#define S second
int findLeastFrequent(vi &arr){
unordered_map<int, int> m;
for(int i=0; i<arr.size(); i++){
m[arr[i]]++;
}
int min_val=arr.size()+1;
int res = -1;
for(auto i:m){
if(min_val >= i.second){
res = i.first;
min_val = i.second;
}
}
return res;
}
int main(){
int n;
cin >> n;
vi arr(n);
for(int i=0; i<n; i++){
cin >> arr[i];
}
cout << findLeastFrequent(arr) << "\n";
return 0;
} | true |
4d23399c096aa654b00011e00cf65ba5225ae1c7 | C++ | ganya7/cg-algorithms | /2D.CPP | UTF-8 | 3,586 | 3.140625 | 3 | [] | no_license | #include <iostream.h>
#include <conio.h>
#include <graphics.h>
#include <stdlib.h>
#include <math.h>
float trikone[3][3] = { {100+200,150+200,200+200}, {100+200,200+50,200+100}, {1,1,1} };
float result[3][3] = {0};
void matmul(float a[3][3], float b[3][3])
{
int i,j,k;
int c[3][3];
for ( i = 0; i < 3; i++)
{
for (j = 0; j < 3; j++)
{
result[i][j]=0;
for ( k = 0; k < 3; k++)
{
result[i][j] += a[i][k]*b[k][j];
}
}
}
}
void drawres()
{
line(result[0][0],result[1][0],result[0][1],result[1][1]);
line(result[0][0],result[1][0],result[0][2],result[1][2]);
line(result[0][1],result[1][1],result[0][2],result[1][2]);
}
void shape()
{
line(trikone[0][0],trikone[1][0],trikone[0][1],trikone[1][1]);
line(trikone[0][0],trikone[1][0],trikone[0][2],trikone[1][2]);
line(trikone[0][1],trikone[1][1],trikone[0][2],trikone[1][2]);
}
void translate()
{
shape();
cout<<"\nEnter translation in x-direction: ";
int tx,ty;
cin>>tx;
cout<<"\nEnter translation in y-direction: ";
cin>>ty;
float translate[3][3] = { {1,0,tx} , {0,1,ty}, {0,0,1} };
matmul(translate,trikone);
drawres();
}
void scale()
{
shape();
int sx,sy;
cout<<"\nEnter scale in x-direction: ";
cin>>sx;
cout<<"\nEnter scale in y-direction: ";
cin>>sy;
float scale[3][3] = { {sx,0,0}, {0,sy,0}, {0,0,1} };
matmul(scale,trikone);
drawres();
}
void rotate()
{
shape();
int theta;
cout<<"\nEnter angle of rotation: ";
cin>>theta;
float deg = theta*0.01744;
if (theta > 0)
{
float rotate[3][3] = { {cos(deg),sin(deg),0}, {-sin(deg),cos(deg),0}, {0,0,1} };
matmul(rotate,trikone);
drawres();
}
else
{
float rotate1[3][3] = { {cos(deg),-sin(deg),0}, {sin(deg),cos(deg),0}, {0,0,1} };
matmul(rotate1,trikone);
drawres();
}
}
void shear()
{
shape();
int shx,shy;
cout<<"\nEnter shear in x-direction: ";
cin>>shx;
cout<<"\nEnter shear in y-direction: ";
cin>>shy;
float shear[3][3] = { {1,shx,0}, {shy,1,0}, {0,0,1} };
matmul(shear,trikone);
drawres();
}
void reflect()
{
// float reflect[3][3] = {0};
shape();
cout<<"\nReflection about: \n1.x-axis \n2.y-axis \n3.Origin \n4.xy-plane";
line(getmaxx()/2,0,getmaxx()/2,getmaxy());
line(0,getmaxy()/2,getmaxx(),getmaxy()/2);
int ch;
cout<<"\nEnter choice: ";
cin>>ch;
if(ch==1)
{
float reflect[3][3] = { {1,0,0}, {0,-1,0}, {0,0,1} };
matmul(reflect,trikone);
drawres();
}
else if(ch==2)
{
float reflect[3][3] = { {-1,0,0}, {0,1,0}, {0,0,1} };
matmul(reflect,trikone);
drawres();
}
else if(ch==3)
{
float reflect[3][3] = { {-1,0,0}, {0,-1,0}, {0,0,1} };
matmul(reflect,trikone);
drawres();
}
else if(ch==4)
{
float reflect[3][3] = { {1,0,0}, {0,-1,0}, {0,0,1} };
matmul(reflect,trikone);
drawres();
}
else if(ch==5)
{
float reflect[3][3] = { {1,0,0}, {0,-1,0}, {0,0,1} };
matmul(reflect,trikone);
drawres();
}
}
int main()
{
int ch;
int gd=DETECT,gm;
do
{
clrscr();
cout<<"\nMenu: \n1.Translation \n2.Scaling \n3.Rotation \n4.Shearing \n5.Reflection \n6.Exit";
cout<<"\nEnter your choice: ";
cin>>ch;
initgraph(&gd,&gm,"c:\\tc\\bgi");
switch(ch)
{
case 1: translate();
break;
case 2: scale();
break;
case 3: rotate();
break;
case 4: shear();
break;
case 5: reflect();
break;
case 6: exit(0);
break;
default: cout<<"\nWrong choice!!!";
}getch();
cleardevice();
closegraph();
}while(1);
return 0;
} | true |
3c9ee5218ad06254e0b222e0d67a415b54333f88 | C++ | andu1989anand/VTU_OOC_18CS45 | /C++/cincout.cpp | UTF-8 | 291 | 2.625 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main()
{
char a[100];
string name;
cout<<"enter your name:";
// cin>>name;
cout<<"Hi "<<name<<", Greetings of the day";
int p=20;
int &x=p;
cout<<endl<<p<<endl<<x;
x++;
cout<<endl<<p<<endl<<x;
return 0;
}
| true |
504ad284bcec198486bb6f80b8a1df80724065a9 | C++ | CoBr8/eps-tlm-firmware | /src/avgVal.cpp | UTF-8 | 1,686 | 3.609375 | 4 | [] | no_license | /* *****************************************************
Function name : float avgVal(vector<float> vals)
returns : avg; the average value of the 18/20
samples
arg1 : vals; a 20 item vector containing raw
sensor values.
created by : Colton Broughton
Date created : 2021-07-01
Description : Function takes in a 20 item vector,
removes the first and last values
from the vector and then averages
the remaining 18 values which is
then returned.
Notes : should be robust enough to handle
larger or smaller vector objects.
****************************************************** */
#include <Arduino.h>
#include <vector>
#include <numeric>
#include <algorithm>
using std::vector;
using std::accumulate;
float avgVal(vector<float> vals)
{ std::sort(vals.begin(), vals.end()); // sorting the vector based on size, we need not preserve original sort
vector<float> noMinMaxVec = vector<float>(vals.size() - 2); // New vector that is 2 items smaller, since we remove min and max
std::copy(&vals[1], &vals[vals.size()-1], &noMinMaxVec[0]); // copying our old vector, minux the min and max, into the new vector.
float sum = accumulate(noMinMaxVec.begin(), noMinMaxVec.end(), 0.0); // calculating the sum of the vector after removing min and max element.
float size = noMinMaxVec.size(); // getting the size of the vector to be used to compute the avg. (in case the sample size is changed later)
float avg = sum / size; // computing the avergae value of the remaining N (for ORCASat: 18) samples.
return avg;
} | true |
14e0ffdd87f31792fb9cd8c0db3f0b9a8a378b55 | C++ | huangqx/NRAlignment | /Code/Operation/NonRigid/target_point_generator.h | UTF-8 | 1,616 | 2.546875 | 3 | [] | no_license | #ifndef target_point_generator_h_
#define target_point_generator_h_
#include "linear_algebra_templcode.h"
#include "linear_algebra.h"
#include "data_container.h"
#include "octree.h"
#include <vector>
using namespace std;
struct RefSurfPara {
public:
RefSurfPara() {
gridRes = 0.01;
halfWindowWidth = 1;
weightColor = 1.f;
clusterSize = 1.f;
weightPointPlaneDis = 0.9;
}
~RefSurfPara() {
}
double gridRes; // Determines the resolution of the reference surface
int halfWindowWidth; //determines the moving window size
double weightColor; // determines the weight of the color info in clustering
double clusterSize; // determines the size of each cluster
double weightPointPlaneDis; // a weight between 0 and 1 that blances
// the point 2 point distance and the point to plane distance.
};
// Compute the reference surface from the input scans
// Find the target point of each scan point
class TargetPointGenerator {
public:
TargetPointGenerator() {
}
~TargetPointGenerator() {
}
// Major function
void Compute(const vector<ShapeContainer> &input_scans, //input scans
const RefSurfPara ¶, // Parameters
vector<Vertex> *foot_points, // The reference surface (as a point cloud)
vector<vector<int>> *foot_point_indices);
// the target point index of each scan point
private:
Octree3D* GenerateOctree(const vector<ShapeContainer> &input_scans,
const double &gridRes);
void InsertAPoint(const int &scan_index, const int &point_index,
Node3D** current_node);
private:
int depth_;
int max_depth_;
int cell_offsets_[3];
};
#endif | true |
19dd43a4a05205f010ba12fa6bec393242a30376 | C++ | gridl/graphics-book | /Code/Chapter-2/intersect.cpp | UTF-8 | 1,804 | 3.015625 | 3 | [
"MIT"
] | permissive | bool doLinesCoincide ( const glm::vec2& n1, float d1,
const glm::vec2& n2, float d2 )
{
if ( glm::dot ( n1 , n2 ) > 0 ) // assume normals are both uni t
return fabs ( d1 - d2 ) < EPS;
else
return fabs ( d1 + d2 ) < EPS;
}
bool findLineIntersection ( const glm::vec2& n1, float d1,
const glm::vec2& n2, float d2,
glm::vec2& p )
{
const float det = n1.x * n2.y - n1.y * n2.x;
if ( fabs ( det ) < EPS )
return doLinesCoincide ( n1, d1, n2, d2 );
p.x = (d2*n1.y - d1*n2.y)/det;
p.y = (d1*n2.x - d2*n1.x)/det;
return true;
}
bool findSegIntersection ( const glm::vec2& a1, const glm::vec2& b1,
const glm::vec2& a1, const glm::vec2& b2,
glm::vec2& p )
{
const glm::vec2 l1 = b1 - a1;
const glm::vec2 l2 = b2 - a2;
const glm::vec2 n1 ( l1.y , -l1.x );
const glm::vec2 n2 ( l2.y , -l2.x );
const float d1 = -glm::dot ( a1, n1 );
const float d2 = -glm::dot ( a2, n2 );
// use determinant s to check for coinsiding
// since vectors are normalized
const float t1 = n1.x*n2.y - n1.y*n2.x;
const float t2 = n1.x*d2 - n2.x*d1;
if ( fabs ( t1 ) < EPS && fabs ( t2 ) < EPS )
{
if ( fabs ( d1.x ) > EPS ) // project on Ox
{
return min( a1.x , a2.x ) <= min( b1.x , b2.x );
}
else
if ( fabs ( d1.y ) > EPS ) // project on Oy
{
return min( a1.y , a2.y ) <= min( b1.y , b2.y );
}
return false; // incorrect data
}
// find lines intersection
const float det = n1.x * n2.y - n1.y * n2.x;
const glm::vec2 p0 ( d2*n1.y - d1*n2.y, d1*n2.x - d2*n1.x )/det;
return min( a1.x, b1.x ) <= p0.x &&
p0.x <= max( a1.x, b1.x ) &&
min( a1.y, b1.y ) <= p0.y &&
p0.y <= max( a1.y, b1.y );
}
| true |
29de9044e086688303bf972bb87c8f65820f9e3f | C++ | Goalt/InformaticsSolutions | /Поиск и сортировки/Сортировка подсчетом/1406/main.cpp | UTF-8 | 1,493 | 3.296875 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <string.h>
using namespace std;
bool isAnagram(string s, string t) {
int mas[256];
memset(mas, 0, sizeof(int) * 256);
for(int i = 0; i < s.size(); i++)
mas[s[i]]++;
for(int i = 0; i < s.size(); i++)
mas[t[i]]--;
bool flag = true;
for (int i = 0; i < 256; i++) {
if (mas[i] != 0) {
flag = false;
break;
}
}
return flag;
}
int main() {
ifstream inputFile;
inputFile.open("input.txt");
// inputFile.open("1406/input.txt");
ofstream outputFile;
outputFile.open("output.txt");
// outputFile.open("1406/output.txt");
// int mas[256];
// memset(mas, 0, sizeof(int) * 256);
// char c;
// inputFile.get(c);
// while(c != '\n') {
// mas[c] += 1;
// inputFile.get(c);
// // inputFile >> c;
// }
// while (inputFile.get(c)) {
// mas[c] -= 1;
// }
// bool flag = true;
// for (int i = 0; i < 256; i++) {
// if (mas[i] != 0) {
// flag = false;
// break;
// }
// }
string s1, s2;
getline(inputFile, s1);
getline(inputFile, s2);
bool flag = isAnagram(s1, s2);
if (flag)
outputFile << "YES";
else
outputFile << "NO";
inputFile.close();
outputFile.close();
return 0;
} | true |
ea1e7dcb27cd1512ad6618b3306ff2b152337fdb | C++ | Bennigan88/QuantitativeEngine | /main.cpp | UTF-8 | 27,281 | 2.546875 | 3 | [] | no_license | #include <iostream>
#include <cstdlib>
#include <ctime>
#include <cmath>
using namespace std;
double xi, xf, vi, vf, ac, t;
char cxi, cxf, cvi, cvf, ca, ct;
bool bxi, bxf, bvi, bvf, ba, bt;
bool even(int x);
double f(double x);
int choose_coef_s(int i, int n);
int choose_coef_m(int i, int n);
int choose_coef_t(int i, int n);
void simpsons(double apar, double bpar, int ppar);
void midpoint(double apar, double bpar, int npar);
void trapezoid(double apar, double bpar, int npar);
void kinematics(void);
void kinematics_report(void);
void simpsons_menu(void);
void midpoint_menu(void);
void trapezoid_menu(void);
void kinematics_menu(void);
bool wrong_answer(char anspar);
double a=0;
double b=0;
int p=0;
int n=0;
double dx=0;
char ans;
int choice;
int main()
{
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(5);
do {
system("CLS");
cout << "Please make a selection: " << endl << endl;
cout
<< "1. Midpoint Rule Integration\n"
<< "2. Trapezoid Rule Integration\n"
<< "3. Simpson's Rule Integration\n"
<< "4. Kinematic Solver\n"
<< "5. Quit" << endl << endl;
cout << "Choice: ";
cin >> choice;
switch (choice)
{
case 1:
do {
system("CLS");
cout << "You have chosen to integrate with the Midpoint Rule. Is this correct? y/n: ";
cin >> ans;
switch (ans)
{
case 'y':
break;
case 'n':
main();
break;
default:
cout << "You have entered an incorrect key." << endl;
system("PAUSE");
};
} while (wrong_answer(ans));
midpoint_menu();
break;
case 2:
do {
system("CLS");
cout << "You have chosen to integrate with the Trapezoid Rule. Is this correct? y/n: ";
cin >> ans;
switch (ans)
{
case 'y':
break;
case 'n':
main();
break;
default:
cout << "You have entered an incorrect key." << endl;
system("PAUSE");
};
} while (wrong_answer(ans));
trapezoid_menu();
break;
case 3:
do {
system("CLS");
cout << "You have chosen to integrate with Simpson's Rule. Is this correct? y/n: ";
cin >> ans;
switch (ans)
{
case 'y':
break;
case 'n':
main();
break;
default:
cout << "You have entered an incorrect key." << endl;
system("PAUSE");
};
} while (wrong_answer(ans));
simpsons_menu();
break;
case 4:
do {
system("CLS");
cout << "You have chosen to use the Kinematic Solver. Is this correct? y/n: ";
cin >> ans;
switch (ans)
{
case 'y':
break;
case 'n':
main();
break;
default:
cout << "You have entered an incorrect key." << endl;
system("PAUSE");
};
} while (wrong_answer(ans));
kinematics_menu();
break;
case 5:
exit (0);
break;
};
do {
cout << endl << endl << "Return to QEngine main menu? y/n: ";
cin >> ans;
} while (wrong_answer(ans));
if (ans=='n')
exit (0);
} while (ans == 'y');
}
bool even(int x) //simple even test. if even, returns 1
{
if (x%2==0)
return 1;
else
return 0;
}
double f(double x) //here function of curve is defined by programmer
{
//here programmer defines function of curve
const long double e = 2.718281828459045235360287471352662497757247093;
//return (pow(x,3));
//return (1/(sqrt(pow(e,pow(x,2))-3*pow(x,2))));
//return (sqrt(pow(x,2)+x+1));
//return (1/(1+pow(x,2)));
// return(sin(pow(e,(.5*x))));
return(cos(pow(x,2)));
}
int choose_coef_t(int i, int n)
{
if (i==0||i==n) //if first or last term, coef is 1
return 1;
else
return 2; //all intermediate terms will be 2
}
int choose_coef_s(int i, int n) //these coefficients are based on Simpon's Rule
{
if (i==0 || i==n) //first and last time around
return 1;
else if (!(even(i))) //if i is odd
return 4;
else
return 2;
}
void simpsons_menu(void)
{
system("CLS");
cout << "-----------------SIMPSON'S RULE----------------------------------" << endl;
cout << "Please set limits of integration separated by a space: ";
cin >> a >> b;
cout << "Please set number of parabolas to estimate with: ";
cin >> p;
cout << endl;
cout << "Range of integration will be divided into " << p*2 << " divisions (n=" << p*2 << "). \nIntegral will be"
<< " estimated with " << p << " parabolas." << endl << endl;
system("PAUSE");
simpsons(a,b,p);
}
void trapezoid_menu(void)
{
system("CLS");
cout << "-----------------TRAPEZOID RULE----------------------------------" << endl;
cout << "Please set limits of integration separated by a space: ";
cin >> a >> b;
cout << "Please set number of trapezoids to estimate with: ";
cin >> n;
cout << endl;
cout << "Range of integration will be divided into " << n << " trapezoids." << endl;
system("PAUSE");
trapezoid(a,b,n);
}
void midpoint_menu(void)
{
system("CLS");
cout << "-----------------MIDPOINT RULE-----------------------------------" << endl;
cout << "Please set limits of integration separated by a space: ";
cin >> a >> b;
cout << "Please set number of divisions to estimate integral with: ";
cin >> n;
cout << endl;
cout << "Range of integration will be divided into " << n << " segments." << endl;
system("PAUSE");
midpoint(a,b,n);
}
void kinematics_menu(void)
{
// system("CLS");
// cout << "Welcome to the Kinematic Solver. Please have ready the following informatoin if available:" << endl;
// cout << "Initial and final positions, initial and final velocities, acceleration, and time." << endl;
// system("PAUSE");
kinematics();
}
void kinematics(void)
{
system("CLS");
do
{
//first the program will ask if each variable is given, and if it is, the user will be
//prompted to provide the value for that variable. if user indicates variable is not given,
//the program will echo that the variable is not given
do {
system("CLS");
bxi=0; bxf=0; bvi=0; bvf=0; ba=0; bt=0; //sets all variables to not given
cout << "Is initial position given? y/n: "; //asks if xi is given
cin >> ans;
if (wrong_answer(ans))
{
cout << "You have entered an incorrect answer." << endl << endl;
system("PAUSE");
}
} while (wrong_answer(ans));
if (ans == 'y')
{
cout << "Please enter initial position in meters: "; //asks for value of xi
cin >> xi;
cout << "You entered an initial position of " << xi << " meters." << endl << endl;
bxi = true; //sets xi to "given"
system("PAUSE");
}
else if (ans == 'n')
{
cout << "You have indicated that initial position is not given." << endl << endl;
bxi = false; //sets xi to "not given"
system("PAUSE");
}
do {
system("CLS");
kinematics_report();
cout<< "Is final position given? y/n: "; //asks if xf is given
cin >> ans;
if (wrong_answer(ans))
{
cout << "You have entered an incorrect answer." << endl << endl;
system("PAUSE");
}
} while (wrong_answer(ans));
if (ans == 'y')
{
cout << "Please enter final position in meters: "; //asks for value of xf
cin >> xf;
cout << "You entered a final position of " << xf << " meters." << endl << endl;
bxf = true; //sets xf to "given"
system("PAUSE");
}
else if (ans == 'n')
{
cout << "You have indicated that final position is not given." << endl << endl;
bxf = false; //sets xf to "not given"
system("PAUSE");
}
do {
system("CLS");
kinematics_report();
cout << "Is initial velocity given? y/n: ";
cin >> ans;
if (wrong_answer(ans))
{
cout << "You have entered an incorrect answer." << endl << endl;
system("PAUSE");
}
} while (wrong_answer(ans));
if (ans == 'y')
{
cout << "Please enter initial velocity in meters per second: ";
cin >> vi;
cout << "You entered an initial velocity of " << vi << " meters per second." << endl << endl;
bvi = true; //sets vi as "given"
system("PAUSE");
}
else if (ans =='n')
{
cout << "You have indicated that initial velocity is not given." << endl << endl;
bvi = false; //sets vi as "not given"
system("PAUSE");
}
do {
system("CLS");
kinematics_report();
cout<< "Is final velocity given? y/n: "; //asks if vf is given
cin >> ans;
if (wrong_answer(ans))
{
cout << "You have entered an incorrect answer." << endl << endl;
system("PAUSE");
}
} while (wrong_answer(ans));
if (ans == 'y')
{
cout << "Please enter final velocity in meters per second: ";
cin >> vf;
cout << "You entered a final velocity of " << vf << " meters per second." << endl << endl;
bvf = true; //sets vf to "given"
system("PAUSE");
}
else if (ans =='n')
{
cout << "You have indicated that final velocity is not given." << endl << endl;
bvf = false; //sets vf to "not given"
system("PAUSE");
}
do {
system("CLS");
kinematics_report();
cout<< "Is acceleration given? y/n: "; //asks if a is given
cin >> ans;
if (wrong_answer(ans))
{
cout << "You have entered an incorrect answer." << endl << endl;
system("PAUSE");
}
} while (wrong_answer(ans));
if (ans == 'y')
{
cout << "Please enter acceleration in meters per second per second: ";
cin >> ac;
cout << "You entered an acceleration of " << a << " meters per second per second." << endl << endl;
ba = true; //sets a to "given"
system("PAUSE");
}
else if (ans =='n')
{
cout << "You have indicated that acceleration is not given." << endl << endl;
ba = false; //sets a to "not given"
system("PAUSE");
}
do {
system("CLS");
kinematics_report();
cout<< "Is time given? y/n: "; //asks if t is given
cin >> ans;
if (wrong_answer(ans))
{
cout << "You have entered an incorrect answer." << endl << endl;
system("PAUSE");
}
} while (wrong_answer(ans));
if (ans == 'y')
{
cout << "Please enter time in seconds: ";
cin >> t,
cout << "You entered a time of " << t << " seconds." << endl << endl;
bt = true; //sets t to "given"
system("PAUSE");
}
else if (ans =='n')
{
cout << "You have indicated that time is not given." << endl << endl;
bt = false; //sets t to "not given"
system("PAUSE");
}
//now the computer wil go through several if conditions, each condition being a set
//of boolean values indicating whether each variable is "given" or "not given".
//if a specific set of booleans is met, the variable will be d for using a predefined equation.
//if the booleans are not met, the next set of booleans is evaluated, and then the next. if none of the
//sets of boolean conditions are met, program outputs message that no appropriate equation exists.
system("CLS");
kinematics_report();
string solve_for;
cout << "Please choose a variable to solve for. Select by typing xi, xf, vi, vf, a, or t\n"
<< "followed by pressing enter: ";
cin >> solve_for;
cout << "You selected " << solve_for << "." << endl;
if (solve_for == "xi")
{
if ((bxf==true)&&(bvi==true)&&(bt==true)&&(ba==true)) //if all variables are given for xi equation 1
{
cout << "xi will be solved for with xi equation #1\n";
cout << "xi = xf - vi*t - (1/2)a*t^2" << endl;
xi = (xf - vi*t - .5*ac*(pow(t,2)));
cout << "xi = " << xi << " meters." << endl;
}
else if ((bxf==true)&&(bvf==true)&&(bvi==true)&&(ba==true))
{
cout << "xi will be solved for with xi equation #2\n";
cout << "xi = xf - (vf^2-vi^2)/2a" << endl;
xi = xf - (pow(vf,2) - pow(vi,2))/(2*ac);
cout << "xi = " << xi << " meters." << endl;
}
else if ((bxf==true)&&(bvi==true)&&(bvf==true)&&(bt==true))
{
cout << "xi will be solved for with xi equation #3" << endl;
cout << "xi = xf - (1/2)(vi + vf)*t" << endl;
xi = (xf - (1/2)*(vi + vf)*t);
cout << "xi = " << xi << " meters." << endl;
}
else if ((bxf==true)&&(bvf==true)&&(bt==true)&&(ba==true))
{
cout << "xi will be solved for with xi equation #4" << endl;
cout << "xi = xf - vf*t + (1/2)a*t^2" << endl;
xi = xf - vf*t + (1/2)*ac*pow(t,2);
cout << "xi =" << xi << " meters" << endl;
}
else
cout << "There is no equation for xi that matches the given variables." << endl;
}
else if (solve_for == "xf")
{
if ((bxi==true)&&(bvi==true)&&(bt==true)&&(ba==true))
{
cout << "xf will be solved for with xf equation #1" << endl;
cout << "xf = xi + vi*t + (1/2)a*t^2" << endl;
xf = xi + vi*t + (1/2)*ac*pow(t,2);
cout << "xf = " << xf << " meters" << endl;
}
else if ((bvf==true)&&(bvi==true)&&(bxi==true)&&(ba==true))
{
cout << "xf will be solved for with xf equation #2" << endl;
cout << "xf = xi + (vf^2 - vi^2)/2a" << endl;
xf = xi + (pow(vf,2) - pow(vi,2))/(2*ac);
cout << "xf = " << xf << " meters." << endl;
}
else if ((bxi==true)&&(bvi==true)&&(bvf==true)&&(bt==true))
{
cout << "xf will be solved for with xf equation #3" << endl;
cout << "xf = xi + (1/2)(vi + vf)*t" << endl;
xf = xi + (1/2)*(vi + vf)*t;
cout << "xf = " << xf << " meters." << endl;
}
else if ((bxi==true)&&(bvf==true)&&(bt==true)&&(ba==true))
{
cout << "xf will be solved for with xf equation #4" << endl;
cout << "xf = xi + vf*t - (1/2)a*t^2" << endl;
xf = xi + vf*t - (1/2)*ac*pow(t,2);
cout << "xf = " << xf << " meters." << endl;
}
else
cout <<"There is no equation for xf that matches the given variables." << endl;
}
else if (solve_for == "vi")
{
if ((bvf==true)&&(ba==true)&&(bt==true))
{
cout << "vi will be solved for with vi equation #1" << endl;
cout << "vi = vf - a*t" << endl;
vi = vf - ac*t;
cout << "vi = " << vi << " meters per second." << endl;
}
else if ((bxf==true)&&(bxi==true)&&(ba==true)&&(bt==true))
{
cout << "vi will be solved for with vi equation #2" << endl;
cout << "vi = (xf - xi)/t - (1/2)a*t" << endl;
vi = (xf - xi)/t - (1/2)*ac*t;
cout << "vi = " << vi << " meters." << endl;
}
else if ((bvf==true)&&(ba==true)&&(bxf==true)&&(bxi==true))
{
cout << "vi will be solved for with vi equation #3" << endl;
cout << "vi = sqrt(vf^2 - 2a(xf - xi))" << endl;
vi = sqrt(pow(vf,2)-(2*ac)*(xf - xi));
cout << "vi = " << vi << " meters per second." << endl;
}
else if ((bxf==true)&&(bxi==true)&&(bvf==true)&&(bt==true))
{
cout << "vi will be solved for with vi equation #4" << endl;
cout << "vi = 2(xf - xi)/t - vf" << endl;
vi = 2*(xf - xi)/t - vf;
cout << "vi = " << vi << " meters per second." << endl;
}
else
{
cout << "There is no equation for vi that matches the given variables." << endl;
}
}
else if (solve_for == "vf")
{
if ((bvi==true)&&(ba==true)&&(bt==true))
{
cout << "vf will be solved for with vf equation #1" << endl;
cout << "vf = vi + a*t";
vf = vi + ac*t;
cout << "vf = " << vf << " meters per second." << endl;
}
else if ((bvi==true)&&(ba==true)&&(bxf==true)&&(bxi==true))
{
cout << "vf will be solved for with vf equation #2" << endl;
cout << "vf = sqrt(vi^2 + 2a(xf - xi))" << endl;
vf = sqrt(pow(vi,2) + (2*ac)*(xf - xi));
cout << "vf = " << vf << " meters per second." << endl;
}
else if ((bxf==true)&&(bxi==true)&&(bvi==true)&&(bt==true))
{
cout << "vf will be solved for with vf equation #3" << endl;
cout << "vf = 2(xf - xi)/t - vi" << endl;
vf = 2*(xf - xi)/t - vi;
cout << "vf = " << vf << " meters per second." << endl;
}
else if ((bxf==true)&&(bxi==true)&&(ba==true)&&(bt==true))
{
cout << "vf will be solved for with vf equation #4" << endl;
cout << "vf = (xf - xi)/t + (1/2)a*t" << endl;
vf = (xf - xi)/t + (1/2)*ac*t;
cout << "vf = " << vf << " meters per second." << endl;
}
else
{
cout << "There is no equation for vf that matches the given variables." << endl;
}
}
else if (solve_for == "a")
{
if ((bvf==true)&&(bvi==true)&&(bt==true))
{
cout << "a will be solved for with a equation #1" << endl;
cout << "a = (vf - vi)/t" << endl;
ac = (vf - vi)/t;
cout << "a = " << a << " meters per second per second." << endl;
}
else if ((bxf==true)&&(bxi==true)&&(bvi==true)&&(bt==true))
{
cout << "a will be solved for with a equation #2" << endl;
cout << "a = 2(xf - xi - vi*t)/t^2" << endl;
ac = 2*(xf - xi - vi*t)/pow(t,2);
cout << "a = " << a << " meters per second per second." << endl;
}
else if ((bvf==true)&&(bvi==true)&&(bxf==true)&&(bxi==true))
{
cout << "a will be solved for with a equation #3" << endl;
cout << "a = (vf^2 - vi^2)/2(xf - xi)" << endl;
ac = (pow(vf,2) - pow(vi,2))/(2*(xf - xi));
cout << "a = " << a << " meters per second per second." << endl;
}
else if ((bxf==true)&&(bxi==true)&&(bvf==true)&&(bt==true))
{
cout << "a will be solved for with a equation #4" << endl;
cout << "a = -2(xf - xi - vf*t)/t^2" << endl;
ac = -2*(xf - xi - vf*t)/pow(t,2);
cout << "a = " << a << " meters per second per second." << endl;
}
else
{
cout << "There is no equation for a that matches the given variables." << endl;
}
}
else if (solve_for == "t")
{
if ((bvf==true)&&(bvi==true)&&(ba==true)&&(ac!=0))
{
cout << "t will be solved for with t equation #1" << endl;
cout << "t = (vf - vi)/a" << endl;
t = (vf - vi)/ac;
cout << "t = " << t << " seconds." << endl;
}
else if ((bvi==true)&&(ba==true)&&(bxf==true)&&(bxi==true))
{
if ((a==0)&&(vi!=0))
{
cout << "t will be solved for with t equation #2 for a=0" << endl;
cout << "t = (xf - xi)/vi" << endl;
t = (xf - xi)/vi;
cout << "t = " << t << " seconds." << endl;
}
else
{
cout << "t will be solved for with t equation #2" << endl;
cout << "t = (-vi + sqrt(vi^2 + 2a(xf - xi)))/a AND t = (-vi - sqrt(vi^2 + 2a(xf-xi)))/a" << endl;
t = (-vi + sqrt(pow(vi,2) + (2*ac)*(xf - xi)))/ac;
cout << "t = " << t << " seconds AND t = ";
t = (-vi - sqrt(pow(vi,2) + (2*ac)*(xf - xi)))/ac;
cout << t << " seconds." << endl; //in this instance, there are two values for t that satisfy conditions
}
}
else if ((bxf==true)&&(bxi==true)&&(bvi==true)&&(bvf==true))
{
cout << "t will be solved for with t equation #3" << endl;
cout << "t = 2(xf - xi)/(vi + vf)" << endl;
t = 2*(xf - xi)/(vi + vf);
cout << "t = " << t << " seconds." << endl;
}
else if ((bvf==true)&&(ba==true)&&(bxf==true)&&(bxi==true))
{
cout << "t will be solved for with t equation #4" << endl;
cout << "t = (-vf + sqrt(vf^2 - 2a(xf - xi)))/-a AND t = (-vf - sqrt(vf^2 - 2a(xf - xi)))/-a" << endl;
t = (-vf + sqrt(pow(vf,2) - (2*ac)*(xf - xi)))/-a;
cout << "t = " << t << " seconds AND t = ";
t = (-vf - sqrt(pow(vf,2) - (2*ac)*(xf - xi)))/-a;
cout << t << " seconds." << endl;
}
else
{
cout << "There is no equation for t that matches the given variables." << endl;
}
}
cout << endl << endl;
do {
cout << "Would you like to do additional kinematic computations? y/n: ";
cin >> ans;
if (wrong_answer(ans))
{
cout << "You have entered a wrong answer." << endl;
system("PAUSE");
}
} while (wrong_answer(ans));
} while (ans == 'y' || ans == 'Y');
}
void trapezoid(double apar, double bpar, int npar)
{
system("CLS");
cout << "-----------------TRAPEZOID RULE----------------------------------" << endl;
dx = (bpar-apar)/n; //dx is length of each division
int coef=0;
double series=0;
cout.precision(5);
cout << "Series looks like: " << endl;
for (int i=0; i<=n; i++)
{
coef = choose_coef_t(i,n);
series += coef*f(apar+(dx*i));
cout << coef << " * " << "f(" << apar+(dx*i) << ") +" << endl;
}
cout.precision(20);
cout << "dx/2 = " << dx/2 << endl;
cout << "series = " << series << endl;
cout.precision(20);
cout << endl << "Definite integral = " << (dx/2)*(series);
}
void midpoint(double apar, double bpar, int npar)
{
system("CLS");
cout << "-----------------MIDPOINT RULE-----------------------------------" << endl;
dx = (bpar-apar)/n; //dx is length of each division
int coef=0;
double series=0;
cout.precision(5);
cout << "Series looks like: " <<endl;
for (int i=0; i<n; i++)
{
//no need to choose a coefficient, all coefficients are 1
series += f(.5*(apar+(dx*i)+apar+(dx*(i+1))));
cout << "f(" << (.5*(apar+(dx*i)+apar+(dx*(i+1)))) << ") +" << endl;
}
cout << "dx = " << dx << endl;
cout << "series = " << series << endl;
cout.precision(20);
cout << "Definite integral = " << dx*series;
}
void simpsons(double apar, double bpar, int ppar)
{
system("CLS");
cout << "-----------------SIMPSON'S RULE----------------------------------" << endl;
n=2*ppar; //two divisions for each parabola
dx = (bpar-apar)/n; //dx is length of each division
int coef=0;
double series=0;
cout.precision(5);
cout << "Series looks like: " << endl;
for (int i=0; i<=n; i++)
{
coef = choose_coef_s(i,n);
series += coef*f(apar+(dx*i));
cout << coef << " * " << "f(" << apar+(dx*i) << ") +" << endl;
}
cout << "dx/3 = " << dx/3 << endl;
cout << "series = " << series << endl;
cout.precision(20);
cout << endl << "Definite integral = " << (dx/3)*(series);
}
bool wrong_answer(char anspar)
{
if (!(anspar=='y'||anspar=='n')) //if ans is not either y, Y, n, or N
return 1; //answer is not appropriate
else
return 0; //answer is appropriate
}
void kinematics_report(void)
{
if (bxi)
cout << "xi = " << xi << "m, ";
if (bxf)
cout << "xf = " << xf << "m, ";
if (bvi)
cout << "vi = " << vi << "m/s, ";
if (bvf)
cout << "vf = " << vf << "m/s, ";
if (ba)
cout << "a = " << ac << "m/s/s, ";
if (bt)
cout << "t = " << t << "s, ";
if ((bxi)||(bxf)||(bvi)||(bvf)||(ba)||(bt))
cout << endl << endl;
}
| true |
9eaa6694c5b3346c3d8c23bbb10f777ceaf1aaec | C++ | ezhou2008/algorithm-basic | /cpp1/JZ-312_474-Lowest-Common-Ancestor-II.cpp | UTF-8 | 4,041 | 3.90625 | 4 | [] | no_license | /*Lowest Common Ancestor II
Description
Given the root and two nodes in a Binary Tree.
Find the lowest common ancestor(LCA) of the two nodes.
The lowest common ancestor is the node with largest depth
which is the ancestor of both nodes.
The node has an extra attribute parent which point to the father of itself.
The root's parent is null.
Example
For the following binary tree:
4
/ \
3 7
/ \
5 6
LCA(3, 5) = 4
LCA(5, 6) = 7
LCA(6, 7) = 7
*/
/**
* Definition of ParentTreeNode:
* class ParentTreeNode {
* public:
* int val;
* ParentTreeNode *parent, *left, *right;
* }
*/
class Solution_1 {
public:
/**
* @param root: The root of the tree
* @param A, B: Two node in the tree
* @return: The lowest common ancestor of A and B
*
* 这个和Lowest Common Ancestor的区别在于有parent指针,可以从下而上遍历
*
* 要点:
* 找出a到root的路径,找出b到root的路径
* 找出两条路径中的最后一个相同节点(反向找)
* 比如:LCA(3, 5)
* path(3) = 3,4
* path(5) = 5,3,4
*
*/
ParentTreeNode *lowestCommonAncestorII(ParentTreeNode *root,
ParentTreeNode *A,
ParentTreeNode *B) {
if (root == NULL) return NULL;
vector<ParentTreeNode*> path_a = find_path(A);
vector<ParentTreeNode*> path_b = find_path(B);
//find the last common in the lists
int idx_a = path_a.size() - 1;
int idx_b = path_b.size() - 1;
int idx_last_common = -1;
while (idx_a >=0 && idx_b >=0 ) {
if (path_a[idx_a] == path_b[idx_b]) {
idx_last_common = idx_a;
idx_a--; idx_b--;
} else {
break;
}
}
if(idx_last_common != -1) {
return path_a[idx_last_common];
}
return NULL;
}
vector<ParentTreeNode*> find_path( ParentTreeNode *target ) {
vector<ParentTreeNode*> res;
if (target == NULL) return res;
while(target) {
res.push_back(target);
target = target->parent;
}
return res;
}
};
/**
* Definition of ParentTreeNode:
* class ParentTreeNode {
* public:
* int val;
* ParentTreeNode *parent, *left, *right;
* }
*/
class Solution_same_as_LCA {
public:
/**
* @param root: The root of the tree
* @param A, B: Two node in the tree
* @return: The lowest common ancestor of A and B
*/
ParentTreeNode *lowestCommonAncestorII(ParentTreeNode *root,
ParentTreeNode *A,
ParentTreeNode *B) {
if (root == A || root == B) return root;
if (root == NULL) return NULL;
ParentTreeNode* left = lowestCommonAncestorII(root->left, A, B);
ParentTreeNode* right = lowestCommonAncestorII(root->right, A,B);
if ( left && right) {
return root;
}
return left?left:right;
}
};
/*
Definition of ParentTreeNode:
class ParentTreeNode {
public:
int val;
ParentTreeNode *parent, *left, *right;
}
*/
class Solution_2 {
public:
/**
* @param root: The root of the tree
* @param A, B: Two node in the tree
* @return: The lowest common ancestor of A and B
*
* 要点:
* 沿着A到root的路径扫描,看是否有B,
* 如果没有的话,B=B->parent,重复扫描
*/
ParentTreeNode *lowestCommonAncestorII(ParentTreeNode *root,
ParentTreeNode *A,
ParentTreeNode *B) {
ParentTreeNode* pCur = A;
while (pCur) { //until root->parent
if (B == pCur) {
return pCur;
}
pCur = pCur->parent;
}
return lowestCommonAncestorII(root, A, B->parent);
}
}; | true |
a234cec8a9299e7f59a21f0398faaac32859711b | C++ | hanaumc/SGpp | /datadriven/examplesPipeline/dataMatrixDatabase.cpp | UTF-8 | 5,707 | 2.875 | 3 | [
"LicenseRef-scancode-generic-exception",
"BSD-3-Clause"
] | permissive | // Copyright (C) 2008-today The SG++ project
// This file is part of the SG++ project. For conditions of distribution and
// use, please see the copyright notice provided with SG++ or at
// sgpp.sparsegrids.org
#include <sgpp/base/grid/Grid.hpp>
#include <sgpp/datadriven/algorithm/DBMatOffline.hpp>
#include <sgpp/datadriven/algorithm/DBMatDatabase.hpp>
#include <sgpp/datadriven/algorithm/DBMatOfflineFactory.hpp>
#include <sgpp/base/exception/algorithm_exception.hpp>
#include <string>
using sgpp::datadriven::DBMatDatabase;
/**
* This example shows how to initialize a data matrix of offline decompositions (needed for
* online objects) which enhances the performance since the decomposition usually takes some time.
* A database is always initialized upon a json file which contains paths to different matrix
* decompositions identified by the configuration of the grid, adaptivity and the density
* estimation itself.
*/
int main() {
/**
* First the database has to be initialized. This is done by passing the file to the json
* database file to the constructor of the DBMatDatabase class.
*/
std::string databasePath = "dataMatrixDatabase.json";
DBMatDatabase database(databasePath);
/**
* To retrieve an offline decomposition one must define the setup the offline matrix must match.
* This is done by defining how the sparse grid is structured, how the sparse grid performs
* refinement and coarsening (adaptivity). Also regularization and density estimation parameters
* must be defined to identify a decomposition. This is done by initializing respective
* structures for all of those settings.
*/
/**
* First the sparse grid itself will be specified using a structure that inherits from the
* sgpp::base::GeneralGridConfiguration supertype. Each structure defines an unique
* type of a sparse grid, such as a regular sparse grid, geometry aware sparse grids.
*/
sgpp::base::RegularGridConfiguration gridConfig;
gridConfig.dim_ = 2;
gridConfig.level_ = 3;
/**
* Next the refinement and coarsening behaviour of the sparse grid is defined. In this example
* the default values are used.
*/
sgpp::base::AdaptivityConfiguration adaptivityConfig;
/**
* Also the regularization must be specified, namely the type of the regularization operator
* and also the regularization strength, lambda. In this case the identity regularization operator
* is chosen.
*/
sgpp::datadriven::RegularizationConfiguration regularizationConfig;
regularizationConfig.type_ = sgpp::datadriven::RegularizationType::Identity;
regularizationConfig.lambda_ = 10e-7;
/**
* Lastly the density estimation it self is configured. Since online / offline learning
* will be performed the density estimation type will be
* sgpp::datadriven::DensityEstimationType::Decomposition. Also the method of decomposition has
* to be specified, in this case Cholesky decomposition (which supports adaptivity of the grid)
* is chosen.
*/
sgpp::datadriven::DensityEstimationConfiguration densityEstimationConfig;
densityEstimationConfig.type_ = sgpp::datadriven::DensityEstimationType::Decomposition;
densityEstimationConfig.decomposition_ = sgpp::datadriven::MatrixDecompositionType::Chol;
/**
* Before the matrix can be initialized the underlying grid needs to be created
*/
std::unique_ptr<sgpp::base::Grid> grid;
if (gridConfig.type_ == sgpp::base::GridType::ModLinear) {
grid =
std::unique_ptr<sgpp::base::Grid>{sgpp::base::Grid::createModLinearGrid(gridConfig.dim_)};
} else if (gridConfig.type_ == sgpp::base::GridType::Linear) {
grid = std::unique_ptr<sgpp::base::Grid>{sgpp::base::Grid::createLinearGrid(gridConfig.dim_)};
} else {
throw sgpp::base::algorithm_exception("LearnerBase::InitializeGrid: An unsupported grid type "
"was chosen!");
}
/**
* This section shows how to store a decomposition in the database. First however the
* matrix has to be created and decomposed. This is done using the configuration structures
* that the database needs to identify a decomposition.
*/
std::string dbmatfilepath = "my/path";
std::cout << "Creating dbmat" << std::endl;
sgpp::datadriven::DBMatOffline *db = sgpp::datadriven::DBMatOfflineFactory::buildOfflineObject(
gridConfig, adaptivityConfig, regularizationConfig, densityEstimationConfig);
db->buildMatrix(grid.get(), regularizationConfig);
db->decomposeMatrix(regularizationConfig, densityEstimationConfig);
db->store(dbmatfilepath);
std::cout << "Created dbmat" << std::endl;
/**
* Afte decomposing the data matrix it can be stored in the database. By passing the
* configuration structures used to create the matrix the database can identify the
* decomposition. The last parameter of the putDataMatrix method specified whether an entry with
* the same configuration will be replaced with a new file path. Note that the database only
* works on file paths, i.e. strings.
*/
database.putDataMatrix(gridConfig, adaptivityConfig, regularizationConfig,
densityEstimationConfig, dbmatfilepath, true);
/**
* Lastly it is shown how to retrieve a file path from the database. To identify a decomposition
* the entire configuration which would be used to initialize the data matrix must be passed
* to the database. If a matching entry is found the getDataMatrix method will return the
* file path associated with this configuration.
*/
std::string path = database.getDataMatrix(gridConfig,
adaptivityConfig, regularizationConfig, densityEstimationConfig);
std::cout << "Success: " << path << std::endl;
return 0;
}
| true |
2a073ce5d378332d100b2a18a0e735cd369d8964 | C++ | tolma488/censor | /censor/encoder.h | UTF-8 | 1,979 | 3.0625 | 3 | [] | no_license | #ifndef ENCODER_H
#define ENCODER_H
#include "includes.h"
#include "MyEx.h"
class Encoder
{
private:
using Byte = int8_t;
using ByteArray = shared_ptr<Byte>;
// asciiToUTFxx converts ascii string to utf string with BOM (BE - BigEndian / LE - LittleEndian)
static u16string asciiToUTF16s(const string& src, bool BE = true);
static u32string asciiToUTF32s(const string& src, bool BE = true);
public:
// returs encoding of current file
static Encoding getFileEncoding(const string& filename);
//returns last space position of block
static string::size_type getLastSpacePos(const string& rawbuf, Encoding enc, const string::size_type defpos = string::npos);
//returns next space position
static string::size_type getSpacePos(const string& buf, Encoding enc, const string::size_type pos = 0);
// returns next nonspace position
static string::size_type getNonSpacePos(const string& buf, Encoding enc, const string::size_type pos = 0);
template<class T>
static T AsciiToUTF( string& s, Encoding enc)
{
try
{
if(typeid(T) == typeid(u16string))
{
u16string es = asciiToUTF16s(s, (enc & fBigEndian) == fBigEndian);
T* ts = reinterpret_cast<T*>(&es);
return *ts;
}
if(typeid(T) == typeid(u32string))
{
u32string es = asciiToUTF32s(s, (enc & fBigEndian) == fBigEndian);
T* ts = reinterpret_cast<T*>(&es);
return *ts;
}
if(typeid(T) == typeid(string))
{
T* ts = reinterpret_cast<T*>(&s);
return *ts;
}
return T();
}
catch(exception& e)
{
throw MyEx("Encoder::Encoder() string: " + s + ".\n\t" + string(e.what()));
}
}
};
#endif // ENCODER_H
| true |
4793a3c4bea5ef9ee8a613434c42ed88c0689060 | C++ | RobertDaleSmith/cosc-1410-help | /code/uh/lab-array.cpp | UTF-8 | 771 | 3.296875 | 3 | [] | no_license | #include <iostream> //Library included for Input/Output Functions.
#include <iomanip> //Library included for spacing and formating.
#include <ctime> //For generating random number based on the time.
using namespace std;
const int ARRAY_SIZE_INT = 10;
int numbers[ARRAY_SIZE_INT] = {1,2,3,4,5,6,7,8,9,10};
int numChk;
int main()
{
for (numChk = 0; numChk < ARRAY_SIZE_INT; numChk++)
{
if (numbers[numChk] % 2 == 0)
{
cout << numbers[numChk] <<" is even\n";
}
}
cout << "\n\n";
for (numChk = 0; numChk < ARRAY_SIZE_INT; numChk++)
{
if (numbers[numChk] % 2 == 1)
{
cout << numbers[numChk] <<" is odd\n";
}
}
system("Pause");
}
| true |
ea9e955ea1db9087b84b04a5679caf1b47de2f80 | C++ | epakhomenko/LearningStroustrup | /function.cc | UTF-8 | 635 | 3.171875 | 3 | [
"Apache-2.0"
] | permissive | //
//Пример из 2.3.10
//
#include <iostream>
using namespace std;
struct pair {
char* name;
int val;
};
const int large = 1024;
static pair vec[large+1];
pair*find(const char* p)
/*
//работает со множеством пар "pair",
//ишет p, если находит, возвращает его "pair"
//в противном случае возвращает неиспользованную "pair"
*/
{
for (int i=0; vec[i].name; i++)
if (strcmp(p,vec[i].name == 0) return &vec[i];
if (i == large) return &vec[large-1];
return &vec[i];
}
int main()
{
cout << "Hello World" << endl;
}
| true |
8cea2cc116afd4c44778b0017f0226b0948cb661 | C++ | Jeffrey-W23/AIE-CodeFolio | /project2D/PathFindEntity1.cpp | UTF-8 | 2,199 | 2.734375 | 3 | [
"MIT"
] | permissive | // #include, using, etc
#include "PathFindEntity1.h"
#include "IdleState.h"
#include "FollowState.h"
#include "CollisionManager.h"
//--------------------------------------------------------------------------------------
// Default Constructor.
//--------------------------------------------------------------------------------------
PathFindEntity1::PathFindEntity1()
{
// Create a collidable object for walls.
CollisionManager* collider = CollisionManager::GetInstance();
collider->AddObject(this);
// Add the AI state and push it to the stack.
m_AIStateMachine->AddState(0, new IdleState());
m_AIStateMachine->AddState(1, new FollowState(1, 88));
m_AIStateMachine->PushState(0);
// set varaibles
m_force = Vector2(10, 10);
m_acceleration = Vector2(0, 0);
m_velocity = Vector2(0, 0);
SetPosition(Vector2(450, 150));
// Set the type of object to wall
this->SetType(ENEMY);
}
//--------------------------------------------------------------------------------------
// Default Destructor
//--------------------------------------------------------------------------------------
PathFindEntity1::~PathFindEntity1()
{
}
//--------------------------------------------------------------------------------------
// Update: A function to update objects.
//
// Param:
// deltaTime: Pass in deltaTime. A number that updates per second.
//--------------------------------------------------------------------------------------
void PathFindEntity1::Update(float deltaTime)
{
// Update the AI Statemachine
m_AIStateMachine->Update(deltaTime, this);
}
//--------------------------------------------------------------------------------------
// Draw: A function to render (or "draw") objects to the screen.
//
// Param:
// renderer2D: a pointer to Renderer2D for rendering objects to screen.
//--------------------------------------------------------------------------------------
void PathFindEntity1::Draw(Renderer2D* m_2dRenderer)
{
// Draw the AI statemachine.
m_AIStateMachine->Draw(m_2dRenderer);
// Draw the Entity.
m_2dRenderer->setRenderColour(1, 0, 1, 1);
m_2dRenderer->drawSpriteTransformed3x3(nullptr, GlobalTrasform, 40, 40);
m_2dRenderer->setRenderColour(0xFFFFFFFF);
} | true |
748228628da64467bd3db93c6cfc8c1813a571fb | C++ | towa7bc/SpotifyWebApiAdapter | /src/detail/HttpHelper.hpp | UTF-8 | 1,899 | 2.515625 | 3 | [
"Unlicense"
] | permissive | //
// Created by Michael Wittmann on 01/05/2020.
//
#ifndef SPOTIFYWEBAPIADAPTER_HTTPHELPER_HPP
#define SPOTIFYWEBAPIADAPTER_HTTPHELPER_HPP
#include <string> // for string
#include <string_view> // for string_view
#include <unordered_map> // for map
#include "../model/modeldata.hpp"
namespace spotify {
inline namespace v1 {
class AuthenticationToken;
class SpotifyNetworkManager;
} // namespace v1
} // namespace spotify
namespace spotify {
inline namespace v1 {
namespace detail {
class HttpHelper {
private:
static SpotifyNetworkManager manager_;
public:
static auto Post1(
std::string_view url,
const std::unordered_map<std::string, std::string> &postData)
-> std::string;
static auto Post2(
std::string_view url, const AuthenticationToken &token,
const std::unordered_map<std::string, std::string> &postData,
bool include_bearer) -> std::string;
static auto Post3(std::string_view url, const AuthenticationToken &token,
const model::playlistdata &pD, bool include_bearer = true)
-> std::string;
static auto Get1(std::string_view url) -> std::string;
static auto Get2(std::string_view url, const AuthenticationToken &token,
bool include_bearer) -> std::string;
static std::string Put1(
std::string_view url, const AuthenticationToken &token,
const std::unordered_map<std::string, std::string> &postData,
bool include_bearer);
static std::string Put2(std::string_view url,
const AuthenticationToken &token,
const model::playlistdata &pD, bool include_bearer);
static std::string Delete(std::string_view url,
const AuthenticationToken &token,
bool include_bearer);
};
} // namespace detail
} // namespace spotify::inline v1
} // namespace spotify
#endif
| true |
6aad322dacdb3960a412d46ae52c15dc266f78b4 | C++ | TUS-OSK/lecture-classical-raytracer-2021 | /src/scene.h | UTF-8 | 1,917 | 2.890625 | 3 | [] | no_license | #pragma once
#define TINYOBJLOADER_IMPLEMENTATION
#include "external/tinyobjloader/tiny_obj_loader.h"
#include <vector>
#include "sphere.h"
#include "intersectinfo.h"
#include "ray.h"
#include "shape.h"
#include <memory>
#include <iostream>
#include "triangle.h"
bool loadObj(const std::string &filepath,std::vector<float> &vertex,std::vector<unsigned int> &index){
tinyobj::ObjReader reader;
if(!reader.ParseFromFile(filepath)){
if(!reader.Error().empty()){
std::cerr << reader.Error();
}
return false;
}
if(!reader.Warning().empty()){
std::cout << reader.Warning();
}
const auto &attrib = reader.GetAttrib();
const auto &shapes = reader.GetShapes();
vertex = attrib.vertices;
for(size_t s = 0; s < shapes.size(); ++s){
for(const auto &idx: shapes[s].mesh.indices){
index.push_back(idx.vertex_index);
}
}
return true;
}
class Scene
{
private:
std::vector<std::shared_ptr<Shape>> object;
public:
Scene(const std::shared_ptr<Shape> &s)
{
object.push_back(s);
}
Scene() {}
void addShape(const std::shared_ptr<Shape> &s)
{
object.push_back(s);
}
void addPolygon(const std::string& filepath,const Material mat,const Vec3f color){
std::vector<float> vertex;
std::vector<unsigned int> index;
loadObj(filepath,vertex,index);
int nface = index.size() /3;
for(int i = 0; i < nface; i++){
Vec3f p[3];
for(int k = 0; k < 3; k++){
unsigned int idx = index[i*3 + k] * 3;
p[k] = Vec3(vertex[idx],vertex[idx+1],vertex[idx+2]);
}
object.push_back(std::make_shared<Triangle>(p[0],p[1],p[2],mat,color));
}
}
bool hit(const Ray &ray, IntersectInfo &info)
{
bool result = false;
info.distance = 10000.0;
for (int i = 0; i < object.size(); i++)
{
IntersectInfo test;
if (object[i]->hit(ray, test))
{
if (info.distance > test.distance)
{
result = true;
info = test;
}
}
}
return result;
}
};
| true |
8406696fa2b9d994af9272eafa91f93898779113 | C++ | rigged-regie/NGU-inputs | /api-injector/injector/main.cpp | UTF-8 | 2,303 | 2.859375 | 3 | [
"WTFPL"
] | permissive | #include <iostream>
#include <Windows.h>
#include <tlhelp32.h>
#include <thread>
namespace cfg {
char const* default_dll_name = ".\\api.dll";
char const* default_proc_name = "NGUIdle.exe";
}
template <typename ...Args>
void assert(bool cond, Args &&...args) {
if (cond) return;
std::cout << "assertion failed:\n\tmsg: ";
((std::cout << std::forward<Args>(args) << " "), ...);
std::cout << "\n\tcode: " << GetLastError() << "\n";
std::cout << std::flush;
getchar();
exit(0);
}
DWORD get_proc_id_by_name(char const* name) {
PROCESSENTRY32 entry;
entry.dwSize = sizeof(PROCESSENTRY32);
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (Process32First(snapshot, &entry))
while (Process32Next(snapshot, &entry))
if (!_stricmp(entry.szExeFile, name))
return entry.th32ProcessID;
return 0;
}
void inject_dll(DWORD proc_id, char const* dll_path) {
HANDLE const hndl = OpenProcess(PROCESS_ALL_ACCESS, 0, proc_id);
assert(hndl, "Unable to open target process");
LPVOID const mem = VirtualAllocEx(hndl, NULL, strlen(dll_path) + 1, MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE);
assert(mem, "Unable to allocate memory in target process");
assert(WriteProcessMemory(hndl, mem, dll_path, strlen(dll_path) + 1, 0), "Unable to write into target process");
LPVOID const loadLibraryAddress = (void*)GetProcAddress(GetModuleHandle("kernel32.dll"), "LoadLibraryA");
assert(loadLibraryAddress, "Unalbe to find LoadLibraryA address in target process");
HANDLE thread = CreateRemoteThreadEx(hndl, 0, 0, (LPTHREAD_START_ROUTINE)loadLibraryAddress, mem, 0, 0, 0);
assert(thread, "Unable to create remote thread, try with admin right?");
assert(CloseHandle(hndl), "Unable to close target process handle");
}
int main(int argc, char **argv) {
char const *target = (argc > 1 ? argv[1] : cfg::default_proc_name);
char const *rel_dll_path = (argc > 2 ? argv[2] : cfg::default_dll_name);
char abs_dll_path[1024];
assert(_fullpath(abs_dll_path, rel_dll_path, 1024), "Unable to get absolute path");
DWORD const proc_id = get_proc_id_by_name(target);
assert(proc_id, "Unable to find proc id");
inject_dll(proc_id, abs_dll_path);
std::cout << "Injection successful" << std::endl;
return 0;
}
| true |
34688b946b622954bcfe26a68a0efce432f3b37d | C++ | iv-sergius/oop | /lab3/1-car/RemoteControl.h | WINDOWS-1251 | 1,037 | 2.609375 | 3 | [] | no_license | #pragma once
#include <boost/noncopyable.hpp>
class CCar;
// boost::noncopyable -
class CRemoteControl : boost::noncopyable
{
public:
CRemoteControl(CCar & car, std::istream & input, std::ostream & output);
bool HandleCommand();
// ,
// CRemoteControl& operator=(const CRemoteControl &) = delete;
private:
void EngineOn(std::istream & args);
void EngineOff(std::istream & args);
void Info(std::istream & args);
void SetGear(std::istream & args);
void SetSpeed(std::istream & args);
private:
typedef std::map<std::string, std::function<void(std::istream & args)>> ActionMap;
CCar & m_car;
std::istream & m_input;
std::ostream & m_output;
const ActionMap m_actionMap;
};
| true |
a0f6fc06ecf722e66ad3f11e87c4968e2e25303f | C++ | nikitos-net/- | /1.cpp | UTF-8 | 709 | 2.953125 | 3 | [] | no_license | #include <iostream>
#include <cmath>
using namespace std;
long int func(long int n){
n=abs(n);
int first, last;
if(n/10==0){
return 0;
}
last=n%100;
while(n/100!=0){
n=n/10;
}
first=n;
if (last==first){
return 0;
}
else{
return first-last;
}
}
int main(){
long int a, b, max, total=0;
cin>>a;
cin>>b;
if(a>=b){
max=b;
for(long int i=b; i<=a; i++){
if(func(i)!=0){
if(i%func(i)==0){
total++;
if(i>max){
max=i;
}
}
}
}
}
else{
max=a;
for(long int i=a; i<=b; i++){
if(func(i)!=0){
if(i%func(i)==0){
total++;
if(i>max){
max=i;
}
}
}
}
}
if (total==0){
max=0;
}
cout<<total<<" "<<max<<endl;
}
| true |