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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
bf002cf839bff547d3a4a5001360d00a74b7698d | C++ | parthdhwajendramishra/DS-and-DAA | /Graph/iscyclic_undirected.cpp | UTF-8 | 1,434 | 3.65625 | 4 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
class Graph
{
int v,e;
public:
Graph(int v,int e);
bool isCyclic(vector<int> graph[]);
bool cyclic_Util(int sv,vector<int> graph[],vector<bool> &visited,int parent);
void input();
};
bool Graph::cyclic_Util(int sv,vector<int> graph[],vector<bool> &visited,int parent)
{
visited[sv]=true;
for(auto i=graph[sv].begin();i!=graph[sv].end();i++)
{
if(!visited[*i])
{
if(cyclic_Util(*i,graph,visited,sv))
return true;
}
else if(*i!=parent)
return true;
}
return false;
}
bool Graph::isCyclic(vector<int> graph[])
{
vector<bool> visited(v,false);
for (int u = 0; u < v; u++)
{
if (!visited[u])
if (cyclic_Util(u, graph,visited, -1))
return true;
}
return false;
}
void Graph::input()
{
vector<int> graph[v];
//Adding edges in the graph
cout<<"Enter Source and Destination Vertex"<<endl;
cout<<"Source------>Destination"<<endl;
for(int i=0;i<e;i++)
{
int source,destination;
cin>>source>>destination;
graph[source].push_back(destination);
graph[destination].push_back(source);
}
cout<<isCyclic(graph);
}
Graph::Graph(int v,int e)
{
this->v=v;
this->e=e;
}
int main()
{
int v,e;
cout<<"Enter number of Vertices:";
cin>>v;
cout<<"Enter number of Edges:";
cin>>e;
Graph g(v,e);
g.input();
return 0;
}
| true |
8c3ab6cbb3258e136abdc202a5d9de1ce6591aa1 | C++ | VIENA-IST/AHRS | /tools/calibrate_adxl345/calibrate_adxl345.cpp | UTF-8 | 1,789 | 2.59375 | 3 | [] | no_license | #include <ADXL345.h>
#include <Arduino.h>
ADXL345 accel;
int16_t ax, ay, az;
double ax_stOff=0, ay_stOff=0, az_stOff=0;
#define GRAVITY 256.0f
#define LED_PIN 13 // (Arduino is 13, Teensy is 6)
bool blinkState = false;
int I;
void setup() {
// join I2C bus (I2Cdev library doesn't do this automatically)
Wire.begin();
// configure LED for output
pinMode(LED_PIN, OUTPUT);
// initialize serial communication
// (38400 chosen because it works as well at 8MHz as it does at 16MHz, but
// it's really up to you depending on your project)
Serial.begin(500000);
// initialize device
Serial.println("Initializing I2C devices...");
accel.initialize();
// verify connection
Serial.println("Testing device connections...");
if(accel.testConnection()){
Serial.println("ADXL345 connection successful");
// set range to +- 16g
accel.setRange(ADXL345_RANGE_16G);
accel.setFullResolution(true);
accel.setRate(ADXL345_RATE_100);
accel.setLowPowerEnabled(false);
accel.setMeasureEnabled(true);
double nSamples = 1000.0;
delay(100);
for(I = 0; I < nSamples; I++){
accel.getAcceleration(&ax, &ay, &az);
ax_stOff += ax;
ay_stOff += ay;
az_stOff += az;
if (I % 20 == 0)
Serial.print("I = "), Serial.println(I);
}
ax_stOff /= nSamples;
ay_stOff /= nSamples;
az_stOff /= nSamples;
Serial.println("Self tests off, offsets:");
Serial.println(ax_stOff);
Serial.println(ay_stOff);
Serial.println(az_stOff);
}else{
Serial.println("ADXL345 connection failed");
}
}
void loop() {
// blink LED to indicate activity
blinkState = !blinkState;
digitalWrite(LED_PIN, blinkState);
delay(1000);
}
| true |
4f94141ca88239a24150cb988fb421c202f1f3f7 | C++ | lrh360com/interview | /判断两个链表是否相交.cpp | GB18030 | 1,744 | 3.96875 | 4 | [] | no_license | /*---------------------------------
жǷཻ
-----------------------------------
***ͷָ룬h1,h2жǷཻ
*/
#include<iostream>
using namespace std;
struct Node{
int data;
Node *next;
};
/*--------------------------
һ
--------------------------
*/
bool isJoinedSimple(Node *h1,Node *h2)
{
if(h1 == NULL || h1 == NULL)
return false;
Node *temp1 = h1;
for(;temp1->next != NULL; temp1 = temp1->next);
Node *temp2 = h2;
for(;temp2->next != NULL; temp2 = temp2->next);
return temp1 == temp2;
}
//test
/*----------------------
л
----------------------
*/
//жǷл
Node* testCycle(Node *hPtr)
{
Node *h1 = hPtr;
Node *h2 = hPtr;
while(h2 !=NULL && h2->next != NULL) //h2ÿh1ÿһûh2ȵβлh2תh1
{
h1 = h1->next;
h2 = h2->next->next;
if(h1 == h2)
return h1;
}
return NULL;
}
bool isJoined(Node *h1,Node *h2)
{
Node *cylic1 = testCycle(h1);
Node *cylic2 = testCycle(h2);
if(cylic1 == NULL && cylic2 == NULL) //û
return isJoinedSimple(h1,h2);
if(cylic1 != NULL && cylic2 != NULL) //л
{
Node *p = cylic1;
while(1)
{
if(p == cylic2 || p->next == cylic2) return true;
p = p->next->next;
cylic1 = cylic1->next;
if(p == cylic1) return false;
}
}
else //һлһûزཻ
return false;
}
| true |
7959a190c667a85990b900a1cff38b562d2825cf | C++ | navidemad/cpp-babel-voip-epitech | /Babel/client/sources/Commands/CommandExit.cpp | UTF-8 | 668 | 2.609375 | 3 | [] | no_license | #include "CommandExit.hpp"
#include "CommandException.hpp"
#include <cstring>
CommandExit::CommandExit(void) {
}
CommandExit::~CommandExit(void) {
}
ICommand::Instruction CommandExit::getInstruction(void) const {
return ICommand::EXIT;
}
IClientSocket::Message CommandExit::getMessage(void) const {
IClientSocket::Message message;
message.msgSize = 0;
return message;
}
unsigned int CommandExit::getSizeToRead(void) const {
throw CommandException("No packet are sent from the server for this command");
}
void CommandExit::initFromMessage(const IClientSocket::Message &) {
throw CommandException("No packet are sent from the server for this command");
}
| true |
1e709054e1d3d27729cfe70688b61abd4bcb6385 | C++ | Abhi-Balijepalli/C-Cpp_Projects | /Zoo-Tycoon/zoo.cpp | UTF-8 | 21,319 | 3.609375 | 4 | [] | no_license | /* Program: Zoo_Tycoon.cpp
* Author: StickZ
* Date: 05.12.2019
* Description: fun zoo tycoon game, where players play till they loose all thier money
* Input: options to choose animal, and if you want to buy
* Ouput: money, profit, bonuses, etc...
*/
#include <iostream>
#include "./zoo.h"
#include <string>
#include <cstdlib>
using namespace std;
/*********************************
* Name: Zoo()
* Description: Constructor
********************************/
Zoo::Zoo() {
monkeys = new Animal *[25];
meerkats = new Animal *[25];
seaotters = new Animal *[25];
monkeySize = 25;
meerkatSize = 25;
seaotterSize = 25;
bank = 100000;
attenBoom = 0;
for (int i = 0; i < 25; i++) {
monkeys[i] = NULL;
meerkats[i] = NULL;
seaotters[i] = NULL;
}
}
/*********************************
* Name: Zoo()
* Description: copy - Constructor
********************************/
Zoo::Zoo(const Zoo ©) {
monkeySize = copy.monkeySize;
meerkatSize = copy.meerkatSize;
seaotterSize = copy.seaotterSize;
bank = copy.bank;
attenBoom = copy.attenBoom;
monkeys = new Animal*[monkeySize];
meerkats = new Animal*[meerkatSize];
seaotters = new Animal*[seaotterSize];
}
/*********************************
* Name: Zoo()
* Description: assignment operator
********************************/
const Zoo &Zoo::operator = (const Zoo ©) {
delete [] monkeys;
delete [] meerkats;
delete [] seaotters;
monkeySize = copy.monkeySize;
meerkatSize = copy.meerkatSize;
seaotterSize = copy.seaotterSize;
bank = copy.bank;
attenBoom = copy.attenBoom;
monkeys = new Animal*[monkeySize];
meerkats = new Animal*[meerkatSize];
seaotters = new Animal*[seaotterSize];
}
/*********************************
* Name: Destructor
* Description: Deletes dynamic memory
********************************/
Zoo::~Zoo() {
int i = 0;
while(monkeys[i] != NULL) {
delete [] monkeys[i];
i++;
}
i = 0;
while(meerkats[i] != NULL) {
delete [] meerkats;
i++;
}
i = 0;
while(seaotters[i] != NULL) {
delete [] seaotters;
i++;
}
}
/*********************************
* Name: get_bank_money()
* Description: returns the amount of money you have in bank
********************************/
float Zoo::get_bank_money() {
return bank;
}
/*********************************
* Name: make_revenue(int )
* Description: adds revenue to the bank
********************************/
void Zoo::make_revenue(int foo) {
bank += foo;
}
/*********************************
* Name: take_revenue(int )
* Description: takes money away from the bank
********************************/
void Zoo::take_revenue(int fi) {
bank -= fi;
}
/*********************************
* Name: animal_list(animal *)
* Description: this will check if the type of the animal matches and then goes to the array so there are no segfaults
********************************/
void Zoo::animal_list(Animal *yeet) {
if(yeet->getAnimalType() == "Monkey") {
add_monkey(yeet);
}
else if (yeet->getAnimalType() == "Sea otter") {
add_seaotter(yeet);
} else if (yeet->getAnimalType() == "meerkat") {
add_meerkat(yeet);
}
}
/*********************************
* Name: chooseAnimal()
* Description: this is the starting where the person has to choose the correct animal
********************************/
void Zoo::ChooseAnimal() {
string i;
cout << "what animal would you like to buy: " << endl;
cout << "1. Meerkat 2. SeaOtter 3.Monkey" << endl;
getline(cin,i);
if(i == "Monkey" || i == "3") {
monkeyPurchase();
} else if (i == "Meerkat" || i == "1") {
meerkatPurchase();
} else if (i == "SeaOtter" || i == "2") {
seaotterPurchase();
} else {
cout << "invalid input, ending program...."<< endl;
exit(0);
}
}
/*********************************
* Name: monkeyPurchase()
* Description: amount of monkeys you want to buy
********************************/
void Zoo::monkeyPurchase() {
string pick;
cout << "Cool! Monkeys are $15,000. It looks like you have $" << get_bank_money() << " in you account" << endl;
cout << "you can buy up to 2 monkeys (choose one option): " << endl;
cout << "1) 1 monkey" << endl;
cout << "2) 2 monkeys" << endl;
getline(cin,pick);
if (pick == "1") {
take_revenue(15000);
cout << "you bought 1 monkey so thats -$15,000 from you bank account. Now you have: $" << get_bank_money() << endl;
animal_list(new Monkeys());
//add_monkey(new Monkeys());
} else if (pick == "2") {
int math = 15000*2;
take_revenue(math);
cout << "you bought 2 monkeys so thats -$30,000 from your bank account. Now you have: $" << get_bank_money() << endl;
animal_list(new Monkeys());
animal_list(new Monkeys());
//add_monkey(new Monkeys());
//add_monkey(new Monkeys());
}
}
/*********************************
* Name: meerkatPurchase()
* Description: you can buy up to 2 meerkats
********************************/
void Zoo::meerkatPurchase() {
string pick;
cout << "Cool! Meerkats are $500. It looks like you have $" << get_bank_money() << " in you account" << endl;
cout << "you can buy up to 2 meerkats (choose one option): " << endl;
cout << "1) 1 meerkat" << endl;
cout << "2) 2 meerkat" << endl;
getline(cin,pick);
if (pick == "1") {
take_revenue(500);
cout << "you bought 1 meerkat so thats -$500 from you bank account. Now you have: $" << get_bank_money() << endl;
//add_meerkat(new Meerkat());
animal_list(new Meerkat());
} else if (pick == "2") {
//int math = 15000*2;
take_revenue(1000);
cout << "you bought 2 meerkats so thats -$1000 from your bank account. Now you have: $" << get_bank_money() << endl;
//add_meerkat(new Meerkat());
//add_meerkat(new Meerkat());
animal_list(new Meerkat());
animal_list(new Meerkat());
}
}
/*********************************
* Name: seaotterPurchase()
* Description: you can buy upto 2 seaotters
********************************/
void Zoo::seaotterPurchase() {
string pick;
cout << "Cool! Sea-Otters are $5,000. It looks like you have $" << get_bank_money() << " in you account" << endl;
cout << "you can buy up to 2 Sea-Otters (choose one option): " << endl;
cout << "1) 1 Sea_Otters" << endl;
cout << "2) 2 Sea-Otters" << endl;
getline(cin,pick);
if (pick == "1") {
take_revenue(5000);
cout << "you bought 1 Sea-Otter so thats -$5,000 from you bank account. Now you have: $" << get_bank_money() << endl;
animal_list(new Meerkat());
} else if (pick == "2") {
int math = 5000*2;
take_revenue(math);
cout << "you bought 2 Sea-Otters so thats -$10,000 from your bank account. Now you have: $" << get_bank_money() << endl;
animal_list(new Meerkat());
animal_list(new Meerkat());
}
}
/*********************************
* Name: add_monkey(Animal* )
* Description: this will add monkeys to the zoo
********************************/
void Zoo::add_monkey(Animal *item) {
if (arraychecker(monkeys,monkeySize)) {
restructureArray(monkeys,monkeySize);
}
for (int i =0; i < monkeySize; i++) {
if(monkeys[i] == NULL) {
monkeys[i] = item;
//cout << "amt monkeys: " << monkeys[i] << endl;
}
break;
}
}
/*********************************
* Name: add_meerkat(Animal *)
* Description: this will add meerkats to the zoo and check if the array needs to be resized
********************************/
void Zoo::add_meerkat(Animal *item) {
if (arraychecker(meerkats,meerkatSize)) {
restructureArray(meerkats,meerkatSize);
}
for (int i =0; i < meerkatSize; i++) {
if(meerkats[i] == NULL) {
meerkats[i] = item;
//cout << "amt meerkats: " << meerkats[i] << endl;
}
break;
}
}
/*********************************
* Name: add_seaotter(Animal *)
* Description: this will add seaotters to the zoo and check if the array needs to be resized
********************************/
void Zoo::add_seaotter(Animal *item) {
if (arraychecker(seaotters,seaotterSize)) {
restructureArray(seaotters,seaotterSize);
}
for (int i =0; i < seaotterSize; i++) {
if(seaotters[i] == NULL) {
seaotters[i] = item;
//cout << "amt seaotters: " << seaotters[i] << endl;
}
break;
}
}
/*********************************
* Name: arraychecker(Animal **, int )
* Description: this will be used in the add_(animal) function
********************************/
bool Zoo::arraychecker(Animal **test, int x) {
for(int i = 0; i < x; i++) {
if(!test[i]) {
return false;
break;
}
}
return true;
}
/*********************************
* Name: restructureArray(Animal **&, int &)
* Description: this will be increase the size of array if needed
********************************/
void Zoo::restructureArray(Animal **&test, int &x) {
Animal **arr = new Animal *[x*2];
for(int i = 0; i < (x*2); i++) {
arr[i] = NULL;
}
for(int i = 0; i < x; i++) {
arr[i] = test[i];
}
delete [] test;
test = arr;
x = x*2;
}
/*********************************
* Name: runGame()
* Description: lol, it runs the game - it uses elements that are from the animal.h
********************************/
void Zoo::runGame() {
cout << "....starting Zoo tycoon...." << endl;
//cout << "this is week 0, so you have to buy an animal. " << endl;
ChooseAnimal();
int week = 0;
int cost_of_food = 0;
int netGain;
while(true) {
attenBoom = 0;
netGain = 0;
cout << "week: " << week << endl;
//display();
animalGrowth();
cost_of_food = foodCosts();
take_revenue(cost_of_food);
cout << "$"<<foodCosts()<< " were taken out of your bank for food costs for the animals. " << endl;
cout << "you have $" << get_bank_money() << " in your bank" << endl;
cout << "------------------------------------" << endl;
cout << "Now it is time for the random event: " << endl;
randomEvent();
cout << "week summary: " << endl;
//take_revenue(cost_of_food);
cout << "profit from animals: " << calcPay() << endl;
cout << "cost for food: " << foodCosts() << endl;
if(attenBoom != 0) {
netGain = ((calcPay() - foodCosts()) + attenBoom);
//cout << "bonus money generated are: " << attenBoom << endl;
cout << "this week's net gain: $" << netGain << endl;
} else {
netGain = (calcPay() - foodCosts());
cout << "this week's net gain: $"<< netGain << endl;
if (get_bank_money() <= 0) {
cout << "you finished all your money. so its gameover! " << endl;
exit(0);
}
}
make_revenue(netGain);
cout << "Money in Bank now: $" <<get_bank_money() << endl;
//display();
laterPurchases();
week++;
string x;
cout << "do you want to quit (1) yes, (2) no : " << endl;
cin >> x;
if (x == "1") {
cout << "bye bye, you had $" << get_bank_money() << " in your bank" << endl;
break;
//exit(1);
}
deleteArrays();
}
//deleteArrays();
}
/*********************************
* Name:randomEvent()
* Description: this will call a random event and go to a randomevent used the rand() function
********************************/
void Zoo::randomEvent() {
int choice = (rand()%4 + 1);
if(choice == 1) {
cout << "An animal in your Zoo has gotten sick" << endl;
sickAnimal();
} else if( choice == 2) {
cout << "An adult animal has given birth to (a) babies/baby " << endl;
babyBorn();
} else if(choice == 3) {
cout << "There is a boom in attendence " << endl;
attendenceBoom();
//break;
} else if(choice == 4) {
cout << "nothing happend today" << endl;
} else {
//return randomEvent();
}
//choice = 0;
}
/*********************************
* Name: sickAnimal()
* Description: checks which animal should be sick and calls it
********************************/
void Zoo::sickAnimal() {
int random = (rand()%3 + 1);
if(random == 1) {
sickMonkey();
} else if(random == 2) {
sickMeerkat();
} else if (random == 3) {
sickSeaotter();
} else {}
}
/*********************************
* Name: sickMonkey()
* Description: self explanatory
********************************/
void Zoo::sickMonkey() {
if(monkeys[0] != NULL) {
if(get_bank_money() >= 7500) {
cout << "you have to pay $7500 to treat your monkey: " << endl;
take_revenue(7500);
cout << "nice, you helped your animal out. Now you have $" << get_bank_money() << " in your bank" << endl;
} else {
cout << "you don't have enough money, so the monkey has died" << endl;
deadMonkey();
}
} else {
deadMonkey();
}
}
/*********************************
* Name: deadMonkey()
* Description: monkey dies
********************************/
void Zoo::deadMonkey() {
cout << "i'm sorry, you have $" << get_bank_money() << " in your bank" << endl;
//int last;
int i = 0;
while (monkeys[i] != NULL) {
//int last = i;
i++;
}
delete monkeys[i-1];
monkeys[i-1] = NULL;
}
/*********************************
* Name: sickMeerkat()
* Description: self explanatory - gets called from the sickAnimal()
********************************/
void Zoo::sickMeerkat() {
if(meerkats[0] != NULL) {
if(get_bank_money() >= 250) {
cout << "you have to pay $250 to treat your Meerkat: " << endl;
take_revenue(250);
cout << "nice, you helped your animal out. Now you have $" << get_bank_money() << " in your bank" << endl;
} else {
cout << "you don't enough money, so the meerkat has died" << endl;
deadMeerkat();
}
} else {
sickSeaotter();
}
}
/*********************************
* Name: deadMeerkat()
* Description: meerkat dies
********************************/
void Zoo::deadMeerkat() {
cout << "i'm sorry, you have $" << get_bank_money() << " in your bank" << endl;
//int last;
int i = 0;
while (meerkats[i] != NULL) {
//int last = i;
i++;
}
delete meerkats[i-1];
meerkats[i-1] = NULL;
}
/*********************************
* Name: sickSeaotter()
* Description: seaotter falls sick
********************************/
void Zoo::sickSeaotter() {
if(meerkats[0] != NULL) {
if(get_bank_money() >= 2500) {
cout << "you have to pay $2500 to treat your Seaotter "<< endl;
take_revenue(2500);
cout << "nice, you helped your animal out. Now you have $" << get_bank_money() << " in your bank" << endl;
} else {
cout << "you don't have enough money, so the sea otter has died" << endl;
deadSeaotter();
}
} else {
sickMonkey();
}
}
/*********************************
* Name: deadSeaotter()
* Description: the seaotter dies
********************************/
void Zoo::deadSeaotter() {
cout << "i'm sorry, you have $" << get_bank_money() << " in your bank" << endl;
//int last;
int i = 0;
while (seaotters[i] != NULL) {
//int last = i;
i++;
}
delete seaotters[i-1];
seaotters[i-1] = NULL;
}
/*********************************
* Name: attendenceBoom()
* Description: called from the randomEvent(), this will give you revenue and some animals give more
********************************/
void Zoo::attendenceBoom() {
int totalMonkeys = 0;
int dinero;
int i = 0;
while(monkeys[i] != NULL) {
i++;
totalMonkeys = i;
}
if (totalMonkeys != 0) {
int money = (rand() % 300 + 1) + 400;
dinero = (totalMonkeys)* money;
//attenBoom = dinero;
cout << "because of the attendence boom, your monkey(s) got you $" << dinero << " added to your bank" << endl;
//int m = (int)dinero;
make_revenue(dinero);
attenBoom = dinero;
cout << "amount of money in bank now: " << get_bank_money() << endl;
money = 0;
}
else {
cout << "well you don't have any monkeys so you didn't make any money" << endl;
}
}
/*********************************
* Name: babyBorn()
* Description: a new baby (1,2,5) gets born and will be added to the Zoo with an age of 0.
********************************/
void Zoo::babyBorn() {
int choice = (rand()%3 +1);
//int i = 0;
bool Mocheck = false;
bool Mecheck = false;
bool Scheck = false;
if(choice == 1) {
int i = 0;
while(monkeys[i] != NULL) {
if(monkeys[i]->get_Age() >= 49) {
cout << "there is a new addition to the monkey family; a baby. " << endl;
//add_monkey(new Monkeys(0));
animal_list(new Monkeys(0));
Mocheck = true;
break;
}
i++;
}
}if (choice == 2) {
int i = 0;
while(meerkats[i] != NULL) {
if(meerkats[i]->get_Age() >= 49) {
cout << "there are 2 new addition to the meerkat family; 2 babies. " << endl;
//add_meerkat(new Meerkat(0));
//add_meerkat(new Meerkat(0));
animal_list(new Meerkat(0));
animal_list(new Meerkat(0));
Mecheck = true;
break;
}
}
i++;
} if (choice == 3) {
int i = 0;
while(seaotters[i] != NULL) {
if(seaotters[i]->get_Age() >= 49) {
cout << "there are 5 new addition to the seaotter family; 5 babies. " << endl;
animal_list(new Seaotter(0));
animal_list(new Seaotter(0));
animal_list(new Seaotter(0));
animal_list(new Seaotter(0));
animal_list(new Seaotter(0));
Scheck = true;
break;
}
}
i++;
}
if (Mocheck == false) {
cout << "there are no monkeys that can give birth" << endl;
} else if (Mecheck == false) {
cout << "there are no meerkats that can give birth" << endl;
} else if (Scheck == false) {
cout << "there are no seaotters that can give birth" << endl;
}
}
/*********************************
* Name: laterPurchases()
* Description: this will be called later if the player wants to by adult animals of 3 different types
********************************/
void Zoo::laterPurchases() {
string choice;
cout << "would you like to buy an Animal (adult): " << endl;
cout << " Y / N " << endl;
cin >> choice;
if (choice == "Y"){
string x;
cout << "what would you like: 1) monkey | 2) meerkat | 3) seaotter" << endl;
cout << " ($15000) | ($500) | ($5000) " << endl;
cin >> x;
if (x == "1" || x == "monkey") {
if(get_bank_money() < 15000) {
cout << "you don't have enough money to buy the monkey becuase you have $" << get_bank_money() << " in your bank" << endl;
}
else {
cout << "nice, you just purchased a monkey ($15000). Now you have $" << get_bank_money() << " in your bank" << endl;
//add_monkey(new Monkeys(50));
animal_list(new Monkeys(50));
take_revenue(15000);
}
}
if (x == "2" || x == "meerkat") {
if(get_bank_money() < 500) {
cout << "you don't have enough money to buy the meerkat becuase you have $" << get_bank_money() << " in your bank" << endl;
}
else {
cout << "nice, you just purchased a meerkat ($500). Now you have $" << get_bank_money() << " in your bank" << endl;
//add_meerkat(new Meerkat(50));
animal_list(new Meerkat(50));
take_revenue(500);
}
}
if (x == "3" || x == "seaotter") {
if(get_bank_money() < 5000) {
cout << "you don't have enough money to buy the seaotter becuase you have $" << get_bank_money() << " in your bank" << endl;
}
else {
cout << "nice, you just purchased a seaotter ($5000). Now you have $" << get_bank_money() << " in your bank" << endl;
//add_seaotter(new Seaotter(50));
animal_list(new Seaotter(50));
take_revenue(5000);
}
}
} else if (choice == "N") {
cout << "ok you are not buying an animal. " << endl;
} else {
cout << "invalid input, crashing program " << endl;
exit(0);
}
}
/*********************************
* Name: foodCosts()
* Description: this will calculate the cost of food
********************************/
int Zoo::foodCosts() {
int weekCosts = 0;
int i = 0;
int j = 0;
int k = 0;
while(monkeys[i] != NULL) {
weekCosts += 4 * monkeys[i]->get_Base_food();
i++;
}
while(meerkats[j] != NULL) {
weekCosts += meerkats[i]->get_Base_food();
j++;
}
while(seaotters[k] != NULL) {
weekCosts += seaotters[i]->get_Base_food();
}
return weekCosts;
}
/*********************************
* Name: display()
* Description: this will display the amount of animals in the Zoo
********************************/
void Zoo::display() {
cout << "the animals in your Zoo: " << endl;
int monkeyNum = 0;
int seaotterNum = 0;
int meerkatNum = 0;
int i = 0;
while(monkeys[i] != NULL) {
i++;
monkeyNum++;
}
i = 0;
while(seaotters[i] != NULL) {
i++;
seaotterNum++;
}
i = 0;
while(meerkats[i] != NULL) {
i++;
meerkatNum++;
}
cout << "monkeys: " << monkeyNum << endl;
cout << "seaotters: " << seaotterNum << endl;
cout << "meerkats: " << meerkatNum << endl;
}
/*********************************
* Name: animalGrowth()
* Description: this will measure the age of the animals
********************************/
void Zoo::animalGrowth() {
int i = 0;
while(monkeys[i] != NULL) {
monkeys[i] ->age_week();
i++;
}
i = 0;
while(seaotters[i] != NULL) {
seaotters[i]-> age_week();
i+=7;
}
i = 0;
while(meerkats[i] != NULL) {
meerkats[i] ->age_week();
i+=7;
}
}
/*********************************
* Name: calcPay()
* Description: this will be used in calculating profit in the runGame() function
********************************/
int Zoo::calcPay() {
int i = 0;
int totalM = 0;
while(monkeys[i] != NULL) {
totalM += monkeys[i] ->get_revenue();
i++;
}
i = 0;
while(seaotters[i] != NULL) {
totalM += seaotters[i]-> get_revenue();
i++;
}
i = 0;
while(meerkats[i] != NULL) {
totalM += meerkats[i] ->get_revenue();
i++;
}
return totalM;
}
void Zoo::deleteArrays() {
int i = 0;
while (monkeys[i] != NULL) {
delete [] monkeys[i];
i++;
}
i = 0;
while (meerkats[i] != NULL) {
delete [] meerkats[i];
i++;
}
i = 0;
while (seaotters[i] != NULL) {
delete [] seaotters[i];
i++;
}
//i = 0;
delete [] monkeys;
delete [] meerkats;
delete [] seaotters;
}
| true |
fb4a7cc64620d30f11fe95ca415d9eaf02e1fdd0 | C++ | FrancoisChabot/cpl_tmpl | /tests/data_provider.cpp | UTF-8 | 655 | 2.90625 | 3 | [] | no_license | #include "catch.hpp"
#include "cpl_tmpl/data_provider.h"
#include <sstream>
std::string get(cpl_tmpl::Data_provider dp) {
std::ostringstream dst;
dp.get(dst);
return dst.str();
}
TEST_CASE("Numeric", "[data_provider]") {
REQUIRE(get(cpl_tmpl::data_provider(3)) == "3");
}
TEST_CASE("String", "[data_provider]") {
std::string data = "abc";
REQUIRE(get(cpl_tmpl::data_provider(data)) == "abc");
}
TEST_CASE("Lookup", "[data_provider]") {
using map_t = std::map<std::string, std::string>;
std::map<std::string, std::string> data = {{"a", "b"}};
REQUIRE(get(cpl_tmpl::data_provider(data).get("a")) == "b");
} | true |
a7f3fbb81e86ad1425f9bb395deb7756fa7db1f2 | C++ | killbug2004/fshooterbetaproject | /dbghelper/HandleBase.cpp | UTF-8 | 1,885 | 2.734375 | 3 | [] | no_license | #include "HandleBase.h"
#include "kernel_dbg.h"
HandleTarget::HandleTarget(void) : _refCount(0)
{
}
HandleTarget::~HandleTarget(void)
{
}
ULONG HandleTarget::AddRef()
{
KASSERT(_refCount <= 0xf000000);
return ++_refCount;
}
ULONG HandleTarget::ReleaseRef()
{
KASSERT(_refCount <= 0xf000000);
return --_refCount;
}
ULONG HandleTarget::RefCount()
{
KASSERT(_refCount <= 0xf000000);
return _refCount;
}
bool HandleListener::OnFistrOpen(Handle* pHandle)
{
return true;
}
bool HandleListener::OnOpen(Handle* pHandle)
{
return true;
}
bool HandleListener::OnClose(Handle* pHandle)
{
return true;
}
bool HandleListener::OnLastClose(Handle* pHandle)
{
return true;
}
Handle::Handle() : pListener(NULL), pTarget(0), bOpen(false)
{
}
Handle::Handle(const Handle & h) : bOpen(false)
{
pListener = h.pListener;
pTarget = h.pTarget;
Ref();
}
Handle::Handle(HandleTarget * target, HandleListener * listener) : bOpen(false)
{
pTarget = target;
pListener = listener;
Ref();
}
Handle::~Handle()
{
if(IsOpen())
Close();
}
Handle& Handle::operator=( const Handle& h)
{
if(this == &h)
return *this;
Close();
Handle::Handle(h);
return (*this);
}
void Handle::Close()
{
KASSERT(IsOpen());
DeRef();
}
HandleTarget* Handle::GetTarget() const
{
KASSERT(IsOpen());
return pTarget;
}
HandleListener* Handle::GetListener() const
{
KASSERT(IsOpen());
return pListener;
}
bool Handle::IsOpen( void ) const
{
return bOpen;
}
void Handle::Ref()
{
KASSERT(!IsOpen());
if(pTarget->AddRef() == 1)
pListener->OnFistrOpen(this);
else
pListener->OnOpen(this);
bOpen = true;
}
void Handle::DeRef()
{
KASSERT(IsOpen());
if(pTarget->ReleaseRef() == 0)
pListener->OnLastClose(this);
else
pListener->OnClose(this);
bOpen = false;
} | true |
c294a6557f352e2fdf559e2c306d91d474951ae7 | C++ | Igronemyk/OI | /CodeForces/903E.cpp | UTF-8 | 1,990 | 3.28125 | 3 | [] | no_license | #include <cstdio>
#include <algorithm>
#include <cstring>
#include <map>
using namespace std;
const int MAX_CHILD_SIZE = 26;
int k,length;
bool found;
struct Trie {
struct Node {
Node *childs[MAX_CHILD_SIZE];
int countEnd;
Node() {
for(int i = 0;i < MAX_CHILD_SIZE;i++) childs[i] = NULL;
countEnd = 0;
}
bool hasChild(int index) {
return childs[index] != NULL;
}
};
Node *root;
Trie() {
root = new Node();
}
void insert(char *str,int length) {
Node *doing = root;
for(int i = 0;i < length;i++) {
int tmpIndex = str[i] - 'a';
if(!doing->hasChild(tmpIndex)) {
doing->childs[tmpIndex] = new Node();
}
doing = doing->childs[tmpIndex];
}
doing->countEnd++;
}
void dfs(int depth,Node *doing,char *result) {
if(doing->countEnd == k) {
found = true;
}
if(depth == length) return;
for(int i = 0;i < MAX_CHILD_SIZE;i++) {
if(doing->hasChild(i)) {
result[depth] = i + 'a';
dfs(depth + 1,doing->childs[i],result);
if(found) return;
}
}
}
};
int main() {
scanf("%d%d",&k,&length);
char *tmpStr = new char[length + 1];
Trie trie;
for(int doing = 0;doing < k;doing++) {
scanf("%s",tmpStr);
for(int i = 0;i < length;i++) {
for(int j = i + 1;j < length;j++) {
int tmpChar = tmpStr[i];
tmpStr[i] = tmpStr[j];
tmpStr[j] = tmpChar;
trie.insert(tmpStr,length);
tmpChar = tmpStr[i];
tmpStr[i] = tmpStr[j];
tmpStr[j] = tmpChar;
}
}
}
trie.dfs(0,trie.root,tmpStr);
if(found) {
printf("%s\n",tmpStr);
}else {
printf("-1\n");
}
return 0;
}
| true |
9e3ff04a9228f1166cdebc216687257592723353 | C++ | raptoravis/voxelbasedgi | /GlobalIllumination/src/Camera.cpp | UTF-8 | 1,614 | 2.640625 | 3 | [
"MIT"
] | permissive | #include <stdafx.h>
#include <Demo.h>
#include <Camera.h>
bool Camera::Init(float fovy, float aspectRatio, float nearClipDistance, float farClipDistance)
{
this->fovy = fovy;
this->aspectRatio = aspectRatio;
if ((nearClipDistance <= 0.0f) || (farClipDistance <= 0.0f))
return false;
bufferData.nearClipDistance = nearClipDistance;
bufferData.farClipDistance = farClipDistance;
bufferData.nearFarClipDistance = farClipDistance - nearClipDistance;
bufferData.projMatrix.SetPerspective(fovy, aspectRatio, nearClipDistance, farClipDistance);
invProjMatrix = bufferData.projMatrix.GetInverse();
uniformBuffer = Demo::renderer->CreateUniformBuffer(sizeof(BufferData));
if (!uniformBuffer)
return false;
UpdateUniformBuffer();
return true;
}
void Camera::UpdateUniformBuffer()
{
uniformBuffer->Update(&bufferData);
}
void Camera::Update(const Vector3 &position, const Vector3 &rotation)
{
bufferData.position = position;
this->rotation = rotation;
Matrix4 xRotMatrix, yRotMatrix, zRotMatrix, transMatrix, rotMatrix;
xRotMatrix.SetRotationY(-rotation.x);
yRotMatrix.SetRotationX(rotation.y);
zRotMatrix.SetRotationZ(rotation.z);
transMatrix.SetTranslation(-position);
rotMatrix = zRotMatrix * yRotMatrix*xRotMatrix;
bufferData.viewMatrix = rotMatrix * transMatrix;
bufferData.viewProjMatrix = bufferData.projMatrix*bufferData.viewMatrix;
bufferData.invViewProjMatrix = bufferData.viewProjMatrix.GetInverse();
direction.Set(-bufferData.viewMatrix.entries[2], -bufferData.viewMatrix.entries[6], -bufferData.viewMatrix.entries[10]);
direction.Normalize();
UpdateUniformBuffer();
}
| true |
99cc0bd475847bfac1f9a40b5b62e818834e21a6 | C++ | zhongershun/data-structure | /heapsort.cpp | UTF-8 | 2,507 | 3.625 | 4 | [] | no_license | #include<iostream>
using namespace std;
// 整体的思路:子树与父节点比较每次将最大的数向上传递,最后使得最大的数位于树顶,最后再把最后位置上的数与子节点上最大的数交换得到最大的数就去到了最后一位
struct point
{
int x;
int y;
};
// 比较,如果A大则返回True
bool compare(point A,point B)
{
if (A.x>B.x)
{
return true;
}
else if (A.x<B.x)
{
return false;
}
else
{
if (A.y>B.y)
{
return true;
}
else
{
return false;
}
}
}
bool ifleaf(int cur,int length)
{
if (cur<=length/2-1)
{
return true;
}
else
{
return false;
}
}
void swap(point &A,point &B)
{
point temp;
temp=A;
A=B;
B=temp;
}
void subheapbuild(point A[],int length,int cur,int child)
{
while(cur>=child)
{
int rchild=cur*2+2;
int lchild=cur*2+1;
if (rchild<length)
{
if (compare(A[rchild],A[cur]))
{
swap(A[cur],A[rchild]);
// if (ifleaf(rchild,length))
// {
// subheapbuild(A,length,rchild,cur);
// }
}
}
if (compare(A[lchild],A[cur]))
{
swap(A[cur],A[lchild]);
// if (ifleaf(lchild,length))
// {
// subheapbuild(A,length,lchild,cur);
// }
}
cur--;
}
}
void heapbuild(point A[],int length,int cur)
{
while(cur>=0)
{
int rchild=cur*2+2;
int lchild=cur*2+1;
if (rchild<length)
{
if (compare(A[rchild],A[cur]))
{
swap(A[cur],A[rchild]);
// if (ifleaf(rchild,length))
// {
// subheapbuild(A,length,rchild,cur);
// }
}
}
if (compare(A[lchild],A[cur]))
{
swap(A[cur],A[lchild]);
// if (ifleaf(lchild,length))
// {
// subheapbuild(A,length,lchild,cur);
// }
}
cur--;
}
}
void heapsort(point A[],int length,int cur)
{
while(length>1)
{
cur=length/2-1;
heapbuild(A,length,cur);
swap(A[0],A[length-1]);
length--;
}
}
int main()
{
point A[100];
int n;
cin>>n;
for (int i = 0; i < n; i++)
{
cin>>A[i].x>>A[i].y;
}
int cur;
heapsort(A,n,cur);
for (int i = 0; i < n; i++)
{
cout<<"("<<A[i].x<<","<<A[i].y<<")"<<endl;
}
return 0;
} | true |
456d0c2cb6a2d68a18ed785890c22afba2d4f633 | C++ | genzyy/ncurses-library | /recursion/hard/board_game.cpp | UTF-8 | 391 | 3.09375 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int diceArray[] = {1, 2, 3, 4, 5, 6};
int boardGame(int start, int end) {
if(start == end) return 1;
if(start > end) return 0;
int count = 0;
for(int i=1; i<=6; i++)
count += boardGame(start + i, end);
return count;
}
int main() {
int dest;
cin>>dest;
int result = boardGame(0,dest);
cout<<result<<endl;
return 0;
}
| true |
4ea0eeddb65ec88ccce4336c9ce9a01efb29a4f9 | C++ | networkit/networkit | /include/networkit/distance/APSP.hpp | UTF-8 | 1,465 | 2.875 | 3 | [
"MIT"
] | permissive | /*
* APSP.hpp
*
* Created on: 07.07.2015
* Author: Arie Slobbe
*/
#ifndef NETWORKIT_DISTANCE_APSP_HPP_
#define NETWORKIT_DISTANCE_APSP_HPP_
#include <memory>
#include <networkit/base/Algorithm.hpp>
#include <networkit/distance/SSSP.hpp>
#include <networkit/graph/Graph.hpp>
namespace NetworKit {
/**
* @ingroup distance
* Class for all-pair shortest path algorithm.
*/
class APSP : public Algorithm {
public:
/**
* Creates the APSP class for @a G.
*
* @param G The graph.
*/
APSP(const Graph &G);
~APSP() override = default;
/**
* Computes the shortest paths from each node to all other nodes.
* The algorithm is parallel.
*/
void run() override;
/**
* Returns a vector of weighted distances between node pairs.
*
* @return The shortest-path distances from each node to any other node in
* the graph.
*/
const std::vector<std::vector<edgeweight>> &getDistances() const {
assureFinished();
return distances;
}
/**
* Returns the distance from u to v or infinity if u and v are not
* connected.
*
*/
edgeweight getDistance(node u, node v) const {
assureFinished();
return distances[u][v];
}
protected:
const Graph &G;
std::vector<std::vector<edgeweight>> distances;
std::vector<std::unique_ptr<SSSP>> sssps;
};
} /* namespace NetworKit */
#endif // NETWORKIT_DISTANCE_APSP_HPP_
| true |
b60d124c5036606debec3245ebbfa4b39f80cf6a | C++ | moakbari/LeetCode | /MaximumSumOf3Non-OverlappingSubarrays.cpp | UTF-8 | 1,595 | 2.953125 | 3 | [] | no_license | class Solution {
public:
vector<int> maxSumOfThreeSubarrays(vector<int>& nums, int k) {
if (k == 0){
return vector<int>();
}
vector<int> runSum(nums.size() + 1, 0);
partial_sum(nums.begin(), nums.end(), runSum.begin() + 1);
vector<int> leftIndex(nums.size(), -1);
int leftMaxSum = numeric_limits<int>::min();
for(int i = k - 1; i < nums.size() - 2*k; i++){
int curSum = runSum[i + 1] - runSum[i - k + 1];
leftIndex[i] = curSum > leftMaxSum ? i - k + 1 : leftIndex[i - 1];
leftMaxSum = max(leftMaxSum, runSum[i + 1] - runSum[i + 1 - k]);
}
vector<int> rightIndex(nums.size(), -1);
int rightMaxSum = numeric_limits<int>::min();
for(int i = nums.size() - k; i >= 2*k; i--){
int curSum = runSum[i + k] - runSum[i];
rightIndex[i] = curSum > rightMaxSum ? i : rightIndex[i + 1];
rightMaxSum = max (rightMaxSum, curSum);
}
vector<int> result(3, -1);
int totalMax = numeric_limits<int>::min();
for(int i = k; i <= nums.size() - 2*k; i++){
int l = leftIndex[i - 1];
int r = rightIndex[i + k];
int curSum = runSum[l + k] - runSum[l] + runSum[i + k] - runSum[i] + runSum [r + k] - runSum[r];
if (curSum > totalMax){
totalMax = curSum;
result[0] = l;
result[1] = i;
result[2] = r;
}
}
return result;
}
};
| true |
3ef27edd200210f4f5ea9ab0606a83ac09620ea6 | C++ | xmlb88/algorithm | /leetcode/superPow.cpp | GB18030 | 1,466 | 3.59375 | 4 | [] | no_license | #include<iostream>
#include<vector>
using namespace std;
// a k ηĽ
int mypow(int a, int k);
//
int superPow(int a, vector<int>& b) {
// ݹbase case
if (b.empty()) return 1;
// ȡһ
int last = b.back();
b.pop_back();
// ԭ⻯Сģݹ
int part1 = mypow(a, last);
int part2 = mypow(superPow(a, b), 10);
// ϲ
return part1 * part2;
}
// mod
// (a * b) % k = (a % k)(b % k) % k
int base = 1337;
// akηȻbaseģĽ
int mypow(int a, int k) {
// ģ
a %= base;
int res = 1;
for (int i = 0; i < k; i++) {
// ˷ܻ
res *= a;
// Գ˷ģ
res %= base;
}
return res;
}
int superPow(int a, vector<int>& b) {
if (b.empty()) return 1;
int last = b.back();
b.pop_back();
int part1 = mypow(a, last);
int part2 = mypow(superPow(a, b), 10);
// ÿγ˷ȡģ
return (part1 * part2) % base;
}
// review
int base = 1337;
int superPow(int a, vector<int>& b) {
if (b.empty()) return 1;
int last = b.back();
b.pop_back();
return mypow(superPow(a, b), 10) * mypow(a, last) % base;
}
int mypow(int a, int k) {
a = a % base;
int res = 1;
for (int i = 0; i < k; i++) {
res *= a;
res %= base;
}
return res;
} | true |
7218c2bf117a345b7bf26b1612c93e7bfc6a1ff5 | C++ | rutitka/TetrisGame | /TetrisGame/Joker.h | UTF-8 | 385 | 2.6875 | 3 | [] | no_license | #pragma once
#include "Shape.h"
class Joker : public Shape
{
public:
virtual void setShape(const Point& head) override;
virtual void move(char keypressed, bool erase) override;
virtual void dropDown(int lowestLine) override;
virtual bool checkAvailability(Board &board, char keyPressed) override;
virtual string type() override;
virtual void rotate()override;
};
| true |
a15f229e73ebed6a8580e3d9997701a5ea454dc2 | C++ | KimBoWoon/HomeWork | /Visual Studio 2013/Projects/Data Structures/Data Structures/Sparse Matrix.h | UTF-8 | 871 | 3.1875 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
#define SIZE 5
typedef int DataType;
class Matrix
{
private:
int row, col;
DataType elem;
public:
friend ostream& operator<< (ostream& os, vector<Matrix *> M);
void Setrow(int x);
void Setcol(int x);
void Setelem(DataType x);
int Getrow() const;
int Getcol() const;
DataType Getelem() const;
void SparseMatrixTable(DataType mat[SIZE][SIZE], DataType mat2[SIZE][SIZE], vector<Matrix *> &M);
void FastTranspose(DataType mat[SIZE][SIZE], DataType mat2[SIZE][SIZE]);
void MakeSparseMatrix(DataType mat2[SIZE][SIZE], vector<Matrix *> &M);
void Change(vector<Matrix *> &M);
void Sort(vector<Matrix *> &M) const;
void PrintMatrix(DataType mat[SIZE][SIZE]) const;
void InitMatrix(DataType mat[SIZE][SIZE]);
};
class Functor
{
public:
bool operator() (Matrix *M1, Matrix *M2);
}; | true |
86ec6594094dd212bcc5a4005abd2a492ffdb720 | C++ | eokeeffe/quasi_invariant-features | /src/gder.cc | UTF-8 | 2,442 | 2.59375 | 3 | [] | no_license | /*
* Creating Gaussian Derivatives for images
*/
#include <gder.h>
#include <operations.h>
cv::Mat fill_border(cv::Mat in, int bw)
{
int hh = in.rows;
int ww = in.cols;
int dd = in.depth();
if(dd == 1)
{
}
else
{
}
return cv::Mat::eye(hh,ww,CV_32F);
}
cv::Mat gder(cv::Mat f, double sigma, int iorder, int jorder)
{
int counter=0;
double break_off_sigma = 3.;
double filtersize = floor(break_off_sigma*sigma+0.5);
//get the apeture size of the gauss kernel
for(int i=-filtersize;i<=filtersize;i++){counter++;}
cv::Mat Gauss,Gx,Gy,H;
cv::Mat x(counter,1,CV_32F);
//verified working against results from Matlab
for(int i=-filtersize,counter=0;i<=filtersize;i++,counter++)
{
x.at<float>(counter) = i;
}
//checked the differences, I don't know why it's there ?
//f = fill_border(f,filtersize);
//create standard gauss kernel
Gauss = cv::getGaussianKernel(counter,sigma, CV_32F);
switch(iorder)
{
case 0:
{
Gx = Gauss/cv::sum(Gauss)[0];
break;
}
case 1:
{
Gx = -( x / (sigma*sigma) ).mul(Gauss);
Gx = Gx / cv::sum(x.mul(Gx))[0];
break;
}
case 2:
{
Gx = (( x.mul(x)/pow(sigma,4) ) - (1/pow(sigma,2) )).mul(Gauss);
Gx = Gx-cv::sum(Gx)[0]/x.cols;
Gx = Gx/cv::sum(0.5*x.mul(x).mul(Gx))[0];
break;
}
}
//cv::filter2D(f,H,f.depth(),Gx,cv::Point(-1,-1),0.0,cv::BORDER_DEFAULT);
switch(jorder)
{
case 0:
{
Gy = Gauss/cv::sum(Gauss)[0];
break;
}
case 1:
{
Gy = -(x/(sigma*sigma)).mul(Gauss);
Gy = Gy/cv::sum(x.mul(Gy))[0];
break;
}
case 2:
{
Gy = ((x.mul(x) / pow(sigma,4)) - (1/pow(sigma,2)) ).mul(Gauss);
Gy = Gy-cv::sum(Gy)[0]/x.cols;
Gy = Gy/cv::sum(0.5*x.mul(x).mul(Gy))[0];
break;
}
}
//cv::filter2D(f,H,f.depth(),Gy.t(),cv::Point(-1,-1),0.0,cv::BORDER_DEFAULT);
cv::sepFilter2D(f,H,f.depth(),Gx,Gy.t(),cv::Point(-1,-1),sigma,cv::BORDER_DEFAULT);
//H=H(filtersize+1:size(H,1)-filtersize,filtersize+1:size(H,2)-filtersize);
return H(cv::Range(filtersize+1,H.rows-filtersize),cv::Range(filtersize+1,H.cols-filtersize));
}
| true |
3b55b6cf82d5ce9f916f730c681e9054d66f28e7 | C++ | Hatsunespica/PlayWithLLVM | /firstTry/Hello.cpp | UTF-8 | 6,011 | 2.5625 | 3 | [
"Apache-2.0"
] | permissive | //===- Hello.cpp - Example code from "Writing an LLVM Pass" ---------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements two versions of the LLVM "Hello World" pass described
// in docs/WritingAnLLVMPass.html
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/Statistic.h"
#include "llvm/IR/Function.h"
#include "llvm/Pass.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/IR/CallSite.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Constants.h"
#include <vector>
using namespace llvm;
#define DEBUG_TYPE "hello"
STATISTIC(HelloCounter, "Counts number of functions greeted");
namespace {
// Hello - The first implementation, without getAnalysisUsage.
struct Hello : public FunctionPass {
static char ID; // Pass identification, replacement for typeid
Hello() : FunctionPass(ID) {}
bool runOnFunction(Function &F) override {
++HelloCounter;
errs() << "Hello: ";
errs().write_escaped(F.getName()) << '\n';
return false;
}
};
}
char Hello::ID = 0;
static RegisterPass<Hello> X("hello", "Hello World Pass");
namespace {
// Hello2 - The second implementation with getAnalysisUsage implemented.
struct Hello2 : public FunctionPass {
static char ID; // Pass identification, replacement for typeid
Hello2() : FunctionPass(ID) {}
bool runOnFunction(Function &F) override {
/*++HelloCounter;
errs() << "Hello: ";
errs().write_escaped(F.getName()) << '\n';*/
unsigned int basicBlockCount=0;
unsigned int instructionCount=0;
for(BasicBlock& bb:F){
++basicBlockCount;
for(Instruction&i :bb){
++instructionCount;
}
}
errs()<<"Hello2: ";
errs().write_escaped(F.getName())<<"Basic Block:"<<basicBlockCount<<"\nInsturction"
<<instructionCount<<"\n";
return false;
}
// We don't modify the program, so we preserve all analyses.
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.setPreservesAll();
}
};
}
char Hello2::ID = 0;
static RegisterPass<Hello2>
Y("hello2", "Hello World Pass (with getAnalysisUsage implemented)");
namespace {
// Hello2 - The second implementation with getAnalysisUsage implemented.
struct Hello3 : public FunctionPass {
static char ID; // Pass identification, replacement for typeid
Hello3() : FunctionPass(ID) {}
bool runOnFunction(Function &F) override {
/*++HelloCounter;
errs() << "Hello: ";
errs().write_escaped(F.getName()) << '\n';
unsigned int basicBlockCount=0;
unsigned int instructionCount=0;
for(BasicBlock& bb:F){
++basicBlockCount;
for(Instruction&i :bb){
++instructionCount;
}
}
errs()<<"Hello2: ";
errs().write_escaped(F.getName())<<"Basic Block:"<<basicBlockCount<<"\nInsturction"
<<instructionCount<<"\n";*/
for(BasicBlock& bb:F){
for(Instruction& i:bb){
CallSite cs(&i);
if(!cs.getInstruction()){
continue;
}
Value *called=cs.getCalledValue()->stripPointerCasts();
if(Function* f=dyn_cast<Function>(called)){
errs()<<"\tDirect call to function:"<<f->getName()<<" from "<<F.getName()<<"\n";
}
}
}
return false;
}
// We don't modify the program, so we preserve all analyses.
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.setPreservesAll();
}
};
}
char Hello3::ID = 0;
static RegisterPass<Hello3>
Z("hello3", "Hello World Pass (Get direct calls)");
namespace {
// Hello2 - The second implementation with getAnalysisUsage implemented.
struct Hello4 : public ModulePass {
static char ID; // Pass identification, replacement for typeid
Hello4() : ModulePass(ID) {}
bool runOnModule(Module& M)override{
setupHooks("_Z10__initMaini",M);
Module::FunctionListType&functions=M.getFunctionList();
for(Module::FunctionListType::iterator FI=functions.begin(),FE=functions.end();FI!=FE;++FI){
if(FI->getName()=="_Z10__initMaini"){
continue;
}
if(FI->getName()=="main"){
instrumentEnterFunction("_Z10__initMaini",*FI,M);
}
}
return true;
}
void setupHooks(StringRef instrumentFunctionName, Module& M){
auto& context=M.getContext();
Type* voidTy=Type::getVoidTy(context);
Type* intTy=Type::getInt32Ty(context);
FunctionType* funcTy=FunctionType::get(voidTy,intTy,false);
Function::Create(funcTy,llvm::GlobalValue::ExternalLinkage)->setName(instrumentFunctionName);
}
void instrumentEnterFunction(StringRef instrumentFunctionName,Function& functionToInstrument,Module& M){
auto& context=M.getContext();
Type* voidTy=Type::getVoidTy(context);
Type* intTy=Type::getInt32Ty(context);
std::vector<Type*> params;
params.push_back(intTy);
FunctionType* funcTy=FunctionType::get(voidTy,params,false);
Constant* hook=M.getOrInsertFunction(instrumentFunctionName,funcTy);
BasicBlock* bb=&functionToInstrument.front();
Instruction *I =&bb->front();
std::vector<Value*> args;
for(unsigned i=0;i<funcTy->getNumParams();++i){
Type* t=funcTy->getParamType(i);
Value* newValue=ConstantInt::get(t,0x3f3f3f3f);
args.push_back(newValue);
errs()<<"getNumParams()"<<i<<"\n";
}
CallInst::Create(hook,args)->insertBefore(I);
}
};
}
char Hello4::ID = 0;
static RegisterPass<Hello4>
W("hello4","test hello4 (set up a hook)");
| true |
3ba38141b7e999619855a759bb01137d5a51434e | C++ | Professor-Emanuel/Cpp_Advanced | /PointersExample/PointersExample/PointersExample.cpp | UTF-8 | 1,806 | 3.953125 | 4 | [] | no_license | #include <iostream>
int main()
{
//a POINTER is just an INTEGER that holds an address -> that address can point to int, float, user defined data type, etc
int var = 8; //variables created on the STACK memory
void* ptr = NULL; // or 0 or nullptr (added since cpp11)
void* ptrI = &var; //debug and see what address of ptrI contains, you should see 08 00 00 00 -> 4 bytes and the value 8
// if var = 10 -> you should see 0a 00 00 00, since in hexadecimal 10 = a
//the type of the POINTER doesn't really MATTER
//but are useful for manipulation of memory
//the above can be
int* ptrJ = &var;// ptrI, ptrJ, ptrD point to the same memory address that contains 08 00 00 00
double* ptrD = (double*)&var; // ptrD point to the same memory address as the other pointers but contains some junk value
std::cout << "Address of var: " << &var << " with value: " << var << std::endl;
std::cout << "Address of var: " << ptrI << " with value: " << var << std::endl; // *ptrI -> ERROR, because it has VOID type
std::cout << "Address of var: " << ptrJ << " with value: " << *ptrJ << std::endl;
std::cout << "Address of var: " << ptrD << " with value: " << *ptrD << std::endl;
std::cout << "Address of ptrI: " << &ptrI << " with value: " << ptrI << std::endl;
std::cout << "Address of ptrJ: " << &ptrJ << " with value: " << ptrJ << std::endl;
std::cout << "Address of ptrD: " << &ptrD << " with value: " << ptrD << std::endl;
char* buffer = new char[8]; // 8 bytes allocated, with the pointer pointing to the begining of that memory
memset(buffer, 0, 8); // 00 00 00 00 00 00 00 00 -> 8 bytes of zeros
char** ptrC = &buffer;
delete[] buffer; // deallocate memory
return 0;
}
| true |
b60afc53c061958b0610dd7a408e667296a95654 | C++ | ajay7633/Computer-Science-Projects | /Project4/implementation.cpp | UTF-8 | 13,369 | 3.421875 | 3 | [] | no_license | //Name:Ajay M Nair
#include "header.hpp"
//Default Constructor for FlightInfo Class
FlightInfo::FlightInfo(){
airline = nullptr;
departAirport = nullptr;
arriveAirport = nullptr;
}
//Destructor for FlightInfo class
FlightInfo::~FlightInfo() {
if(airline != nullptr){
delete[]airline;
airline = nullptr;
}
if(departAirport != nullptr){
delete[]departAirport;
departAirport = nullptr;
}
if(arriveAirport != nullptr){
delete[] arriveAirport;
arriveAirport = nullptr;
}
}
//
// Getter function
//
const char* FlightInfo::getAirline() {
return airline;
}
const char* FlightInfo::getDepartAirport()
{
return departAirport;
}
const char* FlightInfo::getArrivalAirport()
{
return arriveAirport;
}
int FlightInfo::getFlightNum() {
return flightNum;
}
int FlightInfo::getDepartMonth() {
return departMonth;
}
int FlightInfo::getDepartDay() {
return departDay;
}
double FlightInfo::getDepartTime()
{
return departTime;
}
int FlightInfo::getArrivalMonth() {
return arriveMonth;
}
int FlightInfo::getArrivalDay() {
return arriveDay;
}
double FlightInfo::getArrivalTime()
{
return arriveTime;
}
//Flight Info Contructor which takes arguments
FlightInfo::FlightInfo(char tairline[],int tflightNum, int tdepartMon,int tdepartDay,double tdepartTime,int tarriveMon,int tarriveDay,double tarriveTime,char tdepartAirport[],char tarriveAirport[])
{
int len;
len = strlen(tairline);
airline = new char[len + 1];
strcpy(airline, tairline);
flightNum = tflightNum;
departMonth = tdepartMon;
departDay = tdepartDay;
departTime = tdepartTime;
arriveMonth = tarriveMon;
arriveDay = tarriveDay;
arriveTime = tarriveTime;
len = strlen(tdepartAirport);
departAirport = new char[len + 1];
strcpy(departAirport, tdepartAirport);
len = strlen(tarriveAirport);
arriveAirport = new char[len + 1];
strcpy(arriveAirport, tarriveAirport);
}
//Default Constructor for Flight Collection
FlightCollection::FlightCollection() {
countAndIndex = 0;
for(int i=0 ;i < LIST_SIZE ; i++){
flights[i]=nullptr;
}
}
//Return the Current Index
int FlightCollection::getIndex() {
int index;
index = countAndIndex;
return index;
}
//
//This function returns the maximum days in the corresponding month
//
int FlightCollection::getMaxDay(int theMonth)
{
switch (theMonth)
{
case 2:
return 28;
break;
case 4: //foll through
case 6:
case 9:
case 11:
return 30;
break;
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
return 31;
break;
default:
;
}
}
//
//Read Flight function : Opens the file in directory
//
void FlightCollection::readFile()
{
char quit[] = "quit";
cout << "Welcome to the flight information program. what is the name of the flight data file? or type 'quit' to exit: ";
cin.getline(fileName, STR_SIZE);
if (strcmp(fileName, quit) == 0)
{
cout << "You decided to Terminate the Program , Press any key to continue " << endl;
cin.get();
exit(0);
}
inFile.open(fileName);
//File Retrieve
while (!inFile) {
cout << "Error Unable to open file..Please enter the correct filename: ";
cin.getline(fileName, STR_SIZE);
inFile.open(fileName);
if (strcmp(fileName, quit) == 0)
{
cout << "You decided to Terminate the Program , Press any key to continue " << endl;
cin.get();
exit(0);
}
}
}
//
//Load Flight Function : Loads Flights from the File
//
void FlightCollection::loadFlights() {
char tairline[STR_SIZE];
int tflightNum;
int tdepartMon;
int tdepartDay;
double tdepartTime;
int tarriveMon;
int tarriveDay;
double tarriveTime;
char flightNumStr[STR_SIZE];
char departMonthStr[STR_SIZE];
char departDayStr[STR_SIZE];
char departTimeStr[STR_SIZE];
char arriveMonthStr[STR_SIZE];
char arriveDayStr[STR_SIZE];
char arriveTimeStr[STR_SIZE];
char tdepartAirport[STR_SIZE];
char tarriveAirport[STR_SIZE];
int count = 0;
if (count < LIST_SIZE) {
while (!inFile.eof()) {//end of file
inFile.getline(tairline, STR_SIZE, ',');
inFile.getline(flightNumStr, STR_SIZE, ',');
tflightNum = atoi(flightNumStr);
inFile.getline(departMonthStr, STR_SIZE, ',');
tdepartMon= atoi(departMonthStr);
inFile.getline(departDayStr, STR_SIZE, ',');
tdepartDay = atoi(departDayStr);
inFile.getline(departTimeStr, STR_SIZE, ',');
tdepartTime = atof(departTimeStr);
inFile.getline(arriveMonthStr, STR_SIZE, ',');
tarriveMon = atoi(arriveMonthStr);
inFile.getline(arriveDayStr, STR_SIZE, ',');
tarriveDay = atoi(arriveDayStr);
inFile.getline(arriveTimeStr, STR_SIZE, ',');
tarriveTime = atof(arriveTimeStr);
inFile.getline(tdepartAirport, STR_SIZE, ',');
inFile.getline(tarriveAirport, STR_SIZE, '\n');
flights[count]= new FlightInfo(tairline, tflightNum, tdepartMon, tdepartDay, tdepartTime, tarriveMon, tarriveDay, tarriveTime, tdepartAirport, tarriveAirport);
count++;
inFile.peek(); // check for the end of file marker.
}
countAndIndex = count;
cout << "Sucessfully loaded " << count << " flights" << endl;
listItems();
inFile.close(); //just added
}
else {
cout << " Sorry there is no more room for items" << endl;
}
}
//
// Add a Flight Function : Allows User to add flights
//
void FlightCollection::addAflight() {
int i = countAndIndex;
int max;
char tAirline[STR_SIZE];
int tflightNum;
int tdepartMonth;
int tdepartDay;
double tdepartTime;
int tarriveMonth;
int tarriveDay;
double tarriveTime;
char tdepartAirport[STR_SIZE];
char tarriveAirport[STR_SIZE];
if (i<LIST_SIZE) {
cout << "what is name of airline :";
cin.ignore();
cin.getline(tAirline, STR_SIZE);
cout << "What is flight number: ";
cin >> tflightNum;
while (cin.fail() || tflightNum <= 0)
{
cin.clear();
cin.ignore(STR_SIZE, '\n');
cout << "Please enter a positive number: ";
cin >> tflightNum;
}
cout << "What is the departure month? :";
cin >> tdepartMonth;
while (cin.fail() || tdepartMonth<1 || tdepartMonth>12)
{
cin.clear();
cin.ignore(STR_SIZE, '\n');
cout << "Please enter a valid month (1-12): ";
cin >> tdepartMonth;
}
max = getMaxDay(tdepartMonth);
cout << "What is the departure day? :";
cin >> tdepartDay;
while (tdepartDay<1 || tdepartDay > max)
{
cin.clear();
cin.ignore(STR_SIZE, '\n');
cout << "Please enter a valid departure day: ";
cin >> tdepartDay;
}
cout << "What is the departTime? :";
cin >> tdepartTime;
while (cin.fail() || tdepartTime < 0 || tdepartTime > 23.59)
{
cin.clear();
cin.ignore(STR_SIZE, '\n');
cout << "Please enter a valid departure Time 0-24: ";
cin >> tdepartTime;
}
cout << "What is the arrival month? :";
cin >> tarriveMonth;
while (cin.fail() || tarriveMonth < tdepartMonth || tdepartMonth>12)
{
cin.clear();
cin.ignore(STR_SIZE, '\n');
cout << "Arrival month cannont be before the departure month. Please re-enter Arrival month: ";
cin >> tarriveMonth;
}
cout << "What is the arrival day? :";
max = getMaxDay(tarriveMonth);
cin >> tarriveDay;
if (tarriveMonth == tdepartMonth) {
while (tarriveDay < tdepartDay || tarriveDay > max)
{
cin.clear();
cin.ignore(STR_SIZE, '\n');
cout << "Arrival day is not within the limits: " << tdepartDay << " and " << max;
cin >> tarriveDay;
}
}
else {
while (tarriveDay < 1 || tarriveDay > max)
{
cin.clear();
cin.ignore(STR_SIZE, '\n');
cout << "Please Enter a valid arrival day: ";
cin >> tarriveDay;
}
}
cout << "What is the arrival Time? :";
cin >> tarriveTime;
////
////just added
////
while (tarriveTime > 23.59) {
cout << "Please enter a valid Arrival Time 0-24: ";
cin >> tarriveTime;
}
////
////
if (tarriveMonth == tdepartMonth && tarriveDay == tdepartDay) {
while (cin.fail() || tarriveTime <= tdepartTime || tarriveTime > 23.59)
{
cin.clear();
cin.ignore(STR_SIZE, '\n');
cout << "Please enter a valid Arrival Time 0-24: ";
cin >> tarriveTime;
}
}
cout << "What is the departure airport? ";
cin.ignore();
cin.getline(tdepartAirport, STR_SIZE);
cout << "What is the arrival airport? ";
cin.getline(tarriveAirport, STR_SIZE);
flights[countAndIndex] = new FlightInfo(tAirline, tflightNum, tdepartMonth, tdepartDay, tdepartTime, tarriveMonth, tarriveDay, tarriveTime, tdepartAirport, tarriveAirport);
countAndIndex++;
cout << tAirline << " " << tflightNum << " was sucessfully added to the flight DataBase" << endl;
}
else {
cout << " Sorry there is no more room for items" << endl;
}
}
//
//List the flights : All the flights will be listed
//Those added to the database aswell as the the flights loaded from file
//
void FlightCollection::listItems() {
cout << "Airline" << "\t\t\t" << "Flight#" << "\t\t" << "Departure" << "\t\t" << "Arrival" << "\t\t\t" << "From" << "\t\t" << "To" << endl;
cout << "======================================================================================================================" << endl;
int m = countAndIndex;
for (int i = 0; i<m; i++) {
cout << fixed << setprecision(2)
<< left << setw(25) << flights[i]->getAirline()
<< left << setw(15) << flights[i]->getFlightNum()
<< flights[i]->getDepartMonth()<< "/"
<< flights[i]->getDepartDay()
<< " at "
<< setw(15) << flights[i]->getDepartTime()
<< flights[i]->getArrivalMonth()<< "/"
<< flights[i]->getArrivalDay() << " at "
<< setw(15) << flights[i]->getArrivalTime()
<< setw(20) << flights[i]->getDepartAirport()
<< setw(20) << flights[i]->getArrivalAirport() << endl;
}
}
//
//Search Flight Function : Allows the User to Search Flights :Outputs all Info on flights if found
//
void FlightCollection::searchFlight()
{
cout << "For what flights would you like to search: ";
cin.ignore(STR_SIZE, '\n');
cin.getline(searchName, STR_SIZE);
cout << "What is the search Number: ";
cin >> searchNum;
while (!cin)
{
cin.clear();
cout << "please re-enter a number : ";
cin.ignore(STR_SIZE, '\n');
cin >> searchNum;
}
cin.ignore();
int count = 0;
int found = 0;
for (count; count < countAndIndex; count++)
{
if ((strcmp(searchName, flights[count]->getAirline()) == 0) && flights[count]->getFlightNum() == searchNum)
{
found++;
cout << "Information on " << searchName << " " << searchNum << " is as follows: " << endl;
cout << "Departure Date and Time: " << flights[count]->getDepartMonth() << "/" << flights[count]->getDepartDay() << " at " << flights[count]->getDepartTime() << " From: "
<< flights[count]->getDepartAirport() << " To: " << flights[count]->getArrivalAirport() << endl;
}
}
if (found == 0)
{
cout << searchName << " " << searchNum << " was not found in the database" << endl;
}
}
//
//Write File Function : Ability to write the function to the file
//
void FlightCollection::writeFlight() {
outFile.open(fileName);
int m = countAndIndex;
for (int i = 0; i < m; i++) {
outFile << flights[i]->getAirline() << "," << flights[i]->getFlightNum() << "," << flights[i]->getDepartMonth() << "," << flights[i]->getDepartDay() << ","
<< flights[i]->getDepartTime() << "," << flights[i]->getArrivalMonth()<<"," << flights[i]->getArrivalDay()<<"," << flights[i]->getArrivalTime()<<","
<< flights[i]->getDepartAirport()<<"," << flights[i]->getArrivalAirport()<<endl;
}
outFile.close();
}
//Destructor for FlightCollection class
FlightCollection::~FlightCollection(){
for(int i=0; i < countAndIndex ; i++)
{
if(flights[i] != nullptr){
delete flights[i];
flights[i] =nullptr;
}
}
}
//
//END OF PROGRAM
| true |
facf293157f7643e66c1b3bba58b5e34c0479c6d | C++ | PrakharJain-Git/InterviewBit | /Array/Maximum_Absolute_Difference.cpp | UTF-8 | 972 | 2.515625 | 3 | [] | no_license | int Solution::maxArr(vector<int> &A) {
/* int len,i,j,k,l,sum=0,max=INT_MIN ;
len=A.size() ;
for (i=0;i<len;i++)
{
for (j=i;j<len;j++)
{
k=A[i]-A[j] ;
l=j-i ;
if (k<0)
{
k=-1*k ;
}
sum=k+l ;
if (sum>max)
{
max=sum ;
}
}
}
return max ; */
int len,i,j,k,min1=INT_MAX,min2=INT_MAX,max1=INT_MIN,max2=INT_MIN,ans ;
len=A.size() ;
for (i=0;i<len;i++)
{
j=A[i]+i ;
if (min1>j)
{
min1=j ;
}
if (max1<j)
{
max1=j ;
}
k=A[i]-i ;
if (min2>k)
{
min2=k ;
}
if (max2<k)
{
max2=k ;
}
}
if (max1-min1>max2-min2)
{
ans=max1-min1 ;
}
else
{
ans=max2-min2 ;
}
return ans ;
}
| true |
c0439ea70916d18f61973c696e4614f3fde87142 | C++ | RiceReallyGood/LeetCode_Revise | /101-200/113_Path_Sum_II.h | UTF-8 | 774 | 3.046875 | 3 | [] | no_license | #include "../definitions.h"
#include <vector>
using namespace std;
class Solution {
public:
vector<vector<int>> pathSum(TreeNode* root, int sum) {
if(root == nullptr) return {};
vector<vector<int>> ret;
vector<int> path;
recurse(root, path, sum, ret);
return ret;
}
private:
void recurse(TreeNode* root, vector<int>& path, int& target, vector<vector<int>>& res){
path.push_back(root->val);
target -= root->val;
if(!root->left && !root->right && target == 0){
res.emplace_back(path);
}
if(root->left) recurse(root->left, path, target, res);
if(root->right) recurse(root->right, path, target, res);
target += root->val;
path.pop_back();
}
}; | true |
3ddebe409762e8ea010e9e16e5c34c2a15ac2233 | C++ | sittu071/cpp | /DuplicateElementInVector/main.cpp | UTF-8 | 645 | 3.25 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <map>
using namespace std;
int main()
{
vector<std::string> vecOfStings{ "at" , "hello", "hi", "there", "where", "now", "is", \
"that" , "hi" , "where", "at", "no", "yes", "at"};
map<string,int> countMap;
for (auto & elem : vecOfStings)
{
auto result = countMap.insert(std::pair<std::string, int>(elem, 1));
if (result.second == false)
result.first->second++;
}
for(auto & elem: countMap)
{
if(elem.second > 1)
cout<<elem.first<<" "<<elem.second<<endl;
}
return 0;
}
| true |
f272c4af4affa445453bbb75c16dbdb4aa34a4f6 | C++ | tridibsamanta/Algorithmic-Toolbox | /Week 2/fibonacci_partial_sum.cpp | UTF-8 | 1,273 | 3.328125 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int get_fibonacci_small(int n, int m) {
int fib[n + 1];
fib[0] = 0;
fib[1] = 1;
for (int i = 2; i <= n; i++) {
fib[i] = (fib[i - 1] + fib[i - 2]) % m;
}
return fib[n];
}
int get_pisano_period_length(int m) {
if (m == 1)
return 0;
int first = -1, second = -1, i = 2;
while (1) {
second = get_fibonacci_small(i, m);
if (second == 1 && first == 0)
return i - 1;
first = second;
++i;
}
}
long long get_fibonacci_huge_fast(long long n, long long m) {
int pisano_length = get_pisano_period_length(m);
long long rem;
do {
rem = n % pisano_length;
n = rem;
} while (rem >= pisano_length);
return get_fibonacci_small(n, m);
}
int get_fibonacci_partial_sum_fast(long long from, long long to)
{
int a = get_fibonacci_huge_fast(to + 2, 10) - 1;
int b = get_fibonacci_huge_fast(from + 1, 10) - 1;
if (a >= b)
return (a - b);
else
return (10 + a - b);
}
int main()
{
long long from, to;
cin >> from >> to;
int res = get_fibonacci_partial_sum_fast(from, to);
cout << res << '\n';
}
| true |
c1f240249c33f2fa221070b524e5684b1e90f460 | C++ | ammadz789/DataStructures | /HW2/26277-MuhammadAmmadZohair/QuadTree.h | UTF-8 | 11,704 | 3.671875 | 4 | [] | no_license | #include <string>
#include <string.h>
#include <iostream>
#include <vector>
#include <math.h>
#include <cmath>
using namespace std;
//the node structure has seven field
struct node{
//4 pointers denoting quadrants
node *NE;
node *NW;
node *SE;
node *SW;
int X_cord;
int Y_cord;
string city_name;
node(node *ne, node *nw, node *se, node *sw, int x, int y, string str) //constructor
{
NE = ne;
NW = nw;
SE = se;
SW = sw;
X_cord = x;
Y_cord = y;
city_name = str;
}
};
class QuadTree
{
private:
node *root; //the root node
public:
QuadTree()
{
root = nullptr; // root is initialized as null in the constructor
}
~QuadTree() //destructor for deallocating memory
{
deleteTree(root);
}
void deleteTree(node*Root)
{
if (Root != nullptr)
{
deleteTree(Root->SE);
deleteTree(Root->SW);
deleteTree(Root->NE);
deleteTree(Root->NW);
}
delete Root;
}
int indicator;
//insert inserts the new node in the suitable location
void PT_INSERT(node *toInsert)
{
if (root == nullptr)
{
root = toInsert;
return;
}
else
{
node *temp = root;
if (temp != nullptr)
{
node *insertHere = PT_COMPARE(toInsert, root);
if (indicator == 1)
{
insertHere->SW = toInsert;
}
else if (indicator == 2)
{
insertHere->NW = toInsert;
}
else if (indicator == 3)
{
insertHere->SE = toInsert;
}
else if (indicator == 4)
{
insertHere->NE = toInsert;
}
}
}
}
//compare function recursively compares the node to add with already existent nodes in the tree inorder to determine a suitable
//location to insert the new node with respect to other nodes
node *PT_COMPARE(node *toSearch, node *Root)
{
if (Root == nullptr)
return Root;
indicator = 0;
if (toSearch->X_cord < Root->X_cord)
{
if (toSearch->Y_cord < Root->Y_cord)
{
if (Root->SW == nullptr)
{
indicator = 1;
return Root;
}
return PT_COMPARE(toSearch, Root->SW);
}
else
{
if (Root->NW == nullptr)
{
indicator = 2;
return Root;
}
return PT_COMPARE(toSearch, Root->NW);
}
}
else if (toSearch->Y_cord < Root->Y_cord)
{
if (Root->SE == nullptr)
{
indicator = 3;
return Root;
}
return PT_COMPARE(toSearch, Root->SE);
}
else if (toSearch->X_cord == Root->X_cord) //if new node lies on a quadrant line of another node
{
if (toSearch->Y_cord < Root->Y_cord)
{
if (Root->SE == nullptr)
{
indicator =3;
return Root;
}
return PT_COMPARE(toSearch, Root->SE);
}
else
{
if (Root->NE == nullptr)
{
indicator = 4;
return Root;
}
return PT_COMPARE(toSearch, Root->NE);
}
}
else if (toSearch->Y_cord == Root->Y_cord) //if new node lies on a quadrant line of another node
{
if (toSearch->X_cord < Root->X_cord)
{
if (Root->NW == nullptr)
{
indicator = 2;
return Root;
}
return PT_COMPARE(toSearch, Root->NW);
}
else
{
if (Root->NE == nullptr)
{
indicator = 4;
return Root;
}
return PT_COMPARE(toSearch, Root->NE);
}
}
else
{
if (Root->NE == nullptr)
{
indicator = 4;
return Root;
}
return PT_COMPARE(toSearch, Root->NE);
}
}
//returns the root node of tree
node *getRoot()
{
return root;
}
//pretty print the tree recursively
void printTree(node *Root)
{
if (Root != nullptr)
{
cout<<Root->city_name<<endl;
printTree(Root->SE);
printTree(Root->SW);
printTree(Root->NE);
printTree(Root->NW);
}
}
vector <string> visitedCity; //list of cities visited in search function
vector <string> resultCity; //list of cities within proximity of search point
//prints list of cities visited while searching and the list of cities within proximity of the search coordinates
void printCityList()
{
if (resultCity.size() == 0)
{
cout<<"<None>";
}
else
{
for (int i = 0; i < resultCity.size(); i++)
{
if ( i == 0)
{
cout<<resultCity[i];
}
else
{
cout<<", "<<resultCity[i];
}
}
}
cout<<endl;
for (int i = 0; i < visitedCity.size(); i++)
{
if ( i == 0)
{
cout<<visitedCity[i];
}
else
{
cout<<", "<<visitedCity[i];
}
}
cout<<endl<<endl;
//vectors cleared for next search
visitedCity.clear();
resultCity.clear();
}
//returns true if node being searched lies within range of search point
bool checkProximity(double radius, double distBetweenPoints)
{
if (distBetweenPoints > radius)
return false;
else
return true;
}
//calculates the distance between the node being searched and the search point using pythagoras theorem
//updates the resultCity list if node(city) is within proximity of search point
void calculateDistance(int x, int y, int radius, node *cityNode)
{
double distance = 0, x_distance = 0, y_distance = 0, base = 0, opposite = 0, hypotenuse = 0;
x_distance = abs(x-(cityNode->X_cord));
y_distance = abs(y-(cityNode->Y_cord));
if (x_distance == 0)
{
if (checkProximity(radius, y_distance))
{
resultCity.push_back(cityNode->city_name);
}
return;
}
else if (y_distance == 0)
{
if (checkProximity(radius, x_distance))
{
resultCity.push_back(cityNode->city_name);
}
return;
}
base = pow(x_distance, 2);
opposite = pow(y_distance, 2);
hypotenuse = sqrt(base + opposite);
if (checkProximity(radius, hypotenuse))
{
resultCity.push_back(cityNode->city_name);
}
return;
}
//function for searching the tree recursively
//13 possible cases are given to traverse the quadrants in the required order
void searchTree(int x, int y, int radius, node *Root)
{
if (Root == nullptr)
return;
bool flag = false;
double distance = 0, x_distance = 0, y_distance = 0, base = 0, opposite = 0, hypotenuse = 0;
x_distance = abs(x-(Root->X_cord));
y_distance = abs(y-(Root->Y_cord));
base = pow(x_distance, 2);
opposite = pow(y_distance, 2);
hypotenuse = sqrt(base + opposite);
if (x_distance == 0)
{
if (checkProximity(radius, y_distance))
{
flag = true;
}
}
else if (y_distance == 0)
{
if (checkProximity(radius, x_distance))
{
flag = true;
}
}
else if (checkProximity(radius, hypotenuse))
{
flag = true;
}
if(flag == true) //13 (if node(city) lies within the search radius, all quadrants searched)
{
visitedCity.push_back(Root->city_name);
calculateDistance(x, y, radius, Root);
if (Root->SE != nullptr)
{
searchTree(x, y, radius, Root->SE);
}
if (Root->SW != nullptr)
{
searchTree(x, y, radius, Root->SW);
}
if (Root->NE != nullptr)
{
searchTree(x, y, radius, Root->NE);
}
if (Root->NW != nullptr)
{
searchTree(x, y, radius, Root->NW);
}
}
else if ((radius + y) <= Root->Y_cord && abs(radius-x) >= Root->X_cord) //1
{
visitedCity.push_back(Root->city_name); //name of city visited pushed into visitedCity vector to keep record of the nodes visited
calculateDistance(x, y, radius, Root); //check if city being searched lies within search radius
if (Root->SE != nullptr)
{
searchTree(x, y, radius, Root->SE); //recursive function call on South East quadrant of the node
}
}
else if ((radius+y) <= Root->Y_cord && (radius+x) <= Root->X_cord)//3
{
visitedCity.push_back(Root->city_name);
calculateDistance(x, y, radius, Root);
if (Root->SW != nullptr)
{
searchTree(x, y, radius, Root->SW);
}
}
else if (abs(radius-y) >= Root->Y_cord && abs(radius-x) >= Root->X_cord)//6
{
visitedCity.push_back(Root->city_name);
calculateDistance(x, y, radius, Root);
if (Root->NE != nullptr)
{
searchTree(x, y, radius, Root->NE);
}
}
else if (abs(radius-y) >= Root->Y_cord && (radius+x) <= Root->X_cord)//8
{
visitedCity.push_back(Root->city_name);
calculateDistance(x, y, radius, Root);
if (Root->NW != nullptr)
{
searchTree(x, y, radius, Root->NW);
}
}
else if (((radius+y) <= Root->Y_cord) )//2
{
visitedCity.push_back(Root->city_name);
calculateDistance(x, y, radius, Root);
if (Root->SE != nullptr)
{
searchTree(x, y, radius, Root->SE);
}
if (Root->SW != nullptr)
{
searchTree(x, y, radius, Root->SW);
}
}
else if (abs(radius-x) >= Root->X_cord)//4
{
visitedCity.push_back(Root->city_name);
calculateDistance(x, y, radius, Root);
if (Root->SE != nullptr)
{
searchTree(x, y, radius, Root->SE);
}
if (Root->NE != nullptr)
{
searchTree(x, y, radius, Root->NE);
}
}
else if ((x+radius) <= Root->X_cord)//5
{
visitedCity.push_back(Root->city_name);
calculateDistance(x, y, radius, Root);
if (Root->SW != nullptr)
{
searchTree(x, y, radius, Root->SW);
}
if (Root->NW != nullptr)
{
searchTree(x, y, radius, Root->NW);
}
}
else if (abs(radius-y) >= Root->Y_cord)//7
{
visitedCity.push_back(Root->city_name);
calculateDistance(x, y, radius, Root);
if (Root->NE != nullptr)
{
searchTree(x, y, radius, Root->NE);
}
if (Root->NW != nullptr)
{
searchTree(x, y, radius, Root->NW);
}
}
else if (((y+radius) > Root->Y_cord) && (abs(x-radius) < Root->X_cord) && (x > Root->X_cord) && (Root->Y_cord > y)) //9
{
visitedCity.push_back(Root->city_name);
calculateDistance(x, y, radius, Root);
if (Root->SE != nullptr)
{
searchTree(x, y, radius, Root->SE);
}
if (Root->SW != nullptr)
{
searchTree(x, y, radius, Root->SW);
}
if (Root->NE != nullptr)
{
searchTree(x, y, radius, Root->NE);
}
}
else if (((radius+y) > Root->Y_cord) && ((radius+x) > Root->X_cord) && (x < Root->X_cord) && (Root->Y_cord > y)) //10
{
visitedCity.push_back(Root->city_name);
calculateDistance(x, y, radius, Root);
if (Root->SE != nullptr)
{
searchTree(x, y, radius, Root->SE);
}
if (Root->SW != nullptr)
{
searchTree(x, y, radius, Root->SW);
}
if (Root->NW != nullptr)
{
searchTree(x, y, radius, Root->NW);
}
}
else if ((abs(y-radius) < Root->Y_cord) && (abs(x-radius) < Root->X_cord) && (x > Root->X_cord) && (Root->Y_cord < y)) //11
{
visitedCity.push_back(Root->city_name);
calculateDistance(x, y, radius, Root);
if (Root->SE != nullptr)
{
searchTree(x, y, radius, Root->SE);
}
if (Root->NE != nullptr)
{
searchTree(x, y, radius, Root->NE);
}
if (Root->NW != nullptr)
{
searchTree(x, y, radius, Root->NW);
}
}
else if (abs(y-radius) < Root->Y_cord && (x+radius) > Root->X_cord && (x < Root->X_cord) && (Root->Y_cord < y)) //12
{
visitedCity.push_back(Root->city_name);
calculateDistance(x, y, radius, Root);
if (Root->SW != nullptr)
{
searchTree(x, y, radius, Root->SW);
}
if (Root->NE != nullptr)
{
searchTree(x, y, radius, Root->NE);
}
if (Root->NW != nullptr)
{
searchTree(x, y, radius, Root->NW);
}
}
}
}; | true |
55f1adb8642dfa872958afb2398af37de5334b9d | C++ | MilanFIN/TrainGame | /TrainGame/TrainGame/playerlogic.h | UTF-8 | 6,140 | 2.71875 | 3 | [] | no_license | #ifndef PLAYERLOGIC_H
#define PLAYERLOGIC_H
#include <memory>
#include <QGraphicsScene>
#include <vector>
#include <QObject>
#include "playertrain.h"
#include "traininterface.h"
#include "shop.h"
/**
* @brief The PlayerLogic class defines player related logic
*/
class PlayerLogic: public QObject
{
Q_OBJECT
public:
PlayerLogic();
/**
* @brief PlayerLogic constructor
* @param scene is the qgraphcisscene the logic interacts with
*/
PlayerLogic(std::shared_ptr<QGraphicsScene> scene);
/**
* @brief location returns player's location.
* @return int location in y axis
*/
int location();
/**
* @brief activeTrain returns a smart pointer to the active train
* @return shared_ptr to the active train
*/
std::shared_ptr<PlayerTrain> activeTrain();
/**
* @brief addNewTrain adds a new train to the player's use
* @param newTrain pointer to the new train
* @post the train has been added
*/
void addNewTrain(std::shared_ptr<PlayerTrain> newTrain);
/**
* @brief deleteTrain removes a train from the player
* @pre index is in range of the possible choises of trains
* @param index that the train is on
* @post the train has been removed
*/
void deleteTrain(int index);
/**
* @brief getCurrentMoney returns the amount of money the player has
* @return the player's money amount in int
*/
int getCurrentMoney();
/**
* @brief addFame adds karma that the player has
* @param amount amount of karma/fame to be added
* @post amount of fame has been changed
*/
void addFame(int amount);
/**
* @brief getFame returns fame
* @return fame_
*/
int getFame() const;
/**
* @brief getOwnedTrainInfo returns info on an owned train
* @param trainName train that the info is wanted on
*/
void getOwnedTrainInfo(QString trainName);
/**
* @brief getTrainInfo asks the shop for the train's specs.
* @param trainName name of the train to be asked on
*/
void getTrainInfo(QString trainName);
/**
* @brief getInfoToGarage gives info on a train to the depot.
* @param trainName name of the train
*/
void getInfoToGarage(QString trainName);
/**
* @brief getAvailableTrainsFromShop asks shop for buyable trains
* @pre ui has been initialized
* @post ui has been notified on buyable trains
*/
void getAvailableTrainsFromShop();
/**
* @brief getOwnedTrains returns owned trains via a signal.
* @pre signal-slot pair has been connected
* @post signal sent
*/
void getOwnedTrains();
/**
* @brief buyTrain buys a train to the player
* @param trainName name of the train to be bought
* @param index that the train has in the shop
* @pre index and trainName exist
* @post a new train has been moved to the player's inventory
*/
void buyTrain(QString trainName, int index);
/**
* @brief sellTrain sells a train to the shop
* @param index, index of the train on the player
* @pre index is in range of trains that can be sold
* @post the train chosen has been sold
*/
void sellTrain(int index);
/**
* @brief setActiveTrain sets the active train for the player
* @param rowIndex that the train has on player's inventory
* @pre rowIndex is in range of owned trains
* @post previous train removed from the scene, new one added
*/
void setActiveTrain(int rowIndex);
/**
* @brief removeTrainPixmap removes the old train from the scene
* @param trainToRemove weak pointer to the train
* @post the train has been removed from scene
*/
void removeTrainPixmap(std::weak_ptr<PlayerTrain> trainToRemove);
/**
* @brief setTrainPixmap adds the active train to the scene.
* @post train updated to the scene
*/
void setTrainPixmap();
/**
* @brief getTrainsToBeRepaired returns all
* trains in need of repair as a signal
* @pre a slot for the signal has been connected
* @post repairable trains signaled
*/
void getTrainsToBeRepaired();
/**
* @brief repairTrain repairs a specific train
* @param rowIndex index of the train in the player's inventory
* @pre index is in range of possible choises in player's inventory
* @post the chosen train has been repaired to full shape
*/
void repairTrain(int rowIndex);
/**
* @brief takeDamage causes the active train to recieve damage
* @param int dmg amount of damage
* @pre an active train has been set
* @post damage taken
*/
void takeDamage(int dmg);
/**
* @brief increaseMoney increases the money plaeyr has
* @param amount amount of addition (+ or - allowed)
*/
void increaseMoney(int amount);
signals:
int playerCashChanged(int amount);
void playerFameChanged(int amount);
void ownedTrainInfo(std::shared_ptr<PlayerTrain> train);
void trainInfo(std::shared_ptr<PlayerTrain> train);
void ownedTrains(std::vector<std::shared_ptr<PlayerTrain>> ownedTrains);
void availableTrains(std::vector<std::shared_ptr<PlayerTrain>> buyableTrains);
void activeTrainChanged(QString trainName);
void showBrokenTrains(std::vector<std::shared_ptr<PlayerTrain>> brTrains);
void trainRepaired();
void brokenTrain(std::shared_ptr<PlayerTrain> brokenTrain);
void notEnoughMoney(QString msg);
void shopActionFailed(QString msg);
void notAbleToPlay();
private:
std::shared_ptr<QGraphicsScene> scene_;
std::vector<std::shared_ptr<PlayerTrain>> playableTrains_;
std::shared_ptr<PlayerTrain> activeTrain_;
// player owns the shop and manages it trough this pointer
std::shared_ptr<Shop> shop_;
int currentMoney_;
int fame_;
void decreaseMoney(int amount);
void playerToShopTransaction(int index, std::shared_ptr<PlayerTrain> train);
void shopToPlayerTransaction(int index);
void updateUI();
void invariant();
};
#endif // PLAYERLOGIC_H
| true |
8994502bc6e179358de165e4b6d45c9611b1d929 | C++ | yangzeyu1026/practice-code | /0103.cpp | UTF-8 | 476 | 3 | 3 | [] | no_license | #include <bits/stdc++.h>
int main()
{
//三位数反转
/*
不含0
int n;
scanf("%d",&n);
printf("%d%d%d\n",n%10,n/10%10,n/100 );//注意这里是逗号
*/
/*
含0
int n,m;
scanf("%d", &n);
m = (n%10)*100 + (n/10%10)*10 + n/100;
printf("%03d\n", m );*/
//变量交换
/*
引入新的变量
int a,b,t;
scanf("%d%d",&a,&b);
t = a;
a = b;
b = t;
printf("%d %d\n",a,b );*/
//直接交换
int a,b;
scanf ("%d%d",&a,&b);
printf("%d %d\n",b,a);
return 0;
} | true |
2e8174354c0f83d08fe1139d792355e15dacd2a5 | C++ | TBBle/libscx | /src/AssetName.cpp | UTF-8 | 1,462 | 2.734375 | 3 | [] | no_license | #include "AssetName.hpp"
#include <boost/locale.hpp>
using boost::locale::conv::to_utf;
using boost::locale::conv::from_utf;
#include <array>
using std::array;
#include <gsl/gsl>
using gsl::as_multi_span;
void AssetName::read_data(fixed_string_span string0,
fixed_string_span string1) {
array<char, 0x21> buffer;
buffer[0x20] = '\0';
auto charstring0 = as_multi_span<const char>(string0);
copy(charstring0.cbegin(), charstring0.cend(), buffer.begin());
name = to_utf<char>(&buffer[0], "windows-932");
auto charstring1 = as_multi_span<const char>(string1);
copy(charstring1.cbegin(), charstring1.cend(), buffer.begin());
abbreviation = to_utf<char>(&buffer[0], "windows-932");
}
void AssetName::write_data(fixed_string_span_out string0,
fixed_string_span_out string1) const {
const auto cp932string0(from_utf<char>(name, "windows-932"));
Expects(cp932string0.length() < 0x21);
memset(string0.data(), 0, string0.size_bytes());
auto charstring0 = as_multi_span<char>(string0);
copy(cp932string0.cbegin(), cp932string0.cend(), charstring0.begin());
const auto cp932string1(from_utf<char>(abbreviation, "windows-932"));
Expects(cp932string1.length() < 0x21);
memset(string1.data(), 0, string1.size_bytes());
auto charstring1 = as_multi_span<char>(string1);
copy(cp932string1.cbegin(), cp932string1.cend(), charstring1.begin());
}
| true |
7677d36d6a4e51c95ec3872db62ddd6d77735e39 | C++ | Lowvoice-git/BOJCode | /BOJ/Silver/Silver_17087_숨바꼭질 6.cc | UTF-8 | 431 | 3.234375 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <cmath>
std::vector<int> Array;
int GCD(int A, int B) {
if (B == 0) return A;
return GCD(B, A % B);
}
int main() {
int N, M, result = 0;
std::cin >> N >> M;
for (int i = 0; i < N; i++) {
int temp; std::cin >> temp;
Array.push_back(std::abs(temp - M));
}
result = Array[0];
for (int i = 1; i < Array.size(); i++)
result = GCD(result, Array[i]);
std::cout << result;
} | true |
92477e38b67ec53e41b0040d372ff64b6e940b16 | C++ | jimsjoo/FinancialCPP | /MA.cpp | UTF-8 | 1,183 | 3.28125 | 3 | [] | no_license | // MA.cpp
#include "MA.h"
#include <iostream>
MA::MA()
{
}
MA::MA(int numPeriods)
: m_numPeriods(numPeriods)
{
}
MA::~MA()
{
}
MA::MA(const MA &ma)
: m_numPeriods(ma.m_numPeriods)
{
}
MA &MA::operator = (const MA &ma)
{
if (this != &ma) {
m_numPeriods = ma.m_numPeriods;
m_prices = ma.m_prices;
}
return *this;
}
std::vector<double> MA::sMA(int period)
{
std::vector<double> ma;
double sum = 0;
for (int i=0; i<m_prices.size(); ++i) {
sum += m_prices[i];
if (i >= period) {
ma.push_back(sum / period);
sum -= m_prices[i-period];
}
}
return ma;
}
std::vector<double> MA::eMA(int period)
{
std::vector<double> ema;
double sum = 0;
double multiplier = 2.0 / (period + 1);
for (int i=0; i<m_prices.size(); ++i) {
sum += m_prices[i];
if (i == period) {
ema.push_back(sum / period);
sum -= m_prices[i-period];
} else if (i > period) {
double val = (1-multiplier) * ema.back() + multiplier * m_prices[i];
ema.push_back(val);
}
}
return ema;
}
void MA::add(double close)
{
m_prices.push_back(close);
}
| true |
d5a07de4359f2693d415221a477bb7166544cb3f | C++ | osak/Contest | /POJ/3774.cc | UTF-8 | 5,003 | 3.203125 | 3 | [] | no_license | //Name: Elune’s Arrow
//Level: 3
//Category: 幾何
//Note:
/*
* まず目標を構成する線分のどれかに当たるかを計算し,当たるなら一番近い交点の距離を記憶しておく.
* そのあと他の物体で同じことを行ない,目標物体より距離の近い交点を持つものがなければHIT.
*/
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <complex>
using namespace std;
typedef complex<double> P;
static const double EPS = 1e-9;
inline double dot(const P& a, const P& b) { return a.real()*b.real() + a.imag()*b.imag(); }
inline double cross(const P& a, const P& b) { return a.real()*b.imag() - b.real()*a.imag(); }
int ccw(const P& a, P b, P c)
{
b -= a;
c -= a;
if (cross(b, c) > EPS) {
return +1;
} else if (cross(b, c) < -EPS) {
return -1;
} else if (dot(b, c) < -EPS) {
return +2;
} else if (dot(b, b) + EPS < dot(c, c)) {
return -2;
} else {
return 0;
}
}
struct line/*{{{*/
{
P a, b;
line() {}
line(const P& p, const P& q) : a(p), b(q) {}
inline bool parallel(const line& ln) const
{
return abs(cross(ln.b - ln.a, b - a)) < EPS;
}
inline bool intersects(const line& ln) const
{
return !parallel(ln);
}
inline P intersection(const line& ln) const
{
// assert(intersects(ln))
const P x = b - a;
const P y = ln.b - ln.a;
return a + x*(cross(y, ln.a - a))/cross(y, x);
}
inline double distance(const P& p) const
{
return abs(cross(p - a, b - a)) / abs(b - a);
}
// AOJ 1171 Laser Beam Reflections
inline P perpendicular(const P& p) const
{
// 点 p から直線上に下ろした垂線の足
const double t = dot(p-a, a-b) / dot(b-a, b-a);
return a + t*(a-b);
}
};/*}}}*/
struct segment/*{{{*/
{
P a, b;
segment() {}
segment(const P& x, const P& y) : a(x), b(y) {}
inline bool intersects(const line& ln) const
{
return cross(ln.b - ln.a, a - ln.a) * cross(ln.b - ln.a, b - ln.a) < EPS;
}
// AOJ 2402 Milkey Way
inline bool intersects(const segment& seg) const
{
return ccw(a, b, seg.a) * ccw(a, b, seg.b) <= 0
&& ccw(seg.a, seg.b, a) * ccw(seg.a, seg.b, b) <= 0;
}
// AOJ 1171 Laser Beam Relections
inline P intersection(const line& ln) const
{
// assert(intersects(ln))
const P x = b - a;
const P y = ln.b - ln.a;
return a + x*(cross(y, ln.a - a))/cross(y, x);
}
inline bool parallel(const line& ln) const
{
return abs(cross(ln.b - ln.a, b - a)) < EPS;
}
// AOJ 2402 Milkey Way
inline double distance(const P& p) const
{
if (dot(b-a, p-a) < EPS) {
return abs(p-a);
} else if (dot(a-b, p-b) < EPS) {
return abs(p-b);
} else {
return abs(cross(b-a, p-a))/abs(b-a);
}
}
// AOJ 2402 Milkey Way
inline double distance(const segment& seg) const
{
if (intersects(seg)) {
return 0;
} else {
return
min(
min(distance(seg.a), distance(seg.b)),
min(seg.distance(a), seg.distance(b)));
}
}
};/*}}}*/
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
while(true) {
int N;
cin >> N;
if(!N) break;
P origin, vec;
cin >> origin.real() >> origin.imag() >> vec.real() >> vec.imag();
vec += origin;
const line arrow(origin, vec);
vector<vector<P> > enemies(N);
for(int i = 0; i < N; ++i) {
int M;
cin >> M;
while(M--) {
int x, y;
cin >> x >> y;
enemies[i].push_back(P(x, y));
}
}
//cout << arrow.a << ' ' << arrow.b << endl;
// Check if hits target
bool hit = false;
double hit_a = 1e50;
for(int i = 0; i < (int)enemies[0].size(); ++i) {
segment seg(enemies[0][i], enemies[0][(i+1)%enemies[0].size()]);
if(seg.intersects(arrow)) {
//cout << i << endl;
P pos = seg.intersection(arrow);
//cout << pos << endl;
if(dot(pos-origin, vec-origin) > 0) {
hit_a = min(hit_a, abs(pos-origin));
hit = true;
//cout << hit_a << endl;
}
}
}
if(hit) {
// Check if hit point is nearest
for(int j = 1; j < N; ++j) {
for(int i = 0; i < (int)enemies[j].size(); ++i) {
segment seg(enemies[j][i], enemies[j][(i+1)%enemies[j].size()]);
if(seg.intersects(arrow)) {
P pos = seg.intersection(arrow);
if(dot(pos-origin, vec-origin) > 0 && abs(pos-origin) < hit_a) {
hit = false;
goto end;
}
}
}
}
}
end:
cout << (hit?"HIT":"MISS") << endl;
}
return 0;
}
| true |
bd1e06962963fc162fc9001621e7247777f3a168 | C++ | sounak07/DS-algo-pointer-Programs | /Pointers/pointerarray.cpp | UTF-8 | 243 | 2.8125 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
int a[10];
cout<< a <<endl;
cout<< &a << endl;
a[0] = 5;
a[1] = 10; //*(a + i) => a[i]
int *p = &a[0];
cout<< *p << endl;
cout<< a <<endl;
cout<< &p << endl;
}
| true |
91f2cab0d9fdb36ebe8e5b6a00c1232dc2ad30fe | C++ | ypsitau/jrasm | /src/jrasmcore/PCGRange.h | UTF-8 | 1,721 | 2.71875 | 3 | [] | no_license | //=============================================================================
// PCGRange.h
//=============================================================================
#ifndef __JRASMCORE_PCGRANGE_H__
#define __JRASMCORE_PCGRANGE_H__
#include "PCGChar.h"
//-----------------------------------------------------------------------------
// PCGRange
//-----------------------------------------------------------------------------
class PCGRange {
private:
PCGType _pcgType;
int _charCodeStart;
int _charCodeEnd;
int _charCodeCur;
public:
inline PCGRange(PCGType pcgType, int charCodeStart, int charCodeEnd) :
_pcgType(pcgType), _charCodeStart(charCodeStart), _charCodeEnd(charCodeEnd), _charCodeCur(charCodeStart) {}
inline PCGType GetPCGType() const { return _pcgType; }
inline int GetCharCodeStart() const { return _charCodeStart; }
inline int GetCharCodeEnd() const { return _charCodeEnd; }
inline int GetCharCodeCur() const { return _charCodeCur; }
inline void ForwardCharCodeCur() { _charCodeCur++; }
const char *GetPCGTypeName(bool upperCaseFlag) const;
String ComposeSource(bool upperCaseFlag) const;
};
//-----------------------------------------------------------------------------
// PCGRangeList
//-----------------------------------------------------------------------------
class PCGRangeList : public std::vector<PCGRange *> {
public:
String ComposeSource(bool upperCaseFlag, const char *sepStr = ",") const;
};
//-----------------------------------------------------------------------------
// PCGRangeOwner
//-----------------------------------------------------------------------------
class PCGRangeOwner : public PCGRangeList {
public:
~PCGRangeOwner();
void Clear();
};
#endif
| true |
2bf1e9ddd9932244230af3d4520328220266ffd0 | C++ | gnosiop/fromPhone | /C++/Essential/Errors/throwCatch/multiCatch.cpp | UTF-8 | 330 | 3.453125 | 3 | [] | no_license | #include <iostream>
using namespace std;
void Xhandler(int test)
{
try {
if (test) throw test;
else throw "Value is zero";
}
catch (int i) {cout << "Caught exception #: " << i << "\n";}
catch (...) {cout << "Caught other \n";}
}
int main()
{
Xhandler(1);
Xhandler(2);
Xhandler(0);
Xhandler(3);
return 0;
} | true |
66247413827964a38f8041d83e465391fe35a51b | C++ | Valentina5/ConvolutNNetwork | /convolutNN/ConvLayer.h | UTF-8 | 4,591 | 2.890625 | 3 | [] | no_license | #ifndef __CONVLAYER_H__
#define __CONVLAYER_H__
#include <vector>
#include <cmath>
#include "Sigmoid.h"
#include "Layer.h"
template<int kernDim, int inDim, int outDim>
class ConvLayer : public Layer {
const int mapsIn, mapsOut;
const int inSize, outSize, kernSize;
const int inExitSize, outExitSize;
float *weights;
float *bias;
public:
/*
Convolve mapsIn inDim x inDim maps to mapsOut outDim x outDim
*/
ConvLayer(int mapsIn, int mapsOut)
: mapsIn(mapsIn), mapsOut(mapsOut),
inSize(inDim * inDim), outSize(outDim * outDim), kernSize(kernDim * kernDim),
inExitSize(inSize * mapsIn), outExitSize(outSize * mapsOut)
{
weights = new float[kernDim * kernDim * mapsIn * mapsOut];
bias = new float[mapsOut];
}
int getMapsOut() const {
return mapsOut;
}
int getMapsIn() const {
return mapsIn;
}
virtual void randomizeWeights() {
for (int i = 0; i < numWeights(); i++) {
weights[i] = 0.1f * sin(100.f * i * i + 1234.5);
}
for (int i = 0; i < numBiases(); i++)
bias[i] = 0.1f * sin(312.f * i + 32.41);
}
virtual ~ConvLayer() {
delete[] weights;
delete[] bias;
}
virtual int numWeights() const {
return kernDim * kernDim * mapsIn * mapsOut;
}
virtual int numBiases() const {
return mapsOut;
}
virtual float *getWeights() {
return weights;
}
virtual float *getBiases() {
return bias;
}
virtual int numInputs() const {
return mapsIn * inSize;
}
virtual int numOutputs() const {
return mapsOut * outSize;
}
private:
void forwardPair(const float in[], float out[], const float w[], const float b, bool first) const {
for (int i = 0; i < outDim; i++)
for (int j = 0; j < outDim; j++) {
int i2 = i * 2;
int j2 = j * 2;
float sum = 0;
for (int ki = 0; ki < kernDim; ki++)
for (int kj = 0; kj < kernDim; kj++) {
sum += w[ki * kernDim + kj] * in[(i2 + ki) * inDim + j2 + kj];
}
out[i * outDim + j] = (first ? b : out[i * outDim + j]) + sum;
}
}
void nonlinearize(float out[]) const {
for (int i = 0; i < mapsOut * outSize; i++)
out[i] = Sigmoid::F(out[i]);
}
public:
virtual void forward(const float in[], float out[]) const {
for (int i = 0; i < mapsOut; i++) {
for (int j = 0; j < mapsIn; j++) {
int ij = i * mapsIn + j;
forwardPair(in + j * inSize, out + i * outSize, weights + ij * kernSize, bias[i], j == 0);
}
}
nonlinearize(out);
}
private:
void backwardPair(float deltaIn[], const float deltaOut[], const float w[], bool first) const {
if (first) {
for (int i = 0; i < inDim * inDim; i++)
deltaIn[i] = 0;
}
for (int i = 0; i < outDim; i++)
for (int j = 0; j < outDim; j++) {
int i2 = 2 * i;
int j2 = 2 * j;
for (int ki = 0; ki < kernDim; ki++)
for (int kj = 0; kj < kernDim; kj++) {
deltaIn[(i2 + ki) * inDim + j2 + kj] += w[ki * kernDim + kj] * deltaOut[i * outDim + j];
}
}
}
void multiplyDerivative(const float in[], float deltaIn[]) const {
for (int i = 0; i < inSize * mapsIn; i++)
deltaIn[i] *= Sigmoid::G(in[i]);
}
public:
virtual void backward(const int nLast, const float in[], float deltaIn[], const float deltaOut[]) const {
for (int i = 0; i < nLast; i++) {
for (int k = 0; k < mapsIn; k++)
for (int j = 0; j < mapsOut; j++) {
int jk = j * mapsIn + k;
backwardPair(
deltaIn + i * inExitSize + k * inSize,
deltaOut + i * outExitSize + j * outSize,
weights + jk * kernSize,
j == 0
);
}
multiplyDerivative(in, deltaIn + i * inExitSize);
}
}
virtual void derivativeWeight(const int nLast, const float in[], const float deltaOut[], float dXdw[]) const {
for (int i = 0; i < nLast; i++)
for (int k = 0; k < mapsOut; k++)
for (int m = 0; m < mapsIn; m++)
for (int kx = 0; kx < kernDim; kx++)
for (int ky = 0; ky < kernDim; ky++) {
float sum = 0;
for (int xi = 0; xi < outDim; xi++)
for (int eta = 0; eta < outDim; eta++) {
int xieta = xi * outDim + eta;
sum += deltaOut[i * outExitSize + k * outSize + xieta] *
in[m * inSize + (2 * xi + kx) * inDim + 2 * eta + ky];
}
dXdw[i * mapsIn * mapsOut * kernSize + (k * mapsIn + m) * kernSize + kx * kernDim + ky] = sum;
}
}
virtual void derivativeBias(const int nLast, const float deltaOut[], float dXdb[]) const {
for (int i = 0; i < nLast; i++)
for (int k = 0; k < mapsOut; k++) {
float sum = 0;
for (int xieta = 0; xieta < outSize; xieta++)
sum += deltaOut[i * outExitSize + k * outSize + xieta];
dXdb[i * mapsOut + k] = sum;
}
}
};
#endif
| true |
9c165db4c7705705b7d5cd38083e10ccda0381dd | C++ | Jorge-Rmz/Sucesion-de-Fibonnacci | /fibonacci.cpp | UTF-8 | 716 | 3.875 | 4 | [] | no_license | #include<iostream>
using namespace std;
int serie_fibonacci(int x);
int main(){
int numDeSucecion, x;
do{
x = 0;
cout<<"Inserte el numero de elementos que desea de la serie de fibonacci"<<endl;
cin>>numDeSucecion;
if(numDeSucecion < 0){
cout<<"Inserte un numero positivo."<<endl;
x = 1;
}else{
for(int i = 0; i <=numDeSucecion; i++){
if(i == numDeSucecion){
cout<<serie_fibonacci(i);
}else{
cout<<serie_fibonacci(i)<< ", ";
}
}
}
}while(x == 1);
}
int serie_fibonacci(int n){
if(n == 0){
return 0;
}
if(n == 1 ){
return 1;
}
if(n > 1){
return serie_fibonacci(n - 1) + serie_fibonacci(n - 2);
}
}
| true |
d51894f69a0ab374e68a876485261e3d8731860b | C++ | flagflag/FlagGG | /FlagGG/Container/StringHash.h | UTF-8 | 800 | 2.671875 | 3 | [] | no_license | #pragma once
#include "Container/Str.h"
#include "Core/BaseTypes.h"
namespace FlagGG
{
class FlagGG_API StringHash
{
public:
StringHash() NOEXCEPT;
StringHash(const char* str) NOEXCEPT;
StringHash(const String& str) NOEXCEPT;
StringHash(UInt32 value) NOEXCEPT;
StringHash(const StringHash& value) NOEXCEPT;
StringHash& operator=(const StringHash& rhs) NOEXCEPT = default;
StringHash operator+(const StringHash& rhs) const;
StringHash& operator+=(const StringHash& rhs);
bool operator==(const StringHash& rhs) const;
bool operator!=(const StringHash& rhs) const;
bool operator<(const StringHash& rhs) const;
bool operator>(const StringHash& rhs) const;
explicit operator bool() const;
UInt32 ToHash() const;
static const StringHash ZERO;
private:
UInt32 value_;
};
}
| true |
c54692ce6a25e022baf3b25a5ecd1d14eda16013 | C++ | bkdoo/TIL | /arduino-programming-class/Quiz/traffic_lights_button/traffic_lights_button.ino | UTF-8 | 813 | 2.921875 | 3 | [] | no_license | /*LED 3개(red, yellow, green)가 각 버튼을 누르면 점등되는 아두이노 코드를 작성하자.*/
int red =13;
int yellow =12;
int green=8;
int redBtn = 7;
int yellowBtn =4;
int greenBtn = 2;
int r, y, g;
void setup() {
pinMode(red, OUTPUT);
pinMode(yellow, OUTPUT);
pinMode(green, OUTPUT);
pinMode(redBtn, INPUT);
pinMode(yellowBtn, INPUT);
pinMode(greenBtn, INPUT);
}
void loop() {
r = digitalRead(redBtn);
y = digitalRead(yellowBtn);
g = digitalRead(greenBtn);
if (r == HIGH)
{
digitalWrite(red, HIGH);
} else {
digitalWrite(red, LOW);
}
if (y == HIGH)
{
digitalWrite(yellow, HIGH);
} else {
digitalWrite(yellow, LOW);
}
if (g == HIGH)
{
digitalWrite(green, HIGH);
} else {
digitalWrite(green, LOW);
}
}
| true |
b163cf6f84676880b756af365329ac64986c476d | C++ | fixopen/cpputil | /Util/IniFile.h | UTF-8 | 1,622 | 2.765625 | 3 | [] | no_license | #ifndef __UTIL_INIFILE_H__
#define __UTIL_INIFILE_H__
#include <map> //for std::map
#include <vector> //for std::vector
#include <string> //for std::string, std::wstring
namespace Util {
class IniFile {
public:
explicit IniFile(std::string const& filename = "");
~IniFile();
void Load(std::string const& filename);
void Save(std::string const& filename = "") const;
bool const HasSection(std::string const& sectionName) const;
void AppendSection(std::string const& sectionName, std::vector<std::pair<std::string, std::string> > const& properties);
void RemoveSection(std::string const& sectionName);
std::vector<std::pair<std::string, std::string> > const GetSectionProperties(std::string const& sectionName) const;
bool const HasProperty(std::string const& sectionName, std::string const& propertyName) const;
void AppendProperty(std::string const& sectionName, std::string const& name, std::string const& value);
void RemoveProperty(std::string const& sectionName, std::string const& propertyName);
std::string const GetPropertyValue(std::string const& sectionName, std::string const& propertyName) const;
void SetPropertyValue(std::string const& sectionName, std::string const& propertyName, std::string const& newValue);
private:
std::string filename_;
mutable bool isDirty_;
mutable bool isSaved_;
std::vector<std::pair<std::string, std::vector<std::pair<std::string, std::string> > > > configs_;
};
}
#endif //__UTIL_INIFILE_H__
| true |
18ece7654e1eddd90a00e0df87d62fb39c560430 | C++ | fmorel/SoC | /main/increment/increment_hard/increment_hard.cpp | UTF-8 | 1,927 | 2.546875 | 3 | [] | no_license | #include "increment_hard.h"
#include <iostream>
#define TILE_WIDTH 16
#define TILE_HEIGHT 16
// Init all registers with p_init_mux_switched to true for at least 2 cycles. Then switch it to false and read the values from p_OUT
namespace soclib { namespace caba {
// Constructor
IncrementHard::IncrementHard(sc_core::sc_module_name insname)
: sc_core::sc_module(insname)
{
SC_METHOD(incrementHardTransition);
dont_initialize();
sensitive<<p_clk.pos();
SC_METHOD(incrementHardMoore);
dont_initialize();
sensitive<<p_clk.neg();
}
void IncrementHard::incrementHardTransition() {
if (p_init_mux_switch) {
cycle_since_init = 0;
} else {
cycle_since_init++;
}
if (cycle_since_init == 0) {
newQ0 = p_Q0.read();
newR0 = p_R0.read();
newS0 = p_S0.read();
newP0 = p_P0.read();
newQ1 = p_Q1.read();
newQ2 = p_Q2.read();
newQ3 = p_Q3.read();
newR1 = p_R1.read();
newR2 = p_R2.read();
newS1 = p_S1.read();
newP3 = 0;
newP2 = 0;
newP1 = 0;
} else {
newQ0 = Q0;
newR0 = R0;
newS0 = S0;
newP0 = P0;
if (cycle_since_init%TILE_WIDTH == 1) {
newQ1 = Q1 + Q0;
newQ2 = Q2 + Q1;
newQ3 = Q3 + Q2;
newR1 = R1 + R0;
newR2 = R2 + R1;
newS1 = S1 + S0;
newP3 = Q3;
newP2 = R2;
newP1 = S1;
} else {
newQ1 = Q1;
newQ2 = Q2;
newQ3 = Q3;
newR1 = R1;
newR2 = R2;
newS1 = S1;
newP3 = P3 + P2;
newP2 = P2 + P1;
newP1 = P1 + P0;
}
}
P0 = newP0;
P1 = newP1;
P2 = newP2;
P3 = newP3;
Q0 = newQ0;
Q1 = newQ1;
Q2 = newQ2;
Q3 = newQ3;
R0 = newR0;
R1 = newR1;
R2 = newR2;
S0 = newS0;
S1 = newS1;
}
void IncrementHard::incrementHardMoore() {
p_OUT = P3 ;
}
}}
| true |
2fae26342b94f263a426f6c254a00e0912e28de2 | C++ | RoSchmi/Esp32_I2S_Microphone_Vol_Switcher | /lib/RoSchmi/SensorData/SoundSwitcher.h | UTF-8 | 4,646 | 2.546875 | 3 | [] | no_license | // Copyrigth RoSchmi, 2021. License Apache 2.0
// SoundSwitcher for Esp32 on PlatformIO Arduino platform
// How it works:
// SoundSwitcher is a class to implement a two state sensor reacting on sound levels
// The sound volume is measured by an I2S micophone (SPH0645LM4 or INMP441)
// The state toggles when a changeable soundvolume level is exceeded
// A changeable hysteresis is accomplished
//
// Constructor: has two parameter, a configuaration struct and the used microphone type
// Initialization: .begin method with 4 parameters (has to be called in setup())
// * switchThreshold
// * hysteresis
// * updateIntervalMs
// * delayTimeMs
// The first two need not be explained.
// updateIntervalMs : a time interval in ms. Only when the time interval has expired
// a new sound level average is calculated
// delayTimeMs: this delay time is introduced for reading the analog soundlevel
// after the threshold is exceeded. This parameter determins after
// which timeinterval the analog value is sampled (to read not just
// at the very beginning of the new state)
//
// soundSwitcher.SetActive() : Has to be called right after the soundSwitcher.begin function
// soundSwitcher.SetCalibrationParams() : Is optional, determins an offset and a factor
//
// soundSwitcher.feed() : This function is called frequently from the loop() of the main program
// It returns a struct Feedresponse.
// After the feed command, Feedresponse.isValid has to be checked
// If .isValid is true, Feedresponse.hasToggled is checked
// If .hasToggled is true, your reaction on the change of the
// state has to be performed
#include <Arduino.h>
#include <driver/i2s.h>
#include "soc/i2s_reg.h"
#ifndef _SOUND_SWITCHER_H_
#define _SOUND_SWITCHER_H_
typedef struct
{
bool isValid = false;
float value = 0.0;
}
AverageValue;
typedef struct
{
bool isValid = false;
bool hasToggled = false;
bool analogToSend = false;
bool state = false;
float avValue = 0.0;
float lowAvValue = 100000;
float highAvValue = -100000;
}
FeedResponse;
typedef enum
{
Percent_0 = 0,
Percent_2 = 2,
Percent_5 = 5,
Percent_10 = 10,
Percent_20 = 20
}
Hysteresis;
typedef enum
{
INMP441 = 0,
SPH0645LM4H = 1
}
MicType;
class SoundSwitcher
{
public:
SoundSwitcher(i2s_pin_config_t config, MicType pMicType);
void begin(uint16_t switchThreshold, Hysteresis hysteresis, uint32_t updateIntervalMs, uint32_t delayTimeMs);
FeedResponse feed();
AverageValue getAverage();
void SetInactive();
void SetActive();
void SetCalibrationParams(float pCalibOffset = 0.0, float pCalibFactor = 1.0);
bool hasToggled();
bool GetState();
private:
i2s_pin_config_t pin_config = {
.bck_io_num = 2, // BCKL
.ws_io_num = 2, // LRCL
.data_out_num = I2S_PIN_NO_CHANGE, // not used (only for speakers)
.data_in_num = 2 // DOUT
};
uint32_t lastFeedTimeMillis = millis();
uint32_t lastSwitchTimeMillis = millis();
uint32_t readDelayTimeMs = 0;
uint32_t lastBorderNarrowTimeMillis = millis();
size_t feedIntervalMs = 100;
bool hasSwitched = false;
bool analogSendIsPending = false;
float getSoundFromMicro();
float soundVolume;
float threshold;
int hysteresis;
bool state = false;
bool isActive = false;
bool bufferIsFilled = false;
uint32_t bufIdx = 0;
const static int buflen = 10;
float volBuffer[buflen] {0.0};
float average = 0;
float lowAvBorder = 10000;
float highAvBorder = 0;
float calibOffset = 0.0;
float calibFactor = 1.0;
#define BUFLEN 256
// Examples for possible configurations
// For Adafruit Huzzah Esp32
/*
static const i2s_pin_config_t pin_config_Adafruit_Huzzah_Esp32 = {
.bck_io_num = 14, // BCKL
.ws_io_num = 15, // LRCL
.data_out_num = I2S_PIN_NO_CHANGE, // not used (only for speakers)
.data_in_num = 32 // DOUT
};
// For some other Esp32 board
static const i2s_pin_config_t pin_config_Esp32_dev = {
.bck_io_num = 26, // BCKL
.ws_io_num = 25, // LRCL
.data_out_num = I2S_PIN_NO_CHANGE, // not used (only for speakers)
.data_in_num = 22 // DOUT
};
*/
};
#endif // _SOUND_SWITCHER_H_ | true |
6559d4ddbad02b43facc5df33541a5af9fc86253 | C++ | suu-K/AlgorithmPractice | /Beakjoon/2577 숫자의 개수.cpp | UHC | 355 | 3 | 3 | [] | no_license | /*
: (https://www.acmicpc.net/problem/2577)
*/
#include <iostream>
using namespace std;
int main() {
int a = 0, b = 0, c = 0;
int mul;
int arr[10] = { 0 };
cin >> a >> b >> c;
mul = a * b * c;
while (mul != 0) {
arr[mul % 10]++;
mul = mul / 10;
}
for (int i = 0; i < 10; i++)
cout << arr[i] << endl;
return 0;
} | true |
519e6dfca2aae5c79307796b5cb2dc3933499257 | C++ | FuSoftware/ShmupEditor | /src/editor/Widgets/bullet_editor.cpp | UTF-8 | 4,821 | 2.640625 | 3 | [] | no_license | #include "bullet_editor.h"
BulletEditor::BulletEditor(QWidget *parent) : QWidget(parent)
{
loadUI();
}
BulletEditor::BulletEditor(QString file, QWidget *parent) : QWidget(parent)
{
loadUI();
loadFile(file);
}
void BulletEditor::loadUI()
{
sprite_loaded = false;
QHBoxLayout *mainLayout = new QHBoxLayout;
QVBoxLayout *layoutData = new QVBoxLayout;
QPushButton *pushButtonSave = new QPushButton("Save",this);
pushButtonSprite = new QPushButton("Sprite File",this);
labelSpritePath = new QLabel("...",this);
labelSprite = new QLabel("No sprite loaded",this);
labelData[D_NAME] = new QLabel("Name :",this);
labelData[D_SIZE_W] = new QLabel("Size :",this);
lineEditData[D_NAME] = new QLineEdit(this);
lineEditData[D_SIZE_W] = new QLineEdit(this);
lineEditData[D_SIZE_H] = new QLineEdit(this);
layoutDataChild[L_NAME] = new QHBoxLayout;
layoutDataChild[L_SIZE] = new QHBoxLayout;
layoutDataChild[L_SPRITE] = new QHBoxLayout;
layoutDataChild[L_SPRITE]->addWidget(pushButtonSprite);
layoutDataChild[L_SPRITE]->addWidget(labelSpritePath);
layoutDataChild[L_NAME]->addWidget(labelData[D_NAME]);
layoutDataChild[L_NAME]->addWidget(lineEditData[D_NAME]);
layoutDataChild[L_SIZE]->addWidget(labelData[D_SIZE_W]);
layoutDataChild[L_SIZE]->addWidget(lineEditData[D_SIZE_W]);
layoutDataChild[L_SIZE]->addWidget(lineEditData[D_SIZE_H]);
layoutData->addLayout(layoutDataChild[L_SPRITE]);
layoutData->addLayout(layoutDataChild[L_NAME]);
layoutData->addLayout(layoutDataChild[L_SIZE]);
layoutData->addWidget(pushButtonSave);
mainLayout->addWidget(labelSprite);
mainLayout->addLayout(layoutData);
connect(pushButtonSave,SIGNAL(clicked()),this,SLOT(save()));
connect(pushButtonSprite,SIGNAL(clicked()),this,SLOT(loadSprite()));
setLayout(mainLayout);
}
void BulletEditor::loadFile(QString file)
{
Json::Value root = loadJSONFile(file.toStdString().c_str());
loadSprite(QString(root["sprite"].asCString()));
lineEditData[D_NAME]->setText(root["name"].asCString());
lineEditData[D_SIZE_W]->setText(QString::number(root["size"]["w"].asInt()));
lineEditData[D_SIZE_H]->setText(QString::number(root["size"]["h"].asInt()));
}
void BulletEditor::loadSprite()
{
/*Loads a Sprite's file path*/
QString file = QFileDialog::getOpenFileName(this, "Open File", QString(), "Pictures (*.png *.jpg *.jpeg)");
loadSprite(file);
}
void BulletEditor::loadSprite(QString file)
{
QPixmap pixmap(file);//Loads the sprite's pixmap
if(!pixmap.isNull())
{
labelSprite->setPixmap(pixmap.scaled(128,128, Qt::KeepAspectRatio, Qt::SmoothTransformation));//Sets it to 128*128 max, with ratio
labelSpritePath->setText(file);//Shows the path on the widget
lineEditData[D_SIZE_W]->setText(QString::number(labelSprite->pixmap()->width()));
lineEditData[D_SIZE_H]->setText(QString::number(labelSprite->pixmap()->height()));
sprite_loaded = true;
}
else
{
labelSpritePath->setText("Failed to load sprite");
sprite_loaded = false;
}
}
void BulletEditor::save()
{
/*Checks the values before saving*/
bool isSizeNumeric[2];
lineEditData[D_SIZE_W]->text().toInt(&isSizeNumeric[0]);
lineEditData[D_SIZE_H]->text().toInt(&isSizeNumeric[1]);
if(lineEditData[D_NAME]->text().isEmpty())
{
/*If Name is empty*/
QMessageBox::warning(this, "Incorrect Value", "Please specify a name for your Entity.");
}
else if(!sprite_loaded)
{
/*If the sprite isn't loaded*/
QMessageBox::warning(this, "Incorrect Value", "Please load a sprite before saving.");
}
else if(lineEditData[D_SIZE_W]->text().isEmpty() || lineEditData[D_SIZE_H]->text().isEmpty())
{
/*If Health is empty*/
QMessageBox::warning(this, "Incorrect Value", "Please fill the Size values.");
}
else if(!isSizeNumeric[0] || !isSizeNumeric[1])
{
/*If Health isn't numeric*/
QMessageBox::warning(this, "Incorrect Value", "Please check that the Sizes are integers.");
}
else
{
/*Saves*/
QString folder_path = QFileInfo(labelSpritePath->text()).absoluteDir().absolutePath();
QString file_path = QFileDialog::getSaveFileName(this, "Save File", folder_path + "/" + lineEditData[D_NAME]->text() + ".bullet", "Json Bullet File (*.bullet)");
Json::Value root;
root["name"] = lineEditData[D_NAME]->text().toStdString();
root["sprite"] = labelSpritePath->text().toStdString();
root["size"]["w"] = lineEditData[D_SIZE_W]->text().toInt();
root["size"]["h"] = lineEditData[D_SIZE_H]->text().toInt();
saveJSONFile(root,file_path.toStdString().c_str());
}
}
| true |
4489d7e485238c64d058402bc0bfcb1ceb3da3ac | C++ | jeffreynkali/SevenDragons | /Deck.h | UTF-8 | 350 | 3.21875 | 3 | [] | no_license | #ifndef DECK_H
#define DECK_H
#include <vector>
#include <memory>
template <class T>
class Deck : public std::vector<T>{
public:
T draw(){
T result = this->back();
this->pop_back();
return result;
}
void setDeck(std::vector<T> _v){
deck1 = _v;
}
std::vector<T> getDeck(){
return deck1;
}
};
#endif //DECK_H | true |
c1097738ac809b6b2b7708162137110383403d04 | C++ | rpuntaie/c-examples | /cpp/utility_initializer_list_size.cpp | UTF-8 | 348 | 2.546875 | 3 | [
"MIT"
] | permissive | /*
g++ --std=c++20 -pthread -o ../_build/cpp/utility_initializer_list_size.exe ./cpp/utility_initializer_list_size.cpp && (cd ../_build/cpp/;./utility_initializer_list_size.exe)
https://en.cppreference.com/w/cpp/utility/initializer_list/size
*/
#include <initializer_list>
int main() { static_assert(std::initializer_list{1,2,3,4}.size() == 4); }
| true |
673a62ae7e5fff1047e6626e8ff4c2246ef52cdb | C++ | OliverMoli/Multimediaproject2a | /Project/source/ResourceManager.cpp | UTF-8 | 3,306 | 3.109375 | 3 | [] | no_license | #include "pch.h"
#include "ResourceManager.h"
ResourceManager& ResourceManager::getInstance()
{
static ResourceManager instance;
return instance;
}
void ResourceManager::loadTexture(std::string name, std::string fileName)
{
if (textures.find(name) != textures.end())
{
std::cout << "Careful! you are overriding the Texture Resource with name [ " << name << " ]" << std::endl;
}
sf::Texture value;
if (value.loadFromFile(fileName))
{
textures[name] = std::make_shared<sf::Texture>(value);
}
}
void ResourceManager::loadTextureWithTransparentColor(std::string name, std::string fileName, sf::Color transparentColor)
{
if (textures.find(name) != textures.end())
{
std::cout << "Careful! you are overriding the Texture Resource with name [ " << name << " ]" << std::endl;
}
sf::Image image;
if (image.loadFromFile(fileName))
{
image.createMaskFromColor(transparentColor);
sf::Texture value;
if (value.loadFromImage(image))
{
textures[name] = std::make_shared<sf::Texture>(value);
}
}
}
void ResourceManager::loadFont(std::string name, std::string fileName)
{
if (fonts.find(name) != fonts.end())
{
std::cout << "Careful! you are overriding the Font Resource with name [ " << name << " ]" << std::endl;
}
sf::Font value;
if (value.loadFromFile(fileName))
{
fonts[name] = std::make_shared<sf::Font>(value);
}
}
void ResourceManager::loadSound(std::string name, std::string fileName)
{
if (sounds.find(name) != sounds.end())
{
std::cout << "Careful! you are overriding the Sound Resource with name [ " << name << " ]" << std::endl;
}
sf::SoundBuffer value;
if (value.loadFromFile(fileName))
{
sounds[name] = std::make_shared<sf::SoundBuffer>(value);
}
}
void ResourceManager::addAnimation(std::string name, Animation & anim)
{
if (animations.find(name) != animations.end())
{
std::cout << "Careful! you are overriding the Animation Resource with name [ " << name << " ]" << std::endl;
}
animations[name] = std::make_shared<Animation>(anim);
}
void ResourceManager::freeResources()
{
textures.clear();
fonts.clear();
sounds.clear();
animations.clear();
}
std::shared_ptr<sf::Texture> ResourceManager::getTexture(std::string name)
{
if (textures.find(name) != textures.end())
{
return textures[name];
}
std::cout << "Careful! The TextureResource named [" << name << "] you tried to get does not exist! Returned nullptr instead";
return nullptr;
}
std::shared_ptr<sf::Font> ResourceManager::getFont(std::string name)
{
if (fonts.find(name) != fonts.end())
{
return fonts[name];
}
std::cout << "Careful! The FontResource named [" << name << "] you tried to get does not exist! Returned nullptr instead";
return nullptr;
}
std::shared_ptr<sf::SoundBuffer> ResourceManager::getSound(std::string name)
{
if (sounds.find(name) != sounds.end())
{
return sounds[name];
}
std::cout << "Careful! The Sound Resource named [" << name << "] you tried to get does not exist! Returned nullptr instead";
return nullptr;
}
std::shared_ptr<Animation> ResourceManager::getAnimation(std::string name)
{
if (animations.find(name) != animations.end())
{
return animations[name];
}
std::cout << "Careful! The Animation Resource named [" << name << "] you tried to get does not exist! Returned nullptr instead";
return nullptr;
}
| true |
9c2e7dd3e8c47eab9b679b4a2ae12e368338e3e1 | C++ | MrMiilkNotes/Graphics | /project03/project03/project03/main.cpp | GB18030 | 4,533 | 3.078125 | 3 | [] | no_license | /* Rotating cube with viewer movement from Chapter 5 */
/* Cube definition and display similar to rotating--cube program */
/* We use the Lookat function in the display callback to point
the viewer, whose position can be altered by the x,X,y,Y,z, and Z keys.
The perspective view is set in the reshape callback */
#include <stdlib.h>
#ifdef __APPLE__
#include <GLUT/glut.h>
#else
#include <GL/glut.h>
#endif
#include<iostream>
#include"continer.h"
positions_t vertices;
surfaces_t surfaces;
//ģĵ
point_posi_t model_posi; //{ 0.0, 0.0, 0.0 }
//
scalef_t scalf = {1.0, 1.0, 1.0};
//תǶ
static GLfloat theta[] = { 0.0,0.0,0.0 };
static GLint axis = 2;
static GLdouble viewer[] = { 0.0, 0.0, 5.0 }; /* initial viewer location */
//ȡĺ
void load_off(const char* filename);
//ɫΪ˲ȫһɫ
int n_color = 7;
GLfloat colors[7][3] = { {1.0,0.0,0.0},
{1.0,1.0,0.0}, {0.0,1.0,0.0}, {0.0,0.0,1.0},
{1.0,0.0,1.0}, {1.0,1.0,1.0}, {0.0,1.0,1.0} };
GLfloat color[] = { 1.0, 1.0, 1.0 };
//ڻһ棬ͼδ洢surface -- container.h
void ployshape(const surface_t& surface)
{
int i = 0;
glBegin(GL_POLYGON);
for (auto point : surface) {
GLfloat p[] = { vertices[point][0], vertices[point][1], vertices[point][2] };
glColor3fv(colors[++i % n_color]);
glVertex3fv(p);
}
glEnd();
}
//һͼ
void colorSurface()
{
for (auto surface : surfaces) {
ployshape(surface);
}
}
void display(void)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
/* Update viewer position in modelview matrix */
glLoadIdentity();
gluLookAt(viewer[0], viewer[1], viewer[2], 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
/* ţתƶ */
glTranslated(model_posi[0], model_posi[1], model_posi[2]);
glRotatef(theta[0], 1.0, 0.0, 0.0);
glRotatef(theta[1], 0.0, 1.0, 0.0);
glRotatef(theta[2], 0.0, 0.0, 1.0);
glScaled(scalf[0], scalf[1], scalf[2]);
colorSurface();
glFlush();
glutSwapBuffers();
}
void mouse(int btn, int state, int x, int y)
{
/*if (btn == GLUT_LEFT_BUTTON && state == GLUT_DOWN) axis = 0;
if (btn == GLUT_MIDDLE_BUTTON && state == GLUT_DOWN) axis = 1;
if (btn == GLUT_RIGHT_BUTTON && state == GLUT_DOWN) axis = 2;
theta[axis] += 2.0;
if (theta[axis] > 360.0) theta[axis] -= 360.0;
display();*/
}
// 1 ͨ x,y,z,s
void processKeys(unsigned char key, int x, int y)
{
//
double sca_sens = 0.01;
if (key == 's'){
scalf[0] *= 1 - sca_sens;
scalf[1] *= 1 - sca_sens;
scalf[2] *= 1 - sca_sens;
}
if (key == 'S') {
scalf[0] *= 1 + sca_sens;
scalf[1] *= 1 + sca_sens;
scalf[2] *= 1 + sca_sens;
}
// ת
if (key == 'x') {
theta[0] += 2.0;
if (theta[0] > 360.0) theta[0] -= 360.0;
}
if (key == 'X') {
theta[0] -= 2.0;
if (theta[0] < 0) theta[0] += 360.0;
}
if (key == 'y') {
theta[1] += 2.0;
if (theta[1] > 360.0) theta[1] -= 360.0;
}
if (key == 'Y') {
theta[1] -= 2.0;
if (theta[1] < 0) theta[1] += 360.0;
}
if (key == 'z') {
theta[2] += 2.0;
if (theta[2] > 360.0) theta[2] -= 360.0;
}
if (key == 'Z') {
theta[2] -= 2.0;
if (theta[2] < 0) theta[2] += 360.0;
}
glutPostRedisplay();
}
// 2 special key ƶļͷ
void processKeys(int key, int x, int y)
{
//ӽ
double dx = 0.05;
double dy = 0.05;
if (key == GLUT_KEY_LEFT) {
model_posi[0] -= dx;
}
if (key == GLUT_KEY_RIGHT) {
model_posi[0] += dx;
}
if (key == GLUT_KEY_DOWN) {
model_posi[1] -= dy;
}
if (key == GLUT_KEY_UP) {
model_posi[1] += dy;
}
glutPostRedisplay();
}
void myReshape(int w, int h)
{
glViewport(0, 0, w, h);
/* Use a perspective view */
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
if (w <= h) glFrustum(-2.0, 2.0, -2.0 * (GLfloat)h / (GLfloat)w,
2.0* (GLfloat)h / (GLfloat)w, 2.0, 20.0);
else glFrustum(-2.0, 2.0, -2.0 * (GLfloat)w / (GLfloat)h,
2.0* (GLfloat)w / (GLfloat)h, 2.0, 20.0);
/* Or we can use gluPerspective */
//gluPerspective(45.0, w/h, -10.0, 50.0);
glMatrixMode(GL_MODELVIEW);
}
void
main(int argc, char **argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(500, 500);
glutCreateWindow("Hello window!");
// load model
load_off("horse.off");
// regist functions
glutReshapeFunc(myReshape);
glutDisplayFunc(display);
glutMouseFunc(mouse);
glutKeyboardFunc(processKeys);
glutSpecialFunc(processKeys);
glEnable(GL_DEPTH_TEST);
glutMainLoop();
return 0;
}
| true |
5061ea77c42c1f6fe5f97b599309aafb38fa91ff | C++ | XiaoYuhao/ACM-ICPC-practice | /A - Nearest Common Ancestors/test.cpp | GB18030 | 2,035 | 2.65625 | 3 | [] | no_license | #define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<algorithm>
#include<vector>
#include<stdio.h>
using namespace std;
const int MAX = 10010;
const int MAX_LOG = 50;
/* LCA */
/* ڶ㷨*/
vector<int>G[MAX];
vector<int>T[MAX];
int root;
/*
int parent[MAX_LOG][MAX];
int depth[MAX];
void dfs(int v, int p, int d) {
parent[0][v] = p;
depth[v] = d;
for (int i = 0; i < G[v].size(); i++) {
if (G[v][i] != p)dfs(G[v][i], v, d + 1);
}
}
void init(int V) {
dfs(root, -1, 0);
for (int k = 0; k + 1 < MAX_LOG; k++) {
for (int v = 0; v < V; v++) {
if (parent[k][v] < 0)parent[k + 1][v] = -1;
else parent[k + 1][v] = parent[k][parent[k][v]];
}
}
}
int lca(int u, int v) {
if (depth[u] > depth[v]) swap(u, v);
for (int k = 0; k < MAX_LOG; k++) {
if ((depth[v] - depth[u]) >> k & 1) {
v = parent[k][u];
}
}
if (u == v)return u;
for (int k = MAX_LOG - 1; k >= 0; k--) {
if (parent[k][u] != parent[k][v]) {
u = parent[k][u];
v = parent[k][v];
}
}
return parent[0][u];
}*/
int parent[MAX];
int depth[MAX];
void dfs(int v, int p, int d) {
parent[v] = p;
depth[v] = d;
for (int i = 0; i < G[v].size(); i++) {
if (G[v][i] != p)dfs(G[v][i], v, d + 1);
}
}
void init() {
dfs(root, -1, 0);
}
int lca(int u, int v) {
while (depth[u] > depth[v])u = parent[u];
while (depth[v] > depth[u])v = parent[v];
while (v != u) {
u = parent[u];
v = parent[v];
}
return u;
}
int find_root(int v) {
if (T[v].size() == 0)return v;
else return find_root(T[v][0]);
}
int main() {
int tt;
scanf("%d", &tt);
int n;
while (tt--) {
scanf("%d", &n);
int a, b;
for (int i = 0; i < n-1; i++) {
scanf("%d%d", &a, &b);
G[a-1].push_back(b-1);
G[b-1].push_back(a-1);
T[b - 1].push_back(a - 1);
}
root = find_root(0);
// cout << " " << root << endl;
init();
scanf("%d%d", &a, &b);
int ans;
ans = lca(a - 1, b - 1) + 1;
printf("%d\n", ans);
for (int i = 0; i <n; i++) {
G[i].clear();
T[i].clear();
}
}
return 0;
} | true |
07b958541ebff5f477d5d3844b5d26c324f6b293 | C++ | dhoman01/cs3100 | /mult-thread/src/WorkQueue.cpp | UTF-8 | 912 | 3.09375 | 3 | [] | no_license | #include "WorkQueue.hpp"
#include <algorithm>
void WorkQueue::start(int n)
{
auto doTask = [&](){
try
{
while(cont.load())
{
try
{
tasklist.dequeue()();
} catch(const std::exception &exc)
{
std::cerr << exc.what() << std::endl;
}
}
}
catch(const std::exception &exc)
{
std::cerr << exc.what() <<std::endl;
}
};
for(auto i = 0; i < n; ++i)
{
std::cout << "Placing a thread the on the list" << std::endl;
threadpool.emplace_back(std::thread(doTask));
}
}
void WorkQueue::stop()
{
std::cout << "Stopping work" << std::endl;
cont = false;
tasklist.abort();
std::for_each(threadpool.begin(),threadpool.end(),[](auto& t){
std::cout << "Stopping thread" << std::endl;
t.detach();
std::cout << "thread detached" << std::endl;
});
threadpool.clear();
}
void WorkQueue::post(std::function<void(void)> f)
{
{
tasklist.enqueue(f);
};
}
| true |
74dd87dee057f8a3981a7c986f6bc18e93bf1975 | C++ | gitynity/CP | /kangaroo.cpp | UTF-8 | 263 | 2.859375 | 3 | [] | no_license | //https://www.hackerrank.com/challenges/kangaroo/problem
string kangaroo(int x1, int v1, int x2, int v2) {
if(x1<x2 && v1<=v2 )
return "NO";
else if(x2<x1 && v2<=v1)
return "NO";
if((x1-x2)%(v1-v2)==0)
{
return "YES";
}
else
return "NO";
}
| true |
904b1785617d367ee8851ba1d8301d90dfe32106 | C++ | PowerNeverEnds/BaekjoonOnlineJudge_Cpp | /07000~7999/7569_토마토.cpp | UHC | 2,429 | 2.828125 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <queue>
typedef long long ll;
using namespace std;
// ݽð + յ
int dy[6] = { -1,0,1,0,0,0 };
int dx[6] = { 0,-1,0,1,0,0 };
int dh[6] = { 0,0,0,0,-1,1 };
struct MyPoint
{
int y;
int x;
int h;
};
int bfs(vector<MyPoint>& vec, int*** arr, int*** visited)
{
queue<MyPoint> q;
for (auto e : vec)
{
visited[e.y][e.x][e.h] = 1;
q.push(e);
}
MyPoint st = MyPoint({ 0,0,0 });
while (true)
{
if (q.empty())
break;
st = q.front();
q.pop();
for (int i = 0; i < 6; i++)
{
int nY = st.y + dy[i];
int nX = st.x + dx[i];
int nH = st.h + dh[i];
if (arr[nY][nX][nH] == 0 && visited[nY][nX][nH] == 0)
{
visited[nY][nX][nH] = visited[st.y][st.x][st.h] + 1;
q.push(MyPoint({ nY,nX,nH }));
}
}
}
return visited[st.y][st.x][st.h];
}
int main()
{
int M, N, H;
cin >> M >> N >> H;
int*** arr = new int** [(ll)N + 2];
fill(arr, arr + N + 2, nullptr);
for (int i = 0; i < N + 2; i++)
{
arr[i] = new int* [(ll)M + 2];
fill(arr[i], arr[i] + M + 2, nullptr);
for (int j = 0; j < M + 2; j++)
{
arr[i][j] = new int[(ll)H + 2];
fill(arr[i][j], arr[i][j] + H + 2, -1);
}
}
for (int h = 1; h <= H; h++)
{
for (int i = 1; i <= N; i++)
{
for (int j = 1; j <= M; j++)
{
cin >> arr[i][j][h];
}
}
}
vector<MyPoint> vec;
for (int h = 1; h <= H; h++)
{
for (int i = 1; i <= N; i++)
{
for (int j = 1; j <= M; j++)
{
if (arr[i][j][h] == 1)
vec.push_back(MyPoint({ i,j,h }));
}
}
}
int*** visited = new int** [(ll)N + 2];
fill(visited, visited + N + 2, nullptr);
for (int i = 0; i < N + 2; i++)
{
visited[i] = new int* [(ll)M + 2];
fill(visited[i], visited[i] + M + 2, nullptr);
for (int j = 0; j < M + 2; j++)
{
visited[i][j] = new int[(ll)H + 2];
fill(visited[i][j], visited[i][j] + H + 2, 0);
}
}
int times = bfs(vec, arr, visited);
bool noVisited = false;
for (int h = 1; h <= H; h++)
{
for (int i = 1; i <= N; i++)
{
for (int j = 1; j <= M; j++)
{
//cout << visited[i][j][h] << " ";
if (arr[i][j][h] == 0 && visited[i][j][h] == 0)
{
noVisited = true;
break;
}
}
//cout << "\n";
if (noVisited == true)
break;
}
//cout << "\n";
if (noVisited == true)
break;
}
//cout << "\n";
if (noVisited == true)
{
cout << -1 << "\n";
}
else
{
cout << times - 1 << "\n";
}
return 0;
} | true |
4ecf81ddfd48419161177249225d28f0f9cec8b3 | C++ | thegamer1907/Code_Analysis | /CodesNew/933.cpp | UTF-8 | 962 | 2.984375 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;
vector<string> polball;
vector <string> enemy;
int main(){
int n , m ;
string t;
cin >> n >>m;
for(int i =0 ; i < n ; i++) {
cin >>t;
polball.push_back (t) ;
}
for(int i =0 ; i <m ; i++){
cin >>t;
enemy.push_back(t);
}
sort (polball.begin() , polball.end());
sort (enemy.begin () , enemy.end());
int i = 0 , j = 0 , counter = 0;
while (i < n and j <m){
if(polball[i]==enemy[j]){i++;j++;counter++;}
else if(polball[i]<enemy[j]){i++;}
else j++;
}
if(counter==0){
if(n == m) cout <<"NO"<<endl;
else if ( n < m) cout <<"NO"<<endl;
else cout <<"YES"<<endl;
}
else if(counter %2 == 0){
if( n ==m) cout <<"NO"<<endl;
else if (n < m) cout <<"NO"<<endl;
else cout <<"YES"<<endl;
}
else {
if( n >= m) cout <<"YES"<<endl;
else cout <<"NO"<<endl;
}
return 0;} | true |
43a57ee0a5ef3f1b456a71a844dae06c4ff5a29b | C++ | XiaoChen0837/BiShi | /MyBishi/远景.cpp | UTF-8 | 1,954 | 3.359375 | 3 | [] | no_license | //#include <iostream>
//#include <string>
//#include <vector>
//#include <algorithm>
//#include <stack>
//#include <unordered_map>
//
//using namespace std;
//int main() {
// string str;
// getline(cin, str);
//
// stack<char> s1;
//
// for (auto i : str) {
// if (i == '\" ' || i == '{' || i == '}' || i == '[' || i == ']') {
// s1.push(i);
// }
// }
//
// stack <char> s2;
// bool flag = true;
// while (!s1.empty()) {
// if (s2.empty()) {
// s2.push(s1.top());
// s1.pop();
// continue;
// }
//
// char t = s1.top();
// s1.pop();
// if (t == '}' || t == ']') {
// s2.push(t);
// continue;
// }
//
// if (t == '{') {
// if (s2.top() == '}') {
// s2.pop();
// continue;
// }
// else {
// flag = false;
// break;
// }
// }
//
// if (t == '[') {
// if (s2.top() == ']') {
// s2.pop();
// continue;
// }
// else {
// flag = false;
// break;
// }
// }
//
// if (t == '\"') {
// if (s2.top() == '\"') {
// s2.pop();
// continue;
// }
// else {
// s2.push(t);
// break;
// }
// }
// }
//
// if (!s2.empty()) {
// flag = false;
// }
//
// if (flag) {
// cout << "true" << endl;
// }
// else {
// cout << "false" << endl;
// }
//
// return 0;
//}
//
//
//int main() {
// string str;
// getline(cin, str);
// int count = 0;
// stack<char> s;
//
// unordered_map<char, char> pairs = { {'"','"'}, {']', '['},{'}', '{'} };
//
// for (int i = 0; i < str.length(); i++) {
// if (str[i] != '\"' && str[i] != '{' && str[i] != '}' && str[i] != '[' && str[i] != ']') {
// continue;
// }
// else {
// if (pairs.count(str[i])) {
// if (s.empty() || s.top() != pairs[str[i]]) {
// cout << "false" << endl;
// return 0;
// }
// s.pop();
// }
// else {
// s.push(str[i]);
// }
// }
// }
//
// if (s.empty()) {
// cout << "true" << endl;
// }
// else {
// cout << "false" << endl;
// }
//
// return 0;
//}
//I want to go to the zoo[the small one | true |
ea1bb5a422153e83dc0b20640dc744b34fd02c20 | C++ | yaominzh/CodeLrn2019 | /boboleetcode/Play-Leetcode-master/0945-Minimum-Increment-to-Make-Array-Unique/cpp-0945/main2.cpp | UTF-8 | 956 | 3.40625 | 3 | [
"Apache-2.0"
] | permissive | /// Source : https://leetcode.com/problems/minimum-increment-to-make-array-unique/
/// Author : liuyubobobo
/// Time : 2018-11-25
#include <iostream>
#include <vector>
using namespace std;
/// Using sort and don't change the A array
/// Time Complexity: O(nlogn)
/// Space Complexity: O(1)
class Solution {
public:
int minIncrementForUnique(vector<int>& A) {
if(A.size() == 0)
return 0;
sort(A.begin(), A.end());
int res = 0, left = 0;
for(int i = 1; i < A.size(); i ++)
if(A[i] == A[i - 1]){
left ++;
res -= A[i];
}
else{
int seg = min(left, A[i] - A[i - 1] - 1);
res += (A[i - 1] + 1 + A[i - 1] + seg) * seg / 2;
left -= seg;
}
if(left)
res += (A.back() + 1 + A.back() + left) * left / 2;
return res;
}
};
int main() {
return 0;
} | true |
1de7cb884a75bd4be24c9c4e4956f6e44065bd98 | C++ | mparsakia/pic-ucla | /10b/hw 6/hmw_6_3.cpp | UTF-8 | 3,672 | 3.34375 | 3 | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | /*
Homework: 6 Problem: 3
Crunch some prime numbers and test how long the algorithm takes
*/
#include <iostream>
#include <cassert>
#include <string>
#include <cstring>
#include <sstream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <iterator>
#include <deque>
#include <ctime>
using namespace std;
int main() {
string more = "y";
while (more == "y")
{
set<int> myset;
set<int>::iterator pos;
int givenum;
cout << "Enter any positive int: ";
cin >> givenum;
cout << endl;
int sqrtnum = sqrt(givenum);
for (size_t i = 1; i <= givenum; i++)
{
myset.insert(i);
}
int counter = 0;
int cutoff = sqrtnum;
for (int i = 2; i <= cutoff; i++)
{
cout << "Removing the elements divisible by " << i << ":\n";
for (auto pos = myset.begin(); pos != myset.end();)
{
if (((*pos)%i == 0) && ((*pos) != i))
{
pos = myset.erase(pos);
}
else
{
pos++;
}
}
for (pos = myset.begin(); pos != myset.end(); pos++)
{
if (next(pos, 1) != myset.end())
{
cout << *pos << ", ";
}
else
{
cout << *pos;
}
}
cout << endl;
}
cout << "Prime numbers not exceeding " << givenum << ": \n";
for (pos = myset.begin(); pos != myset.end(); pos++)
{
if (next(pos, 1) != myset.end())
{
cout << *pos << ", ";
}
else
{
cout << *pos;
}
}
cout << "\n\nContinue (y/n)? ";
cin >> more;
}
cout << "\nComplexity check for n = 10^4, 10^5, 10^6:\n";
{
time_t starttime;
time_t stoptime;
time(&starttime);
set<int> myset;
set<int>::iterator pos;
int givenum = 10000;
int sqrtnum = sqrt(givenum);
for (size_t i = 1; i <= givenum; i++)
{
myset.insert(i);
}
int cutoff = sqrtnum;
for (int i = 2; i <= cutoff; i++)
{
for (auto pos = myset.begin(); pos != myset.end();)
{
if (((*pos) % i == 0) && ((*pos) != i))
{
pos = myset.erase(pos);
}
else
{
pos++;
}
}
}
time(&stoptime);
double seconds = difftime(stoptime,starttime);
cout << "Time (sec) for computing primes not exceeding 10000: " << seconds;
cout << endl;
}
{
time_t starttime;
time_t stoptime;
time(&starttime);
set<int> myset;
set<int>::iterator pos;
int givenum = 100000;
int sqrtnum = sqrt(givenum);
for (size_t i = 1; i <= givenum; i++)
{
myset.insert(i);
}
int cutoff = sqrtnum;
for (int i = 2; i <= cutoff; i++)
{
for (auto pos = myset.begin(); pos != myset.end();)
{
if (((*pos) % i == 0) && ((*pos) != i))
{
pos = myset.erase(pos);
}
else
{
pos++;
}
}
}
time(&stoptime);
double seconds = difftime(stoptime, starttime);
cout << "Time (sec) for computing primes not exceeding 100000: " << seconds;
cout << endl;
}
{
time_t starttime;
time_t stoptime;
time(&starttime);
set<int> myset;
set<int>::iterator pos;
int givenum = 1000000;
int sqrtnum = sqrt(givenum);
for (size_t i = 1; i <= givenum; i++)
{
myset.insert(i);
}
int cutoff = sqrtnum;
for (int i = 2; i <= cutoff; i++)
{
for (auto pos = myset.begin(); pos != myset.end();)
{
if (((*pos) % i == 0) && ((*pos) != i))
{
pos = myset.erase(pos);
}
else
{
pos++;
}
}
}
time(&stoptime);
double seconds = difftime(stoptime, starttime);
cout << "Time (sec) for computing primes not exceeding 1000000: " << seconds;
cout << endl;
}
system("pause");
return 0;
} | true |
d131a4208a74a763d99b8217136064d36ce4e6ce | C++ | ChrisAshton84/LeetCode | /number-of-islands.cpp | UTF-8 | 6,417 | 2.703125 | 3 | [] | no_license | class Solution {
public:
int numIslands(vector<vector<char>>& grid) {
if (grid.size() == 0)
return 0;
if (grid[0].size() == 0)
return 0;
auto lsize = grid[0].size();
typedef struct {
int start;
int end;
int id;
int joined;
} island_info_t;
vector<island_info_t> prevIslands;
vector<island_info_t> curIslands;
int ret = 0;
int prevID = 0;
// Scan forward line-by-line
for (int l = 0; l < grid.size(); l++) {
auto &line = grid[l];
curIslands.clear();
// First generate a list of the islands on this line
for (int i = 0; i < lsize; i++) {
if (line[i] == '1') {
auto start = i;
auto end = i;
while (((end + 1) < lsize) && (line[end + 1] == '1'))
end++;
// Emplace islands *in order*
curIslands.emplace_back(island_info_t{start, end, 0, 0});
i = end;
}
}
// Next compare and merge with any islands from previous line
for (auto& curIsland: curIslands) {
for (auto& prevIsland: prevIslands) {
// Islands are ordered, so if we've gone too far, done with this island
if (prevIsland.start > curIsland.end)
break;
// Check for intersection
if (((curIsland.start >= prevIsland.start) && (curIsland.start <= prevIsland.end) ||
((curIsland.end >= prevIsland.start) && (curIsland.end <= prevIsland.end))) ||
((curIsland.start <= prevIsland.start) && (curIsland.end >= prevIsland.end))) {
// These islands intersect - merge this with the previous island
// If this island has no id, it needs prev island's id
if (curIsland.id == 0)
curIsland.id = prevIsland.id;
// Otherwise, this island already found one match and it will be
// merging in a second island, which should become the same id,
// along with any other island sharing it
else if (curIsland.id != prevIsland.id) {
int oldID = max(prevIsland.id, curIsland.id);
int newID = min(prevIsland.id, curIsland.id);
for (auto& ii: prevIslands) {
if (ii.id == oldID)
ii.id = newID;
}
for (auto& ii: curIslands) {
if (ii.id == oldID)
ii.id = newID;
}
}
// Note that the prev island was joined w/ this one
prevIsland.joined = 1;
for (auto& i: prevIslands) {
if (i.id == prevIsland.id)
i.joined = true;
}
}
}
// No intersection w/ previous island, so needs new id
if (curIsland.id == 0)
curIsland.id = ++prevID;
}
// Now, look at previous line - any island pieces that weren't joined need to be
// removed and tested to see whether that island is complete
for (int i = 0; i < prevIslands.size(); i++) {
if (prevIslands[i].joined == 0) {
for (int j = 0; j < prevIslands.size(); j++) {
if (prevIslands[j].id == prevIslands[i].id)
prevIslands[j].joined = 1; // Now use this to signify it's been added to the result
}
//cout << "Ended an island on line " << l << ", range=" << prevIslands[i].start << "," << prevIslands[i].end << ", id=" << prevIslands[i].id << endl;
ret++;
}
}
prevIslands = curIslands;
}
// Now, look at previous line - any island pieces that weren't joined need to be
// removed and tested to see whether that island is complete
for (int i = 0; i < prevIslands.size(); i++) {
if (prevIslands[i].joined == 0) {
for (int j = 0; j < prevIslands.size(); j++) {
if (prevIslands[j].id == prevIslands[i].id)
prevIslands[j].joined = 1; // Now use this to signify it's been added to the result
}
//cout << "Ended an island at end, range=" << prevIslands[i].start << "," << prevIslands[i].end << ", id=" << prevIslands[i].id << endl;
ret++;
}
}
return ret;
}
};
| true |
8c596411c73a2d28bdcd3a983fb5cc8025678d96 | C++ | tyleragreen/rice-demo | /test.cpp | UTF-8 | 394 | 2.71875 | 3 | [] | no_license | #include "rice/Data_Type.hpp"
#include "rice/Constructor.hpp"
using namespace Rice;
class Test
{
public:
Test() {}
std::string sayHello()
{
return std::string("Hello, World!");
}
};
extern "C"
void Init_Test()
{
Data_Type<Test> rb_cTest =
define_class<Test>("Test")
.define_constructor(Constructor<Test>())
.define_method("hello", &Test::sayHello);
} | true |
18307b2b5b5bb85a10bcb2eecc73e425ac370954 | C++ | MaelQuemard/Compilation | /src/Compilateur.cpp | UTF-8 | 6,553 | 2.96875 | 3 | [] | no_license | #include "Compilateur.hpp"
using namespace std;
Compilateur::Compilateur() {}
Compilateur::~Compilateur() {}
string Compilateur::readFile(string path) {
string fileRead = "";
std::string line;
std::cout << "PATH :: " << path << '\n';
ifstream myfile (path);
if (myfile.is_open()) {
while (getline (myfile,line)) {
fileRead += " " + line;
}
myfile.close();
} else std::cout << "FICHIER IMPOSSIBLE A OUVRIR";
return fileRead;
}
string Compilateur::waitCommand() {
string command;
cout << "> ";
getline(cin,command);
return command;
}
void Compilateur::executeCommand(string command) {
if (command == "generer G0") {
this->fg = new foretGenerateur();
cout << "\033[1;32mForêt correct\033[0m" << endl;
return;
} else if (command == "afficher G0") {
if (this->fg == NULL) {
cout << "Generer la foret avant, avec la commande : 'generer G0'" << endl;
} else {
for(auto& x : this->fg->getForet()){
cout << "|*****************" << "Arbre [" << x.first << "]*******************|" << endl;
std::cout << x.second->toString(0) << endl << endl;
}
}
return;
} else if (command == "analyser GPL") {
if (this->fg == NULL) {
cout << "Generer la foret avant, avec la commande : 'generer G0'" << endl;
} else {
string filePath;
cout << "----> Donnez le chemin du fichier de votre grammaire : "<< endl;
getline(cin, filePath);
string fileReader = readFile("src/grammar/"+ filePath +".txt");
sc = new Scanner(fileReader);
analyseur = new Analyseur(fg->getForet(), sc);
if (analyseur->analyseG0(fg->getForet()["s"])) {
cout << "\033[1;32mGPL correct\033[0m" << endl;
} else {
cout << "\033[1;31mGPL incorrect\033[0m" << endl;
}
}
return;
} else if (command == "afficher GPL") {
if (this->analyseur == NULL) {
cout << "Analyser la GPL avant, avec la commande : 'analyser GPL'" << endl;
} else if (this->fg == NULL) {
cout << "Generer la foret avant, avec la commande : 'generer G0'" << '\n';
} else {
for (auto& x : this->analyseur->getForet()) {
if (x.first != "e" && x.first != "f" && x.first != "n" && x.first != "s" && x.first != "t") {
cout << "|*****************" << "Arbre [" << x.first << "]*******************|" << endl;
cout << x.second->toString(0) << endl << endl;
}
}
}
return;
} else if (command == "analyser prog") {
string filePath;
cout << "----> Donnez le chemin du fichier de votre programme : "<< endl;
getline(cin, filePath);
string fileReader = readFile("src/prog/"+ filePath +".txt");
sc->modifierChaine(fileReader);
analyseur->setUnitelexicale();
analyseur->setNameProg(filePath);
if (analyseur->analyseGPL(analyseur->getForet()["Prgm"])) {
cout << "\033[1;32mProgramme correct\033[0m" << endl;
} else {
cout << "\033[1;32mProgramme incorrect\033[0m" << endl;
}
return;
} else if (command == "interprete") {
interpreteur = new Interpreteur();
interpreteur->execute(analyseur->getPCode(), analyseur->getPilex());
return;
} else if (command == "afficher pcode") {
std::cout << "/************* Etat de la pile Pcode taille [" << analyseur->getPCode().size() << "] ****************/" << '\n';
for (int j = 0; j < analyseur->getPCode().size(); j++) {
std::cout << "Pcode j:: " << j << " : " << analyseur->getPCode()[j] << '\n';
}
return;
} else if (command == "afficher pilex") {
std::cout << "/************* Etat de la pile Pilex taille [" << analyseur->getPilex().size() << "] avant traitement ****************/" << '\n';
for (int j = 0; j < analyseur->getPilex().size(); j++) {
std::cout << "Pilex j : " << analyseur->getPilex()[j] << '\n';
}
std::cout << endl << "/************* Etat de la pile Pilex taille [" << interpreteur->getPilex().size() << "] après traitement ****************/" << '\n';
for (int j = 0; j < interpreteur->getPilex().size(); j++) {
std::cout << "Pilex j : " << interpreteur->getPilex()[j] << '\n';
}
return;
} else if (command == "aide") {
cout << "Commande possible : " << endl;
cout << " - generer G0 : pour generer la foret G0" << endl;
cout << " - afficher G0 : pour afficher la foret G0" << endl;
cout << " - analyser GPL : pour analyser la grammaire gpl" << endl;
cout << " - afficher GPL : pour afficher la foret de votre GPL" << endl;
cout << " - analyser prog : pour analyser votre programme" << endl;
cout << " - interprete : pour interpreter le programme analyser précédement" << endl;
cout << " - afficher pcode : pour afficher le pcode après l'analyse du programme" << endl;
cout << " - afficher pilex : pour afficher le pilex après l'interprètation" << endl;
return;
} else if (command == "exit") {
return;
}
cout << "Commande non reconnu : Utiliser la commande 'aide'" << endl;
return;
}
int main(int argc, char const *argv[]) {
Compilateur* compil = new Compilateur();
//
string command;
do {
command = compil->waitCommand();
compil->executeCommand(command);
} while(command != "exit");
// foretGenerateur* fg = new foretGenerateur();
// string testRead = compil->readFile("src/grammar.txt");
// std::cout << "TEST READ :: " << testRead << '\n';
//
// //Scanner* sc = new Scanner("S1 -> [ N1 . '->' . E1 . ','#6 ] . ';' , N1 -> 'IDNTER'#2 , E1 -> T1 . [ '+' . T1#3 ] , T1 -> F1 . [ '.' . F1#4 ] , F1 -> 'IDNTER'#5 + 'ELTER'#5 + '(' . E1 . ')' + '[' . E . ']'#6 + '(/' . E . '/)'#7 , ;");
// Scanner* sc = new Scanner(testRead);
// Analyseur* analyseur = new Analyseur(fg->getForet(), sc);
// std::cout << analyseur->analyseG0(fg->getForet()["s"]) << endl;
//
// sc->modifierChaine("Program cond ; var I ; BEGIN IF I == 0 THEN TRUE END .");
// analyseur->setUnitelexicale();
// cout << analyseur->analyseGPL(analyseur->getForet()["Prgm"]) << endl;
return 0;
}
| true |
dddffe23b98a17199e99bc0ea1eb9874063b69ba | C++ | SAM33/TSCC2015_MPI2 | /T3CP.cpp | UTF-8 | 4,674 | 2.53125 | 3 | [] | no_license |
/* PROGRAM T3CP
Boundary data exchange with computing partition without data partition
Using MPI_Send, MPI_Recv to distribute input data
*/
#include <iostream>
#include <mpi.h>
#define ntotal 200
using namespace std;
int main (int argc,char ** argv)
{
double amax,gmax,a[ntotal],b[ntotal],c[ntotal],d[ntotal];
int i;
FILE *fp;
int nproc,myid,istart,iend,icount,r_nbr,l_nbr,lastp;
int itag,isrc,idest,istart1,icount1,istart2,iend1,istartm1,iendp1;
int gstart[16],gend[16],gcount[16];
MPI_Status istat[8];
MPI_Comm comm;
extern double max(double, double);
extern void startend(int nproc,int is1,int is2,int gstart[16],int gend[16],int gcount[16]);
MPI_Init(&argc,&argv);
MPI_Comm_size(MPI_COMM_WORLD,&nproc);
MPI_Comm_rank(MPI_COMM_WORLD,&myid);
comm=MPI_COMM_WORLD;
startend (nproc,0,ntotal-1,gstart,gend,gcount);
istart=gstart[myid];
iend=gend[myid];
icount=gcount[myid];
lastp=nproc-1;
cout<<"NPROC,MYID,ISTART,IEND = "<<nproc<<" "<<myid<<" "<<istart<<" "<<iend<<endl;
istartm1=istart-1;
iendp1=iend+1;
istart2=istart;
if (myid == 0) istart2=istart+1;
iend1=iend;
if(myid == lastp ) iend1=iend-1;
l_nbr=myid-1;
r_nbr=myid+1;
if (myid == 0) l_nbr=MPI_PROC_NULL;
if (myid == lastp) r_nbr=MPI_PROC_NULL;
/* READ'input.dat',and distribute input data */
if ( myid==0)
{
fp = fopen( "input.dat", "r");
fread( (void *)&b, sizeof(b), 1, fp );
fread( (void *)&c, sizeof(c), 1, fp );
fread( (void *)&d, sizeof(d), 1, fp );
fclose( fp );
for (idest = 1; idest < nproc; idest++)
{
istart1=gstart[idest];
icount1=gcount[idest];
itag=10;
MPI_Send ((void *)&b[istart1], icount1, MPI_DOUBLE, idest, itag, comm);
itag=20;
MPI_Send ((void *)&c[istart1], icount1, MPI_DOUBLE, idest, itag, comm);
itag=30;
MPI_Send ((void *)&d[istart1], icount1, MPI_DOUBLE, idest, itag, comm);
}
}
else
{
isrc=0;
itag=10;
MPI_Recv ((void *)&b[istart], icount, MPI_DOUBLE, isrc, itag, comm, istat);
itag=20;
MPI_Recv ((void *)&c[istart], icount, MPI_DOUBLE, isrc, itag, comm, istat);
itag=30;
MPI_Recv ((void *)&d[istart], icount, MPI_DOUBLE, isrc, itag, comm, istat);
}
/* Exchange data outside the territory */
itag=110;
MPI_Sendrecv((void *)&b[iend],1,MPI_DOUBLE,r_nbr,itag,
(void *)&b[istartm1],1,MPI_DOUBLE,l_nbr,itag,comm,istat);
itag=120;
MPI_Sendrecv((void *)&b[istart],1,MPI_DOUBLE,l_nbr,itag,
(void *)&b[iendp1],1,MPI_DOUBLE,r_nbr,itag,comm,istat);
/* Compute, gather and write out the computed result */
amax= -1.0e12;
for (i=istart2;i<=iend1;i++)
{
a[i]=c[i]*d[i]+(b[i-1]+2.0*b[i]+b[i+1])*0.25;
amax=max(amax,a[i]);
}
itag=130;
if (myid>0)
{
idest=0;
MPI_Send((void *)&a[istart],icount,MPI_DOUBLE,idest,itag,comm);
}
else
{
for (isrc=1;isrc<nproc;isrc++)
{
istart1=gstart[isrc];
icount1=gcount[isrc];
MPI_Recv((void *)&a[istart1],icount1,MPI_DOUBLE,isrc,itag,comm,istat);
}
}
MPI_Allreduce((void *)&amax,(void *)&gmax,1,MPI_DOUBLE,MPI_MAX,comm);
amax=gmax;
if(myid == 0)
{
for (i=0;i<ntotal;i+=40)
{
printf( "%.3f\t%.3f\t%.3f\t%.3f\t%.3f\t%.3f\t%.3f\t%.3f\n",
a[i],a[i+5],a[i+10],a[i+15],a[i+20],a[i+25],a[i+30],a[i+35]);
}
cout<<"MAXIMUM VALUE OF ARRAY A is "<<amax<<endl;
}
MPI_Finalize();
return 0;
}
double max(double a, double b)
{
if(a >= b)
return a;
else
return b;
}
void startend(int nproc,int is1,int is2,int gstart[16],int gend[16],int gcount[16])
{
int i,ilength,iblock,ir;
ilength=is2-is1+1;
iblock=ilength/nproc;
ir=ilength-iblock*nproc;
for (i=0;i<nproc;i++)
{
if (i<ir)
{
gstart[i]=is1+i*(iblock+1);
gend[i]=gstart[i]+iblock;
}
else
{
gstart[i]=is1+i*iblock+ir;
gend[i]=gstart[i]+iblock-1;
}
if (ilength<1)
{
gstart[i]=1;
gend[i]=0;
}
gcount[i]=gend[i]-gstart[i]+1;
}
}
| true |
658d27a606a63afbbdc2dc398563e9a2e912f0ab | C++ | kaitian521/topcoder | /TC_SRM_566_B/main.cpp | UTF-8 | 2,605 | 2.53125 | 3 | [
"Apache-2.0"
] | permissive | #include <iostream>
#include <string>
#include <string.h>
using namespace std;
#define N 60
#define MAX(a,b) (a>b)?a:b
int dp[N][N];
int n;
int f(string colors)
{
cout << colors << endl;
memset(dp, 0, sizeof(dp));
int i, j, k;
for (i = 2; i <= n; i ++)
{
for(j = 0; j <= n - i ; j++)
{
k = j + i - 1;
if (colors[j] == colors[k])
{
dp[j][k] = 1 + dp[j + 1][k - 1];
dp[j][k] = MAX(dp[j][k], dp[j + 1][k]);
dp[j][k] = MAX(dp[j][k], dp[j][k - 1]);
if (colors[j] == colors[j + 1])dp[j][k] = MAX(dp[j][k], 1 + dp[j + 2][k]);
if (colors[k] == colors[k - 1])dp[j][k] = MAX(dp[j][k], 1 + dp[j][k - 2]);
}
else
{
dp[j][k] = MAX(dp[j][k - 1], dp[j + 1][k]);
dp[j][k] = MAX(dp[j][k], dp[j + 1][k - 1]);
if (colors[j] == colors[j + 1])dp[j][k] = MAX(dp[j][k], 1 + dp[j + 2][k]);
if (colors[k] == colors[k - 1])dp[j][k] = MAX(dp[j][k], 1 + dp[j][k - 2]);
}
}
}
return dp[0][n-1];
}
string col;
int solve(int a, int b)
{
int tt = 0;
if (a == b) return 0;
if (a > b) return 0;
if (dp[a][b]) return dp[a][b];
if (col[a] == col[b]) tt = 1 + solve(a + 1, b - 1);
int ttt = solve(a, b - 1);
tt = MAX(tt, ttt);
ttt = solve(a + 1, b);
tt = MAX(tt, ttt);
if (col[a] == col[a + 1]) tt = MAX(tt, 1 + solve(a + 2, b));
if (col[b] == col[b - 1]) tt = MAX(tt, 1 + solve(a, b - 2));
for (int i = a + 1; i < b; i++)
{
if (col[i] == col[a]) ttt = 1 + solve(a + 1, i - 1) + solve(i + 1, b);
tt = MAX(tt, ttt);
}
dp[a][b] = tt;
return tt;
}
class PenguinPals
{
public:
int findMaximumMatching(string colors)
{
//if (colors == "RBRBRBRBRBBRBRBRBBRBRBBBRBRBBRBRBRBBRBBBRBBBRBB")return 23;
//if (colors == "BRBRBRBRBRBBRBRBRBRBBRBBBBBRRRRRRBRRBBRBRBR") return 21;
/*
int ans = 0;
int t;
n = colors.size();
t = n;
string str = colors;
while(t--)
{
char rr = str[0];
str = str.substr(1, n - 1) + rr;
int tt = f(str);
ans = MAX(tt, ans);
}
*/
n = colors.size();
col = colors;
solve(0, n- 1);
return dp[0][n-1];
}
};
int main()
{
PenguinPals x;
cout << x.findMaximumMatching("RBRBRBRBRBRBRBRBRBRBRBRRBRBRBRBRBRBRBRB") << endl;
return 0;
}
| true |
9a49beee314f915cf810e3afab1cbcfde78276fe | C++ | pinghaoluo/499-zhihanz-usc-edu | /service/kvstore_client.h | UTF-8 | 3,936 | 2.546875 | 3 | [] | no_license | #ifndef KVSTORE_CLIENT_H_
#define KVSTORE_CLIENT_H_
#include "../kvstore/cchash.h"
#include "../service/service_helper.h"
#include "kvstore.grpc.pb.h"
#include "kvstore.pb.h"
#include "service.pb.h"
#include <grpcpp/grpcpp.h>
#include <iostream>
#include <memory>
#include <string>
#include <vector>
using chirp::Chirp;
using chirp::DeleteReply;
using chirp::DeleteRequest;
using chirp::GetReply;
using chirp::GetRequest;
using chirp::KeyValueStore;
using chirp::PutReply;
using chirp::PutRequest;
using chirp::Timestamp;
using grpc::Channel;
using grpc::ClientContext;
using grpc::Status;
using grpc::StatusCode;
// KeyValue Store Client is used by service layer to communicate with key value
// store database Support Put or Update key value pair Put given key value pair
// API Get Value through key operation tell server whether key value store has
// given key and delete key value pair through given in key value store
// operations
class KeyValueStoreClient {
public:
KeyValueStoreClient(std::shared_ptr<Channel> channel)
: stub_(KeyValueStore::NewStub(channel)) {}
// Requests each key in the vector and displays the key and its corresponding
// value as a pair
void GetValues(const std::vector<std::string> &keys) {
// Context for the client. It could be used to convey extra information to
// the server and/or tweak certain RPC behaviors.
ClientContext context;
auto stream = stub_->get(&context);
for (const auto &key : keys) {
// Key we are sending to the server.
GetRequest request;
request.set_key(key);
stream->Write(request);
// Get the value for the sent key
GetReply response;
stream->Read(&response);
}
stream->WritesDone();
Status status = stream->Finish();
if (!status.ok()) {
std::cout << status.error_code() << ": " << status.error_message()
<< std::endl;
}
}
// Put or Update given key value pair to database
Status PutOrUpdate(const std::string &key, const std::string &value) {
PutRequest request;
request.set_key(key);
request.set_value(value);
PutReply reply;
ClientContext context;
Status status = stub_->put(&context, request, &reply);
return status;
}
// Put the given key value pair to database
// If database has given key return StautusCode:;ALREADY_EXISTS status
Status Put(const std::string &key, const std::string &value) {
if (Has(key).ok()) {
return Status(StatusCode::ALREADY_EXISTS, "key exists");
}
PutRequest request;
request.set_key(key);
request.set_value(value);
PutReply reply;
ClientContext context;
Status status = stub_->put(&context, request, &reply);
return status;
}
// Get the value through key in key value store
std::string GetValue(const std::string &key) {
ClientContext context;
auto stream = stub_->get(&context);
GetRequest request;
request.set_key(key);
stream->Write(request);
// Get the value for the sent key
GetReply response;
stream->Read(&response);
stream->WritesDone();
Status status = stream->Finish();
return response.value();
}
// Return the status shows that whether database has such key
Status Has(const std::string &key) {
ClientContext context;
auto stream = stub_->get(&context);
GetRequest request;
request.set_key(key);
stream->Write(request);
// Get the value for the sent key
GetReply response;
stream->Read(&response);
stream->WritesDone();
Status status = stream->Finish();
return status;
}
// Delete a key value pair in databse through key
Status Delete(const std::string &key) {
DeleteRequest request;
request.set_key(key);
DeleteReply reply;
ClientContext context;
Status status = stub_->deletekey(&context, request, &reply);
return status;
}
private:
std::unique_ptr<KeyValueStore::Stub> stub_;
};
#endif
| true |
2c6a2f3a7936e69c4a682b1027984fd34a762e4a | C++ | ruishaopu561/lc | /design_patterns/chapter28/action.cpp | UTF-8 | 875 | 3.0625 | 3 | [] | no_license | #include "action.h"
#include "person.h"
#include <iostream>
void Success::getManConclusion(Man *man)
{
std::cout << "男人成功时,背后多半有一个伟大的女人。" << std::endl;
}
void Success::getWomanConclusion(Woman *woman)
{
std::cout << "女人成功时,背后大多有一个不成功的男人。" << std::endl;
}
void Failing::getManConclusion(Man *man)
{
std::cout << "男人失败时,闷头喝酒,谁也不用劝。" << std::endl;
}
void Failing::getWomanConclusion(Woman *woman)
{
std::cout << "女人失败时,眼泪汪汪,谁也劝不了。" << std::endl;
}
void Amativeness::getManConclusion(Man *man)
{
std::cout << "男人恋爱时,凡事不懂也要装懂。" << std::endl;
}
void Amativeness::getWomanConclusion(Woman *woman)
{
std::cout << "女人恋爱时,遇事懂也装作不懂。" << std::endl;
} | true |
51759643a246f8ef97ee08b3aa28f40bdad8035c | C++ | dv66/programming_problems_cpp | /2char.cpp | UTF-8 | 817 | 2.8125 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int len(string str){
int i;
for( i = 0; str[i]; i++);
return i;
}
int onlytwo(string str )
{
int ara[150] = {0} , cnt = 0 , i;
for(i=0; str[i] ; i++){
ara[(int)str[i]]++;
}
for(i=95; i<125; i++){
if(ara[i]>0) cnt++;
}
if(cnt>2) return 0;
else return 1;
}
int main()
{
int n , l = 0, i;
string str = "" , temp;
cin >> n;
for(i=0 ; i<n; i++){
cin >> temp;
if(onlytwo(temp)==1){
if(onlytwo(str+temp)==1 ) {
str = str + temp ;
l = len(str);
}
else if(onlytwo(temp)==1 && len(temp) > len(str)){
str = temp;
l = len(temp);
}
}
}
cout << l;
return 0;
}
| true |
70bd84dc901773ddf471952c620a6d0d0dc99fef | C++ | Leon-Cao/CarND-Extended-Kalman-Filter | /src/kalman_filter.cpp | UTF-8 | 2,234 | 2.96875 | 3 | [
"MIT"
] | permissive | #include "kalman_filter.h"
#include <iostream>
using Eigen::MatrixXd;
using Eigen::VectorXd;
using std::cout;
using std::endl;
/*
* Please note that the Eigen library does not initialize
* VectorXd or MatrixXd objects with zeros upon creation.
*/
const double PI = 3.141592653589793238463;
const double EPS = 0.0001;
KalmanFilter::KalmanFilter() {}
KalmanFilter::~KalmanFilter() {}
void KalmanFilter::Init(VectorXd &x_in, MatrixXd &P_in, MatrixXd &F_in,
MatrixXd &H_in, MatrixXd &R_in, MatrixXd &Q_in) {
x_ = x_in;
P_ = P_in;
F_ = F_in;
H_ = H_in;
R_ = R_in;
Q_ = Q_in;
}
void KalmanFilter::Predict() {
/**
* TODO: predict the state, Lession25-section9, Lession22-Section24
*/
x_ = F_ * x_;
/* Lession25- section10, it is a little bit different with lession22-section24, add Q */
MatrixXd Ft = F_.transpose();
P_ = F_ * P_ * Ft + Q_;
}
void KalmanFilter::CommonUpdateForLidarAndRadar(const VectorXd& y) {
MatrixXd Ht = H_.transpose();
MatrixXd S = H_*P_*Ht + R_;
MatrixXd Si = S.inverse();
MatrixXd PHt = P_*Ht;
MatrixXd K = PHt*Si;
//new estimate
x_ = x_ + (K*y);
long x_size = x_.size();
MatrixXd I = MatrixXd::Identity(x_size, x_size);
P_ = (I-K*H_) * P_;
}
void KalmanFilter::Update(const VectorXd &z) {
/**
* TODO: update the state by using Kalman Filter equations
*/
VectorXd y = z - (H_ * x_);
CommonUpdateForLidarAndRadar(y);
}
void KalmanFilter::UpdateEKF(const VectorXd &z) {
/**
* TODO: update the state by using Extended Kalman Filter equations
*/
double px = x_(0);
double py = x_(1);
double vx = x_(2);
double vy = x_(3);
const double rho = sqrt(px*px + py*py);
const double phi = fabs(px) > EPS ? atan2(py, px) : 0.0; // atan2 returns values between -pi and pi
const double rho_dot = fabs(rho) > EPS ? (px*vx + py*vy) / rho : 0.0;
VectorXd z_pred(3);
z_pred << rho, phi, rho_dot;
VectorXd y = z-z_pred;
/* correction for phi in y to be not in the range -pi to pi
* Errored on this place to make RMSE wrong. */
y(1) = y(1)>PI ? y(1)-2*PI
: y(1)<-PI ? y(1)+2*PI
: y(1);
CommonUpdateForLidarAndRadar(y);
}
| true |
f16ee3e24c8c587fcbe275f82dc84521a7e52198 | C++ | enricobu96/second-antlr4-exercise | /tinyrexx/MyListener.cpp | UTF-8 | 3,795 | 2.734375 | 3 | [] | no_license | // Generated from tinyrexx.g4 by ANTLR 4.7
#include <iostream>
#include "MyListener.h"
using namespace std;
MyListener::MyListener(const std::set<std::string> &ids) {
vars = ids;
}
void MyListener::enterProgram(tinyrexxParser::ProgramContext *ctx) {
cout << "#include <iostream>" << endl << endl
<< "using namespace std;" << endl << endl
<< "int main() {" << endl;
indent += 4;
// Dichiara le variabili
for (auto name : vars) {
cout << string(indent, ' ') << "int " << name << " = 0;" << endl;
}
}
void MyListener::exitProgram(tinyrexxParser::ProgramContext *ctx) {
cout << "}" << endl;
}
void MyListener::enterAssign(tinyrexxParser::AssignContext * ctx) {
string name = ctx->ID()->getText();
cout << string(indent, ' ') << name << " = " ;
}
void MyListener::exitAssign(tinyrexxParser::AssignContext * ctx) {
cout << ";" << endl;
}
void MyListener::enterPrint(tinyrexxParser::PrintContext * ctx) {
cout << string(indent, ' ') << "cout << " ;
}
void MyListener::exitPrint(tinyrexxParser::PrintContext * ctx) {
cout << " << endl;" << endl;
}
void MyListener::exitInput(tinyrexxParser::InputContext * ctx) {
string name = ctx->ID()->getText();
cout << string(indent, ' ') << "cin >> " << name << ";" << endl;
}
void MyListener::enterA_expr(tinyrexxParser::A_exprContext * ctx) {
// controllo in quale caso sono
if(ctx->ID() != NULL) {
// caso ID semplice
cout << ctx->ID()->getText();
} else if(ctx->NUMBER() != NULL) {
// caso valore numerico semplice
cout << ctx->NUMBER()->getText();
} else if(ctx->MINUS() != NULL) {
// caso operatore - unario
cout << "-" ;
} else if(ctx->a_op() != NULL) {
// caso operatore binario: gestito da enterA_op
} else {
// caso parentesi
cout << "(" ;
}
}
void MyListener::exitA_expr(tinyrexxParser::A_exprContext * ctx) {
// controllo in quale caso sono
if(ctx->ID() != NULL) {
// caso ID semplice
} else if(ctx->NUMBER() != NULL) {
// caso valore numerico semplice
} else if(ctx->MINUS() != NULL) {
// caso operatore - unario
} else if(ctx->a_op() != NULL) {
// caso operatore binario: gestito da exitA_op
} else {
// caso parentesi
cout << ")" ;
}
}
void MyListener::exitA_op(tinyrexxParser::A_opContext * ctx) {
// controllo operatore aritmetico
if(ctx->PLUS() != NULL) {
cout << " + ";
} else if(ctx->MINUS() != NULL) {
cout << " - ";
} else if(ctx->MUL() != NULL) {
cout << " * ";
} else if(ctx->DIV() != NULL) {
cout << " / ";
}
}
void MyListener::exitR_op(tinyrexxParser::R_opContext * ctx) {
// controllo operatore aritmetico
if(ctx->EQUAL() != NULL) {
cout << " == ";
} else if(ctx->LT() != NULL) {
cout << " < ";
} else if(ctx->LEQ() != NULL) {
cout << " <= ";
} else if(ctx->GT() != NULL) {
cout << " > ";
} else if(ctx->GEQ() != NULL) {
cout << " >= ";
}
}
//implementazione enterTerminate
void MyListener::enterTerminate(tinyrexxParser::TerminateContext * ctx) {
cout << "return ";
}
//implementazione exitTerminate
void MyListener::exitTerminate(tinyrexxParser::TerminateContext * ctx) {
cout << ";";
}
void MyListener::enterW_loop(tinyrexxParser::W_loopContext * ctx){
cout << string(indent, ' ') << "while";
indent += 4;
}
void MyListener::exitW_loop(tinyrexxParser::W_loopContext * ctx){
indent -= 4;
cout << string(indent, ' ') << "}" << endl;
}
void MyListener::enterTest(tinyrexxParser::TestContext * ctx){
cout << "(";
}
void MyListener::exitTest(tinyrexxParser::TestContext * ctx){
cout << ") {" << endl;
}
| true |
2369bb2527a2948f16159c753ab81f69a09ccbb9 | C++ | desinghkar/Object-Search-ROS | /icpr_prob_module/src/test_viewpoint.cpp | UTF-8 | 7,231 | 2.609375 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <math.h>
#include <ros/ros.h>
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#define RANGE 40
#define SCALE 10
using namespace std;
using namespace cv;
class Potential_map
{
ros::NodeHandle nh;
Mat P_map;
Mat Prob1, Prob2, Prob3, Prob4;
float TotalA;
Mat disp_Prob;
public:
Potential_map()
{}
Potential_map(string path)
{
P_map = imread(path);
disp_Prob.create(P_map.rows*10, P_map.cols*10, CV_8UC3);
getTableArea();
create_prob_maps();
show_map("Potential_map");
}
~Potential_map()
{
}
void read_map(string path)
{
P_map = imread(path);
}
void getTableArea()
{
for(int i=0; i<P_map.cols; i++)
for(int j=0; j<P_map.rows; j++)
if(P_map.at<Vec3b>(j, i)[0]==0&&P_map.at<Vec3b>(j, i)[1]==255&&P_map.at<Vec3b>(j, i)[2]==0)
TotalA++;
TotalA = TotalA * 0.05 * 0.05;
}
void show_map(string window_name)
{
namedWindow(window_name, 0);
imshow(window_name, P_map);
waitKey(0);
}
void create_prob_maps()
{
float theta = 0;
initialize(Prob1);
updateVPProb(Prob1, theta, "Prob1.png");
theta = 90;
initialize(Prob2);
updateVPProb(Prob2, theta, "Prob2.png");
theta = 180;
initialize(Prob3);
updateVPProb(Prob3, theta, "Prob3.png");
theta = 270;
initialize(Prob4);
updateVPProb(Prob4, theta, "Prob4.png");
}
void initialize(Mat & Prob)
{
Prob.create(P_map.size(), CV_32F);
for(int i=0; i<P_map.cols; i++)
for(int j=0; j<P_map.rows; j++)
{
if(P_map.at<Vec3b>(i, j)[0]==205 && P_map.at<Vec3b>(i, j)[1]==205 && P_map.at<Vec3b>(i, j)[2]==205)
Prob.at<float>(i, j) = 999; //Grey
else if(P_map.at<Vec3b>(i, j)[0]==0 && P_map.at<Vec3b>(i, j)[1]==255 && P_map.at<Vec3b>(i, j)[2]==0)
Prob.at<float>(i, j) = 555; //Green
else if(P_map.at<Vec3b>(i, j)[0]==0 && P_map.at<Vec3b>(i, j)[1]==0 && P_map.at<Vec3b>(i, j)[2]==0)
Prob.at<float>(i, j) = 888; //Black
else
Prob.at<float>(i, j) = 0; //Otherwise
}
}
void updateVPProb(Mat & Prob, float theta, string path)
{
int kar=0;
for(int i=0; i<Prob.cols; i++)
for(int j=0; j<Prob.rows; j++)
{
// cout<<kar++<<" "<<endl;
if(Prob.at<float>(j, i)!=999 && Prob.at<float>(j, i)!=555 && Prob.at<float>(j, i)!=888)
{
float ViewA = 1.0*PatchTraceAt(i, j, theta)*0.05*0.05;
Prob.at<float>(j, i) = ViewA/TotalA;
// cout<<" [ "<<PatchTraceAt(i, j, theta)<<" ]"<<endl;
}
}
// cout<<Prob<<endl;
disp_Probability(Prob, theta, path);
}
int PatchTraceAt(int x, int y, float theta)
{
// cout<<"In PatchTrace"<<endl;
float min_theta =(theta - 45);
float max_theta =(theta + 45);
int count = 0;
float si = max_theta;
for(float si=min_theta; si<max_theta; si++)
{
int x2 = x + RANGE*cos(si*M_PI/180);
int y2 = y - RANGE*sin(si*M_PI/180);
int x1 = x;
int y1 = y;
count+=rayTrace2D(x1, y1, x2, y2);
}
return count;
}
int rayTrace2D(int x1, int y1, int x2, int y2)
{
// cout<<"In rayTrace2D"<<endl;
double distance = dist(x1, y1, x2, y2);
if(distance>RANGE)
return 0;
int steps = (int)floor(distance)+1;
double x_step = 1.0*(x2-x1)/steps;
double y_step = 1.0*(y2-y1)/steps;
int B, G, R;
int count=0;
double x = x1, y = y1;
int xi1, xi2, yi1, yi2;
int vector = 0;
double dx, dy; //bool temp = false;
while(++vector <=steps)
{
xi1 = (int)x; xi2 = (xi1<P_map.cols - 1)? xi1+1: xi1;
yi1 = (int)y; yi2 = (yi1<P_map.rows - 1)? yi1+1: yi1;
dx = x - xi1; dy = y - yi1;
if(dx < 0.5)
if(dy < 0.5) {
B = P_map.at<Vec3b>(yi1, xi1)[0];
G = P_map.at<Vec3b>(yi1, xi1)[1];
R = P_map.at<Vec3b>(yi1, xi1)[2];
}
else {
B = P_map.at<Vec3b>(yi2, xi1)[0];
G = P_map.at<Vec3b>(yi2, xi1)[1];
R = P_map.at<Vec3b>(yi2, xi1)[2];
}
else
if(dy < 0.5) {
B = P_map.at<Vec3b>(yi1, xi2)[0];
G = P_map.at<Vec3b>(yi1, xi2)[1];
R = P_map.at<Vec3b>(yi1, xi2)[2];
}
else {
B = P_map.at<Vec3b>(yi2, xi2)[0];
G = P_map.at<Vec3b>(yi2, xi2)[1];
R = P_map.at<Vec3b>(yi2, xi2)[2];
}
if(B==0&&G==255&&R==0)
{
count++;
// cout<<"Green "<<count<<endl;
}
else if(B==0&&G==0&&R==0)
return count;
x+= x_step;
y+= y_step;
}
return count;
}
double dist(int a1, int b1, int a2, int b2)
{
double d = 1.0*(a1-a2)*(a1-a2) + 1.0*(b1-b2)*(b1-b2);
return sqrt(d);
}
void show_vector_map(string window_name)
{
}
void disp_Probability(Mat& Prob, float theta, string path)
{
int x, y;
for(int i=0; i<P_map.rows; i++)
for(int j=0; j<P_map.cols; j++)
{
cv::Point P1, P2;
P1.x = i*SCALE; P1.y = j*SCALE;
P2.x = (i+1)*SCALE-1; P2.y = (j+1)*SCALE-1;
int v;
if((Prob.at<float>(j, i)!=999)&&(Prob.at<float>(j, i)!=888)&&Prob.at<float>(j, i)!=555)
{
v = roundup(255*Prob1.at<float>(j, i));
// x = j; y = i;
}
else
v = 255;
rectangle(disp_Prob, P1, P2, cv::Scalar(110, 255-v, 0), -1);
}
/*****************************************************************/
x = P_map.rows/2; y = P_map.cols/2;
float min_theta =(theta - 45);
float max_theta =(theta + 45);
cout<<"min theta is "<<min_theta<<" max theta is "<<max_theta<<endl;
int q = 0;
for(float si=min_theta; si<=max_theta; si++)
{
q++;
int x2 = x + RANGE*cos(si*M_PI/180);
int y2 = y - RANGE*sin(si*M_PI/180);
int x1 = x;
int y1 = y;
//count+=rayTrace2D(x1, y1, x2, y2);
double distance = dist(x1, y1, x2, y2);
//if(distance>RANGE)
// continue;
int steps = (int)floor(distance)+1;
double x_step = 1.0*(x2-x1)/steps;
double y_step = 1.0*(y2-y1)/steps;
int B, G, R;
int count=0;
double x = x1, y = y1;
int xi1, xi2, yi1, yi2;
int vector = 0;
double dx, dy; //bool temp = false;
while(++vector <=steps)
{
xi1 = (int)x; xi2 = (xi1<P_map.cols - 1)? xi1+1: xi1;
yi1 = (int)y; yi2 = (yi1<P_map.rows - 1)? yi1+1: yi1;
dx = x - xi1; dy = y - yi1;
cv::Point P1, P2;
if(dx < 0.5)
if(dy < 0.5) {
P1.y = yi1*SCALE; P1.x = xi1*SCALE;
P2.y = (yi1+1)*SCALE-1; P2.x = (xi1+1)*SCALE-1;
}
else {
P1.y = yi2*SCALE; P1.x = xi1*SCALE;
P2.y = (yi2+1)*SCALE-1; P2.x = (xi1+1)*SCALE-1;
}
else
if(dy < 0.5) {
P1.y = yi1*SCALE; P1.x = xi2*SCALE;
P2.y = (yi1+1)*SCALE-1; P2.x = (xi2+1)*SCALE-1;
}
else {
P1.y = yi2*SCALE; P1.x = xi2*SCALE;
P2.y = (yi2+1)*SCALE-1; P2.x = (xi2+1)*SCALE-1;
}
rectangle(disp_Prob, P1, P2, cv::Scalar(0, 0, 255), -1);
x+= x_step;
y+= y_step;
}
}
cout<<"Q is "<<q<<endl;
namedWindow("Probability", 0);
imshow("Probability", disp_Prob);
waitKey(0);
imwrite(path, disp_Prob);
}
int roundup(double v)
{
int buff = v;
if(v-buff>=0/5)
return buff+1;
else
return buff;
}
};
int main(int argc, char* argv[])
{
Mat potential_map;
if(argc<2)
{
cout<<"Enter the potential map path with the binary"<<endl;
exit(0);
}
ros::init(argc, argv, "probability_update");
Potential_map P(argv[1]);
ros::spin();
}
| true |
5275bf6185c05efafbeb163f10fbafba5261647b | C++ | JeongYeonUk/MemoryManager | /MEMORY MANAGEMENT.h | UTF-8 | 997 | 2.828125 | 3 | [] | no_license | #pragma once
#include <iostream>
#include <windows.h>
using namespace std;
enum MemoryMenu
{
MM_NONE,
MM_ONE,
MM_TWO,
MM_THREE,
MM_EXIT
};
typedef struct _tagMemory
{
int iStart;
int iSize;
}MEMORY;
typedef struct _tagNode
{
MEMORY tMemory;
_tagNode *pPrev;
_tagNode *pNext;
}NODE, *PNODE, *Addr;
typedef struct _tagList
{
PNODE pHead;
PNODE pTail;
int iSeries;
}LIST, *PLIST;
static int InputInt()
{
int iInput;
cin >> iInput;
if (cin.fail())
{
cin.clear();
cin.ignore(1024, '\n');
return INT_MAX;
}
return iInput;
}
static int OutputMenu()
{
system("cls");
cout << "1. SCENARIO ONE(FREE FAIL)" << endl << endl;
cout << "2. SCENARIO TWO(Memory DisContinuous)" << endl << endl;
cout << "3. SCENARIO THREE(BEST-FIT)" << endl << endl;
cout << "4. EXIT" << endl << endl;
cout << "Select Menu : ";
int iInput = InputInt();
if (iInput <= MM_NONE || iInput > MM_EXIT)
return MM_NONE;
return iInput;
}
| true |
48d7e7c6818d500afe0b2fe27a4ce95e44535761 | C++ | pannunzio/Unb-Nightmare | /src/EndState.cpp | UTF-8 | 2,272 | 2.546875 | 3 | [] | no_license | #include "EndState.h"
#define DEBUG
#ifdef DEBUG
//se estiver definido debug, imprime os trecos
#define DEBUG_PRINT(message) do{std::cout << message << std::endl;}while(0);
#define DEBUG_ONLY(x) do{x;}while(0);
#else
//caso contrario, recebe argumentos mas faz nada
#define DEBUG_PRINT(message)
#define DEBUG_ONLY(x) //do{;}while(0)
#endif //DEBUG
EndState::EndState(){;
this->isVictoryScreen = true; // stateData.playerVictory;
this->menu = Menu(500, 350, 50);
this->menu.AddMenuOption("Restart");
this->menu.AddMenuOption("Quit Game");
this->bg.SetFile(BG_FILE);
this->derrota.SetFile("img/derrota.png");
this->derrota.SetFrameCount(12);
this->derrota.SetFrameTime(0.2);
}
EndState::~EndState(){
this->music.Stop();
DEBUG_PRINT("ENDSTATE DESTROYED")
}
void EndState::LoadAssets(){
DEBUG_PRINT("load Assets ENDSTATE ")
this->menu.Load();
if(this->isVictoryScreen){
this->bg.Load("img/cerrado_win.jpg");
this->music.Open("audio/tematerreo_vitoria.ogg");
} else {
this->derrota.Load();
this->bg.Load(BG_FILE);
this->music.Open("audio/tematerreo_desespero.ogg");
}
this->music.Play(-1);
}
void EndState::Update(float dt){
if(!this->isVictoryScreen)
this->derrota.Update(dt);
this->HandleInputs();
this->menu.Update(dt);
if(menu.GetSelection()){
switch(menu.GetSelectedOption()){
case MENU_RESTART:
this->popRequested = true;
Game::GetInstance().Push(new StageState());
break;
case MENU_QUIT:
this->popRequested = true;
this->quitRequested = true;
break;
}
}
}
void EndState::Render(){
this->bg.Render(0,0);
if(!this->isVictoryScreen)
this->derrota.Render(300,300);
this->menu.Render();
// this->option1->Render(0, 0);
// this->option2->Render(0, 0);
}
void EndState::Pause(){
}
void EndState::Resume(){
}
void EndState::HandleInputs(){
if(InputManager::GetInstance().KeyPress(ESCAPE_KEY)){
this->popRequested = true;
this->quitRequested = true;
}
}
#ifdef DEBUG
#undef DEBUG
#endif // DEBUG
| true |
cc2104d328bba73e80ceada7ecaea76f140eaa34 | C++ | jaspersong/Project_CS-4500 | /src/dataframe/copy_writer.cpp | UTF-8 | 1,213 | 2.8125 | 3 | [
"MIT"
] | permissive | /**
* Name: Snowy Chen, Joe Song
* Date: 24 March 2020
* Section: Jason Hemann, MR 11:45-1:25
* Email: chen.xinu@husky.neu.edu, song.jo@husky.neu.edu
*/
// Lang::Cpp
#include "copy_writer.h"
CopyWriter::CopyWriter(DataFrame *source_dataframe) {
assert(source_dataframe != nullptr);
this->source_dataframe = source_dataframe;
this->curr_row = 0;
}
void CopyWriter::visit(Row &r) {
// Go through the columns and copy the data into the row
for (size_t c = 0; c < this->source_dataframe->ncols(); c++) {
// Handle adding to the rows based off of the type of the column
switch (this->source_dataframe->get_schema().col_type(c)) {
case ColumnType_Bool: {
r.set(c, this->source_dataframe->get_bool(c, this->curr_row));
break;
}
case ColumnType_Integer: {
r.set(c, this->source_dataframe->get_int(c, this->curr_row));
break;
}
case ColumnType_Float: {
r.set(c, this->source_dataframe->get_float(c, this->curr_row));
break;
}
case ColumnType_String:
default: {
r.set(c, this->source_dataframe->get_string(c, this->curr_row));
}
}
}
this->curr_row += 1;
}
bool CopyWriter::done() {
return this->curr_row >= this->source_dataframe->nrows();
}
| true |
678836b64b24c03a63586317e2144edc1fdc178b | C++ | Footpad/Cyclometer | /DisplayDistance.cpp | UTF-8 | 1,504 | 2.9375 | 3 | [] | no_license | /*
* DisplayDistance.cpp
*
* Created on: Feb 5, 2013
* Author: dam7633
*/
#include "DisplayDistance.h"
#include "SetCircumference.h"
#include "DisplayTime.h"
#include "NormalOperation.h"
#include "PulseScanner.h"
#include "CyclometerController.h"
#include <math.h>
DisplayDistance::DisplayDistance(StateParent* parent, StateContext* context) :
State(parent, context) {}
void DisplayDistance::accept(Event event) {
if (event == evSetDepressed) {
StateParent* context_parent = ((State*)parent)->getParent();
context_parent->doTransition(new SetCircumference(context_parent, context), NULL);
} else if (event == evModeDepressed) {
parent->doTransition(new DisplayTime(parent, context), NULL);
}
}
DisplayInfo DisplayDistance::getData() {
DisplayInfo info;
// Clear the display.
for (int i = 0; i < NUM_DIGITS; i++) {
info.val[i] = BLANK_DIGIT;
info.dp[i] = false;
}
// Always display the decimal point.
info.dp[1] = true;
// The get the distance number.
double distance = ((CyclometerController*)context)->getPulseScanner()->distance();
// Round the distance to the nearest tenth.
distance = round(distance * 10.0f) / 10.0f;
info.val[0] = lround(distance * 10.0f) % 10; // Tenths
info.val[1] = (int)distance % 10; // Ones
if (distance >= 10) {
info.val[2] = (int)(distance / 10) % 10; // Tens
if (distance >= 100) {
info.val[3] = (int)(distance / 100) % 10; // Hundreds
}
}
return info;
}
| true |
c3408f5f7fec04fbacff006b16508f72819ad589 | C++ | ysdeal/LeetCode | /addBinary.h | UTF-8 | 2,542 | 3.375 | 3 | [] | no_license | /**
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100".
*/
class Solution {
public:
string addBinary(string a, string b) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int n = a.size()-1;
int m = b.size()-1;
string sum="";
char f = '0';
while(n>=0 && m >=0){
if(f=='0'){
if(a[n]=='1' && b[m] =='1'){
f = '1';
sum.insert(sum.begin(),'0');
}else if(a[n]=='1' || b[m] =='1')
sum.insert(sum.begin(),'1');
else
sum.insert(sum.begin(),'0');
}else{
if(a[n]=='1' && b[m] =='1'){
f = '1';
sum.insert(sum.begin(),'1');
}else if(a[n]=='1' || b[m] =='1'){
f = '1';
sum.insert(sum.begin(),'0');
}else{
f = '0';
sum.insert(sum.begin(),'1');
}
}
n--;
m--;
}
while(n>=0){
if(f=='0') sum.insert(sum.begin(),a[n]);
else{
if(a[n]=='1'){
f = '1';
sum.insert(sum.begin(),'0');
}else{
sum.insert(sum.begin(),'1');
f = '0';
}
}
n--;
}
while(m>=0){
if(f=='0') sum.insert(sum.begin(),b[m]);
else{
if(b[m]=='1'){
f = '1';
sum.insert(sum.begin(),'0');
}else{
sum.insert(sum.begin(),'1');
f = '0';
}
}
m--;
}
if(f=='1') sum.insert(sum.begin(),'1');
return sum;
}
};
/* neat solution*/
string addBinary(string a, string b) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
string sum="";
int la=a.length()-1;
int lb=b.length()-1;
int c=0;
while (la >=0 || lb >= 0 ||c >0)
{
int v = c;
if (la >=0) v+=a[la]-'0';
if (lb >=0) v+=b[lb]-'0';
c = v/2;
sum = string(1,('0'+(v&1)))+sum;
la--;
lb--;
}
return sum;
}
| true |
001fa05c6e46024585cacd524da8d82de50f2276 | C++ | qq464418017/bintalk | /runtime/cpp/bintalk/ProtocolReader.cpp | UTF-8 | 2,993 | 2.515625 | 3 | [] | no_license | #include "Config.h"
#include "ProtocolReader.h"
namespace bintalk
{
bool ProtocolReader::readMID(BinaryReader* r, MID& mid)
{
#if BINTALK_BIG_ENDIAN
if(!r->read(&mid, sizeof(MID))) return false;
mid = swapEndian(mid);
return true;
#endif //BINTALK_BIG_ENDIAN
return r->read(&mid, sizeof(MID));
}
#if BINTALK_BIG_ENDIAN
#define BINTALK_PROTOCOLREADER_SINGLE_IMP(T)\
bool ProtocolReader::read##T(BinaryReader* r, T& v, UINT32 maxArray, UINT32 maxValue)\
{if(!r->read(&v, sizeof(T))) return false;\
v = swapEndian<T>(v); return true;\ }
#else //BINTALK_BIG_ENDIAN
#define BINTALK_PROTOCOLREADER_SINGLE_IMP(T)\
bool ProtocolReader::read##T(BinaryReader* r, T& v, UINT32 maxArray, UINT32 maxValue)\
{ return r->read(&v, sizeof(T)); }
#endif //BINTALK_BIG_ENDIAN
#define BINTALK_PROTOCOLREADER_ARRAY_IMP(T)\
bool ProtocolReader::read##T##A(BinaryReader* r, std::vector<T>& v, UINT32 maxArray, UINT32 maxValue)\
{\
UINT32 s;\
if(!readDynSize(r, s) || s > maxArray) return false;\
v.resize(s);\
for(UINT32 i = 0; i < s; i++) if(!read##T(r, v[i], maxArray, maxValue)) return false;\
return true;\
}
#define BINTALK_PROTOCOLREADER_SIMPLE_IMP(T)\
BINTALK_PROTOCOLREADER_SINGLE_IMP(T);\
BINTALK_PROTOCOLREADER_ARRAY_IMP(T);
BINTALK_PROTOCOLREADER_SIMPLE_IMP(INT64);
BINTALK_PROTOCOLREADER_SIMPLE_IMP(UINT64);
BINTALK_PROTOCOLREADER_SIMPLE_IMP(DOUBLE);
BINTALK_PROTOCOLREADER_SIMPLE_IMP(FLOAT);
BINTALK_PROTOCOLREADER_SIMPLE_IMP(INT32);
BINTALK_PROTOCOLREADER_SIMPLE_IMP(UINT32);
BINTALK_PROTOCOLREADER_SIMPLE_IMP(INT16);
BINTALK_PROTOCOLREADER_SIMPLE_IMP(UINT16);
BINTALK_PROTOCOLREADER_SIMPLE_IMP(INT8);
BINTALK_PROTOCOLREADER_SIMPLE_IMP(UINT8);
bool ProtocolReader::readBOOL(BinaryReader* r, BOOL& v, UINT32 maxArray, UINT32 maxValue)
{
UINT8 v1 = v?1:0;
return r->read(&v, sizeof(BOOL));
}
bool ProtocolReader::readBOOLA(BinaryReader* r, std::vector<BOOL>& v, UINT32 maxArray, UINT32 maxValue)
{
UINT32 s;
if(!readDynSize(r, s) || s > maxArray) return false;
v.resize(s);
for(UINT32 i = 0; i < s; i++)
{
BOOL b;
if(!readBOOL(r, b, 0, maxValue))
return false;
v[i] = b;
}
return true;
}
bool ProtocolReader::readSTRING(BinaryReader* r, STRING& v, UINT32 maxArray, UINT32 maxValue)
{
UINT32 len;
if(!readDynSize(r, len) || len > maxValue)
return false;
v.resize(len);
return r->read((void*)v.c_str(), len);
}
BINTALK_PROTOCOLREADER_ARRAY_IMP(STRING);
bool ProtocolReader::readBINARY(BinaryReader* r, BINARY& v, UINT32 maxArray, UINT32 maxValue)
{
UINT32 len;
if(!readDynSize(r, len) || len > maxValue)
return false;
v.resize(len);
if(len > 0)
return r->read((void*)(&(v[0])), len);
return true;
}
BINTALK_PROTOCOLREADER_ARRAY_IMP(BINARY);
bool ProtocolReader::readDynSize(BinaryReader* r, UINT32& s)
{
s = 0;
UINT8 b;
if(!r->read(&b, sizeof(UINT8)))
return false;
size_t n = (b & 0XC0)>>6;
s = (b & 0X3F);
for(size_t i = 0; i < n; i++)
{
if(!r->read(&b, sizeof(UINT8)))
return false;
s = (s<<8)|b;
}
return true;
}
} | true |
9cb1a5af46ff0558e50772e15cf98ad51804af8e | C++ | S391D4002S576/ParFM | /src/utils/SVGViewbox.h | UTF-8 | 1,093 | 2.515625 | 3 | [
"MIT"
] | permissive | #ifndef SSSVGVIEWBOX_H_
#define SSSVGVIEWBOX_H_
#include <vector>
using std::vector;
using std::ios_base;
#include <iostream>
#include <fstream>
using std::ostream;
using std::ofstream;
#include <string>
using std::string;
#include "Point.h"
#include "Color.h"
#include "SVGElement.h"
#include "SVGEElementCollection.h"
#include "SVGELine.h"
#include "SVGECircle.h"
class CSVGEViewBox: public CSVGElement {
public:
CSVGElement* subElement;
int xPct;
int yPct;
int wPct;
int hPct;
int width;
int height;
CSVGEViewBox(CSVGElement* iSubElement, int iXPct, int iYPct, int iWPct, int iHPct, int iWidth, int iHeight)
: subElement(iSubElement), xPct(iXPct), yPct(iYPct), wPct(iWPct), hPct(iHPct), width(iWidth), height(iHeight) {
}
void encode(ostream& os) {
os
<< "<svg x=\"" << xPct
<< "\" y=\"" << yPct
<< "\" width=\"" << wPct
<< "\" height=\"" << hPct
<< "\" viewBox=\"0 0 " << width << " " << height << "\">\n"
<< subElement
<< "</svg>";
}
virtual ~CSVGEViewBox() { delete subElement; };
};
#endif /*SSSVGVIEWBOX_H_*/
| true |
13dc49471248b15551427b8171b10c6ef08a37e9 | C++ | mcyril/barcodes | /core/lib/aztec/src/base/bin_dec_conversion.h | UTF-8 | 2,487 | 3.359375 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | #pragma once
#include <cstddef>
#include <cassert>
#include <climits>
#include <iterator>
#include <algorithm>
template <typename BinIterator, typename DecValue>
void dec2bin(BinIterator bin_first, BinIterator bin_last, DecValue dec)
{
assert(bin_last - bin_first > 0);
for (BinIterator bin_current = bin_first;
bin_current != bin_last; ++bin_current)
{
*bin_current =
typename std::iterator_traits<BinIterator>::value_type(dec & 1);
dec >>= 1;
}
assert(dec == 0 || dec == -1);
using std::reverse;
reverse(bin_first, bin_last);
}
template <typename BinIterator, typename DecIterator>
void dec2bin(BinIterator bin_first, BinIterator bin_last,
DecIterator dec_first, DecIterator dec_last)
{
const typename std::iterator_traits<BinIterator>::difference_type bin_size =
bin_last - bin_first;
const typename std::iterator_traits<DecIterator>::difference_type dec_size =
dec_last - dec_first;
assert(dec_size > 0);
assert(bin_size % dec_size == 0);
const typename std::iterator_traits<BinIterator>::difference_type bits =
bin_size / dec_size;
while (dec_first != dec_last)
{
dec2bin(bin_first, bin_first + bits, *dec_first);
bin_first += bits;
++dec_first;
}
}
template <typename DecValue, typename BinIterator>
void bin2dec(DecValue *dec, BinIterator bin_first, BinIterator bin_last)
{
assert(dec != NULL);
assert(bin_last - bin_first > 0 &&
bin_last - bin_first <= sizeof(DecValue) * CHAR_BIT);
*dec = 0;
while (bin_first != bin_last)
{
assert(*bin_first == 0 || *bin_first == 1);
*dec <<= 1;
if (*bin_first != 0)
*dec |= 1;
++bin_first;
}
}
template <typename DecIterator, typename BinIterator>
void bin2dec(DecIterator dec_first, DecIterator dec_last,
BinIterator bin_first, BinIterator bin_last)
{
const typename std::iterator_traits<BinIterator>::difference_type bin_size =
bin_last - bin_first;
const typename std::iterator_traits<DecIterator>::difference_type dec_size =
dec_last - dec_first;
assert(dec_size > 0);
assert(bin_size % dec_size == 0);
const typename std::iterator_traits<BinIterator>::difference_type bits =
bin_size / dec_size;
while (dec_first != dec_last)
{
bin2dec(&*dec_first, bin_first, bin_first + bits);
bin_first += bits;
++dec_first;
}
}
| true |
9757d49402b8f72c6ed1b6f137f8223ad5aabade | C++ | WizardCarter/OpenGL-Pong | /src/ParticleSystem.cpp | UTF-8 | 2,578 | 2.828125 | 3 | [
"Unlicense"
] | permissive | #include "ParticleSystem.h"
#include <SFML/System.hpp>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <GL/glew.h>
#include "Shader.h"
ParticleSystem::ParticleSystem(glm::vec2 pos, Shader s, unsigned int particleNum, glm::mat4 proj, float lifeT, glm::vec2 ballVel)
{
position = pos; //set up class variables
shader = s;
particles = new Particle[particleNum];
this->proj = proj;
this->particleNum = particleNum;
particleLife = lifeT;
for (int i=0;i<particleNum;i++) { //initialize the particles
resetParticle(i, ballVel);
}
glGenVertexArrays(1, &vao);
glGenBuffers(1, &vbo);
glBindVertexArray(vao);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
float vertices[] = {
0.0, 0.0
};
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, 0);
glBindVertexArray(0);
}
ParticleSystem::~ParticleSystem()
{
glDeleteBuffers(1, &vbo);
glDeleteVertexArrays(1, &vao);
delete particles;
}
void ParticleSystem::resetParticle(int index, glm::vec2 velocity)
{
Particle& p = particles[index];
p.lifetime = particleLife;
p.alpha = 1.0;
p.position = this->position;
p.color = glm::vec3(0.0, 0.0, 1.0);
p.scale = glm::vec2(1.0, 1.0);
p.velocity = -1.0f*velocity;
}
void ParticleSystem::update(float dt, glm::vec2 ballVel)
{
for (int i=0;i<particleNum;i++) {
Particle& p = particles[i];
p.lifetime -= dt;
if (p.lifetime <= 0) {
resetParticle(i, ballVel);
}
p.alpha = p.lifetime/particleLife;
p.position += -1.0f*ballVel*dt;
}
}
void ParticleSystem::render()
{
shader.Use(); //use the shader
shader.SetMatrix4("proj", proj); //set the projection matrix
for (int i=0;i<particleNum;i++) { //for each particle
glm::mat4 model;
model = glm::translate(model, glm::vec3(particles[i].position, 0.0));
model = glm::scale(model, glm::vec3(particles[i].scale, 0.0)); //set its model matrix
shader.SetMatrix4("model", model); //set the particle's alpha and color
shader.SetFloat("alpha", particles[i].alpha);
shader.SetVector3f("color", particles[i].color);
glBindVertexArray(vao); //bind and draw
glDrawArrays(GL_POINTS, 0, 1);
}
glBindVertexArray(0); //unbind at the end
}
| true |
79f1d5e335949a2fa9b570045a3dd749c4a31518 | C++ | SirHall/chess | /src/ai/Test.cpp | UTF-8 | 1,186 | 2.921875 | 3 | [] | no_license | #include "ai/Test.hpp"
#include "Board.hpp"
#include "Piece.hpp"
#include <limits>
#include <utility>
#include <vector>
struct PathResult
{
PieceMove pieceMove;
std::int16_t score;
PathResult(PieceMove m, std::int16_t s) : pieceMove(m), score(s) {}
PathResult() : score(0) {}
};
PathResult GetBestSubpath(Board const &board, Color team, int maxDepth,
int depth = -1)
{
if (depth <= 0)
depth = maxDepth;
PathResult best;
best.score = std::numeric_limits<std::int16_t>::min();
PieceMove currentPieceMove;
board.IteratePossibleTurns(team, [&](Board const &newboard, auto moveMade) {
PathResult res =
(depth <= 1) ? PathResult(moveMade, newboard.TeamScore(team))
: GetBestSubpath(newboard, team, maxDepth, depth - 1);
if (res.score > best.score)
{
best.pieceMove = moveMade;
best.score = res.score;
}
return true;
});
return best;
}
PieceMove ai::Test(Board const &board, Color myColor)
{
auto bestImmediateMove = GetBestSubpath(board, myColor, 4);
return bestImmediateMove.pieceMove;
} | true |
93783fcd41dd789a0f4fa3703d3293609918d0c2 | C++ | kazunetakahashi/atcoder | /201510_201609/1205_code_thanks_2015/F.cpp | UTF-8 | 1,006 | 2.828125 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <cmath>
#include <set>
#include <algorithm>
#include <string>
#include <vector>
#include <stack>
using namespace std;
vector<int> V[100010];
int main() {
int N;
cin >> N;
for (auto i = 0; i < N-1; i++) {
int s, t;
cin >> s >> t;
s--; t--;
V[s].push_back(t);
V[t].push_back(s);
}
vector<int> W;
bool visited[100010];
fill(visited, visited+100010, false);
visited[0] = true;
for (auto root : V[0]) {
stack<int> S;
S.push(root);
int cnt = 0;
while (!S.empty()) {
int now = S.top();
S.pop();
if (!visited[now]) {
visited[now] = true;
cnt++;
for (auto x : V[now]) {
if (!visited[x]) {
S.push(x);
}
}
}
}
W.push_back(cnt);
}
if (W.size() == 1) {
cout << "A" << endl;
} else {
int odd = 0;
for (auto x : W) {
if (x%2 == 1) {
odd++;
}
}
cout << ((odd%2 == 1) ? "A" : "B") << endl;
}
}
| true |
7b52da7293fc90b66342b2c504f5d11989061ea6 | C++ | mxiao6/CS225_Daily-leetcode | /potd-q25/q25.cpp | UTF-8 | 2,245 | 3.859375 | 4 | [] | no_license | #include <iostream>
using namespace std;
struct node{
int val;
node * next;
};
void printList(node * head){
if(head == NULL){
cout << "Empty list" << endl;
return;
}
node * temp = head;
int count = 0;
while(temp != NULL){
cout << "Node " << count << ": " << temp ->val << endl;
count++;
temp = temp->next;
}
}
void insertSorted(node ** head, node * insert){
// if (head == NULL) {
// head = &insert;
// (*head) -> next = NULL;
// return;
// }
node * temp = *head;
if(temp == NULL){
*head = insert;
insert->next = NULL;
return;
}
if(temp->val >= insert->val){ // this node becomes the new head
insert->next = temp;
*head = insert;
}
else{
node * prev = *head;
temp = temp->next;
while(temp != NULL){
if(temp->val >= insert->val){
insert->next = temp;
prev->next = insert;
return;
}
temp = temp->next;
prev = prev->next;
}
// we reached the end of list, this node must go at the end
// prev points to last node, temp points to NULL
prev->next = insert;
insert->next = NULL;
}
}
void sortList(node ** head) {
// if (head == NULL || *head == NULL)
// return;
// cout << "line 56" << endl;
node * newhead = NULL;
node * curr = *head;
node * insert;
// cout << "line 59" << endl;
while(curr != NULL) {
insert = curr;
curr = curr -> next;
insert -> next = NULL;
insertSorted(&newhead, insert);
}
// cout << "line 70" << endl;
*head = newhead;
newhead = NULL;
}
// Write a sortlist method here.
int main(){
node * head = new node();
node * curr = head;
node * prev = head;
for (int i = 3; i > 0; i--) {
prev = curr;
curr -> val = i;
curr -> next = new node();
curr = curr -> next;
}
delete curr;
prev -> next = NULL;
printList(head);
node ** bigHead = &head;
sortList(bigHead);
cout << "line 96" << endl;
printList(*bigHead);
return 0;
}
| true |
9cc13153c8d6bf0b6b351bb6d2c9de345e8d73cc | C++ | Sul123/Demo | /Lisp interpreter/lispp/lispp.cpp | UTF-8 | 1,265 | 2.765625 | 3 | [] | no_license | #include "lispp.h"
#include "scope.h"
#include <iostream>
#include "tokenizer.h"
#include "parser.h"
#include <sstream>
#include <string>
#include "errors.h"
Interpreter::Interpreter() : global_scope_(std::make_shared<Scope>(MakeGlobalScope())) {}
Interpreter::~Interpreter() {
global_scope_->Reset();
}
void Interpreter::Repl() {
std::cout << "Welcome to Lispp interpeter!\n";
while (true) {
try {
ObjectPtr result;
std::cout << "> ";
std::string s;
std::getline(std::cin, s);
std::stringstream ss(s);
Tokenizer tok(&ss);
ObjectPtr expression = Parse(&tok);
result = expression->Evaluate(global_scope_);
if (result->Printable()) {
std::cout << result->Print() << "\n";
}
} catch (const LispError& error) {
std::cout << error.what() << "\n";
}
}
}
std::string Interpreter::Test(const std::string& s) {
std::stringstream ss(s);
Tokenizer tok(&ss);
ObjectPtr expression = Parse(&tok);
ObjectPtr result = expression->Evaluate(global_scope_);
std::string print;
if (result->Printable()) {
print = result->Print();
}
return print;
} | true |
1de1db2d9a60181e698edb7635020f1ecdb37aba | C++ | aws/aws-sdk-cpp | /generated/src/aws-cpp-sdk-ecs/include/aws/ecs/model/ClusterServiceConnectDefaults.h | UTF-8 | 4,912 | 2.578125 | 3 | [
"Apache-2.0",
"MIT",
"JSON"
] | permissive | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/ecs/ECS_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>
namespace Aws
{
namespace Utils
{
namespace Json
{
class JsonValue;
class JsonView;
} // namespace Json
} // namespace Utils
namespace ECS
{
namespace Model
{
/**
* <p>Use this parameter to set a default Service Connect namespace. After you set
* a default Service Connect namespace, any new services with Service Connect
* turned on that are created in the cluster are added as client services in the
* namespace. This setting only applies to new services that set the
* <code>enabled</code> parameter to <code>true</code> in the
* <code>ServiceConnectConfiguration</code>. You can set the namespace of each
* service individually in the <code>ServiceConnectConfiguration</code> to override
* this default parameter.</p> <p>Tasks that run in a namespace can use short names
* to connect to services in the namespace. Tasks can connect to services across
* all of the clusters in the namespace. Tasks connect through a managed proxy
* container that collects logs and metrics for increased visibility. Only the
* tasks that Amazon ECS services create are supported with Service Connect. For
* more information, see <a
* href="https://docs.aws.amazon.com/AmazonECS/latest/developerguide/service-connect.html">Service
* Connect</a> in the <i>Amazon Elastic Container Service Developer
* Guide</i>.</p><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/ecs-2014-11-13/ClusterServiceConnectDefaults">AWS
* API Reference</a></p>
*/
class ClusterServiceConnectDefaults
{
public:
AWS_ECS_API ClusterServiceConnectDefaults();
AWS_ECS_API ClusterServiceConnectDefaults(Aws::Utils::Json::JsonView jsonValue);
AWS_ECS_API ClusterServiceConnectDefaults& operator=(Aws::Utils::Json::JsonView jsonValue);
AWS_ECS_API Aws::Utils::Json::JsonValue Jsonize() const;
/**
* <p>The namespace name or full Amazon Resource Name (ARN) of the Cloud Map
* namespace. When you create a service and don't specify a Service Connect
* configuration, this namespace is used.</p>
*/
inline const Aws::String& GetNamespace() const{ return m_namespace; }
/**
* <p>The namespace name or full Amazon Resource Name (ARN) of the Cloud Map
* namespace. When you create a service and don't specify a Service Connect
* configuration, this namespace is used.</p>
*/
inline bool NamespaceHasBeenSet() const { return m_namespaceHasBeenSet; }
/**
* <p>The namespace name or full Amazon Resource Name (ARN) of the Cloud Map
* namespace. When you create a service and don't specify a Service Connect
* configuration, this namespace is used.</p>
*/
inline void SetNamespace(const Aws::String& value) { m_namespaceHasBeenSet = true; m_namespace = value; }
/**
* <p>The namespace name or full Amazon Resource Name (ARN) of the Cloud Map
* namespace. When you create a service and don't specify a Service Connect
* configuration, this namespace is used.</p>
*/
inline void SetNamespace(Aws::String&& value) { m_namespaceHasBeenSet = true; m_namespace = std::move(value); }
/**
* <p>The namespace name or full Amazon Resource Name (ARN) of the Cloud Map
* namespace. When you create a service and don't specify a Service Connect
* configuration, this namespace is used.</p>
*/
inline void SetNamespace(const char* value) { m_namespaceHasBeenSet = true; m_namespace.assign(value); }
/**
* <p>The namespace name or full Amazon Resource Name (ARN) of the Cloud Map
* namespace. When you create a service and don't specify a Service Connect
* configuration, this namespace is used.</p>
*/
inline ClusterServiceConnectDefaults& WithNamespace(const Aws::String& value) { SetNamespace(value); return *this;}
/**
* <p>The namespace name or full Amazon Resource Name (ARN) of the Cloud Map
* namespace. When you create a service and don't specify a Service Connect
* configuration, this namespace is used.</p>
*/
inline ClusterServiceConnectDefaults& WithNamespace(Aws::String&& value) { SetNamespace(std::move(value)); return *this;}
/**
* <p>The namespace name or full Amazon Resource Name (ARN) of the Cloud Map
* namespace. When you create a service and don't specify a Service Connect
* configuration, this namespace is used.</p>
*/
inline ClusterServiceConnectDefaults& WithNamespace(const char* value) { SetNamespace(value); return *this;}
private:
Aws::String m_namespace;
bool m_namespaceHasBeenSet = false;
};
} // namespace Model
} // namespace ECS
} // namespace Aws
| true |
7ad1b041eed633047244e38be192344a0b2d47f9 | C++ | nguyenvanson1998/Cmpsc-Casino-Game | /Craps.h | UTF-8 | 688 | 3.09375 | 3 | [] | no_license | //Craps.h - header class for craps minigame (dice)
//Written by Emma Roudabush
#pragma once
#include "Game.h"
#include "Dice.h"
#include <iostream>
using namespace std;
class Craps : public Game
{
public:
//default constructor which calls its superclass
Craps(const Money& playerMoney): Game(playerMoney) {}
//function to play the game
int Play();
//function to display an ASCII craps board
void DisplayBoard();
//function to proceed with play if player chooses to do a Pass line Bet
void PassLineBet();
//function to proceed with play if player chooses to do a Pass line Bet
void DontPassBet();
private:
int CurrentPoint; //for betting
Dice PairOfDice; //for the gameplay
}; | true |
76ce669848d646c8ff8f4312b924a01b72ef3652 | C++ | bayu-baskara/SpaceDefender-GLUT | /SpaceDefender/Player.h | UTF-8 | 985 | 3.078125 | 3 | [] | no_license | #ifndef PLAYER_H_INCLUDED
#define PLAYER_H_INCLUDED
#include <utility>
#include "Enemy.h"
using namespace std;
/*
* Player game object.
* Can move horizontally and fire charges.
* Can be destroyed by an enemy.
*/
class Player {
public:
Player( double playerXPos, double playerYPos, double playerLength, double playerMaxSpeed, pair<double, double>* matrixSize );
double getXPos();
double getYPos();
double getLength();
double getHeight();
double getMaxSpeed();
double getSpeed();
unsigned int getScore();
void setXPos( double playerXPos, pair<double, double>* matrixSize );
void setSpeed( double playerSpeed );
void setScore( unsigned int playerScore );
bool isCollidingWith( Enemy* enemy );
private:
double xPos; // triangle centre
double yPos; // triangle centre
double length; // of triangle
double height; // of triangle
double maxSpeed;
double speed;
unsigned int score;
};
#endif // PLAYER_H_INCLUDED
| true |
949849a24bbe84ca0e2fcced92ccb09cfcb9524a | C++ | SirRodriguez/AreaAbsorberGame | /lib/shapes/derivedShapes/Square.h | UTF-8 | 974 | 3.015625 | 3 | [] | no_license | #ifndef SQUARE_H
#define SQUARE_H
#include "../Shape.h"
class Square: public Shape{
protected:
int length;
public:
Square(olc::PixelGameEngine& pge, AnimationContainer& ac, olc::vi2d& pos, int _speed, const olc::Pixel& _color, int newLength)
: Shape(pge, ac, pos, _speed, _color), length(newLength){}
virtual void draw() override {
pixelGameEngine->FillRectDecal(getTopLeftPoint(), olc::vi2d(length, length), color);
}
// Moving ---
virtual void move() = 0;
// Lengths ---
void setLength(int l){ length = l; }
void addLength(int l){ length += l; }
int getLength(){ return length; }
// Points ---
olc::vi2d getTopLeftPoint(){ return position + olc::vi2d(-length / 2, -length / 2); }
olc::vi2d getTopRightPoint(){ return position + olc::vi2d(length / 2, -length / 2); }
olc::vi2d getBotLeftPoint(){ return position + olc::vi2d(-length / 2, length / 2); }
olc::vi2d getBotRightPoint(){ return position + olc::vi2d(length / 2, length / 2); }
};
#endif | true |
ad1d0f4af4feb9b0af62301c99992a3999c40248 | C++ | NikolenkoMaria/Checker01 | /Board.h | UTF-8 | 364 | 2.65625 | 3 | [] | no_license | #pragma once
#ifndef BOARD_H
#define BOARD_H
class Figure;
class Board
{
public:
Board(int size = 8);
~Board();
Board(const Board& other);
Board& operator=(const Board& other);
char** ToCharArray();
int GetSize() { return m_Size; }
protected:
private:
int m_Size;
Figure*** m_Board;
};
#endif | true |
cf523ad5aa24f5886ffe9e60d83ff9aeba2c39aa | C++ | arnaudduval/TTman | /src/Circuit.cpp | UTF-8 | 986 | 2.796875 | 3 | [] | no_license | #include <Circuit.h>
#include <string>
#include <fstream>
#include <stdexcept>
Point::Point(const GPSPoint& c, const double& e)
{
alt = e;
coords = c;
}
Circuit::Circuit(const GPXFile& f)
{
for(auto itrack = f.tracks.begin() ; itrack != f.tracks.end() ; ++itrack)
{
for(auto isegment = (*itrack).trksegs.begin() ; isegment != (*itrack).trksegs.end() ; ++isegment)
{
for(auto ipoint = (*isegment).trkpts.begin() ; ipoint != (*isegment).trkpts.end() ; ++ipoint)
{
push_back(Point((*ipoint).coords, (*ipoint).elevation));
}
}
}
}
Circuit ReadCircuit(std::string const &fileName)
{
std::ifstream ifs(fileName);
if(ifs.good())
{
Circuit _circuit;
double _lat, _lon, _alt;
while (!ifs.eof())
{
ifs >> _lat >> _lon >> _alt;
_circuit.push_back(Point{GPSPoint{_lat, _lon}, _alt});
}
return _circuit;
}
else
{
throw std::runtime_error("failed to open file: " + fileName);
}
}
| true |
5e4c7b9efccaee591713826c58a54cea1903ad60 | C++ | yuliangl/Algorithm-sets | /剑指Offer题解/offer12/main.cpp | UTF-8 | 3,507 | 3.828125 | 4 | [] | no_license | /******剑指 Offer 12. 矩阵中的路径******
请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。
路径可以从矩阵中的任意一格开始,每一步可以在矩阵中向左、右、上、下移动一格。
如果一条路径经过了矩阵的某一格,那么该路径不能再次进入该格子。
例如,在下面的3×4的矩阵中包含一条字符串“bfce”的路径(路径中的字母用加粗标出)。
[["a","b","c","e"],
["s","f","c","s"],
["a","d","e","e"]]
但矩阵中不包含字符串“abfb”的路径,
因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,
路径不能再次进入这个格子。
********/
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
bool findpath(const vector<vector<char>>& board, const string& word, vector<bool>& visited, size_t row, size_t column, string::iterator& itr)
{
if (itr == word.end()) //到达字符末尾,匹配成功
return true;
if (row < 0 || row >= board.size() || column < 0 || column >= board[0].size()) //如果坐标不在矩阵范围内
return false; //返回false
bool haspath = false; //标记子节点是否含有下一个字符
int columns = board[0].size(); //矩阵的列数
//cout << row << " " << column << " " << *itr << endl; //大家可以使用cout来查看每一步访问节点的位置,便于理解
if (!visited[row * columns + column] && board[row][column] == *itr) //当前位置未被访问,且当前位置可以和字符串匹配上
{
++itr; //迭代器后移一个字符
visited[row * columns + column] = true; //标记为以访问,防止该节点的子节点再将该节点加入其子节点
haspath = findpath(board, word, visited, row, column - 1, itr) //左边是否有路径
|| findpath(board, word, visited, row, column + 1, itr) //右边是否有路径
|| findpath(board, word, visited, row - 1, column, itr) //上边是否有路径
|| findpath(board, word, visited, row + 1, column, itr); //下边是否有路径
if (!haspath) //如果子节点没有路径,则说明从当前节点不可能找到路径,回溯
{
--itr; //迭代器回退
visited[row * columns + column] = false; //将该节点标记为未访问,方便其他节点再进行访问
}
}
return haspath; //返回结果
}
bool exist(vector<vector<char>>& board, string& word)
{
if (!word.size()) //所给的word为空
return true;
//获得矩阵的行列数
unsigned int rows = board.size(), columns = board[0].size();
for (size_t i = 0; i < rows; ++i)
for (size_t j = 0; j < columns; ++j)
{
if (board[i][j] == word[0]) //找到可行节点位置
{
auto itr = word.begin();
vector<bool> visited(rows * columns, false); //标记节点是否被访问
if (findpath(board, word, visited, i, j, itr)) //从该节点出发寻找到了路径
return true;
}
}
return false; //所有可能的路径都找了也没到找,返回false
}
};
int main()
{
return 0;
}
| true |
89ef97e2a7093ac1e19d1e9f640e3f11993bdfb1 | C++ | saifpathan/cpp-programs | /src/8_constructors/7_marks.cpp | UTF-8 | 1,407 | 3.5625 | 4 | [] | no_license | #include<stdio.h>
#include<string.h>
class marks
{
int rollno;
char name[20];
double percentage;
int total;
int rank;
public:
marks()
{
this->rollno = 10;
strcpy(this->name, "not given");
this->percentage = 80.2;
this->total = 410;
this->rank = 5;
}
marks(int r, char* nm, double p, int t, int rn)
{
this->rollno = r;
strcpy(this->name, nm);
this->percentage = p;
this->total = t;
this->rank = rn;
}
void setRollno(int r)
{
this->rollno = r;
}
void setName(char* nm)
{
strcpy(this->name, nm);
}
void setTotal(int t)
{
this->total = t;
}
void setPercentage(double p)
{
this->percentage = p;
}
void setRank(int rn)
{
this->rank = rn;
}
int getRollno()
{
return this->rollno;
}
char* getName()
{
return this->name;
}
double getPercentage()
{
return this->percentage;
}
int getTotal()
{
return this->total;
}
int getRank()
{
return this->rank;
}
void display()
{
printf("\nMarks details=(using display())");
printf("\nRoll no. is=%d", this->rollno);
printf("\nName is=%s", this->name);
printf("\nTotal marks obtained=%d", this->total);
printf("\nPercentage=%lf", this->percentage);
printf("\nRank=%d", this->rank);
printf("\n\n");
}
};
int main()
{
marks m1;
m1.display();
m1.setRollno(18);
m1.setName("Saif");
m1.setTotal(450);
m1.setPercentage(90);
m1.setRank(1);
m1.display();
printf("\n\n");
} | true |
1500236b8d472df2081f21aeb0a0f636f1105b5b | C++ | nicyun/DirectedMST | /src/main.cpp | UTF-8 | 523 | 2.609375 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <vector>
#include "Network.hpp"
using namespace std;
int main(int args, char * argv[])
{
int n, m;
if(args < 2){
cout << "USAGE: " << argv[0] << " " << "test_file" << endl;
return 1;
}
ifstream fin(argv[1]);
while(fin >> n >> m){
Network network(n);
while(m--){
int x, y;
double dist;
fin >> x >> y >> dist;
network.addEdge(x, y, dist);
}
cout << network.simulateDistribution(0) << endl;
cout << network.zhuliu(0) << endl;
}
return 0;
}
| true |
c3c27c498a9f6ec0f4c3c3fecd2086d30f0c2d34 | C++ | cha63506/chromium-44 | /chrome/browser/prerender/prerender_manager.h | UTF-8 | 2,841 | 2.515625 | 3 | [
"BSD-3-Clause"
] | permissive | // Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_PRERENDER_PRERENDER_MANAGER_H_
#define CHROME_BROWSER_PRERENDER_PRERENDER_MANAGER_H_
#pragma once
#include <list>
#include "base/non_thread_safe.h"
#include "base/scoped_ptr.h"
#include "base/time.h"
#include "googleurl/src/gurl.h"
class PrerenderContents;
class Profile;
class TabContents;
// PrerenderManager is responsible for initiating and keeping prerendered
// views of webpages.
class PrerenderManager : NonThreadSafe {
public:
// Owned by a Profile object for the lifetime of the profile.
explicit PrerenderManager(Profile* profile);
virtual ~PrerenderManager();
// Preloads the URL supplied.
void AddPreload(const GURL& url);
// For a given TabContents that wants to navigate to the URL supplied,
// determines whether a preloaded version of the URL can be used,
// and substitutes the prerendered RVH into the TabContents. Returns
// whether or not a prerendered RVH could be used or not.
bool MaybeUsePreloadedPage(TabContents* tc, const GURL& url);
// Allows PrerenderContents to remove itself when prerendering should
// be cancelled. Also deletes the entry.
void RemoveEntry(PrerenderContents* entry);
// Retrieves the PrerenderContents object for the specified URL, if it
// has been prerendered. The caller will then have ownership of the
// PrerenderContents object and is responsible for freeing it.
// Returns NULL if the specified URL has not been prerendered.
PrerenderContents* GetEntry(const GURL& url);
base::TimeDelta max_prerender_age() const { return max_prerender_age_; }
void set_max_prerender_age(base::TimeDelta td) { max_prerender_age_ = td; }
unsigned int max_elements() const { return max_elements_; }
void set_max_elements(unsigned int num) { max_elements_ = num; }
protected:
// The following methods exist explicitly rather than just inlined to
// facilitate testing.
virtual base::Time GetCurrentTime() const;
virtual PrerenderContents* CreatePrerenderContents(const GURL& url);
private:
struct PrerenderContentsData;
bool IsPrerenderElementFresh(const base::Time start) const;
void DeleteOldEntries();
Profile* profile_;
base::TimeDelta max_prerender_age_;
unsigned int max_elements_;
// List of prerendered elements.
std::list<PrerenderContentsData> prerender_list_;
// Default maximum permitted elements to prerender.
static const unsigned int kDefaultMaxPrerenderElements = 1;
// Default maximum age a prerendered element may have, in seconds.
static const int kDefaultMaxPrerenderAgeSeconds = 20;
DISALLOW_COPY_AND_ASSIGN(PrerenderManager);
};
#endif // CHROME_BROWSER_PRERENDER_PRERENDER_MANAGER_H_
| true |
3d1de07acaf8081fc7974bd5f622811f8bc17331 | C++ | ninag09/test | /lorder.cpp | UTF-8 | 634 | 3.296875 | 3 | [] | no_license | #include "common.h"
using namespace std;
int height(treenode* root){
if(!root) return 0;
return (1+max(height(root->left), height(root->right)));
}
void printLevel(treenode* root, int l){
if(!root) return;
if(l == 1) cout << root->val << endl;
printLevel(root->left, l-1);
printLevel(root->right, l-1);
}
int main(){
treenode* root = new treenode(3);
root->left = new treenode(1);
root->left->right = new treenode(2);
root->right = new treenode(4);
root->right->right = new treenode(5);
int h = height(root);
for(int i=1; i<=h; i++)
printLevel(root,i);
return 0;
}
| true |
5892d75f361c99faa880855bcd1594e23952a6f4 | C++ | busebd12/InterviewPreparation | /LeetCode/C++/General/Medium/RangeAddition/solution.cpp | UTF-8 | 3,266 | 3.671875 | 4 | [
"MIT"
] | permissive | #include <string>
#include <unordered_map>
#include <vector>
using namespace std;
/*
Solution 1: Brute force.
Time complexity: O(u * L) [where u is the number of updates and L is the average length of an update interval]
Space complexity: O(1)
*/
class Solution
{
public:
vector<int> getModifiedArray(int length, vector<vector<int>> & updates)
{
vector<int> result(length, 0);
for(auto & update : updates)
{
int start=update[0];
int end=update[1];
int increment=update[2];
for(int index=start;index<=end;index++)
{
result[index]+=increment;
}
}
return result;
}
};
/*
Solution 2: see comments.
Time complexity: O(n + u) [where n is the number of updates and u is the number of unique update intervals]
Space complexity: O(u)
*/
class Solution
{
public:
vector<int> getModifiedArray(int length, vector<vector<int>> & updates)
{
vector<int> result(length, 0);
//<key, value> map where the key is a string composed of the start and end values for each update interval separated by a -
//and the value is the total increment value. Since unordered_map doesn't allow duplicate keys, all update intervals that
//are the same will be represented by one key
unordered_map<string, int> intervalToIncrement;
//Iterate through the intervals
for(auto & update : updates)
{
int intervalStart=update[0];
int intervalEnd=update[1];
int increment=update[2];
//Create the key
string key=to_string(intervalStart) + "-" + to_string(intervalEnd);
//If the hashtable doesn't have the key yet, map the key to the increment value
if(intervalToIncrement.find(key)==end(intervalToIncrement))
{
intervalToIncrement[key]=increment;
}
//Else, the hashtable does have the key so just add to the already existing increment value
else
{
intervalToIncrement[key]+=increment;
}
}
//Iterate through the hashtable
for(auto & [key, increment] : intervalToIncrement)
{
auto dashIndex=key.find('-');
//Parse out the start index of the intervl
int start=stoi(key.substr(0, dashIndex));
//Prase out the end index of the interval
int end=stoi(key.substr(dashIndex + 1, string::npos));
//Loop over the interval and apply the increment to the indices
for(int index=start;index<=end;index++)
{
result[index]+=increment;
}
}
return result;
}
}; | true |
fcd8eecc8efd3af4e9c5fb08c0420fb38b53c0d8 | C++ | killvxk/rc | /src/rc/core/num/mod.h | UTF-8 | 827 | 2.9375 | 3 | [] | no_license | #pragma once
#include "rc/core/intrin.h"
namespace rc::num {
template <class T>
constexpr auto max_value() -> T {
static_assert(rc::is_integeral<T>());
if constexpr (rc::is_unsigned<T>()) {
return ~T(0);
}
if constexpr (rc::is_signed<T>()) {
return ~T(1 << (8 * sizeof(T) - 1));
}
}
template <class T>
constexpr auto abs(T val) -> T {
return val < 0 ? T(-val) : val;
}
template <class T>
auto one_less_than_next_power_of_two(T val) -> T {
static_assert(rc::is_unsigned<T>());
if (val <= 1) {
return 0;
}
const auto cnt = intrin::ctlz(val - 1);
const auto ret = num::max_value<T>() >> cnt;
return T(ret);
}
template <class T>
auto next_power_of_two(T val) -> T {
static_assert(rc::is_unsigned<T>());
return num::one_less_than_next_power_of_two(val) + 1;
}
} // namespace rc::num
| true |
3f9b4e390570135537ac52ed70bf65cc59fd626f | C++ | bluepine/topcoder | /topcoder-master/TheFansAndMeetingsDivTwo.cpp | UTF-8 | 1,072 | 2.6875 | 3 | [] | no_license | #include<iostream>
#include<cstdio>
#include<cctype>
#include<cmath>
#include<cstdlib>
#include<algorithm>
#include<vector>
#include<string>
#include<list>
#include<deque>
#include<map>
#include<set>
#include<queue>
#include<stack>
#include<utility>
#include<sstream>
#include<cstring>
using namespace std;
class TheFansAndMeetingsDivTwo {
public:
double find(vector <int> minJ, vector <int> maxJ, vector <int> minB, vector <int> maxB) {
double a, b, result = 0.0;
int size = minJ.size();
for (int r = 1; r <= 50; ++r) {
a = b = 0.0;
for (int i = 0; i < size; ++i) {
if (minJ[i] <= r && maxJ[i] >= r) {
a += (1/(double)size) * (1/(double)(maxJ[i]-minJ[i]+1));
}
if (minB[i] <= r && maxB[i] >= r) {
b += (1/(double)size) * (1/(double)(maxB[i]-minB[i]+1));
}
}
result += a * b;
}
return result;
}
};
| true |
baf1dcca914c6020edd43cb91d76ee5a2b6acdaf | C++ | lythro/ProjectHeartbeat | /ProjectHeartbeat.ino | UTF-8 | 2,881 | 2.828125 | 3 | [] | no_license | #include "EffectManager.h"
#include <SPI.h>
// max len of incoming message
#define INCOMING_MAX_LEN 100
// global message buffer
char incoming[INCOMING_MAX_LEN];
int cnt = 0;
EffectManager effectManager;
int numLEDs;
// timer
HardwareTimer timer(1);
// incoming data flag to pause led updates!
volatile bool receiving;
void setup() {
receiving = false;
numLEDs = effectManager.getNumLEDs();
// init serial connection (bluetooth)
Serial3.begin(9600);
// init SPI for LED-strip
SPI.beginTransaction(SPISettings(10000000, MSBFIRST, SPI_MODE0));
// setup timer interrupt for periodic LED update
timer.pause();
//timer.setPeriod( 10000 ); // 10 ms --> 100 Hz
// currently setting only one led per period
// --> at 120 LEDs: ~83 microseconds per LED for 100 Hz
timer.setPeriod( 100 );
//
timer.setChannelMode( TIMER_CH1, TIMER_OUTPUT_COMPARE );
timer.setCompare( TIMER_CH1, 1 );
timer.attachInterrupt( 1, handler_led );
timer.refresh();
timer.resume();
}
// full msg
void loop() {
int unread = Serial3.available();
if (unread > 0) {
receiving = true;
timer.pause();
while(true) {
char c = Serial3.read();
if (c == '\n') {
incoming[cnt] = '\0';
cnt = 0;
processMessage();
timer.resume();
receiving = false;
break;
} else {
incoming[cnt++] = c;
if (cnt >= INCOMING_MAX_LEN - 1) {
cnt = INCOMING_MAX_LEN - 1;
}
}
while (Serial3.available() == 0) {} // wait for data
}// end while
}
}
// apply given configuration
void processMessage() {
// TODO
//Serial3.print( "I got this: " );
//Serial3.print( incoming );
effectManager.setConfig( incoming );
}
// update one LED per ISR
// plus a bit of counting to be done
// should be fast enough to notice transmissions between two LEDs!
void handler_led() {
static byte currentLED = 0;
if (currentLED == 0) {
// send start frame
SPI.transfer( 0 );
SPI.transfer( 0 );
SPI.transfer( 0 );
SPI.transfer( 0 );
}
byte r, g, b;
effectManager.getRGB( currentLED, &r, &g, &b );
SPI.transfer( 0xff );
SPI.transfer( b );
SPI.transfer( g );
SPI.transfer( r );
currentLED++;
if (currentLED >= numLEDs) {
currentLED = 0;
effectManager.nextStep();
}
}
/* // all LEDs updated in ONE ISR!
// THIS TAKES LONG, dropped UART bytes!
void handler_led() {
if (receiving) return;
byte numLEDs = effectManager.getNumLEDs();
effectManager.nextStep();
// start frame
SPI.transfer( 0 );
SPI.transfer( 0 );
SPI.transfer( 0 );
SPI.transfer( 0 );
byte r, g, b;
for (int i = 0; i < numLEDs; i++) {
effectManager.getRGB( i, &r, &g, &b );
SPI.transfer( 0xff ); // full brightness (global)
SPI.transfer( b );
SPI.transfer( g );
SPI.transfer( r );
}
//SPI.endTransaction();
}
*/
| true |
0773a3649a87eccf454f3d727a0631faa2a51649 | C++ | Vulkan4D/v4d_core | /utilities/graphics/vulkan/ImageObject.cpp | UTF-8 | 10,316 | 2.515625 | 3 | [] | no_license | #include "ImageObject.h"
namespace v4d::graphics::vulkan {
COMMON_OBJECT_CPP(ImageObject, VkImage)
ImageObject::ImageObject(VkImageUsageFlags usage, uint32_t mipLevels, uint32_t arrayLayers, const std::vector<VkFormat>& preferredFormats, VkImageViewType viewType)
: usage(usage),
mipLevels(mipLevels),
arrayLayers(arrayLayers),
preferredFormats(preferredFormats)
{
imageInfo.mipLevels = mipLevels;
imageInfo.arrayLayers = arrayLayers;
imageInfo.usage = usage;
viewInfo.subresourceRange.levelCount = mipLevels;
viewInfo.subresourceRange.layerCount = arrayLayers;
viewInfo.viewType = viewType;
}
ImageObject::~ImageObject() {}
void ImageObject::Create(Device* device) {
if (this->device == nullptr) {
this->device = device;
imageInfo.extent.width = width;
imageInfo.extent.height = height;
// Map usage to features
if (usage & VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT) formatFeatures |= VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT;
if (usage & VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) formatFeatures |= VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT;
if (usage & VK_IMAGE_USAGE_SAMPLED_BIT) formatFeatures |= VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT;
if (usage & VK_IMAGE_USAGE_STORAGE_BIT) formatFeatures |= VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT;
if (usage & VK_IMAGE_USAGE_TRANSFER_DST_BIT) formatFeatures |= VK_FORMAT_FEATURE_TRANSFER_DST_BIT;
if (usage & VK_IMAGE_USAGE_TRANSFER_SRC_BIT) formatFeatures |= VK_FORMAT_FEATURE_TRANSFER_SRC_BIT;
format = device->GetPhysicalDevice()->FindSupportedFormat(preferredFormats, imageInfo.tiling, (VkFormatFeatureFlagBits)formatFeatures);
imageInfo.format = format;
viewInfo.format = format;
if (viewInfo.viewType == VK_IMAGE_VIEW_TYPE_CUBE) imageInfo.flags |= VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT;
if (sharedAccessQueues.size() > 2 || (sharedAccessQueues.size() == 2 && sharedAccessQueues[0] != sharedAccessQueues[1])) {
imageInfo.queueFamilyIndexCount = sharedAccessQueues.size();
imageInfo.pQueueFamilyIndices = sharedAccessQueues.data();
imageInfo.sharingMode = VK_SHARING_MODE_CONCURRENT;
} else {
imageInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
}
device->CreateAndAllocateImage(imageInfo, memoryUsage, obj, &allocation);
if (format == VK_FORMAT_D32_SFLOAT) {
viewInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
}
if (format == VK_FORMAT_D32_SFLOAT_S8_UINT) {
viewInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT;
}
viewInfo.image = obj;
if (device->CreateImageView(&viewInfo, nullptr, &view) != VK_SUCCESS)
throw std::runtime_error("Failed to create image view");
if (usage & VK_IMAGE_USAGE_SAMPLED_BIT) {
if (device->CreateSampler(&samplerInfo, nullptr, &sampler) != VK_SUCCESS)
throw std::runtime_error("Failed to create sampler");
}
}
}
void ImageObject::Destroy() {
if (device) {
if (sampler != VK_NULL_HANDLE) {
device->DestroySampler(sampler, nullptr);
sampler = VK_NULL_HANDLE;
}
if (view != VK_NULL_HANDLE) {
device->DestroyImageView(view, nullptr);
view = VK_NULL_HANDLE;
}
if (VkImage(obj) != VK_NULL_HANDLE) {
device->FreeAndDestroyImage(obj, allocation);
}
device = nullptr;
width = 0;
height = 0;
}
}
void ImageObject::TransitionLayout(VkCommandBuffer commandBuffer, VkImageLayout oldLayout, VkImageLayout newLayout) {
assert(device);
VkImageAspectFlags aspectMask = 0;
if (format == VK_FORMAT_D32_SFLOAT) aspectMask |= VK_IMAGE_ASPECT_DEPTH_BIT;
if (format == VK_FORMAT_D32_SFLOAT_S8_UINT) aspectMask |= VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT;
if (!aspectMask && (usage & VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT)) aspectMask |= VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT;
TransitionImageLayout(device, commandBuffer, obj, oldLayout, newLayout, mipLevels, arrayLayers, aspectMask);
}
void ImageObject::TransitionImageLayout(Device* device, VkCommandBuffer commandBuffer, VkImage image, VkImageLayout oldLayout, VkImageLayout newLayout, uint32_t mipLevels, uint32_t layerCount, VkImageAspectFlags aspectMask) {
VkImageMemoryBarrier barrier = {};
barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
barrier.oldLayout = oldLayout; // VK_IMAGE_LAYOUT_UNDEFINED if we dont care about existing contents of the image
barrier.newLayout = newLayout;
// If we are using the barrier to transfer queue family ownership, these two fields should be the indices of the queue families. Otherwise VK_QUEUE_FAMILY_IGNORED
barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
//
barrier.image = image;
barrier.subresourceRange.baseMipLevel = 0;
barrier.subresourceRange.levelCount = mipLevels;
barrier.subresourceRange.baseArrayLayer = 0;
barrier.subresourceRange.layerCount = layerCount;
barrier.srcAccessMask = 0;
barrier.dstAccessMask = 0;
//
if (aspectMask) {
barrier.subresourceRange.aspectMask = aspectMask;
} else {
if (newLayout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL) {
barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT;
} else {
barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
}
}
//
VkPipelineStageFlags srcStage = VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, dstStage = VK_PIPELINE_STAGE_ALL_COMMANDS_BIT;
// Source layouts (old)
// Source access mask controls actions that have to be finished on the old layout
// before it will be transitioned to the new layout
switch (oldLayout) {
case VK_IMAGE_LAYOUT_UNDEFINED:
// Image layout is undefined (or does not matter)
// Only valid as initial layout
// No flags required, listed only for completeness
barrier.srcAccessMask = 0;
break;
case VK_IMAGE_LAYOUT_PREINITIALIZED:
// Image is preinitialized
// Only valid as initial layout for linear images, preserves memory contents
// Make sure host writes have been finished
barrier.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT;
break;
case VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL:
// Image is a color attachment
// Make sure any writes to the color buffer have been finished
barrier.srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
break;
case VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL:
// Image is a depth/stencil attachment
// Make sure any writes to the depth/stencil buffer have been finished
barrier.srcAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
break;
case VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL:
// Image is a transfer source
// Make sure any reads from the image have been finished
barrier.srcAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
break;
case VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL:
// Image is a transfer destination
// Make sure any writes to the image have been finished
barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
break;
case VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL:
// Image is read by a shader
// Make sure any shader reads from the image have been finished
barrier.srcAccessMask = VK_ACCESS_SHADER_READ_BIT;
break;
default:
// Other source layouts aren't handled (yet)
break;
}
// Target layouts (new)
// Destination access mask controls the dependency for the new image layout
switch (newLayout) {
case VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL:
// Image will be used as a transfer destination
// Make sure any writes to the image have been finished
barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
break;
case VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL:
// Image will be used as a transfer source
// Make sure any reads from the image have been finished
barrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
break;
case VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL:
// Image will be used as a color attachment
// Make sure any writes to the color buffer have been finished
barrier.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
break;
case VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL:
// Image layout will be used as a depth/stencil attachment
// Make sure any writes to depth/stencil buffer have been finished
barrier.dstAccessMask = barrier.dstAccessMask | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
break;
case VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL:
// Image will be read in a shader (sampler, input attachment)
// Make sure any writes to the image have been finished
if (barrier.srcAccessMask == 0)
{
barrier.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT;
}
barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
break;
default:
// Other source layouts aren't handled (yet)
break;
}
/*
Transfer writes must occur in the pipeline transfer stage.
Since the writes dont have to wait on anything, we mayy specify an empty access mask and the earliest possible pipeline stage VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT for the pre-barrier operations.
It should be noted that VK_PIPELINE_STAGE_TRANSFER_BIT is not a Real stage within the graphics and compute pipelines.
It is more of a pseudo-stage where transfers happen.
The image will be written in the same pipeline stage and subsequently read by the fragment shader, which is why we specify shader reading access in the fragment pipeline stage.
If we need to do more transitions in the future, then we'll extend the function.
One thing to note is that command buffer submission results in implicit VK_ACCESS_HOST_WRITE_BIT synchronization at the beginning.
Since the TransitionImageLayout function executes a command buffer with only a single command, we could use this implicit synchronization and set srcAccessMask to 0 if we ever needed a VK_ACCESS_HOST_WRITE_BIT dependency in a layout transition.
There is actually a special type of image layout that supports all operations, VK_IMAGE_LAYOUT_GENERAL.
The problem with it is that it doesnt necessarily offer the best performance for any operation.
It is required for some special cases, like using an image as both input and output, or for reading an image after it has left the preinitialized layout.
*/
//
device->CmdPipelineBarrier(
commandBuffer,
srcStage, dstStage,
0,
0, nullptr,
0, nullptr,
1, &barrier
);
}
}
| true |
020ee5573de000a74598ae6c462e377e9bba849a | C++ | geekanamika/Interview-Prep-DS-Algo | /arrays/c++/findMissingAndRepeating.cpp | UTF-8 | 1,921 | 3.984375 | 4 | [] | no_license | /*
Time Complexity: O(n)
Auxiliary Space: O(n)
Find Missing And Repeating
Given an unsorted array of size N of positive integers.
One number 'A' from set {1, 2, …N} is missing and
one number 'B' occurs twice in array. Find these two numbers.
Note: If you find multiple answers then
print the Smallest number found. Also, expected solution is O(n) time
and constant extra space.
Input:
The first line of input contains an integer T denoting
the number of test cases. The description of T test cases follows.
The first line of each test case contains a single integer N
denoting he size of array. The second line contains N space-separated
integers A1, A2, ..., AN denoting the elements of the array.
Output:
Print B, the repeating number followed by A which is missing
in a single line.
Constraints:
1 ≤ T ≤ 100
1 ≤ N ≤ 106
1 ≤ A[i] ≤ N
Example:
Input:
2
2
2 2
3
1 3 3
Output:
2 1
3 2
Explanation:
Testcase 1: Repeating number is 2 and smallest positive missing number is 1.
Testcase 2: Repeating number is 3 and smallest positive missing number is 2.
*/
#include<iostream>
#include<algorithm>
using namespace std;
void printMissingRepeating(vector<long> arr, long n) {
long i;
long a = -1, b = -1;
// create an array count of size n+1
vector<long> count(n+1, 0);
// count occurence of all elements
for(i=0; i<n; i++) {
count[arr[i]]++;
}
for(i=1; i<=n; i++) {
//cout<<count[i]<<" ";
if(count[i] == 2) {
a = i;
}
if(count[i]==0)
b = i;
}
//cout<<endl;
cout<<a<<" "<<b<<endl;
}
int main() {
int t, temp;
long n;
cin>>t;
while(t--) {
cin>>n;
vector<long> arr;
for(int i=0; i<n; i++) {
cin>>temp;
arr.push_back(temp);
}
printMissingRepeating(arr, n);
}
return 0;
} | true |
4a4cdf7d057113abe06b502eaa92303ee0082920 | C++ | LiyliLee/PracticaRVR | /rvr-release1.0/prediction/prediction.cc | UTF-8 | 11,615 | 2.6875 | 3 | [
"MIT"
] | permissive | #include <memory>
#include <iostream>
#include <mutex>
#include <condition_variable>
#include <cstdint>
#include <thread>
#include <tuple>
#include <map>
#include <chrono>
#include <string>
#include <unistd.h>
#include "XLDisplay.h"
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
// Interpolación en el jugador 2
bool interpolation = false;
// Predicción en el jugador 1
bool prediction = false;
// Tick interno de simulación
#define SIM_TICK 35
// define la frecuencia de actualizaciones que envía el servidor
#define UPDATE_FREQ 5
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
enum input_t : uint8_t { none = 0, left = 1, right = 2};
using state_t = std::tuple<uint32_t, input_t>;
using state_buffer_t = std::map<uint32_t, state_t>;
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
class InputThread
{
public:
void input()
{
XLDisplay& dpy = XLDisplay::display();
while(true)
{
char k = dpy.wait_key();
imutex.lock();
switch (k)
{
case 'a':
key = input_t::left;
ready = true;
break;
case 'd':
key = input_t::right;
ready = true;
break;
default:
break;
}
imutex.unlock();
}
}
bool read_input(input_t &i)
{
std::unique_lock<std::mutex> lock(imutex);
bool r = ready;
i = key;
ready = false;
return r;
}
private:
std::mutex imutex;
std::condition_variable icv;
input_t key;
bool ready = false;
};
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
class Network
{
public:
enum host_t { p1 = 0, p2 = 1, server = 2 };
Network(uint32_t _lat1, uint32_t _lat2, uint32_t tick_time)
{
lat1 = _lat1 / tick_time;
lat2 = _lat2 / tick_time;
}
void send_message(uint32_t t, host_t from, host_t to, state_t s_pair)
{
if ( from == host_t::p1 || to == host_t::p1 )
{
t = t + lat1;
}
else if ( from == host_t::p2 || to == host_t::p2 )
{
t = t + lat2;
}
switch (to)
{
case host_t::p1:
p1_in.insert(std::pair<uint32_t, state_t>(t, s_pair));
break;
case host_t::p2:
p2_in.insert(std::pair<uint32_t, state_t>(t, s_pair));
break;
case host_t::server:
server_in.insert(std::pair<uint32_t, state_t>(t, s_pair));
break;
}
}
bool recv_message(uint32_t& t, host_t h, state_t& s)
{
state_buffer_t * sb;
uint32_t lat;
switch (h)
{
case host_t::p1:
sb = &p1_in;
lat = lat1;
break;
case host_t::p2:
sb = &p2_in;
lat = lat2;
break;
case host_t::server:
sb = &server_in;
lat = 0;
break;
}
auto msg_it = sb->find(t);
if ( msg_it == sb->end() )
{
return false;
}
t -= lat;
s = msg_it->second;
return true;
}
private:
uint32_t lat1;
uint32_t lat2;
state_buffer_t p1_in;
state_buffer_t p2_in;
state_buffer_t server_in;
};
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
class Player
{
public:
Player(uint32_t tick_ini, uint32_t x_ini, uint32_t _y, XLDisplay::XLColor _c)
:y(_y), c(_c)
{
insert_state(tick_ini, x_ini);
};
void insert_state(uint32_t tick, uint32_t x, input_t i = input_t::none)
{
state_t s_pair(x, i);
states.insert(std::pair<uint32_t, state_t>(tick, s_pair));
};
void render(uint32_t tick)
{
XLDisplay& dpy = XLDisplay::display();
uint32_t x;
auto s_it = states.find(tick);
if ( s_it == states.end() )
{
auto last = states.rbegin();
x = std::get<0>(last->second);
}
else
{
x = std::get<0>(s_it->second);
}
dpy.set_color(c);
dpy.rectangle(x, y, 45, 45, true);
}
void move(uint32_t tick, input_t k)
{
auto s_it = states.find(tick - 1);
uint32_t x = std::get<0>(s_it->second);
switch(k)
{
case input_t::left:
x -= 5;
break;
case input_t::right:
x += 5;
break;
case input_t::none:
break;
}
insert_state(tick, x, k);
}
state_t get_state(uint32_t tick)
{
auto s_it = states.find(tick);
return s_it->second;
}
void interpolate(uint32_t ini, uint32_t fin, state_t msg)
{
state_t ini_state = get_state(ini);
int32_t x_ini = (int32_t) std::get<0>(ini_state);
int32_t x_fin = (int32_t) std::get<0>(msg);
int32_t steps = fin - ini;
int32_t delta = x_fin - x_ini;
int32_t inc = delta /steps;
uint32_t x = std::get<0>(ini_state) + inc;
for (uint32_t t=ini+1 ; t <= fin; t++, x+=inc)
{
insert_state(t, x, input_t::none);
}
}
private:
uint32_t y;
XLDisplay::XLColor c;
state_buffer_t states;
};
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
class Simulation
{
public:
Simulation(uint32_t p1_lat, uint32_t p2_lat):
tick(1),
net(p1_lat, p2_lat, SIM_TICK),
server(0, 100, 111, XLDisplay::BROWN),
p1(0, 100, 45, XLDisplay::GREEN),
p2(0, 100, 177, XLDisplay::RED)
{
// Desplaza el tick en el jugador 2 para poder usar el mismo tick
p2_tick_delta = (p2_lat / SIM_TICK) + UPDATE_FREQ;
ithread.reset(new std::thread([&](){it.input();}));
}
void server_step()
{
static uint32_t send = 0;
state_t msg;
input_t p1_input = input_t::none;
if ( net.recv_message(tick, Network::server, msg) )
{
p1_input = std::get<1>(msg);
}
server.move(tick, p1_input);
if ( send == UPDATE_FREQ )
{
send = 0;
state_t current = server.get_state(tick);
net.send_message(tick, Network::server, Network::p1, current);
net.send_message(tick, Network::server, Network::p2, current);
}
send++;
}
void player_one_step()
{
input_t p1_key;
bool kr = it.read_input(p1_key);
if (kr)
{
state_t istate(0, p1_key);
net.send_message(tick, Network::p1, Network::server, istate);
}
else
{
p1_key = input_t::none;
}
/* --------------------------- */
/* Prediction */
/* --------------------------- */
if (prediction)
{
p1.move(tick, p1_key);
}
uint32_t msg_tick = tick;
state_t msg;
if ( net.recv_message(msg_tick, Network::p1, msg) )
{
if (prediction)
{
state_t past_state = p1.get_state(msg_tick);
if ( std::get<0>(past_state) != std::get<1>(msg) )
{
/* --------------------------- */
/* Correction */
/* --------------------------- */
}
}
else
{
p1.insert_state(tick, std::get<0>(msg));
}
}
}
void player_two_step()
{
static uint32_t last_prev_tick = 0;
static uint32_t last_tick = 0;
uint32_t msg_tick = tick;
state_t msg;
if ( net.recv_message(msg_tick, Network::p2, msg) )
{
if (interpolation)
{
/* --------------------------- */
/* Interpolation */
/* --------------------------- */
last_prev_tick = last_tick;
last_tick = msg_tick;
p2.interpolate(last_prev_tick, last_tick, msg);
}
else
{
p2.insert_state(tick, std::get<0>(msg));
}
}
}
void loop()
{
while(true)
{
player_one_step();
server_step();
player_two_step();
render();
std::this_thread::sleep_for(std::chrono::milliseconds(SIM_TICK));
tick++;
}
}
void render()
{
XLDisplay& dpy = XLDisplay::display();
dpy.clear();
dpy.set_color(XLDisplay::BLACK);
dpy.text(10,95, "Jugador 1");
dpy.line(0,101,500,101);
dpy.text(10, 161, "Servidor");
dpy.line(0,167,500,167);
dpy.text(10, 230, "Jugador 2");
server.render(tick);
p1.render(tick);
if ( interpolation )
{
if ( tick < p2_tick_delta )
{
p2.render(0);
}
else
{
p2.render(tick - p2_tick_delta);
}
}
else
{
p2.render(tick);
}
dpy.flush();
}
private:
uint32_t tick;
uint32_t p2_tick_delta;
Network net;
InputThread it;
Player server;
Player p1;
Player p2;
std::unique_ptr<std::thread> ithread;
};
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int main(int argc, char **argv)
{
int c;
std::string lat1_s;
std::string lat2_s;
XLDisplay::init(100, 200, "RVR Modulo 3");
while ((c = getopt(argc, argv, "1:2:pih")) != -1)
{
switch (c)
{
case 'p':
prediction = true;
break;
case 'i':
interpolation = true;
break;
case '1':
lat1_s = optarg;
break;
case '2':
lat2_s = optarg;
break;
case '?':
case 'h':
std::cerr << "Uso prediccion -1 <latencia jug1> -2 <latencia jug2> -p -i\n";
return -1;
}
}
std::cout << "P1 Latencia: " << lat1_s << std::endl;
std::cout << "P2 Latencia: " << lat2_s << std::endl;
std::cout << "Interpolación: " << interpolation << std::endl;
std::cout << "Predicción: " << prediction << std::endl;
Simulation sim(std::stoi(lat1_s), std::stoi(lat2_s));
sim.loop();
return 0;
};
| true |
3d58901202d162ce97a3c023933d619bf434ad1c | C++ | a-kashirin-official/spbspu-labs-2018 | /shalgueva.sofiya/common/circle.cpp | UTF-8 | 1,021 | 3.359375 | 3 | [] | no_license | #include "circle.hpp"
#define _USE_MATH_DEFINES
#include <cmath>
#include <iostream>
shalgueva::Circle::Circle(const point_t & pos, const double radius) :
position_(pos),
radius_(radius),
angle_(0.0)
{
if (radius_ < 0.0)
{
throw std::invalid_argument("Error. Invalid radius");
}
}
double shalgueva::Circle::getArea() const noexcept
{
return M_PI * radius_ * radius_;
}
shalgueva::rectangle_t shalgueva::Circle::getFrameRect() const noexcept
{
return {radius_ * 2, radius_ * 2, position_};
}
void shalgueva::Circle::move(double dx, double dy) noexcept
{
position_.x += dx;
position_.y += dy;
}
void shalgueva::Circle::move(const point_t & posTo) noexcept
{
position_ = posTo;
}
void shalgueva::Circle::scale(double coefficient)
{
if (coefficient < 0.0)
{
throw std::invalid_argument("Error. Invalid parameter of scaling");
}
radius_ *= coefficient;
}
void shalgueva::Circle::rotate(double alpha) noexcept
{
angle_ += alpha;
if (angle_ > 360.0)
{
angle_ -= 360;
}
}
| true |
4eff563ac0ecbe8bf05000e21a6c11b3ee31267c | C++ | lukedoucet92/Art | /SVGCanvas.cpp | UTF-8 | 994 | 2.796875 | 3 | [
"MIT"
] | permissive | //
// SVGCanvas.cpp
// Art
//
// Created by Luke Doucet on 4/4/17.
// Copyright © 2017 Luke Doucet. All rights reserved.
//
#include "SVGCanvas.h"
SVGCanvas::SVGCanvas() {
this->objects = vector<SVGObject*>();
this->size = Size();
}
SVGCanvas::SVGCanvas(Size size) {
this->objects = vector<SVGObject*>();
this->size = size;
}
SVGCanvas::~SVGCanvas() {
objects.clear();
}
string SVGCanvas::getSvg() {
string svg = "<svg width=\"" + to_string(roundf(size.width)) + "\" height=\"" + to_string(roundf(size.height)) + "\">\n";
for (vector<SVGObject*>::iterator it = objects.begin() ; it != objects.end(); ++it) {
svg += (*it)->getSvg();
}
svg += SVG_CLOSE_TAG;
return svg;
}
Size SVGCanvas::getSize() {
return this->size;
}
Point SVGCanvas::getMidPoint() {
return Point(size.width/2, size.height/2);
}
Point SVGCanvas::getMinPoint() {
return Point(0, 0);
}
Point SVGCanvas::getMaxPoint() {
return Point(size.width, size.height);
}
| true |
40d859797aee7aad9e19a765ab983cfaf24421f0 | C++ | spondiirty/junhong_utils | /std_utils.h | UTF-8 | 3,639 | 2.578125 | 3 | [] | no_license | #ifndef __STD_UTILS_H__
#define __STD_UTILS_H__
#include <string>
#include <vector>
#include <iostream>
#include <fstream>
#include <limits>
#include <unordered_map>
#include <unordered_set>
#include <cstdlib>
#include <cstdio>
#include <algorithm>
#include <cctype>
#define umap unordered_map;
#define uset unordered_set;
#define SYS_PAUSE() system("PAUSE");
#define CNT_LOOP(num,i) for(i=0;i<num;++i)
#define CNT_2D_LOOP(m,n,i,j) for(i=0;i<m;++i)for(j=0;j<n;++j)
#define ITER_LOOP(container, iter) for((iter)=(container).begin();(iter)!=(container).end();(iter)++)
#define iCNT_LOOP(num,i) for(int i=0;i<num;++i)
#define iCNT_2D_LOOP(m,n,i,j) for(int i=0;i<m;++i)for(int j=0;j<n;++j)
#define iITER_LOOP(container, iter) for(auto iter=(container).begin();iter!=(container).end();iter++)
#define DISP(statement) std::cout<<statement<<endl
#define TRACE(var) std::cout<<#var<<" = "<<var<<endl
#define TRACE2(var1, var2) std::cout<<#var1<<" = "<<var1<<" , "<<#var2<<" = "<<var2<<endl
#define UT_SWAP(a,b,t) ((t) = (a), (a) = (b), (b) = (t))
#ifndef MIN
# define MIN(a,b) ((a) > (b) ? (b) : (a))
#endif
#ifndef MAX
# define MAX(a,b) ((a) < (b) ? (b) : (a))
#endif
#ifndef TMIN
# define TMIN(a,b) a = ((a) > (b) ? (b) : (a))
#endif
#ifndef TMAX
# define TMAX(a,b) a = ((a) < (b) ? (b) : (a))
#endif
#define CONDITION_TMAX(max_v, v, condition) if(condition) TMAX(max_v, v)
#define CONDITION_TMIN(min_v, v, condition) if(condition) TMIN(min_v, v)
#define DO_ON_MAX(max_v, v, expression) if(v > max_v) { max_v = v; expression;}
#define DO_ON_MIN(min_v, v, expression) if(v > min_v) { min_v = v; expression;}
#ifndef ABS
#define ABS(a) ((a) < 0 ? (a)*(-1) : (a))
#endif
#ifndef ABS_DIFF
# define ABS_DIFF(a,b) (MAX(a,b)-MIN(a,b))
#endif
inline std::unordered_map<std::string, std::string> utFileParts(const std::string& file_name)
{
using namespace std;
std::unordered_map<std::string, std::string> ret;
std::string temp = file_name.substr(0, file_name.find_last_of("/\\")+1);
ret["path"] = temp;
temp = file_name.substr(file_name.find_last_of("/\\")+1, file_name.find_last_of(".") - file_name.find_last_of("/\\") - 1);
ret["nake"] = temp;
temp = file_name.substr(file_name.find_last_of("."));
ret["ext"] = temp;
ret["fullfile"] = ret["nake"] + ret["ext"];
return ret;
}
inline bool utFileExist(const std::string& filename)
{
std::fstream file;
file.open(filename,std::ios::in);
if(!file)
{
return false;
}
else
{
file.close();
return true;
}
}
std::vector<std::string> utFile2Strings(std::string filename);
std::string utFile2String(std::string filename);
template<typename T>
inline T max_v() {
return (std::numeric_limits<T>::max)();
}
template<typename T>
inline T min_v() {
return (std::numeric_limits<T>::min)();
}
#define MIN_VALUE(type) min_v<type>()
#define MAX_VALUE(type) max_v<type>()
inline void utString2File(std::string filename, std::string content)
{
FILE* fp = fopen(filename.c_str(), "wt");
fprintf(fp, "%s", content.c_str());
fclose(fp);
}
template<typename T>
inline T utRetainPrecision(T float_num, int precision = 6)
{
if (typeid(T) != typeid(float) && typeid(T) != typeid(double)) return float_num;
float tens = 1.0f; bool sig = precision >= 0;
while(precision--) tens *= 10;
if(!sig) tens = 1.0 / tens;
return round(float_num * tens) / tens;
}
inline void toLower(std::string & str) {
std::transform(str.begin(), str.end(), str.begin(), std::tolower);
}
inline void toUpper(std::string & str) {
std::transform(str.begin(), str.end(), str.begin(), std::toupper);
}
#endif
| true |