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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
c2937617fda8bef6c00a5ba59c353b34c66f91e8 | C++ | VeggieOrz/Algorithm-Practice | /leetcode/lwh/Daily_1006 笨阶乘.cpp | UTF-8 | 1,443 | 3.921875 | 4 | [] | no_license | /*
* 题目:1006. 笨阶乘
* 链接:https://leetcode-cn.com/problems/clumsy-factorial/
* 知识点:栈、数学
*/
class Solution {
public:
int clumsy(int N) {
vector<int> nums(1, N);
int i = 0;
while (--N) {
switch(i%4) {
// 符号*
case 0:
nums.back() *= N;
break;
// 符号/
case 1:
nums.back() /= N;
break;
// 符号+
case 2:
nums.push_back(N);
break;
// 符号-
case 3:
nums.push_back(-N);
break;
}
i++;
}
int ans = 0;
for (auto num : nums) {
ans += num;
}
return ans;
}
// 数学方法
// 题解链接:https://leetcode-cn.com/problems/clumsy-factorial/solution/ben-jie-cheng-by-leetcode-solution-deh2/
int clumsy_(int N) {
if (N == 1) {
return 1;
} else if (N == 2) {
return 2;
} else if (N == 3) {
return 6;
} else if (N == 4) {
return 7;
}
if (N % 4 == 0) {
return N + 1;
} else if (N % 4 <= 2) {
return N + 2;
} else {
return N - 1;
}
}
};
| true |
ead9b68c271efa5b6bed049dbd4667971a7f807a | C++ | jaronwakley/Prime-Numbers | /prime_compressor.cpp | UTF-8 | 2,878 | 3.046875 | 3 | [] | no_license | //This program takes the files generated by prime_generator and compresses the contents down to files of 1,000,000 primes keeping only every 1,000th .
#include <fstream>
#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>
#include <stdio.h>
using namespace std;
int main()
{
string *prime_list;
prime_list = new string[4000000];
ifstream file("info.txt");
string *info;
info = new string[2];
if(file.is_open())
{
for(int i = 0; i < 2; ++i)
{
file >> info[i];
}
}
file.close();
string past_prime = info[0];
double p = atof(past_prime.c_str());
int past_file_number = atoi(info[1].c_str());
delete[] info;
int first_file_number = (p / 100000000) + 1;
cout << "Start = ";
cout << first_file_number << endl;
cout << "Which file would you like to end on?" << endl;
int last_file_number;
cin >> last_file_number;
string input_name = to_string(first_file_number) + ".txt";
input_name = "b" + input_name;
ifstream input(input_name);
if(input.is_open())
{
for(int i = 0; i < 4000000; ++i)
{
input >> prime_list[i];
}
}
input.close();
int index = 0;
int start = 0;
while(index < 4000000 && prime_list[index] != "")
{
if(past_prime == prime_list[index])
{
start = index;
}
index++;
}
index--;
int next = start + 1000;
int new_file_number = past_file_number + 1;
ofstream output;
string file_name = to_string(new_file_number) + ".txt";
file_name = "primes" + file_name;
output.open(file_name);
stringstream ss;
int counter = 0;
string prime_to_save = "";
while(first_file_number < last_file_number)
{
while(next <= index)
{
ss << prime_list[next] + " ";
counter++;
if(counter == 1000)
{
prime_to_save = prime_list[next];
counter = 0;
output << ss.str();
output.close();
new_file_number++;
file_name = to_string(new_file_number) + ".txt";
file_name = "primes" + file_name;
output.open(file_name);
ss.str(string());//Clears the contents of the string stream.
}
next = next + 1000;
}
next = (next - index) - 1;
cout << "new next " << next << endl;
first_file_number++;
if(first_file_number < last_file_number)
{
remove(input_name.c_str());
}
input_name = to_string(first_file_number) + ".txt";
input_name = "b" + input_name;
ifstream input(input_name);
int l = 0;
while(l < 4000000)
{
prime_list[l] = "";
l++;
}
if(input.is_open())
{
for(int i = 0; i < 4000000; ++i)
{
input >> prime_list[i];
}
}
input.close();
index = 0;
while(index < 4000000 && prime_list[index] != "")
{
index++;
}
index--;
}
ofstream out;
out.open("info.txt");
out << prime_to_save << " " << new_file_number - 1;
out.close();
delete[] prime_list;
return 0;
} | true |
af04c7045db453d22b52169eb8f22c81dadc4172 | C++ | CarlHernaez15/Experiment3 | /Experiment3/Exp3.2.cpp | UTF-8 | 826 | 3.15625 | 3 | [] | no_license | #include <iostream>
#include <conio.h>
using namespace std;
int main()
{
int provinceA[7];
int provinceB[7];
int provinceC[7];
int j = 1;
for(int i =0; i<7; i++)
{
cout <<"Province A, Day " << i+1 <<": ";
cin >> provinceA[i];
}
for(int i =0; i<7; i++)
{
cout <<"Province B, Day " << i+1 <<": ";
cin >> provinceB[i];
}
for(int i =0; i<7; i++)
{
cout <<"Province C, Day " << i+1 <<": ";
cin >> provinceC[i];
}
cout<< "Displaying Values: ";
for(int i=0; i<7; i++)
{
cout<<"Province A, Day = " << j + 1 << provinceA[i]<< endl;
}
for(int i=0; i<7; i++)
{
cout<<"Province B, Day = " << j + 1 << provinceB[i]<< endl;
}
for(int i=0; i<7; i++)
{
cout<<"Province C, Day = " << j + 1 << provinceC[i]<< endl;
}
_getch();
return 0;
}
| true |
6265a27dd7663cc32bce8960726e5c370708601f | C++ | azlove2021/c- | /14. 可删除的点.cpp | GB18030 | 672 | 2.796875 | 3 | [] | no_license | #include<iostream>
using namespace std;
#include<string>
#include<vector>
int main()
{
int n;
cin >> n;
// int H = n;
// int* x = new int[n];
int L = 0, R = 0;
long x, temp;
while ( n--)
{
cin >> x >> temp;
if (x < 0)
L++;
else
{
R++;
}
}
if (L == 1 || R == 1||L==0||R==0)
cout << "Yes";
else
{
cout << "No";
}
return 0;
//cout << L << "" << R;
//߽ Ե㶼ͬһҲԣ
}
/*
*/
| true |
2fe2e11e74e072e8e38c57e8bf26b75fe380b466 | C++ | huafei1137/Autobraid | /include/data-structures/Lattice.hpp | UTF-8 | 816 | 3.078125 | 3 | [] | no_license | #ifndef LATTICE_HPP
#define LATTICE_HPP
#include "Gate.hpp"
#include "Point.hpp"
#include <vector>
// represents grid of cells and how logical qubits are arranged in that grid
class Lattice {
public:
// assigns a default mapping (identity map)
Lattice(int length);
// sets a logical to physical qubit mapping
void setMapping(std::vector<int> mp);
int latticeLength() const { return length; }
Cell getLatticePosition(int logQubit) const; // convert 1d -> 2d coordinate
int getPhysQubitNumber(const Cell& c) const; // convert 2d -> 1d coordinate
int getArea(const Gate& g) const;
bool checkOverlap(const Gate& g1, const Gate& g2) const;
void swapLogicalQubit(int log1, int log2); // alter log->phys mapping
private:
int length;
std::vector<int> log2phys;
};
#endif | true |
393c79354007d2d18111e4b8ee5cc96ea88dc505 | C++ | cursedtoxi/hurby-1 | /Eye.cpp | UTF-8 | 9,083 | 2.984375 | 3 | [] | no_license | /*************************************************************************************
This file is the implementation file of the Eye class
*************************************************************************************/
#include "Eye.h"
// callback for unassigned handlers (two void* args)
static void NULL_CALLBACK_2(void *scope, void *args){}
/** Eye Constructor ******************************************************************/
Eye::Eye(uint8_t id, SPI * spi_port, DigitalOut *cs_pin, DigitalOut *cd_pin, DigitalOut *rst_pin,DigitalOut *bl_pin){
// delete image references
for(uint8_t i =0 ; i < 5; i++){
this->img[i] = 0;
}
// setup default data
this->activeImg = 0;
this->blinkStep = 0.01; //10ms
this->blinkDelay = 2; // 2seconds
this->moveDelay = 0.05; //50ms
this->blinkStat = 0;
this->type = id;
this->targetPosition = MOVE_CC;
this->OnBlinkEnd = NULL_CALLBACK_2;
this->blinkCaller = 0;
this->OnMoveEnd = NULL_CALLBACK_2;
this->moveCaller = 0;
// set position at center
this->left = (LCDDriver::X_SIZE/2) - (IMAGE_X_SIZE/2);
this->top = (LCDDriver::Y_SIZE/2) - (IMAGE_Y_SIZE/2);
// initializes driver
this->lcd = new LCDDriver(spi_port, cs_pin, cd_pin, rst_pin, bl_pin);
}
/** Eye Destructor ******************************************************************/
Eye::~Eye(void){
// destroy allocated objects
if(this->lcd){
delete(this->lcd);
}
}
/** Load eye with an image and open it ***********************************************/
void Eye::Load(BITMAP_FLASH *imgs[], void (*OnBlinkCallback)(void*, void*), void* blinkScope, void (*OnMoveCallback)(void*, void*), void *moveScope){
// installa event handlers
this->OnBlinkEnd = (OnBlinkCallback)? OnBlinkCallback : NULL_CALLBACK_2;
this->blinkCaller = blinkScope;
this->OnMoveEnd = (OnMoveCallback)? OnMoveCallback : NULL_CALLBACK_2;
this->moveCaller = moveScope;
// loads image screenshots
for(uint8_t i=0; i<5; i++){
this->img[i] = imgs[i];
}
// starts displaying from first one
this->tmr.detach();
this->moveStat = 0;
this->blinkStat = 0;
this->Blink();
}
/** Open the eye in the center *******************************************************/
void Eye::Close(void){
this->tmr.detach();
this->moveStat = 0;
this->blinkStat = 0;
this->lcd->Sleep();
}
/** Get actual target position *******************************************************/
uint8_t Eye::GetPosition(void){
return this->targetPosition;
}
/** Blink service ********************************************************************/
void Eye::Blink(void){
// updates eye image
uint8_t id = (this->blinkStat > 4)? (8-this->blinkStat) : this->blinkStat;
this->activeImg = this->img[id];
// refresh LCD content
this->lcd->PutImage(this->activeImg, this->left, this->top);
switch(id){
// on eyes wide open, set timeout to start blinking
case 0:{
this->tmr.attach(this, &Eye::OnBlinkCallback, this->blinkDelay);
break;
}
// on blinking action, reload step time for next image
case 1:
case 2:
case 3:
case 4:{
this->tmr.attach(this, &Eye::OnBlinkCallback, this->blinkStep);
break;
}
}
}
/** Blink callback *******************************************************************/
void Eye::OnBlinkCallback(void){
// loads next image
if(this->blinkStat < 8){
this->blinkStat++;
}
// or restore eyes wide open image
else{
this->blinkStat = 0;
}
// invokes blinking action
this->Blink();
// on eyes wide open after a blinking action, notify blink completed to external caller
if(this->blinkStat == 0){
this->OnBlinkEnd(this->blinkCaller, this);
}
}
/** Movement service *****************************************************************/
void Eye::Move(uint8_t mcode, uint8_t moveSpeed, uint8_t blinkSpeed, float percent){
const float BLINK_SPEED[]={0.05, 0.03, 0.01}; // 50ms 30ms 10ms
const float MOVE_SPEED[]={0.2, 0.1, 0.05}; //200ms 100ms 50ms
uint8_t x_new, y_new;
double xdiff;
double ydiff;
// intializes movement variables
this->tmr.detach();
this->moveStat = 0;
this->blinkStat = 0;
this->blinkStep = (blinkSpeed <= BLINK_FAST)? BLINK_SPEED[blinkSpeed] : BLINK_SPEED[BLINK_FAST];
this->moveDelay = (moveSpeed <= MOVE_FAST)? MOVE_SPEED[moveSpeed] : MOVE_SPEED[MOVE_FAST];
// loads first one (eyes wide open)
this->activeImg = this->img[0];
// setup final location depending on predefined code
switch(mcode){
case MOVE_NW:{
if(this->type == IS_RIGHT){
x_new = (LCDDriver::X_SIZE/4) - (IMAGE_X_SIZE/2)+10;
y_new = ((3*LCDDriver::Y_SIZE)/4) - (IMAGE_Y_SIZE/2);
}
else{
x_new = ((3*LCDDriver::X_SIZE)/4) - (IMAGE_X_SIZE/2)-10;
y_new = (LCDDriver::Y_SIZE/4) - (IMAGE_Y_SIZE/2);
}
break;
}
case MOVE_NC:{
if(this->type == IS_RIGHT){
x_new = (LCDDriver::X_SIZE/4) - (IMAGE_X_SIZE/2)+10;
y_new = (LCDDriver::Y_SIZE/2) - (IMAGE_Y_SIZE/2);
}
else{
x_new = ((3*LCDDriver::X_SIZE)/4) - (IMAGE_X_SIZE/2)-10;
y_new = (LCDDriver::Y_SIZE/2) - (IMAGE_Y_SIZE/2);
}
break;
}
case MOVE_NE:{
if(this->type == IS_RIGHT){
x_new = (LCDDriver::X_SIZE/4) - (IMAGE_X_SIZE/2)+15;
y_new = (LCDDriver::Y_SIZE/4) - (IMAGE_Y_SIZE/2)+5;
}
else{
x_new = ((3*LCDDriver::X_SIZE)/4) - (IMAGE_X_SIZE/2)-15;
y_new = ((3*LCDDriver::Y_SIZE)/4) - (IMAGE_Y_SIZE/2)-5;
}
break;
}
case MOVE_CW:{
if(this->type == IS_RIGHT){
x_new = (LCDDriver::X_SIZE/2) - (IMAGE_X_SIZE/2)+4;
y_new = ((3*LCDDriver::Y_SIZE)/4) - (IMAGE_Y_SIZE/2);
}
else{
x_new = (LCDDriver::X_SIZE/2) - (IMAGE_X_SIZE/2)-4;
y_new = (LCDDriver::Y_SIZE/4) - (IMAGE_Y_SIZE/2);
}
break;
}
case MOVE_CC:{
if(this->type == IS_RIGHT){
x_new = (LCDDriver::X_SIZE/2) - (IMAGE_X_SIZE/2)+5;
y_new = (LCDDriver::Y_SIZE/2) - (IMAGE_Y_SIZE/2);
}
else{
x_new = (LCDDriver::X_SIZE/2) - (IMAGE_X_SIZE/2)-5;
y_new = (LCDDriver::Y_SIZE/2) - (IMAGE_Y_SIZE/2);
}
break;
}
case MOVE_CE:{
if(this->type == IS_RIGHT){
x_new = (LCDDriver::X_SIZE/2) - (IMAGE_X_SIZE/2)+4;
y_new = (LCDDriver::Y_SIZE/4) - (IMAGE_Y_SIZE/2);
}
else{
x_new = (LCDDriver::X_SIZE/2) - (IMAGE_X_SIZE/2)-4;
y_new = ((3*LCDDriver::Y_SIZE)/4) - (IMAGE_Y_SIZE/2);
}
break;
}
case MOVE_SW:{
if(this->type == IS_RIGHT){
x_new = ((3*LCDDriver::X_SIZE)/4) - (IMAGE_X_SIZE/2);
y_new = ((3*LCDDriver::Y_SIZE)/4) - (IMAGE_Y_SIZE/2);
}
else{
x_new = (LCDDriver::X_SIZE/4) - (IMAGE_X_SIZE/2);
y_new = (LCDDriver::Y_SIZE/4) - (IMAGE_Y_SIZE/2);
}
break;
}
case MOVE_SC:{
if(this->type == IS_RIGHT){
x_new = ((3*LCDDriver::X_SIZE)/4) - (IMAGE_X_SIZE/2)+6;
y_new = (LCDDriver::Y_SIZE/2) - (IMAGE_Y_SIZE/2);
}
else{
x_new = (LCDDriver::X_SIZE/4) - (IMAGE_X_SIZE/2)-6;
y_new = (LCDDriver::Y_SIZE/2) - (IMAGE_Y_SIZE/2);
}
break;
}
case MOVE_SE:{
if(this->type == IS_RIGHT){
x_new = ((3*LCDDriver::X_SIZE)/4) - (IMAGE_X_SIZE/2);
y_new = (LCDDriver::Y_SIZE/4) - (IMAGE_Y_SIZE/2);
}
else{
x_new = (LCDDriver::X_SIZE/4) - (IMAGE_X_SIZE/2);
y_new = ((3*LCDDriver::Y_SIZE)/4) - (IMAGE_Y_SIZE/2);
}
break;
}
}
// generates a trajectory of 4 movements
xdiff = (double)((double)x_new - this->left)/3;
ydiff = (double)((double)y_new - this->top)/3;
// apply percentage
xdiff = xdiff * (double)percent;
ydiff = ydiff * (double)percent;
// calculate trajectory
this->x[0] = this->left;
this->x[1] = (uint8_t)((double)this->left+xdiff);
this->x[2] = (uint8_t)((double)this->left+(2*xdiff));
this->x[3] = x_new;
this->y[0] = this->top;
this->y[1] = (uint8_t)((double)this->top+ydiff);
this->y[2] = (uint8_t)((double)this->top+(2*ydiff));
this->y[3] = y_new;
// set target
this->targetPosition = mcode;
// starts movement
this->OnMoveCallback();
}
/** Movement callback ****************************************************************/
void Eye::OnMoveCallback(void){
// load next location
this->left = this->x[this->moveStat];
this->top = this->y[this->moveStat];
// update screen content
this->lcd->PutImage(this->activeImg, this->left, this->top);
// if movement finished...
if(this->moveStat >= 3){
// destroy timer, restart blinking action
this->tmr.detach();
this->blinkStat = 0;
this->Blink();
// notify movement completion event to external caller
this->OnMoveEnd(this->moveCaller, this);
return;
}
this->moveStat++;
// ... else, setup next timed movement update
this->tmr.attach(this, &Eye::OnMoveCallback, this->moveDelay);
}
| true |
ace42cb3efe34d8c6999442bb28cf386a1745f93 | C++ | DiegoGarzaro/POO | /Lista7/Classe.h | UTF-8 | 1,084 | 2.90625 | 3 | [] | no_license | #include <iostream>
#include <iomanip>
#include <string>
class Motor
{
private:
int NumCilindro;
int Potencia;
public:
Motor();
Motor(int NumCilindro, int Potencia);
~Motor();
void getdata();
void putdata();
};
class Veiculo
{
private:
int Peso;
int VelocMax;
float Preco;
public:
Veiculo();
Veiculo(int Peso, int VelocMax, float Preco);
~Veiculo();
void getdata();
void putdata();
};
class CarroPasseio: private Motor, Veiculo
{
private:
std::string Cor;
std::string Modelo;
public:
CarroPasseio();
CarroPasseio(int NumCilindro, int Potencia, int Peso, int VelocMax, float Preco, std::string Cor, std::string Modelo);
~CarroPasseio();
void getdata();
void putdata();
};
class Caminhao: private Motor, Veiculo
{
private:
int Toneladas;
int AlturaMax;
int Comprimento;
public:
Caminhao();
Caminhao(int NumCilindro, int Potencia, int Peso, int VelocMax, float Preco, int Toneladas, int AlturaMax, int Comprimento);
~Caminhao();
void getdata();
void putdata();
}; | true |
6aab744aebba54eb208259b0cbd51b915b68b9c2 | C++ | umer-amjad/Baby-Wolf | /Constant.hpp | UTF-8 | 823 | 2.78125 | 3 | [
"MIT"
] | permissive | //
// Constant.hpp
// BabyWolf
//
//
#ifndef Constant_hpp
#define Constant_hpp
#include "AbstractFunction.hpp"
class Constant : public AbstractFunction {
double val;
const Function wrap() const override;
const Function flatten() const override;
const Function collapse() const override;
AbstractFunction* copy() const override;
public:
Constant(double val);
Constant(const Constant& c);
Constant& operator=(Constant c);
double evaluate(double arg) const override;
Function substitute(const Function subFn) const override;
Function derivative() const override;
std::string getPrefixString() const override;
std::string getInfixString() const override;
FunctionType getType() const override;
double getValue() const override;
};
#endif /* Constant_hpp */
| true |
4adf8ebf8b96b77e93405a70d226b43579c1668a | C++ | AshleshaBhamare/CPSC5910-DataStructures | /P4- Hashing the Hobbit/WordCounter.h | UTF-8 | 6,705 | 3.859375 | 4 | [] | no_license | // Ashlesha Bhamare
// WordCounter.h
// 11/21/2020
// Specification and Implementation file for the WordCounter class
// having different public functions like addWord, removeWord, getCapacity,
// getWordCount, getUniqueWordCount, getTotalWordCount, empty and private
// function like getHashKey.
#ifndef P4_WORDCOUNTER_H
#define P4_WORDCOUNTER_H
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <unordered_map>
#include<iostream>
using namespace std;
class WordCounter {
public:
WordCounter();
// Default Constructor
WordCounter(int capacity);
// Constructor that takes capacity as a parameter
~WordCounter();
// Destructor
WordCounter(const WordCounter &table);
//Copy constructor
WordCounter &operator=(const WordCounter &rhs);
// Overloaded Assignment operator
int addWord(const string &word) ;
// Adds word to WordCounter. If the word is already added then it will
// increment count
// precondition: the word should be added
// postcondition: add word to the wordCounter and increment the count
bool removeWord(const string &word);
// Remove the word
// precondition: the word should be added
// postcondition: remove word completely from hashtable
int getCapacity() const;
// To find capacity of hashtable
// precondition: words should be added
// postcondition: Returns the capacity of the hash table.
int getWordCount(const string &word);
// To find count of word
// precondition: words should be added
// postcondition: Returns the count of the specified (passed in) word
int getUniqueWordCount() const;
// To find entries in the hash table
// precondition: words should be added
// postcondition: Returns the number of unique words encountered
int getTotalWordCount() const;
// To find he total number of words encountered,
// precondition: words should be added
// postcondition: Returns the total number of words encountered,
// including duplicates
bool empty() const;
// To find is hashtable is empty
// precondition: the hashtable should be empty.
// postcondition: Returns true if no words have been added to the hash
// table. Otherwise, returns false
private:
const int defaultSize = 500; // To hold defaultSize
int uniqueWordCount = 0; // To hold uniqueWordCount
int capacity = 0; // To hold capacity
int totalWordCount = 0; // To hold totalWordCount
struct LinkedListNode{
string word;
int wordCount=1;
LinkedListNode *next;
};
LinkedListNode **hashTable;
int getHashKey(const std::string &word) const;
// To find hashKey
// precondition: the woed should be added
// postcondition: Returns the hashKey
};
WordCounter::WordCounter() {
hashTable = new LinkedListNode*[defaultSize];
for (int i = 0; i < defaultSize; i++)
hashTable[i] = nullptr;
this->capacity = defaultSize;
}
WordCounter::WordCounter(int capacity) {
hashTable = new LinkedListNode*[capacity];
for (int i = 0; i < capacity; i++)
hashTable[i] = nullptr;
this->capacity = capacity;
}
WordCounter::~WordCounter() {
delete *hashTable;
}
WordCounter::WordCounter(const WordCounter &table) {
// Copy data elements
uniqueWordCount = table.uniqueWordCount;
totalWordCount = table.totalWordCount;
capacity =table.capacity;
// Allocate memory with new capacity
hashTable = new LinkedListNode*[capacity];
// Copy over elements from other
for (int i = 0; i < capacity; i++) {
*hashTable[i] = *table.hashTable[i];
}
}
WordCounter &WordCounter::operator=(const WordCounter &table) {
if (this != &table) {
delete[] this->hashTable;
//copy
this->uniqueWordCount = table.uniqueWordCount;
this->totalWordCount = table.totalWordCount;
this->capacity = table.capacity;
// re allocate memory
this->hashTable = new LinkedListNode*[capacity];
// Copy over elements from other hashtable
for (int i = 0; i < capacity; i++) {
*this->hashTable[i] = *table.hashTable[i];
}
}
return *this;
}
int WordCounter::addWord(const string &word) {
int result = 0;
totalWordCount++;
if (getWordCount(word) == 0) {
int hashKey =getHashKey(word);
LinkedListNode* node = new LinkedListNode();
node->word=word;
if (hashTable[hashKey] != nullptr) { // check if bucket is occupied
LinkedListNode* temp = hashTable[hashKey];
hashTable[hashKey] = node;
hashTable[hashKey]->next = temp;
}
else {
hashTable[hashKey] = node;
}
uniqueWordCount++;
result = hashTable[hashKey]->wordCount;
}
else {
int hashKey =getHashKey(word);
LinkedListNode* curr = hashTable[hashKey];
while (curr->word != word)
curr = curr->next;
result = curr->wordCount + 1;
curr->wordCount++;
}
return result;
}
bool WordCounter ::removeWord(const string &word) {
if (getWordCount(word) == 0)
return false;
int hashKey = getHashKey(word);
LinkedListNode * curr = hashTable[hashKey];
// check if the value is first in list
if (curr->word == word) {
totalWordCount = totalWordCount - curr->wordCount;
hashTable[hashKey] = curr->next;
}
else {
LinkedListNode* prev = curr;
while (curr->word != word) {
prev = curr;
curr = curr->next;
}
totalWordCount = totalWordCount - curr->wordCount;
prev->next = curr->next;
}
uniqueWordCount--;
return true;
}
int WordCounter::getCapacity() const
{
return this->capacity;
}
int WordCounter::getWordCount(const string &word) {
int result = 0;
int hashKey = getHashKey(word);
LinkedListNode* curr = hashTable[hashKey];
while (curr != nullptr) {
if (curr->word == word) {
result = curr->wordCount;
break;
}
curr = curr->next;
}
return result;
}
int WordCounter::getUniqueWordCount() const {
return uniqueWordCount;
}
int WordCounter::getTotalWordCount() const {
return totalWordCount;
}
bool WordCounter::empty() const
{
if(totalWordCount==0)
return true;
else
return false;
}
int WordCounter::getHashKey(const string &word) const {
hash<string> hashKey;
size_t hashCode = hashKey(word);
int index = hashCode % capacity;
return index;
}
#endif | true |
44f4bbce64e70cefe6d402dc3c191129bdd2c8f9 | C++ | Elvins/Algorithm-problem | /others/2017网易游戏实习编程/网易实习1.cpp | UTF-8 | 2,328 | 3.203125 | 3 | [] | no_license | /**
时间限制:1秒
空间限制:65536K
题目描述
小Q是名小学生,他最喜欢数学中的加法竖式填空了。例如下面的填空题,每个空格表示1…9中的一个数字。
有时候这种竖式题不一定只有唯一解,小Q很想知道,给定一个这样的竖式,总共可能的解有多少个。
被加数和加数的位数不会超过3位。和的位数不会超过4位。空格只可能存在于被加数和加数中。
输入描述:
每个输入数据包含多个测试点。
第一行为测试点的个数T(T<=30)。
每个测试点包含一行,包含了三个长度大于0的字符串,分别表示被加数,加数和结果。每个字符串之间有一个空格。每个字符串只会包含“X”和“1”…“9”,其中“X”表示竖式中的空格。保证竖式至少有一个解。
输出描述:
对于每个测试点,输出一行,表示一共可能的解的个数。
输入例子:
2
X7 9X 123
X X 4
输出例子:
1
3
(样例解释:样例1的解为27+96,样例2的解为1+3,2+2,3+1。)
**/
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<string>
using namespace std;
int res, cnt;
int kongge[10];
void dfs(int rest,int num)
{
if(rest < 0)
{
return;
}
if(num == cnt)
{
if(rest == 0)
res++;
return;
}
for(int i = 1; i <= 9; i++)
dfs(rest-kongge[num]*i, num+1);
}
int main()
{
int T;
scanf("%d", &T);
char jia1[10], jia2[10], he[10];
for(int cas = 1; cas <= T; cas++)
{
memset(kongge, 0, sizeof(kongge));
scanf("%s%s%s", jia1, jia2, he);
int sum1 = 0,sum2 = 0;
cnt = 0;
res = 0;
for(int i = 0; i < strlen(he); i++)
{
sum1 = sum1 * 10 + he[i] - '0';
}
int temp = 1;
for(int i = strlen(jia1)-1; i >= 0; i--)
{
if(jia1[i] == 'X')
{
kongge[cnt++] = temp;
temp *= 10;
continue;
}
sum2 += temp * (jia1[i] - '0');
temp *= 10;
}
temp = 1;
for(int i = strlen(jia2)-1; i >= 0; i--)
{
if(jia2[i] == 'X')
{
kongge[cnt++] = temp;
temp *= 10;
continue;
}
sum2 += temp * (jia2[i] - '0');
temp *= 10;
}
int rest=sum1-sum2;
// printf("%d %d %d %d\n",sum1,sum2,rest,cnt);
// for(int i=0;i<cnt;i++)
// printf("%d\n",kongge[i]);
dfs(rest, 0);
printf("%d\n", res);
// printf("%d\n",sum);
}
return 0;
}
| true |
8d725bc275187505aab58f9ab311eeb7d3fa83df | C++ | John-Janzen/Major-Project | /Major Project Engine/Header Files/EventHandler.h | UTF-8 | 2,137 | 3.09375 | 3 | [] | no_license | #pragma once
#ifndef _EVENTHANDLER_H
#define _EVENTHANDLET_H
#include <map>
#include <list>
static std::uint16_t id_counter = 0;
enum EventType
{
NULL_TYPE,
GAME_CLOSED,
NEW_FRAME,
OPEN_DEBUGGER,
DEBUG_FINISHED_LOAD,
RENDER_NEW_OBJECT,
RENDER_FINISHED,
STATE_CHANGE,
LEFT_MOUSE_BUTTON,
T_BUTTON_PRESSED,
PAUSED_BUTTON,
FULL_PAUSED_BUTTON,
PHYSICS_NEW_OBJECT,
PLAYER_INPUT_TO_PHYSICS,
BOX_COLLISION_PHYSICS_TO_RENDER,
BULLET_COLLISION_PHYSICS_TO_RENDER,
JOB_FINISHED,
JOB_REENTER,
EVENT_COUNT
};
/*
The Event Listener class only has an id to identify the class.
*/
class EventListener
{
public:
EventListener()
{
_id = id_counter++;
}
/*
To Handle events create your own function
*/
virtual void HandleEvent(const EventType & e, void * data) = 0;
virtual ~EventListener() {}
bool operator==(const EventListener & other)
{
return (this->_id == other._id);
}
private:
std::uint16_t _id; // identification
};
/*
The Event Handler is a singleton that is an inbetween class that
takes events to listeners that want them.
*/
class EventHandler
{
public:
~EventHandler() {}
/*
Static Instantiation
Call this first
*/
static EventHandler & Instance()
{
static EventHandler inst;
return inst;
}
/*
Send the event out to all who listen.
and attack any kind of point object.
*/
void SendEvent(const EventType & e, void * data = nullptr)
{
for (auto & listener : *event_map[e])
{
if (listener != nullptr)
listener->HandleEvent(e, data);
}
}
/*
Subscribe to a new event
*/
void SubscribeEvent(const EventType & e, EventListener * listener)
{
if (event_map.find(e) == event_map.end())
event_map.emplace(e, new std::list<EventListener*>());
event_map[e]->emplace_back(listener);
}
/*
Unsubscribe to an event
*/
void UnSubscribeEvent(const EventType & e, EventListener * listener)
{
for (auto it : *event_map[e])
{
if ((*it) == *listener)
{
event_map[e]->remove(it);
}
}
}
private:
EventHandler() {}
typedef std::list<EventListener*> * Listeners;
std::map<EventType, Listeners> event_map;
};
#endif // !_EVENTHANDLER_H
| true |
db2fd5181e0fe9b5ce5e696ff9ab212c56c08b9d | C++ | tres-xxx/Codeforces-Exercises | /A/100-199/141A-AmusingJoke.cpp | UTF-8 | 1,091 | 2.625 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main() {
char guest[100];
char hoster[100];
char check[100];
cin >> guest >> hoster >> check;
int found = 1;
for(int i = 0; check[i]!='\0' && found < 2;i++){
found = 0;
if(check[i] != ' '){
for(int j = 0; hoster[j] != '\0' && check[i] != ' '; j++){
if(check[i] == hoster[j]){
//cout << hoster[j];
//cout << check[i];
check[i] = ' ';
found = 1;
hoster[j] = ' ';
}
}
}
}
//cout << hoster;
//cout << check;
//cout << hoster;
for(int i = 0; hoster[i] != '\0' && found < 2; i++)
if(hoster[i] != ' ') found = 2;
for(int i = 0; check[i]!='\0' && found < 2;i++){
found = 0;
if(check[i] != ' '){
for(int j = 0; guest[j] != '\0' && check[i] != ' '; j++){
if(check[i] == guest[j]){
check[i] = ' '; found = 1;
guest[j] = ' ';
}
}
}
}
for(int i = 0; guest[i] != '\0' && found < 2; i++)
if(guest[i] != ' ') found = 2;
for(int i = 0; check[i] != '\0' && found < 2; i++)
if(check[i] != ' ') found = 2;
if(found < 2) cout << "YES";
else cout << "NO";
return 0;
} | true |
e76812e1d1ab20babc56e779e176a3bed0dac61a | C++ | LGuitron/CyPS | /UnitTest/ValueParametrized/valueParametrized.h | UTF-8 | 211 | 3.375 | 3 | [] | no_license | #include <iostream>
template <class T>
void printValue(T value)
{
std::cout<<value<<std::endl;
}
template <class T>
void printValues(T value1, T value2)
{
std::cout<<value1<<" , "<<value2<<std::endl;
}
| true |
0163a9847d55db43b54eb41d1f74222e1263d85e | C++ | AnnaGorina/Artificial-intelligence | /Lab1/State.h | UTF-8 | 353 | 2.703125 | 3 | [] | no_license | #pragma once
#include<vector>
class State {
std::vector<int> SequenceWidth;
std::vector<bool> isVisited;
public:
explicit State(int N);
bool isEnd(int** A, int N);
bool isSequence(int i) const;
void set_number(int i);
int get_last_number() const;
int get_first_number() const;
std::vector<int> get_vector() const;
void pop_back();
};
| true |
e4afb16f7c562ca1723146d9e730547b0a77bff1 | C++ | gulrak/filesystem | /examples/dir.cpp | UTF-8 | 1,891 | 2.734375 | 3 | [
"MIT",
"BSD-3-Clause"
] | permissive | #include <chrono>
#include <iomanip>
#include <iostream>
#include <string>
#if defined(__cplusplus) && __cplusplus >= 201703L && defined(__has_include)
#if __has_include(<filesystem>)
#define GHC_USE_STD_FS
#include <filesystem>
namespace fs = std::filesystem;
#endif
#endif
#ifndef GHC_USE_STD_FS
#include <ghc/filesystem.hpp>
namespace fs = ghc::filesystem;
#endif
template <typename TP>
std::time_t to_time_t(TP tp)
{
// Based on trick from: Nico Josuttis, C++17 - The Complete Guide
std::chrono::system_clock::duration dt = std::chrono::duration_cast<std::chrono::system_clock::duration>(tp - TP::clock::now());
return std::chrono::system_clock::to_time_t(std::chrono::system_clock::now() + dt);
}
static std::string perm_to_str(fs::perms prms)
{
std::string result;
result.reserve(9);
for (int i = 0; i < 9; ++i) {
result = ((static_cast<int>(prms) & (1 << i)) ? "xwrxwrxwr"[i] : '-') + result;
}
return result;
}
int main(int argc, char* argv[])
{
#ifdef GHC_FILESYSTEM_VERSION
fs::u8arguments u8guard(argc, argv);
if (!u8guard.valid()) {
std::cerr << "Invalid character encoding, UTF-8 based encoding needed." << std::endl;
std::exit(EXIT_FAILURE);
}
#endif
if (argc > 2) {
std::cerr << "USAGE: dir <path>" << std::endl;
exit(1);
}
fs::path dir{"."};
if (argc == 2) {
dir = fs::u8path(argv[1]);
}
for (auto de : fs::directory_iterator(dir)) {
auto ft = to_time_t(de.last_write_time());
auto ftm = *std::localtime(&ft);
std::cout << (de.is_directory() ? "d" : "-") << perm_to_str(de.symlink_status().permissions()) << " " << std::setw(8) << (de.is_directory() ? "-" : std::to_string(de.file_size())) << " " << std::put_time(&ftm, "%Y-%m-%d %H:%M:%S") << " "
<< de.path().filename().string() << std::endl;
}
return 0;
}
| true |
71726554aa6c535615e8896eb8377b5e8ea5d94e | C++ | gurus158/codingPractice | /solutions/mergeTwoSortedList_easy.cpp | UTF-8 | 830 | 3.21875 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
struct ListNode{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution{
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if(!l1)
return l2;
if(!l2)
return l1;
if(l1->val < l2->val){
l1->next = mergeTwoLists(l1->next,l2);
return l1;
}else{
l2->next = mergeTwoLists(l1,l2->next);
return l2;
}
}
};
int main(){
ListNode* h1=new ListNode(1);
h1->next = new ListNode(2);
ListNode* h2 = new ListNode(1);
h2->next = new ListNode(3);
h2->next->next=new ListNode(4);
Solution s;
ListNode* mergedhead = s.mergeTwoLists(h1,h2);
while (mergedhead!=NULL) {
/* code */
cout<<mergedhead->val<<"-->";
mergedhead=mergedhead->next;
}
std::cout << "NULL" << '\n';
}
| true |
702452eca3b258d99782f7cf4e68da2b0be6ce00 | C++ | georgistoilov8/Object-Oriented-Programming | /Social media/Version 1/FMI Book/FMI Book/text_post.cpp | UTF-8 | 801 | 2.96875 | 3 | [] | no_license | #define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include "text_post.h"
char* TextPost::wrapToHtml() const {
int content_length = strlen(getContent());
int html_length = 48;
char* result = new char[html_length + content_length + 1];
strcpy(result, "<!DOCTYPE html><html><body><p>");
strcat(result, getContent());
strcat(result, "</p></body></html>");
/*
<!DOCTYPE html>
<html>
<body>
<p>
Text
</p>
</body>
</html>
*/
return result;
}
char* TextPost::getHtmlContent() const {
int content_length = strlen(getContent());
int html_length = 7;
char* result = new char[html_length + content_length + 1];
strcpy(result, "<p>");
strcat(result, getContent());
strcat(result, "</p>");
return result;
}
TextPost* TextPost::clone() const {
return new TextPost(*this);
} | true |
fed1ad6b1ab0465b8b6bf7f4a2ad9622c2a76e58 | C++ | prasad-joshi/CPPCodes | /pcap/FindDevice.cpp | UTF-8 | 1,028 | 2.734375 | 3 | [] | no_license | #include <iostream>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pcap.h>
std::ostream& operator << (std::ostream& os, pcap_addr_t& addr) {
return os;
}
std::ostream& operator << (std::ostream& os, pcap_if_t& dev) {
os << dev.name << ": "
<< (dev.description ? dev.description : "");
for (pcap_addr_t* addrp = dev.addresses; addrp; addrp = addrp->next) {
auto in = reinterpret_cast<struct sockaddr_in*>(addrp->addr);
os << "addr: " << inet_ntoa(in->sin_addr) << ' ';
if (addrp->dstaddr) {
in = reinterpret_cast<struct sockaddr_in*>(addrp->dstaddr);
os << "dstaddr: " << inet_ntoa(in->sin_addr) << ' ';
}
}
return os;
}
int main() {
char errbuf[PCAP_ERRBUF_SIZE];
pcap_if_t* devicesp{};
int rc = pcap_findalldevs(&devicesp, errbuf);
if (rc) {
std::cout << "Error finding device " << errbuf << std::endl;
return 1;
}
for (pcap_if_t* devp = devicesp; devp; devp = devp->next) {
std::cout << *devp << std::endl;
}
pcap_freealldevs(devicesp);
return 0;
}
| true |
090f7b9d76d199d2b9fb7ba4a6b43e7a9fa2c8e0 | C++ | saifullah3396/team-nust-robocup-v2 | /src/TNRSModules/UserCommModule/include/Deprecated/BoostTcpServer.h | UTF-8 | 2,569 | 2.6875 | 3 | [
"BSD-3-Clause"
] | permissive | //
// server.cpp
// ~~~~~~~~~~
//
// Copyright (c) 2003-2008 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/lexical_cast.hpp>
#include <iostream>
#include <vector>
#include "connection.hpp" // Must come before boost/serialization headers.
#include <boost/serialization/vector.hpp>
/// Serves stock quote information to any client that connects to it.
class TcpServer
{
public:
/// Constructor opens the acceptor and starts waiting for the first incoming
/// connection.
TcpServer(boost::asio::io_service& io_service, unsigned short port)
: acceptor_(io_service, boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), port))
{
// Start an accept operation for a new connection.
connection_ptr new_conn(new connection(acceptor_.get_io_service()));
acceptor_.async_accept(new_conn->socket(),
boost::bind(&server::handle_accept, this,
boost::asio::placeholders::error, new_conn));
}
/// Handle completion of a accept operation.
void handle_accept(const boost::system::error_code& e, connection_ptr conn)
{
if (!e)
{
// Successfully accepted a new connection. Send the list of stocks to the
// client. The connection::async_write() function will automatically
// serialize the data structure for us.
conn->async_write(stocks_,
boost::bind(&server::handle_write, this,
boost::asio::placeholders::error, conn));
// Start an accept operation for a new connection.
connection_ptr new_conn(new connection(acceptor_.get_io_service()));
acceptor_.async_accept(new_conn->socket(),
boost::bind(&server::handle_accept, this,
boost::asio::placeholders::error, new_conn));
}
else
{
// An error occurred. Log it and return. Since we are not starting a new
// accept operation the io_service will run out of work to do and the
// server will exit.
std::cerr << e.message() << std::endl;
}
}
/// Handle completion of a write operation.
void handle_write(const boost::system::error_code& e, connection_ptr conn)
{
// Nothing to do. The socket will be closed automatically when the last
// reference to the connection object goes away.
}
private:
/// The acceptor object used to accept incoming socket connections.
boost::asio::ip::tcp::acceptor acceptor_;
};
| true |
d4dd4022f132a53e4840271a16f2356f2c1e429f | C++ | gmevelec/npuzzle | /srcs/implementation.cpp | UTF-8 | 4,841 | 3.25 | 3 | [] | no_license | #include "implementation.h"
#include <queue>
#include <map>
#include <iostream>
template<typename T, typename priority_t>
struct PriorityQueue
{
typedef std::pair<priority_t, T> PQElement;
std::priority_queue<PQElement, std::vector<PQElement>, std::greater<PQElement> > elements;
inline bool empty() const
{
return elements.empty();
}
inline void put(T item, priority_t priority)
{
elements.emplace(priority, item);
}
inline T get()
{
T bestItem = elements.top().second;
elements.pop();
return (bestItem);
}
};
std::vector<Node> reconstruct_path(Node start, Node goal, std::unordered_map<Node, Node>& came_from)
{
std::vector<Node> path;
Node current = goal;
path.push_back(current);
while (current != start)
{
current = came_from.at(current);
path.push_back(current);
}
std::reverse(path.begin(), path.end());
return (path);
}
void getZero(Node puzzle, int& x, int& y)
{
for (int i = 0; i < puzzle.size; ++i)
{
for (int j = 0; j < puzzle.size; ++j)
{
if (puzzle.puzzle[i][j] == 0)
{
x = j;
y = i;
return ;
}
}
}
}
std::vector<Node> getNeighbors(Node puzzle)
{
int x, y;
std::vector<Node> neighbors;
getZero(puzzle, x, y);
if (x < puzzle.size - 1)
{
Node tmp = puzzle;
tmp.puzzle[y][x] = tmp.puzzle[y][x + 1];
tmp.puzzle[y][x + 1] = 0;
neighbors.push_back(tmp);
}
if (x > 0)
{
Node tmp = puzzle;
tmp.puzzle[y][x] = tmp.puzzle[y][x - 1];
tmp.puzzle[y][x - 1] = 0;
neighbors.push_back(tmp);
}
if (y < puzzle.size - 1)
{
Node tmp = puzzle;
tmp.puzzle[y][x] = tmp.puzzle[y + 1][x];
tmp.puzzle[y + 1][x] = 0;
neighbors.push_back(tmp);
}
if (y > 0)
{
Node tmp = puzzle;
tmp.puzzle[y][x] = tmp.puzzle[y - 1][x];
tmp.puzzle[y - 1][x] = 0;
neighbors.push_back(tmp);
}
return (neighbors);
}
int heuristic(Node puzzle, Node goal)
{
int n = 0;
for (int i = 0; i < puzzle.size; ++i)
{
for (int j = 0; j < puzzle.size; ++j)
{
if (puzzle.puzzle[i][j] != goal.puzzle[i][j] && puzzle.puzzle[i][j] != 0)
{
n++;
}
}
}
return (n);
}
void getRowColByValue(Node puzzle, int& expectedRow, int& expectedColumn, int value)
{
for (int i = 0; i < puzzle.size; ++i)
{
for (int j = 0; j < puzzle.size; ++j)
{
if (puzzle.puzzle[i][j] == value)
{
expectedRow = i;
expectedColumn = j;
return ;
}
}
}
}
int manhattan(Node puzzle, Node goal)
{
int heuristic = 0;
for (int i = 0; i < puzzle.size; ++i)
{
for (int j = 0; j < puzzle.size; ++j)
{
int value = puzzle.puzzle[i][j];
if (value == 0)
{
continue;
}
int expectedRow;
int expectedColumn;
getRowColByValue(goal, expectedRow, expectedColumn, value);
int diff = abs(i - expectedRow) + abs(j - expectedColumn);
heuristic += diff;
}
}
return (heuristic);
}
int linearVerticalConflict(Node puzzle)
{
int linearConflict = 0;
for (int i = 0; i < puzzle.size; ++i)
{
int max = -1;
for (int j = 0; j < puzzle.size; ++j)
{
int value = puzzle.puzzle[i][j];
if (value != 0 && (value - 1) / puzzle.size == i)
{
if (value > max)
{
max = value;
}
else
{
linearConflict += 2;
}
}
}
}
return (linearConflict);
}
int linearHorizontalConflict(Node puzzle)
{
int linearConflict = 0;
for (int j = 0; j < puzzle.size; ++j)
{
int max = -1;
for (int i = 0; i < puzzle.size; ++i)
{
int value = puzzle.puzzle[i][j];
if (value != 0 && value % puzzle.size == j + 1)
{
if (value > max)
{
max = value;
}
else
{
linearConflict += 2;
}
}
}
}
return (linearConflict);
}
int linearConflict(Node puzzle, Node goal)
{
int heuristic = manhattan(puzzle, goal);
heuristic += linearVerticalConflict(puzzle);
heuristic += linearHorizontalConflict(puzzle);
return (heuristic);
}
void a_star_search(
Node start,
Node goal,
std::unordered_map<Node, Node>& came_from,
std::unordered_map<Node, float>& cost_so_far,
info_values& info)
{
PriorityQueue<Node, float> open;
std::cout << YELLOW;
std::cout << start;
std::cout << RESET;
open.put(start, 0);
came_from.emplace(Node(start), start);
cost_so_far[start] = 0;
std::vector<Node> neighbors;
while (!open.empty())
{
auto current = open.get();
info.nbStatesSelected++;
if (current == goal)
{
std::cout << "FINISHED" << std::endl;
break;
}
neighbors.clear();
neighbors = getNeighbors(current);
for (auto next : neighbors)
{
float new_cost = cost_so_far[current] + 1;
if (!cost_so_far.count(next) || new_cost < cost_so_far[next])
{
cost_so_far[next] = new_cost;
info.maxNbofStates++;
next.h = linearConflict(next, goal);
next.g = new_cost;
next.f = next.g + next.h;
open.put(next, next.f);
info.maxNbofStates++;
came_from.emplace(Node(next), current);
}
}
}
}
| true |
86324ad499525f5df8a3a009d1ff857867550cbd | C++ | Antonio180233/C-programming | /Actividad_4.cpp | UTF-8 | 3,567 | 3.71875 | 4 | [] | no_license | #include <iostream>
using namespace std;
/*Estructura nodo*/
struct nodo {//Se crea una estructura con el nombre nodo con dos componentes
int numero;//Almacena un dato numerico en el nodo que tenemos
struct nodo* sig;//Almacena la direccion de memoria del nodo continuo
};
typedef nodo* P;//Define un tipo de dato estructura nodo
void mostrar_pila(P p)//Al no haber manipulacion directa de la pila, no es necesario hacer referencia
{
P aux;//Creo un auxiliar es de tipo nodo *P
aux = p;//se iguala la ultima direccion que apunta la pila al auxiliar
while (aux != NULL)//Mientras el puntero auxiliar no apunte a nulo
{
cout << endl << aux->numero << endl; //Se imprime el numero que hay en cada nodo
aux = aux->sig;
}
}
void push(P& p, int n)
{
P aux;
aux = new nodo;//Creamos y apuntamos a un nuevo nodo
aux->numero = n;//Se asigna el número ingresado de teclado
aux->sig = p; //el siguiente elemento se apunta al anterior creado
p = aux;//Asignación del nodo creado a la pila original
}
int pop(P& p)//Habrá manipulacion a la pila, por lo que tiene que mandar la referencia
{
int num;
P aux;
aux = p;//Se le asigna direccion de la pila a un puntero auxiliar
num = aux->numero; //El numero dentro del nodo se almacena a una variable entera
p = aux->sig; //Se la direccion del ultimo nodo se cambia al nodo anterior
//desvinculando el nodo a eliminar
delete(aux); //Se elimina el ultimo nodo creado
return num; //Se regresa el numero del nodo eliminado para su impresión
}
void destruir_pila(P& p)
{
P aux;
while (p != NULL)
{
aux = p;
p = aux->sig;
delete(aux);
}
cout << endl << "Pila borrada..." << endl;
}
int mostrar_cantidad(P p)
{
P aux;
int total = 0;
aux = p;
while (aux != NULL)
{
total++;
aux = aux->sig;
}
return total;
}
int tope_pila(P p)
{
int num;
num = p->numero;
return num;
}
int ultimo_pila(P p)
{
P aux;
int z = 0;
P pen = p;
aux = p;
while (aux != NULL)
{
pen = aux;
aux = aux->sig;
}
return pen->numero;
}
int main()
{
P pila = NULL;//Iniciando la pila en Nulo
int dato = 0, opc = 0, x;
do {
cout << "***MENU PILAS*** " << endl << endl <<
"1-Apilar (Push)" << endl <<
"2-Desapilar (Pop)" << endl <<
"3-Mostrar pila" << endl <<
"4-Ultimo numero de la pila" << endl <<
"5-Tope de la pila" << endl <<
"6-Borrar pila" << endl <<
"7-Mostrar la cantidad de nodos" << endl <<
"8 Salir" << endl;
cout << endl << "Ingrese una opcion:";
cin >> opc;
switch (opc)
{
case 1:
cout << endl << "Ingresa numero: ";
cin >> dato;
push(pila, dato);
system("pause");
break;
case 2:
x = pop(pila);
cout << endl << "Se elimina el nodo con el numero" << x;
system("pause");
break;
case 3:
if (pila != NULL)
mostrar_pila(pila);
else
cout << endl << "Pila vacia..." << endl;
system("pause");
break;
case 4:
cout << ultimo_pila(pila) << endl;
system("pause");
break;
case 5:
cout << tope_pila(pila) << endl;
system("pause");
break;
case 6:
destruir_pila(pila);
system("pause");
break;
case 7:
cout << mostrar_cantidad(pila) << endl;
system("pause");
break;
default:
cout << endl << "ERROR 001";
cout << endl << "Ingrese una opcion valida o digite 8 para salir de la pila";
break;
}
} while (opc != 7);
return 0;
}
| true |
981f6500295dc4d62bcd452fc578ede5e12c70dc | C++ | Alfeim/njuee_LeetCode_Solutions | /Cpp/Submit Records/274. H-Index.cpp | UTF-8 | 568 | 3.109375 | 3 | [] | no_license | /********************************************
作者:Alfeim
题目:H指数
时间消耗:8ms
解题思路:排序
********************************************/
class Solution {
public:
int hIndex(vector<int>& citations) {
if(citations.empty())
return 0;
int res;
sort(citations.begin(),citations.end(),greater<int>());
res = citations[0] >= 1 ? 1 : 0 ;
for(int i = 1 ; i < citations.size();++i){
if(citations[i] > i)
res = min(i+1,citations[i]);
}
return res;
}
};
| true |
dc6cf42236ec103d1c0024e845befd93fc97f952 | C++ | rafaellg8/MP | /Practicas/P6/imagen/imagen/src/testarteASCII.cpp | UTF-8 | 2,911 | 3.265625 | 3 | [] | no_license | //lee imagenes/gio.pgm y la convierte en ascii con los caracteres "@%#*+=-:. "
#include <iostream>
#include <imagen.h>
using namespace std;
/**
* @brief Funcion auxiliar para imprimir la matriz arteASCII
*/
void imprimir(char ** arteASCII, int f, int c){
if (arteASCII!=0)
for (int i=0; i<f; i++) {
for (int j=0; j<c; j++) {
cout<<arteASCII[i][j];
}
cout <<"\n";
}
}
/**
* @brief Funcion auxiliar que crea he inicializa la matriz por defecto arteASCII
* @param arteASCII matriz de tipo char para crear
* @param f entero numero de filas
* @param c entero numero de columnas
*/
void crear(char ** &arteASCII, int f, int c){
//Si esta sin crear arteASCII lo creamos
if (arteASCII == 0) {
arteASCII = new char * [f];
arteASCII[0]= new char [f*c]; //Primera columna que apunta al array
//Enlazamos desde la posicion 1 al final
for (int i=1; i< f; i++) {
arteASCII [i] = arteASCII [i-1] + c;
}
//asignar valor
for (int i=0; i<f; i++)
for (int j=0; j<c; j++)
arteASCII[i][j] = 0;
}
}
int main(){
// const char * grises = "@#%xo;:,. ";
const char * grises = "#$:. ";
char ** arteASCII=0;
Imagen origen;
int cardinal = 0;
//Obtenemos el cardinal
do{
cardinal++;
}while(grises[cardinal]!= ' ');
cardinal++; //añadimos el ultimo caracter /n para que el tamaño sea correcto
cout<<cardinal;
// Leer la imagen gio.pgm
if (!origen.leerImagen("imagenes/gio.pgm")) {
cerr << "error leyendo imagenes/gio.pgm\n";
return 1;
}
crear(arteASCII,origen.filas(),origen.columnas()); //Reservamos espacio para la matriz arteASCII
cout << "\nLa imagen en arte ASCII es:\n";
if(origen.aArteASCII(grises,arteASCII,4500,cardinal))
cout<<arteASCII[0]<<endl;
else
cout << "La conversion no ha sido posible" << endl;
// cout << "Ahora Forzamos que no quepa. Debe aparecer un mensaje de error\n";
// if(origen.aArteASCII(grises, arteASCII,4199))
// imprimir(arteASCII,origen.filas(),origen.columnas());
// else
// cout << "La conversion no ha sido posible" << endl;
if (arteASCII[0] != 0) //Si fila de filas * columnas no esta vacia
delete [] arteASCII [0]; //Borramos la primera fila
if (arteASCII != 0)
delete [] arteASCII;
arteASCII = 0;
}
| true |
3ce39c189b45a12a427f613a70c75cb0e48a2676 | C++ | Soumya-padala/NcrWork | /C/Assignment1/Program10/Program10/Sumofdigits.cpp | UTF-8 | 247 | 3.203125 | 3 | [] | no_license | # include<stdio.h>
int getSum(int n)
{
int sum = 0;
while (n != 0)
{
sum = sum + n % 10;
n = n / 10;
}
return sum;
}
int main()
{
int n;
printf("enter number");
scanf_s("%d", &n);
printf(" %d ", getSum(n));
getchar();
return 0;
}
| true |
b3e4a0a1f6bfe99ebf4b5e4381c451a2c489049f | C++ | aspcodenet/Iot20AlgorithmDemos | /Iot20AlgorithmDemos/Iot20AlgorithmDemos.cpp | ISO-8859-1 | 6,270 | 3.59375 | 4 | [] | no_license | // Iot20AlgorithmDemos.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include <iostream>
#include <string>
#include <vector>
#include <list>
#include <algorithm>
#include <numeric> //POWER OF ABSTRACTION. ok tyckte du det var svrt att anvnda DVD-spelaren?
//svrt att anvnda accumulate? Kolla in "kretskortet"
using namespace std;
typedef enum
{
SIZE_SMALL,
SIZE_MEDIUM,
SIZE_LARGE
}SIZE;
class Julklapp
{
private:
string _till;
float _value;
SIZE _size;
string _sak;
public:
string GetTillVem()
{
return _till;
}
SIZE GetSize()
{
return _size;
}
string GetSak()
{
return _sak;
}
float GetValue()
{
return _value;
}
void SetValue(float newValue)
{
_value = newValue;
}
Julklapp(string till, float value, SIZE size, string sak)
{
_till = till;
_value = value;
_size = size;
_sak = sak;
}
};
void a(int b)
{
}
int main()
{
//// namn = 0x011111432
//char namn[123] = "Stefan";
//namn[3] = 'A'; //0x011111432 + (sizeof(char) * 3)
//list<char> ma; // ma = hller en pekare till frsta. 0x231312
//ma.push_back('S'); //0x231312 - 'S' struct - char 'S' - eklare till nsta 0x473829678342
//ma.push_back('t'); //0x473829678342 - 't' struct - char 't' - eklare till nsta 0x432243432
//ma.push_back('e'); //0x432243432
//ma.push_back('f');
//
//vector<int> ints = { 12,11,44,55 };
//ints.push_back(66);
//sort(ints.begin(), ints.end(),std::greater<int>());
//for(int i: ints)
//{
// cout << i;
//}
//
//int summa = 0;
//for(int i = 0; i < ints.size();i++)
//{
// summa += ints[i]; //start + sizeof(det som lagras) * index
//}
//
//int sum = accumulate(ints.begin(), ints.end(),0);
//list<int> intLista = { 12,11,44,55 };
//intLista.push_back(1111);
//sum = accumulate(intLista.begin(), intLista.end(), 0);
////Old way...
////sum = 0;
////for(int i = 0 ; i < intLista.size();i++)
////{
//// summa += intLista[i];
////}
////sum = 0;
///*for (vector<int>::iterator it = ints.begin(); it != ints.end(); it++) {
// sum += *it;
//}*/
////
//////Hello iterators
////sum = 0;
////for (list<int>::iterator it = intLista.begin(); it != intLista.end(); it++) {
//// sum += *it;
////}
////goodbuy iterators...eller INTE = detta R samma som ovan - bara syntaktiskt socker
//sum = 0;
//for (int i : intLista) {
// sum += i;
//}
//
vector<Julklapp> julklappar = {
Julklapp("Stefan", 300, SIZE_SMALL, "Raspberry Pi4"),
Julklapp("Kerstin", 20, SIZE_SMALL, "Strumpor"),
Julklapp("Stefan", 100, SIZE_MEDIUM, "Skor"),
Julklapp("Oliver", 300, SIZE_SMALL, "GTA Online fr PC"),
Julklapp("Stefan", 50, SIZE_SMALL, "Handbok mobil"), //S han kan lra sig byta signal ;)
Julklapp("Oliver", 10000, SIZE_LARGE, "Speldator"),
Julklapp("Oliver", 500, SIZE_SMALL, "GTA Online konto"),
};
int w = 13;
int antal1 = 12223;
for(Julklapp k : julklappar)
{
if (k.GetTillVem() == "Stefan") antal1++;
w = 3422334;
}
//TRUE om den ska rknas
//FALSE om den INTE ska rknas
int antal = count_if(julklappar.begin(), julklappar.end(), [](Julklapp k)
{
if (k.GetTillVem() == "Stefan") return true;
return false;
});
bool allaTillStefan = all_of(julklappar.begin(), julklappar.end(), [](Julklapp k)
{
if (k.GetTillVem() == "Stefan") return true;
return false;
});
//ANY OF TRUE om den finns = SHORTCUTTAR = hoppas ur loopen
bool finnsLiten = any_of(julklappar.begin(), julklappar.end(), [](Julklapp k)
{
if (k.GetTillVem() == "Stefan" && k.GetSize() == SIZE_SMALL) return true;
return false;
});
//ANY OF TRUE om den finns = SHORTCUTTAR = hoppas ur loopen
finnsLiten = any_of(julklappar.begin(), julklappar.end(), [](Julklapp k)
{
if (k.GetTillVem() == "Kerstin" ) return true;
return false;
});
bool alla = all_of(julklappar.begin(), julklappar.end(), [](Julklapp k)
{
if (k.GetValue() > 10) return true;
return false;
});
if(finnsLiten)
{
cout << "Trkigt..." << endl;
}
////INFLATION... Loopa igenom alla och stt pris till pris * 2
/// for vs for_each & vs inte...
for (Julklapp &julklapp : julklappar) { // & *[]
julklapp.SetValue(julklapp.GetValue()*2) ;
}
for (Julklapp& julklapp : julklappar) { // & *[]
julklapp.SetValue(julklapp.GetValue() * 2);
}
for (Julklapp julklapp : julklappar) {
cout << julklapp.GetTillVem() << " " << julklapp.GetValue() << endl;
}
float summan = 0;
for (Julklapp julklapp : julklappar) {
summan += julklapp.GetValue();
}
for_each(julklappar.begin(), julklappar.end(), [](Julklapp& j)
{
if(j.GetTillVem() == "Stefan")
{
j.SetValue(j.GetValue() - 50);
}
});
for_each(julklappar.begin(), julklappar.end(), [](Julklapp &j)
{
j.SetValue(j.GetValue() * 2);
});
for_each(julklappar.begin(), julklappar.end(), [](Julklapp j)
{
cout << j.GetTillVem() << endl;
});
//LAMBDA fr sort = sg vem av dessa tv som ska komma frst
// men exakt??? om TRUE s ska A komma frst
// om FALSE ska B komma frst
// hur ska man veta det??? TESTA... som 0,1 index = trial and error
sort(julklappar.begin(), julklappar.end(), [](Julklapp a, Julklapp b) {
if (a.GetValue() > b.GetValue())
return true;
return false;
});
//reverse(julklappar.begin(), julklappar.end());
//LAMBDA fr sort = sg vem av dessa tv som ska komma frst
// men exakt??? om TRUE s ska A komma frst
// om FALSE ska B komma frst
// hur ska man veta det??? TESTA... som 0,1 index = trial and error
sort(julklappar.begin(), julklappar.end(), [](Julklapp a, Julklapp b) {
if (a.GetTillVem() == b.GetTillVem()) return a.GetSize() < b.GetSize();
return a.GetTillVem() < b.GetTillVem();
});
for (Julklapp julklapp : julklappar) {
cout << julklapp.GetTillVem() << " " << julklapp.GetValue() << endl;
}
sort(julklappar.begin(), julklappar.end(), [](Julklapp a, Julklapp b) {
//
string sortKeyForA = a.GetTillVem() + to_string(a.GetSize());
string sortKeyForB = b.GetTillVem() + to_string(b.GetSize());
return sortKeyForA < sortKeyForB;
});
//vs for
//Gr ngt med alla...
//
for (Julklapp julklapp : julklappar) {
cout << julklapp.GetTillVem();
}
} | true |
2c37fcdf8966cafeb6ef4973c8073a1844e7ed11 | C++ | Kushal148/C-DAC-Feb2020 | /DerivedDataTypes.cpp | UTF-8 | 1,893 | 3.890625 | 4 | [] | no_license | //DerivedDataTypes.cpp
/*
Data types that are derived from the primitive or builtin types are called as Derived Types
Functions, Arrays, pointers and references are the examples of derived types.
A Function is a set of statements that performs a computation based in inputs given to it in
the form of arguments and provide the output from that operation as a return value of that function
All functions dont return a value. Functions without a return value are called Sub-routines.
If U want to put some commonly performed tasks into a group and use it quite frequently in ur
program, then U should make that as a function and use it in a single line instead of writing
the same code again and again.
POINTS to REMEMBER:
A Function must have a declaration, body and Calling mechanism.
The declaration tells the compiler about the parameters and their data types, order of placing
and the return type of the function. If the function does not return any value, it is void function
Every function U create must be called in the program either directly or indirectly.
main is the only function that is called by the OS, not by the programmer.
return statement is used to terminate the function.
In C++, functions can return any data type except Arrays. However U could use pointers in place.
It is good practise to declare the functions in a seperate file called Header file and implement
them inside a CPP file. But U could implement UR Functions in the header file also.
*/
#include<iostream>
using namespace std;
//This function is used to extract the max value from 2 variables given...
int getMax(int x, int y){
if(x > y)
return x;
else
return y;
}
void print(char* msg){
cout<<msg<<endl;
}
int main(){
print("An apple");
print("A Mango");
cout<<"The max value is " <<getMax(23,20)<<endl;//Using a function like a variable...
}
| true |
e328151d6d4e471c56e7914966b0c3ae0e19f8d4 | C++ | anibalvale666/ParallelWordCount | /WordCount.cpp | UTF-8 | 5,256 | 3.390625 | 3 | [] | no_license | // WordCount.cpp : Este archivo contiene la función "main". La ejecución del programa comienza y termina ahí.
#include <iostream>
#include <thread>
#include <vector>
#include <fstream>
#include <sstream>
#include <map>
#include <iomanip>
#include <cctype>
#include <chrono>
#include <string>
using namespace std;
std::vector<std::string> allwords;
//vector<pair<string, int>> wordCount;
ifstream file;
bool lectura()
{
int tam_vec = 100000000;
string word;
allwords.clear();
int i = 0;
while (file >> word && i < tam_vec)
{
i++;
allwords.push_back(word);
//allwords[i++] = word;
}
std::cout << "cantidad de palabras " << allwords.size() << endl;
std::cout << "tamanio del vector en bytes " << sizeof(string) * 94000000 << endl;
return allwords.empty();
}
std::map<std::string, size_t> contar(std::vector<std::string> const& words)
{
auto wordCount = std::map<std::string, size_t>{};
for (auto const& word : words)
{
++wordCount[word];
}
std::cout << "palabras contadas" << wordCount.size() << endl;
return wordCount;
}
auto wordCount = std::map<std::string, size_t>{};
std::map<std::string, size_t> localWorldCount[6];
void contarP( int ini, int end,int localIte)
{
string word;
for (unsigned it = ini;it<end;it++)
{
word = allwords[it];
//++wordCount[word];
++localWorldCount[localIte][word];
}
std::cout << "palabras contadas" << localWorldCount[localIte].size() << endl;
//res = wordCount;
return;
}
void print(std::map<std::string, size_t> mymap)
{
// show content:
for (std::map<string, size_t>::iterator it = mymap.begin(); it != mymap.end(); ++it)
std::cout << it->first << " => " << it->second << '\n';
}
void save(string arc)
{
ofstream file;
file.open(arc);
//std::cout << "palabras csssontadas" << wordCount.size() << endl;
for (std::map<string, size_t>::iterator it = wordCount.begin(); it != wordCount.end(); ++it)
{
//std::cout << it->first << " => " << it->second << '\n';
file << it->first << " => " << it->second << '\n';
}
file.close();
}
int main()
{
//inicializamos allwords
//for (int i = 0; i < 50000000; i++)
//allwords.push_back("");
//file.open("texto_prueba2.txt");
file.open("C:/Users/nibar/Documents/texto5G.txt");
bool finish = true;
unsigned iteration=0;
double principal,principal_lect;
principal = principal_lect = 0;
while (true)
{
//----------------------------------lectura---------------------------------------//
auto start_lect = std::chrono::steady_clock::now();
//finish = lectura("texto_prueba2.txt");
finish = lectura();
auto end_lect = std::chrono::steady_clock::now();
if (finish) break; //condicion de termino
std::cout << "iteracion nro: " << iteration++ << endl;
//------------------------------creacion de hilos-------------------------------------------//
//const auto numThread = std::thread::hardware_concurrency();
//int part_per_thread = allwords.size() /numThread;
unsigned numTread = 6;
int part_per_thread = allwords.size() / numTread;
std::vector<std::thread> threads;
auto start_p = std::chrono::steady_clock::now();
std::map<std::string, size_t> localWorldCount[6];
unsigned i;
for (i = 0; i < numTread - 1; i++)
{
std::cout << i * part_per_thread << " " << (i + 1) * part_per_thread << endl;
threads.push_back(std::thread(contarP, i * part_per_thread, (i + 1) * part_per_thread, i));
}
std::cout << i * part_per_thread << " " << allwords.size() << endl;
threads.push_back(std::thread(contarP, i * part_per_thread, allwords.size(), i));
//threads.push_back(std::thread(contar, allwords));
for (auto& th : threads) th.join();
threads.clear();
auto end_p = std::chrono::steady_clock::now();
//contadas = contar(allwords);
//print(contadas);
std::cout << "lectura de todas las palabras: " << std::chrono::duration_cast<std::chrono::milliseconds>(end_lect - start_lect).count() << "ms\n"
<< "procesamiento principal: " << std::chrono::duration_cast<std::chrono::milliseconds>(end_p - start_p).count() << "ms\n\n\n\n";
principal += std::chrono::duration_cast<std::chrono::milliseconds>(end_p - start_p).count();
principal_lect += std::chrono::duration_cast<std::chrono::milliseconds>(end_lect - start_lect).count();
}
for (int ii = 0; ii < 6; ii++)
for (std::map<string, size_t>::iterator jj = localWorldCount[ii].begin(); jj != localWorldCount[ii].end(); ++jj)
wordCount[jj->first] += jj->second;
save("out.txt");
std::cout << "lectura total de todas las palabras: " << principal_lect << "ms\n"
<< "procesamiento principal total: " << principal << "ms\n\n\n";
file.close();
return 0;
}
| true |
69bf7c753843380cda73d74722bad654af31237a | C++ | cmorris9/ProjectTwo | /CMorris_COMP340_Project1/Items.cpp | UTF-8 | 767 | 2.921875 | 3 | [] | no_license | #include "Items.h"
#include <string>
#include <vector>
Item::Item()
{
}
Item::Item(std::string ItemName)
{
this->WeapModifier = 0;
this->ItemName = ItemName;
this->IsHidden = false;
}
Item::~Item()
{
}
Item* Item::GenerateItems(int x)
{
switch (x)
{
case 1:
this->ItemName = "Sword";
break;
case 2:
this->ItemName = "Health Potion";
break;
case 3:
this->ItemName = "Key";
break;
case 4:
this->ItemName = "Dirty Sock";
break;
default:
this->ItemName = "Dirt";
break;
}
return this;
}
std::string Item::getItemName()
{
return this->ItemName;
}
void Item::ChangeWeapModifier(int x)
{
//This will change the weapon modifier to account for spec. attck damage or healing points
this->WeapModifier = x;
} | true |
201c93307c9c250232917ad9fa0e9c24c3c727e5 | C++ | CyrilKoe/tronAI | /game/map.h | UTF-8 | 1,343 | 2.921875 | 3 | [] | no_license | #ifndef MAP_H
#define MAP_H
#include <SDL2/SDL.h>
#include "utils.h"
class Game;
class Map
{
private:
Game *game;
unsigned int screen_width, screen_height;
unsigned int width, height, size;
unsigned int boxes_width, boxes_height;
uint8_t *content = nullptr;
public:
Map(unsigned int _screen_width, unsigned int _screen_height, unsigned int _width, unsigned int _height) : screen_width(_screen_width), screen_height(_screen_height), width(_width), height(_height)
{
boxes_width = screen_width / width;
boxes_height = screen_height / height;
size = width * height;
content = new uint8_t[size];
for (unsigned int i = 0; i < size; i++)
content[i] = 0;
}
~Map()
{
if (content)
delete[] content;
}
void update(float dt);
bool update_player_pos(unsigned int pos_x, unsigned int pos_y, uint8_t player_id)
{
if (!((pos_x >= 0 && pos_x < width) && (pos_y >= 0 && pos_y < height)))
return false;
if (content[pos_x + pos_y * width])
return false;
content[pos_x + pos_y * width] = player_id;
return true;
}
void draw(SDL_Renderer *renderer);
unsigned int read_distance(unsigned int pos_x, unsigned int pos_y, direction_t reading_direction);
};
#endif | true |
415eff18349c68b74fe2919036d43f615002fe46 | C++ | shribadiger/interviewpreparation | /AlgorithmDesignModel/SelectionSort.cpp | UTF-8 | 474 | 3.546875 | 4 | [] | no_license | #include<iostream>
using namespace std;
//utility function to print the list
void PrintArray(int Array[],int n) {
for(int i=0;i<n;i++){
cout<<"\t"<<Array[i];
}
cout<<endl;
}
int main() {
int Array[] = {9,8,7,6,5,4,3,2,1};
PrintArray(Array,9);
for(int i=0;i<9;i++) {
int min = i;
for(int j=i+1;j<9;j++) {
if(Array[min] >Array[j]) {
min=j;
}
}
int temp = Array[min];
Array[min]=Array[i];
Array[i]=temp;
}
PrintArray(Array,9);
return 0;
}
| true |
6d119c9c5310312f1d3987a3b2bd98c8571aa10d | C++ | Seneca-244200/BTP-Workshops | /WS03/part 2 (DIY)/calorieListTester.cpp | UTF-8 | 4,145 | 3.203125 | 3 | [] | no_license | // Workshop 3:
// Version: 1
// Date: 2023/05
// Author: Fardad Soleimanloo
// Update: Cornel
// Description:
// This file tests the DIY section of your workshop
// Do not modify this code when submitting
/////////////////////////////////////////////
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include "Food.h"
#include "Food.h" // intentional
#include "CalorieList.h"
#include "CalorieList.h" //intentional
int cout = 0; // won't compile if headers don't follow convention
const int c_breakfast = 1; // the food will be consumed at breakfast
const int c_lunch = 2; // the food will be consumed at lunch
const int c_dinner = 3; // the food will be consumed at dinner
const int c_snack = 4; // the food will be consumed as a snack
/// <summary>
/// Prints a string, an integer, and a floating point number to the screen
/// using current formatting options (alignment & precision).
/// </summary>
/// <param name="title"></param>
void checkOutputFormatting(const char* title)
{
std::cout << title << "\n";
std::cout << "==========:==========:==========:==========:==========\n";
// check filling character and alignment for strings
std::cout << '*';
std::cout.width(52);
std::cout << "ABC" << "*\n";
// check formatting for floating point numbers
std::cout << '*';
std::cout.width(52);
std::cout << 1.23456789 << "*\n";
// check formatting for integers
std::cout << '*';
std::cout.width(52);
std::cout << 123 << "*\n";
}
int main()
{
// change the filling character
std::cout.fill('*');
// checking the default formatting options
checkOutputFormatting("T1: Default output formatting options");
sdds::CalorieList theList;
{
// TEST: Too few items in the bill
std::cout << "\n\nT2: An incomplete list ---> # items < capacity\n";
std::cout << "==========:==========:==========:==========:==========\n";
theList.init(6);
theList.add("Cheerios cereal with 2% milk", 170, c_breakfast);
theList.display();
}
{
// after student's code printed some data, check
// if the formatting options are the same or
// were side effects (should not be side effects)
checkOutputFormatting("\n\nT3: Current output formatting options");
std::cout.fill('#');
std::cout.precision(10);
}
{
// TEST: Bad items in the list
std::cout << "\n\nT4: An invalid list ---> bad food items\n";
std::cout << "==========:==========:==========:==========:==========\n";
theList.add(nullptr, 100, c_breakfast);
theList.add("Cheeseburger", 303, c_lunch);
theList.add("Pepsi", 150, 0);
theList.add("Apple", 52, c_snack);
theList.add("Cake", 3001, c_dinner);
theList.display();
theList.reset();
}
{
// TEST: A good list
std::cout << "\n\nT5: A good list\n";
std::cout << "==========:==========:==========:==========:==========\n";
theList.init(9);
theList.add("Cheerios cereal with 2% milk", 170, c_breakfast);
theList.add("Tim Hortons medium coffee double double", 230, c_breakfast);
theList.add("Cheeseburger", 303, c_lunch);
theList.add("French fries", 312, c_lunch);
theList.add("Pepsi", 150, c_lunch);
theList.add("Apple", 52, c_snack);
theList.add("Bread and cheese", 195, c_dinner);
theList.add("Garden salad with dressing", 220, c_dinner);
if (!theList.add("Red wine", 85, c_dinner))
std::cout << "This should not be printed!\n";
if (theList.add("This should not be added", 100, c_dinner))
std::cout << "This should not be printed!\n";
theList.display();
theList.reset();
}
{
// TEST: Dynamic memory allocation
std::cout << "\n\nT6: Dynamic memory allocation\n";
std::cout << "==========:==========:==========:==========:==========\n";
theList.init(25);
for (int i = 0; i < 25; i++)
theList.add("Tim Hortons medium coffee double double", 200 + i * 123 % 17, i % 4 + 1);
const auto& cref = theList;
cref.display(); // if compilation error here, make sure the "display()" is a query.
theList.reset();
}
{
// Cheching the output formatting options again for side effects.
checkOutputFormatting("\n\nT7: Current output formatting options");
std::cout.fill('#');
std::cout.precision(10);
}
return cout;
}
| true |
e470d1cbcee1cc89e32680b35a6eec08f093c0e7 | C++ | grokitgames/giga | /Source/Engine/Resource/ResourceSystem.cpp | UTF-8 | 3,857 | 2.859375 | 3 | [] | no_license |
#include <giga-engine.h>
ResourceSystem::~ResourceSystem() {
}
void ResourceSystem::AddResource(ResourceObject *resource) {
m_resources.AddObject(resource);
}
void ResourceSystem::RemoveResource(ResourceObject* resource) {
m_resources.RemoveObject(resource);
}
void ResourceSystem::Initialize() {
}
ResourceObject* ResourceSystem::LoadResource(std::string filename, std::string type) {
// Check to see if we've loaded this resource
ResourceObject* resource = this->Find(filename);
// If not, try to find and load it
if(resource == 0) {
for(size_t i = 0; i < m_resourceTypes.size(); i++) {
if(m_resourceTypes[i]->name == type) {
resource = m_resourceTypes[i]->createFunc();
break;
}
}
GIGA_ASSERT(resource != 0, "Resource type not found.");
// First, get the full path by searching out search paths
std::string fullpath = FindResourcePath(filename);
if(fullpath.empty()) {
ErrorSystem::Process(new Error(ERROR_WARN, (char*)"Unable to locate resource file", filename));
return(0);
}
// Create a resource and load
Resource* rs = new Resource();
rs->SetType(type);
rs->SetFilename(fullpath);
rs->Load();
resource->m_resource = rs;
resource->ProcessData();
AddResource(resource);
}
return(resource);
}
ResourceObject* ResourceSystem::Find(std::string name) {
// See if we've already loaded it
std::vector<ResourceObject*> resources = m_resources.GetList();
std::vector<ResourceObject*>::iterator i = resources.begin();
for (i; i != resources.end(); i++) {
if((*i)->m_resource->GetFilename() == name) {
return((*i));
}
}
return(0);
}
void ResourceSystem::AddSearchPath(std::string path) {
m_paths.push_back(path);
}
std::string ResourceSystem::FindResourcePath(std::string filename) {
std::string ret;
// First try to open the file with the path it's on now
File* f = new File;
if(f->Open(filename, FILEMODE_READ | FILEMODE_BINARY)) {
f->Close();
ret = filename;
delete f;
return(ret);
}
delete f;
// Loop through our list of files, try to open this one
std::vector<std::string>::iterator i = m_paths.begin();
for(; i != m_paths.end(); i++) {
File* f = new File;
std::string fn(*i);
fn += "/";
fn += filename;
if(f->Open(fn, FILEMODE_READ | FILEMODE_BINARY)) {
f->Close();
delete f;
return(fn);
}
f->Close();
delete f;
}
return(ret);
}
void ResourceSystem::Update(double delta) {
// Get current timestamp
DateTime* current = DateTime::GetCurrent();
time_t timestamp = current->GetTimestamp();
std::vector<ResourceObject*> resources = m_resources.GetList();
std::vector<ResourceObject*>::iterator i = resources.begin();
for (i; i != resources.end(); i++) {
Resource* resource = (*i)->m_resource;
if(timestamp - resource->GetLastAccess() > RESOURCE_DELETION_TIME) {
resource->Unload();
}
}
delete current;
}
Variant* ResourceSystem::LoadResource(Variant* object, int argc, Variant** argv) {
GIGA_ASSERT(argc == 1, "LoadResource expects two arguments.");
GIGA_ASSERT(argv[0]->IsString(), "First parameter should be a filename string.");
GIGA_ASSERT(argv[0]->IsString(), "Second parameter should be a class name string.");
ResourceSystem* resourceSystem = GetSystem<ResourceSystem>();
return(new Variant(resourceSystem->LoadResource(argv[0]->AsString(), argv[1]->AsString())));
}
| true |
fd53805236cfed2886b006af8c1b6077594ab1d2 | C++ | Sourabh-1309/Data-Structure-Course | /Trees/Search_BST.cpp | UTF-8 | 1,297 | 3.71875 | 4 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
struct node{
int data;
struct node *left;
struct node *right;
}*root = NULL;
struct node *createnode(int val){
struct node *temp = new node;
temp->data = val;
temp->left = temp->right = NULL;
return temp;
}
struct node *insertnode(struct node *node, int val){
if (node==NULL) return createnode(val);
else if(val < node->data)
node->left = insertnode(node->left, val);
else if(val > node->data)
node->right = insertnode(node->right, val);
return node;
}
void Search(node *root, int d) {
int depth = 0;
node *temp = new node;
temp = root;
while(temp != NULL) {
depth++;
if(temp->data == d) {
cout<<"\nitem found at depth: "<<depth;
return;
} else if(temp->data > d)
temp = temp->left;
else
temp = temp->right;
}
cout<<"\n item not found";
return;
}
int main(){
int n,no,r,s;
cout<<"How many nodes you want to enter? ";
cin>>no;
cout<<"Enter the root element: ";
cin>>r;
root = insertnode(root, r);
for(int i = 0; i < no - 1 ; ++i){
cout<<"Enter the node: ";
cin>>n;
insertnode(root,n);
}
cout<<"\nEnter the Element to be searched: ";
cin>>s;
Search(root, n);
}
| true |
0dbe2ca41d3dbd4dfe9590af85acc9605f282c10 | C++ | wcybxzj/cplusplus_www | /1.tan_c++/6.pointer/2.quote.cpp | UTF-8 | 814 | 3.65625 | 4 | [] | no_license | #include <iostream>
using namespace std;
//声明一个引用后不能再使之成为另外一个变量的引用
void test1()
{
int a1, a2;
int &b = a1;
//int &b = a2;//error
}
//数组不能被引用
void test2()
{
int a[5];
//int &b[5]= &a;//error
}
//可以建立引用的引用
void test3()
{
int a=3;
int &b = a;
int &c = b;
//a=100;
cout << c << endl;
}
//不能建立指向引用的指针
void test4()
{
int a =3;
int &b =a;
//int *p = b;//error
//cout << *p << endl;
}
//可以取引用的地址
void test5()
{
int a=123;
int &b =a;
int *pt;
pt = &b;
cout << *pt;
}
void test6()
{
int a=123;
int &b = a;//b引用a
cout << &b <<endl;//打印b的地址
}
int main(int argc, const char *argv[])
{
//test1();
//test2();
//test3();
//test4();
//test5();
test6();
return 0;
}
| true |
804575470e3600b38450ac03a6e6bff7add56b76 | C++ | piotrekvs/AGH | /archive/Sem1/Games/game8vs8.hpp | UTF-8 | 11,135 | 2.890625 | 3 | [] | no_license | #include "userInterface.hpp"
#include "jumpingPawnsFunctions.hpp"
void StartField8vs8(char GameField[8][8], pawnsCordinates Pawns[16]) {
for(int r = 0; r < 8; r++) {
for(int c = 0; c < 8; c++) {
GameField[r][c] = 'N';
}
}
pawnsCordinates initial;
for(int i = 0; i < 8; i++){
GameField[6 + i % 2][i] = 'B'; initial.x = 6 + i % 2; initial.y = i;
Pawns[i+8] = initial;
GameField[0 + i % 2][i] = 'W'; initial.x = 0 + i % 2;
Pawns[i] = initial;
}
}
void ChangePawns(pawnsCordinates Pawns[16], coordinates move) {
for(int i = 0; i < 16; i++) {
if(Pawns[i].x == move.xS and Pawns[i].y == move.yS) {
Pawns[i].x = move.xD; Pawns[i].y = move.yD; return;
}
}
}
void IsWinner(char GameField[8][8], gameData &dataForGame) {
if(dataForGame.whoseMove < 24) {
dataForGame.endFlag = true;
}
bool blackWinFlag = true, whiteWinFlag = true;
for(int w = 0; w < 8; w++) {
if(GameField[6 + w % 2][w] != 'W') whiteWinFlag = false;
if(GameField[0 + w % 2][w] != 'B') blackWinFlag = false;
}
if(blackWinFlag and whiteWinFlag) {
dataForGame.endFlag = false; dataForGame.whoWins = "DRAW!";
} else if(whiteWinFlag) {
dataForGame.endFlag = false; dataForGame.whoWins = "White WIN!";
} else if(blackWinFlag) {
dataForGame.endFlag = false; dataForGame.whoWins = "Black WIN!";
}
}
//PLAYER MOVE GROUP
bool IsPossibleToMoveForward(char GameField[8][8], pawnsCordinates Pawns[16], int whoseMove, string &hint) {
string source = "", destination = "";
if(whoseMove % 2 == 0) { /*for white pawns*/
for(int i = 0; i < 8; i++) {
if(/*not necessary to check if x >= 0*/ Pawns[i].x + 1 < 8 and (Pawns[i].y - 1 >= 0 and GameField[Pawns[i].x + 1][Pawns[i].y - 1] == 'N')) {
hint = "Possible move: " + CoordinatesTranslationToString(Pawns[i].x, Pawns[i].y) + " --> " + CoordinatesTranslationToString(Pawns[i].x + 1, Pawns[i].y - 1);
return true;
}
if(Pawns[i].x + 1 < 8 and (Pawns[i].y + 1 < 8 and GameField[Pawns[i].x + 1][Pawns[i].y + 1] == 'N')) {
hint = "Possible move: " + CoordinatesTranslationToString(Pawns[i].x, Pawns[i].y) + " --> " + CoordinatesTranslationToString(Pawns[i].x + 1, Pawns[i].y + 1);
return true;
}
if(/*not necessary to check if x >= 0*/ Pawns[i].x + 2 < 8 and (Pawns[i].y - 2 >= 0 and GameField[Pawns[i].x + 2][Pawns[i].y - 2] == 'N' and GameField[Pawns[i].x + 1][Pawns[i].y - 1] != 'N')) {
hint = "Possible move: " + CoordinatesTranslationToString(Pawns[i].x, Pawns[i].y) + " --> " + CoordinatesTranslationToString(Pawns[i].x + 2, Pawns[i].y - 2);
return true;
}
if(Pawns[i].x + 2 < 8 and (Pawns[i].y + 2 < 8 and GameField[Pawns[i].x + 2][Pawns[i].y + 2] == 'N' and GameField[Pawns[i].x + 1][Pawns[i].y + 1] != 'N')) {
hint = "Possible move: " + CoordinatesTranslationToString(Pawns[i].x, Pawns[i].y) + " --> " + CoordinatesTranslationToString(Pawns[i].x + 2, Pawns[i].y + 2);
return true;
}
}
hint = "There is no possible forward move. Try back ...";
return false;
} else { /*for black pawns*/
for(int i = 8; i < 16; i++) {
if(/*not necessary to check if x < 8*/ Pawns[i].x - 1 >= 0 and (Pawns[i].y - 1 >= 0 and GameField[Pawns[i].x - 1][Pawns[i].y - 1] == 'N')) {
hint = "Possible move: " + CoordinatesTranslationToString(Pawns[i].x, Pawns[i].y) + " --> " + CoordinatesTranslationToString(Pawns[i].x - 1, Pawns[i].y - 1);
return true;
}
if(Pawns[i].x - 1 >= 0 and (Pawns[i].y + 1 < 8 and GameField[Pawns[i].x - 1][Pawns[i].y + 1] == 'N')) {
hint = "Possible move: " + CoordinatesTranslationToString(Pawns[i].x, Pawns[i].y) + " --> " + CoordinatesTranslationToString(Pawns[i].x - 1, Pawns[i].y + 1);
return true;
}
if(/*not necessary to check if x < 8*/ Pawns[i].x - 2 >= 0 and (Pawns[i].y - 2 >= 0 and GameField[Pawns[i].x - 2][Pawns[i].y - 2] == 'N' and GameField[Pawns[i].x - 1][Pawns[i].y - 1] != 'N')) {
hint = "Possible move: " + CoordinatesTranslationToString(Pawns[i].x, Pawns[i].y) + " --> " + CoordinatesTranslationToString(Pawns[i].x - 2, Pawns[i].y - 2);
return true;
}
if(Pawns[i].x - 2 >= 0 and (Pawns[i].y + 2 < 8 and GameField[Pawns[i].x - 2][Pawns[i].y + 2] == 'N' and GameField[Pawns[i].x - 1][Pawns[i].y + 1] != 'N')) {
hint = "Possible move: " + CoordinatesTranslationToString(Pawns[i].x, Pawns[i].y) + " --> " + CoordinatesTranslationToString(Pawns[i].x - 2, Pawns[i].y + 2);
return true;
}
}
hint = "There is no possible forward move. Try back ...";
return false;
}
}
bool BackMovePossibility(char GameField[8][8], int xS, int yS, int xD, int yD, int whoseMove) {
if(whoseMove % 2 == 0) {
if(xS == xD + 1 and (yS == yD + 1 or yS == yD - 1)) return true;
} else {
if(xS == xD - 1 and (yS == yD + 1 or yS == yD - 1)) return true;
}
}
bool RecursiveJumpsPossibilityWhite(char GameField[8][8], int xS, int yS, int xD, int yD, bool &jumpPossibiilityFlag, int level) {
/* cout << "start recursive" << endl; */
if(jumpPossibiilityFlag) {/* cout << "jumpPossFlag = true" << endl; */ return true;}
//if(xS == xD and yS != yD) {cout << "fuck false" << endl; return false;}
if(xS == xD and yS == yD) {jumpPossibiilityFlag = true; /* cout << "jumpPossFlag change to true" << endl;*/ return true;}
if(/*only addition - not necessary to check limes infimum*/xS+2<8 and yS+2<8 and GameField[xS+2][yS+2] == 'N' and GameField[xS+1][yS+1] != 'N') {/*cout << "path1" << endl;*/ return RecursiveJumpsPossibilityWhite(GameField, xS+2, yS+2, xD, yD, jumpPossibiilityFlag, level+1);}
if(xS+2<8 and yS-2>=0 and GameField[xS+2][yS-2] == 'N' and GameField[xS+1][yS-1] != 'N') {/*cout << "path2" << endl;*/ return RecursiveJumpsPossibilityWhite(GameField, xS+2, yS-2, xD, yD, jumpPossibiilityFlag, level+1);}
if(!jumpPossibiilityFlag and level == 0) {/*cout << "return false" << endl;*/ return false;}
}
bool RecursiveJumpsPossibilityBlack(char GameField[8][8], int xS, int yS, int xD, int yD, bool &jumpPossibiilityFlag, int level) {
/*cout << "start recursive" << endl;*/
if(jumpPossibiilityFlag) {/*cout << "jumpPossFlag = true" << endl;*/ return true;}
//if(xS == xD and yS != yD) {cout << "fuck false" << endl; return false;}
if(xS == xD and yS == yD) {jumpPossibiilityFlag = true; /*cout << "jumpPossFlag change to true" << endl;*/ return true;}
if(xS-2>=0 and yS+2<8 and GameField[xS-2][yS+2] == 'N' and GameField[xS-1][yS+1] != 'N') {/*cout << "path1" << endl;*/ return RecursiveJumpsPossibilityBlack(GameField, xS-2, yS-2, xD, yD, jumpPossibiilityFlag, level+1);}
if(xS-2>=0 and yS-2>=0 and GameField[xS-2][yS-2] == 'N' and GameField[xS-1][yS-1] != 'N') {/*cout << "path2" << endl;*/ return RecursiveJumpsPossibilityBlack(GameField, xS-2, yS+2, xD, yD, jumpPossibiilityFlag, level+1);}
if(!jumpPossibiilityFlag and level == 0) {/*cout << "return false" << endl;*/ return false;}
}
bool IsMovePossible(char GameField[8][8], pawnsCordinates Pawns[16], int whoseMove, coordinates move, string &hint) { //input ONLY correct coordinates [A-H] and [1-8]
bool jumpPossibiilityFlag = false; int level = 0;
if(move.xS % 2 != move.yS % 2 or move.xD % 2 != move.yD % 2 /*field from or to is not in game*/) {cout << "field from or to is not in game" << '\n'; return false;}
if(GameField[move.xD][move.yD] != 'N' or GameField[move.xS][move.yS] == 'N' /*move to not empty field or move from empty field*/) {cout << "move to not empty field or move from empty field" << '\n'; return false;}
if(GameField[move.xS][move.yS] == 'W' and whoseMove % 2 != 0 /*black try to move white*/) {cout << "black try to move white" << '\n'; return false;}
if(GameField[move.xS][move.yS] == 'B' and whoseMove % 2 != 1 /*white try to move black*/) {cout << "white try to move black" << '\n'; return false;}
if((whoseMove % 2 == 0 and move.xS == move.xD) or (whoseMove % 2 == 1 and move.xS == move.xD)) {cout << "try not move" << '\n'; return false;}
if(IsPossibleToMoveForward(GameField, Pawns, whoseMove, hint)) {
if((whoseMove % 2 == 0 and move.xS >= move.xD) or (whoseMove % 2 == 1 and move.xS <= move.xD)) {cout << "try not back" << '\n'; return false;}
if((move.xD == move.xS + 1 and (move.yD == move.yS + 1 or move.yD == move.yS - 1)) /*one field move for white and one field move for black*/
or (move.xD == move.xS - 1 and (move.yD == move.yS + 1 or move.yD == move.yS - 1))) return true;
if(move.xS % 2 == move.xD % 2 and move.yS % 2 == move.yD % 2 and whoseMove % 2 == 0) {
return RecursiveJumpsPossibilityWhite(GameField, move.xS, move.yS, move.xD, move.yD, jumpPossibiilityFlag, level);
} else if(move.xS % 2 == move.xD % 2 and move.yS % 2 == move.yD % 2 and whoseMove % 2 == 1) {
return RecursiveJumpsPossibilityBlack(GameField, move.xS, move.yS, move.xD, move.yD, jumpPossibiilityFlag, level);
}
} else {
return BackMovePossibility(GameField, move.xS, move.yS, move.xD, move.yD, whoseMove);
}
}
void PlayerMove(char GameField[8][8], pawnsCordinates Pawns[16], int whoseMove, bool &endGameFlag) {
coordinates move; int tryMoves = 0; string hint = "";
bool moveDoneFlag = true;
while(moveDoneFlag and endGameFlag) {
PrintGameField(GameField);
WhoseMove(whoseMove);
move = PlayerInput(endGameFlag);
IsPossibleToMoveForward(GameField, Pawns, whoseMove, hint);
if(IsMovePossible(GameField, Pawns, whoseMove, move, hint)) {
GameField[move.xS][move.yS] = 'N';
ChangePawns(Pawns, move);
if(whoseMove % 2 == 0) {GameField[move.xD][move.yD] = 'W';}
else {GameField[move.xD][move.yD] = 'B';}
moveDoneFlag = false;
}
if(tryMoves >= 3) cout << hint << endl; /*hint after third mistake*/
tryMoves++; cout << '\n';
}
}
//END PLAYER MOVE GROUP
int Game8vs8() {
char GameField[8][8];
pawnsCordinates Pawns[16];
bool endGameflag = true;
gameData dataForGame;
dataForGame.whoseMove = 0;
dataForGame.endFlag = true;
dataForGame.whoWins = "";
StartField8vs8(GameField, Pawns);
// testWinGame(GameField, Pawns);
// testPrintGameField(GameField);
// testPrintPawns(Pawns);
while(dataForGame.endFlag and endGameflag) {
PlayerMove(GameField, Pawns, dataForGame.whoseMove, endGameflag );
IsWinner(GameField, dataForGame);
if(!dataForGame.endFlag) cout << dataForGame.whoWins << '\n' << endl;
// testPrintPawns(Pawns);
dataForGame.whoseMove++;
}
return 0;
}
| true |
95e83b167c30b4e1f4bd1806ab73fde06534446e | C++ | caizhixiang/zikao | /C++/程序第2-5章/3.4 函数重载 -3.cpp | UTF-8 | 187 | 2.859375 | 3 | [
"MIT"
] | permissive | #include <iostream>
using namespace std;
int add(int m1=0,int m2=0,int m3=0,int m4=0)
{return m1 + m2 + m3 + m4;}
void main( )
{cout<<add(1,3)<<","<<add(1,3,5)<<","<<add(1,3,5,7)<<endl;} | true |
bfb01e70187e448e6b6e00d4fe39f381ac72a585 | C++ | taijihua/Udacity_Projects | /Project5_Extended_Kalman_Filter/src/kalman_filter.cpp | UTF-8 | 1,691 | 2.734375 | 3 | [
"MIT"
] | permissive | #include "kalman_filter.h"
using Eigen::MatrixXd;
using Eigen::VectorXd;
// Please note that the Eigen library does not initialize
// VectorXd or MatrixXd objects with zeros upon creation.
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
*/
x_ = F_*x_;
P_ = F_*P_*F_.transpose()+Q_;
}
void KalmanFilter::Update(const VectorXd &z) {
/**
TODO:
* update the state by using Kalman Filter equations
*/
Eigen::VectorXd y;
y = z-H_*x_;
Eigen::MatrixXd s;
s = H_*P_*H_.transpose()+R_;
Eigen::MatrixXd kalmanGain;
kalmanGain = P_*H_.transpose()*s.inverse();
x_ = x_ + (kalmanGain*y);
Eigen::MatrixXd I;
I = MatrixXd::Identity(P_.rows(), P_.cols());
P_ = (I-kalmanGain*H_)*P_;
}
void KalmanFilter::UpdateEKF(const VectorXd &z, const VectorXd &PredictedMeasurement) {
/**
TODO:
* update the state by using Extended Kalman Filter equations
*/
Eigen::VectorXd y;
//y = z-H_*x_;
y = z-PredictedMeasurement;
if(y(1)<-3.1415926)
y(1) += 3.1415926*2;
if(y(1)>3.1415926)
y(1) -= 3.1415926*2;
// the following are same as regular KF, with the H_ being Jacobian matrix for linearity approximation.
Eigen::MatrixXd s;
s = H_*P_*H_.transpose()+R_;
Eigen::MatrixXd kalmanGain;
kalmanGain = P_*H_.transpose()*s.inverse();
x_ = x_ + (kalmanGain*y);
Eigen::MatrixXd I;
I = MatrixXd::Identity(P_.rows(), P_.cols());
P_ = (I-kalmanGain*H_)*P_;
}
| true |
03db8c742e9b848441aed07d912bb822f48b1962 | C++ | bgporter/JuceRpc | /Source/RpcException.h | UTF-8 | 890 | 2.65625 | 3 | [] | no_license | /*
Copyright 2016 Art & Logic Software Development.
*/
#ifndef h_RpcException
#define h_RpcException
#include "../JuceLibraryCode/JuceHeader.h"
class RpcException
{
public:
RpcException(uint32 code) : fCode(code) {};
// use default ctor, op=, copy ctor.
//
uint32 GetCode() const {return fCode;};
void AppendExtraData(const var& v) { fExtraData.add(v);};
int GetExtraDataSize() const { return fExtraData.size(); };
var GetExtraData(const int index) const
{
if (index < this->GetExtraDataSize())
{
return fExtraData.getReference(index);
}
else
{
return var();
}
}
private:
uint32 fCode;
// we can pass in additional data values as JUCE var objects if that's useful.
// They'll be added to the RPC message and can be unpacked at the other end.
Array<var> fExtraData;
};
#endif | true |
c2d35b1f62d83d001988742a8291f607bf20fe66 | C++ | alexandraback/datacollection | /solutions_5669245564223488_0/C++/Arorua/train.cc | UTF-8 | 727 | 2.875 | 3 | [] | no_license | #include <string>
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
bool validate(string s)
{
bool t[256] = {0};
char last = 0;
for (int i = 0; i < s.size(); ++i)
if (s[i] != last) {
if (t[s[i]]) return false;
last = s[i];
t[last] = 1;
}
return true;
}
int proc(int k)
{
int m;
cin >> m;
vector<string> v;
int a[20];
for(int i = 0; i < m; i++) {
a[i] = i;
string s;
cin >> s;
v.push_back(s);
}
int ans = 0;
do {
string s;
for (int i = 0; i < m; ++i) s += v[a[i]];
if (validate(s)) ans += 1;
} while(next_permutation(a, a + m));
cout << "Case #" << k << ": " << ans << endl;
}
int main()
{
int k;
cin >> k;
for (int i = 1; i <= k; ++i) proc(i);
}
| true |
82160b04d8cb63d7de9ed87e3fd0dbe94d2f037b | C++ | capagot/swpathtracer | /acceleration/sbvh_node.h | UTF-8 | 1,733 | 2.875 | 3 | [
"MIT"
] | permissive | #ifndef ACCELERATION_SBVH_NODE_H
#define ACCELERATION_SBVH_NODE_H
#include <algorithm>
#include <memory>
#include <vector>
#include "primitive_ref.h"
class SBVHNode {
public:
struct Comparator {
static bool sortInX(const PrimitiveRef& a, const PrimitiveRef& b) {
return a.poly_centroid_.x < b.poly_centroid_.x;
}
static bool sortInY(const PrimitiveRef& a, const PrimitiveRef& b) {
return a.poly_centroid_.y < b.poly_centroid_.y;
}
static bool sortInZ(const PrimitiveRef& a, const PrimitiveRef& b) {
return a.poly_centroid_.z < b.poly_centroid_.z;
}
};
void sortReferences(int axis) {
switch (axis) {
case 0:
std::sort(primitive_ref_list_->begin(), primitive_ref_list_->end(), Comparator::sortInX);
break;
case 1:
std::sort(primitive_ref_list_->begin(), primitive_ref_list_->end(), Comparator::sortInY);
break;
case 2:
std::sort(primitive_ref_list_->begin(), primitive_ref_list_->end(), Comparator::sortInZ);
break;
}
}
inline std::size_t getNumReferences() const {
return primitive_ref_list_->size();
}
inline PrimitiveRef& getReferenceAt(unsigned long int id) const {
return (*primitive_ref_list_)[id];
}
inline unsigned int getActualPrimitiveId(unsigned long int id) const {
return (*primitive_ref_list_)[id].id_;
}
std::unique_ptr<std::vector<PrimitiveRef>> primitive_ref_list_;
AABB aabb_;
std::unique_ptr<SBVHNode> left_node_;
std::unique_ptr<SBVHNode> right_node_;
};
#endif // ACCELERATION_SBVH_NODE_H
| true |
0da7965b5d71cc3c34f841b196608f11d53e971c | C++ | sunyinkai/ACM_ICPC | /FutherTraining/Futher_Training10_网络流/b.cpp | UTF-8 | 3,364 | 2.65625 | 3 | [] | no_license | //枚举割边在残留图上增广
//important:割边集合:跑完最大流后vis[e.from]=1&&vis[e.to]=0&&e.cap>0
#include<cstdio>
#include<cstring>
#include<vector>
#include<queue>
#include<algorithm>
using namespace std;
const int INF=2e9+11;
const int MAXN=107;
struct edge{ int from,to,cap,flow; };
vector<int>G[MAXN];
vector<edge>es;
void addEdge(int a,int b,int c){
es.push_back(edge{a,b,c,0});
es.push_back(edge{b,a,0,0});
int m=es.size();
G[a].push_back(m-2);//以a为顶点的第i条边的编号
G[b].push_back(m-1);
}
bool visit[MAXN];
int d[MAXN];
int cur[MAXN];
int s,t;
bool bfs(){//构造层次图
memset(visit,0,sizeof(visit));
queue<int>q;
q.push(s);
d[s]=0;
visit[s]=1;
while(!q.empty()){
int x=q.front();q.pop();
for(int i=0;i<G[x].size();++i){
edge &e=es[G[x][i]];
if(!visit[e.to]&&e.cap>e.flow){//没有被访问过且流量还有剩余
visit[e.to]=1;
d[e.to]=d[x]+1;
q.push(e.to);
}
}
}
return visit[t];//终点是否被参观过
}
int dfs(int x,int a){//从s->x的最小剩余流量
if(x==t||a==0)return a;
int flow=0,f;
for(int &i=cur[x];i<G[x].size();++i){
edge& e=es[G[x][i]];
if(d[x]+1==d[e.to]&&(f=dfs(e.to,min(a,e.cap-e.flow)))>0){
e.flow+=f;
es[G[x][i]^1].flow-=f;
flow+=f;
a-=f;//当前弧优化
if(a==0)break;
}
}
return flow;
}
int Maxflow(int s,int t){
int flow=0;
while(bfs()){//每次完成后最短增广路长度单调递
memset(cur,0,sizeof(cur));
flow+=dfs(s,INF);
}
return flow;
}
int N,E,C;
vector<int>Gtmp[MAXN];
vector<edge>estmp;
void copy(){
estmp.clear();
for(int i=0;i<=N;++i)Gtmp[i].clear();
int len=es.size();
for(int i=0;i<len;++i)estmp.push_back(es[i]);
for(int i=0;i<=N;++i){
for(int j=0;j<G[i].size();++j){
Gtmp[i].push_back(G[i][j]);
}
}
}
int top;
struct node{
int u,v;
bool operator<(const node&other)const{
return u<other.u||(u==other.u&&v<other.v);
}
}no[MAXN*MAXN];
bool solve(int k){
int has=k;//hasget
copy();
int len=estmp.size();
top=0;
bool hasAns=false;
for(int k=0;k<len;k+=2){//枚举加边
if(estmp[k].cap==estmp[k].flow){
for(int i=0;i<=N;++i)G[i].clear();
es.clear();
for(int i=0;i<len;++i){
if(i!=k)
es.push_back(estmp[i]);//边的信息
else{
es.push_back({estmp[i].from,estmp[i].to,INF,estmp[i].flow});
}
// printf("%d->%d c=%d f=%d\n",es[i].from,es[i].to,es[i].cap,es[i].flow);
}
for(int i=0;i<=N;++i){//图的连接信息
for(int j=0;j<Gtmp[i].size();++j){
G[i].push_back(Gtmp[i][j]);
}
}
// printf("u=%d,v=%d\n",u,v);
int val=Maxflow(s,t);
if(has+val>=C){
//printf("hasval=%d\n",val);
no[top].u=estmp[k].from;no[top++].v=estmp[k].to;
hasAns=true;
}
}
}
return hasAns;
}
int main(){
int test=1;
//freopen("in.txt","r",stdin);
//freopen("out.txt","w",stdout);
while(~scanf("%d%d%d",&N,&E,&C)&&N+E+C){
es.clear();
for(int i=0;i<MAXN;++i)G[i].clear();
for(int i=0;i<E;++i){
int a,b,c;scanf("%d%d%d",&a,&b,&c);
addEdge(a,b,c);
}
s=1,t=N;
int val=Maxflow(s,t);
printf("Case %d: ",test);
++test;
if(val>=C){
printf("possible\n");
}else if(solve(val)){
sort(no,no+top);
printf("possible option:");
for(int i=0;i<top;++i){
if(i!=0)printf(",");
printf("(%d,%d)",no[i].u,no[i].v);
}
printf("\n");
}else{
printf("not possible\n");
}
}
return 0;
}
| true |
e47a79629555ae8710cc658276ec2199ead1fbe6 | C++ | SANDRAKUMI/PrivacyGuard | /DataConsumer/App/operations.cpp | UTF-8 | 2,743 | 3.03125 | 3 | [
"MIT"
] | permissive | #include "operations.h"
#include <stdio.h>
#include <stdlib.h>
/* Send a transaction invoking the request function of DO or DB's contract */
// payment unit: ether
// For DO's contract: [range_start, range_end] refers to the range of data files
// For DB's contract: [range_start, range_end] refers to the range of DOs
int request_Contract(char* ContractAddress, int range_start, int range_end, int operation, double payment)
{
int ret = 0;
char buffer1[1000], nodejs_arg[1000];
/* Six fields of a naked transaction */
long gas_price = 1000000000;
long gasLimit = 6000000;
char to[100];
long long int value = payment * 1000 * 1e15; // unit: wei (1 ether = 1e18 wei)
char data[500];
sprintf(to, "0x%s", ContractAddress);
sprintf(data, "0xad352967%064x%064x%064x", range_start, range_end, operation);
/* Get the digest (RLP_hash) of the nake transaction */
sprintf(nodejs_arg, "%ld %ld %s %lld %s", gas_price, gasLimit, to, value, data);
sprintf(buffer1, "node App/txSendDirectly.js %s", nodejs_arg);
printf("%s\n", buffer1);
ret = system(buffer1);
return ret;
}
/* Send a transaction invoking the cancel function of DO or DB's contract */
int cancelTransaction(char* contract_addr)
{
int ret = 0;
char buffer1[1000], nodejs_arg[1000];
/* Six fields of a naked transaction */
long gas_price = 1000000000; // unit: wei
long gasLimit = 500000;
char to[100];
long value = 0; // unit: wei
char data[500];
sprintf(to, "0x%s", contract_addr);
sprintf(data, "0xea8a1af0");
/* Get the digest (RLP_hash) of the nake transaction */
sprintf(nodejs_arg, "%ld %ld %s %ld %s", gas_price, gasLimit, to, value, data);
sprintf(buffer1, "node App/txSendDirectly.js %s", nodejs_arg);
printf("%s\n", buffer1);
ret = system(buffer1);
return ret;
}
/* Convert uint8_t array to char array like this: {0x12, 0xde} ==> "12de" */
void u_array2c_array(char *c_arr, uint8_t *u_arr, int len)
{
int i;
for(i = 0; i < len; i++)
{
sprintf(&c_arr[2*i], "%02x", u_arr[i]);
}
}
/* Convert string to uint8_t array like this: "12de" ==> {0x12, 0xde} */
// len: size of the output u_arr (Bytes)
void string2u_array(uint8_t *u_arr, std::string str, int len)
{
int i;
char c1, c2, high, low;
for(i = 0; i < len; i++)
{
c1 = str[2*i];
c2 = str[2*i+1];
if(c1 < 0x40) // number char
{
high = c1 - 48;
}
else
{
high = c1 - 87;
}
if(c2 < 0x40) // number char
{
low = c2 - 48;
}
else
{
low = c2 - 87;
}
u_arr[i] = high * 16 + low;
}
} | true |
028a908a07f1ad66ff287d639f4cd0dfb33be7bf | C++ | Ciubix8513/Vulkan-engine | /Math/Vector2.h | UTF-8 | 1,083 | 2.609375 | 3 | [] | no_license | #pragma once
#ifndef _VECTOR2_H_
#define _VECTOR2_H_
#include <math.h>
#include <exception>
#include <DirectXMath.h>
//using namespace std;
namespace EngineMath
{
#define Deg2Rad 0.0174532925f
#define PI (double)3.1415926535897932384626433832795f
using namespace EngineMath;
struct Vector2
{
public:
#pragma region VectorCreation + Consts
Vector2();
Vector2(float NewX, float NewY);
static Vector2 Up();
static Vector2 Down();
static Vector2 Right();
static Vector2 Left();
static Vector2 Zero();
#pragma endregion
#pragma region Functions
float Length();
static float Length(Vector2& v);
Vector2 Normalized();
static void Normalize(Vector2& v);
void Normalize();
static float DotProduct(Vector2 a, Vector2 b);
#pragma endregion
#pragma region operators
Vector2 operator+(Vector2 v);
Vector2 operator-(Vector2 v);
Vector2 operator*(float c);
Vector2 operator/(float c);
void operator+=(Vector2 v);
void operator-=(Vector2 v);
void operator*=(float c);
void operator/=(float c);
#pragma endregion
float x,y;
};
};
#endif
| true |
a1907167df60721ad1666d20ca77bac4825e180a | C++ | travisdowns/zero-fill-bench | /metric-column.hpp | UTF-8 | 838 | 3.171875 | 3 | [] | no_license | #ifndef METRIC_COLUMN_H_
#define METRIC_COLUMN_H_
#include "stamp.hpp"
#include <string>
/**
* A Column object represents a thing which knows how to print a column of data.
* It injects what it wants into the StampConfig object and then gets it back out after.
*
* Templated on the result type R.
*/
template <typename R>
class ColumnT {
public:
private:
const char* header;
protected:
public:
ColumnT(const char* heading) : header{heading} {}
virtual ~ColumnT() {}
virtual std::string get_header() const { return header; }
/* subclasses can implement this to modify the StampConfig as needed in order to get the values needed
for this column */
virtual void update_config(StampConfig& sc) const {}
std::string get_value(const R& result) const = 0;
};
#endif // #include METRIC_COLUMN_H_ | true |
69f3863c250bdb8b00f98df767e10c611a3cc15a | C++ | peace-shillong/Computer-Applications-Theory-and-Practical-Part-1 | /MCA/2nd Sem/Programs/OOPD/Worksheet 2/POWER.CPP | UTF-8 | 536 | 3.453125 | 3 | [
"MIT",
"LicenseRef-scancode-proprietary-license"
] | permissive | #include<iostream.h>
#include<conio.h>
double power(double m,int n=2);
void main()
{
int n;
double m;
clrscr();
cout<<endl<<"Program to find a number raised to another number"<<endl;
cout<<"Enter the value of m ";
cin>>m;
cout<<"Enter the value of n "<<endl<<"Enter a negative number to SKIP ";
cin>>n;
if(n>=0)
cout<<endl<<power(m,n);
else
cout<<endl<<power(m);
cout<<"\n";
getch();
}
double power(double m,int n){
double mn,pow=1;
int nn;
mn=m;
nn=n;
for(int i=0;i<nn;i++){
pow=pow*mn;
}
return pow;
} | true |
e72cbbff562941a28fc008ee617550a81659c40d | C++ | fwsGonzo/LiveUpdate | /verify.cpp | UTF-8 | 1,540 | 2.890625 | 3 | [] | no_license | /**
* Master thesis
* by Alf-Andre Walla 2016-2017
*
**/
#include <cassert>
#include <cstdio>
#include <cstdlib>
#include <unistd.h>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <util/crc32.hpp>
int main(void)
{
uint32_t x = CRC32_BEGIN();
for (int i = 0; i < 1000; i++) {
int len = 4096;
auto* buf = new char[len];
memset(buf, 'A', len);
x = crc32(x, buf, len);
delete[] buf;
}
const uint32_t FINAL_CRC = CRC32_VALUE(x);
printf("CRC32 should be: %08x\n", FINAL_CRC);
const uint16_t PORT = 6667;
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in serv_addr;
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
inet_pton(AF_INET, "10.0.0.42", &serv_addr.sin_addr);
serv_addr.sin_port = htons(PORT);
if (connect(sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0)
perror("ERROR connecting");
uint32_t crc = 0xFFFFFFFF;
while (true)
{
char buffer[4096];
int n = read(sockfd, buffer, sizeof(buffer));
if (n < 0) perror("ERROR reading from socket");
if (n == 0) break;
// update CRC32 partially
crc = crc32(crc, buffer, n);
if (~crc == FINAL_CRC)
break;
else
printf("Partial CRC: %08x\n", ~crc);
}
crc = ~crc;
printf("Final CRC: %08x vs %08x\n", crc, FINAL_CRC);
close(sockfd);
assert(crc == FINAL_CRC);
return 0;
}
| true |
73f9a0046e7b34ecc65aa0884cda27dc2297dbe2 | C++ | llenroc/CP | /LeetCode/tags/array/longest-continuous-increasing-subsequence.cpp | UTF-8 | 578 | 2.515625 | 3 | [] | no_license |
#include<bits/stdc++.h>
using namespace std;
#define endl '\n'
#define INF LLONG_MAX/4
#define MOD 1e9+7
#define DEBUG(x) cerr << #x << " is " << (x) << endl;
class Solution {
public:
int findLengthOfLCIS(vector<int>& nums) {
int n=nums.size();
if(n==0) return 0;
int curr=1, ans=1;
for(int i=1;i<n;i++) {
if(nums[i-1]<nums[i]) {
curr++;
ans = max(ans, curr);
} else {
ans = max(ans, curr);
curr=1;
}
}
return ans;
}
};
| true |
db2da51618e510e2d56b3ee42d7febd21c95e795 | C++ | sawlani/densest-subgraph | /alternate_code/iterative_peeling_naive.cpp | UTF-8 | 3,557 | 3.09375 | 3 | [] | no_license | // Saurabh Sawlani
// Find maximum subgraph density
// Uses BBST to store intermediate degrees
// 6-10 x slower than recursive_peeling_yu, but simpler to understand
#include <iostream>
#include <fstream>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include<cassert>
#include <vector>
#include <queue>
#include<list>
#include <set>
#include<cstring>
#include<ctime>
#include <unordered_set>
#include <algorithm>
#include <numeric>
#include <chrono>
using namespace std;
vector<int> deg;
struct classcomp {
bool operator() (const int& lhs, const int& rhs) const
{return deg[lhs]<deg[rhs] || (deg[lhs]==deg[rhs] && lhs<rhs);}
};
set<int,classcomp> deg_sorted; //BBST storing degrees
//////////////////////////////////////////////////////////////////////////////////////////////////////
// MAIN
//////////////////////////////////////////////////////////////////////////////////////////////////////
int main(int argc, char** argv) {
cout << "Finding maximum subgraph density (naive version using BBST)..." << endl;
auto startio = chrono::steady_clock::now();
int iters = atoi(argv[1]);
int m, n;
cin >> n >> m;
int * init_deg = new int[n];
memset(init_deg, 0, sizeof(int) * n);
int * w = new int[n];
memset(w, 0, sizeof(int) * n);
deg.reserve(n);
unordered_set<int> * nbrs = new unordered_set<int>[n];
for (int i = 0; i < m; i++) {
int p, q;
cin >> p >> q;
p -= 1;
q -= 1;
nbrs[p].insert(q);
nbrs[q].insert(p);
init_deg[p]++;
init_deg[q]++;
}
double mm_density = 0;
vector<bool> exists(n);
auto endio = chrono::steady_clock::now();
int init_time = chrono::duration_cast<chrono::milliseconds>(endio - startio).count();
cout << "Time for reading input and initialization: " << init_time << " ms" << endl;
int sum_iter_times = 0;
for (int tt = 0; tt < iters; tt++) {
auto startiter = chrono::steady_clock::now();
deg_sorted.clear();
for (int i = 0; i < n; i++) {
deg[i] = w[i] + init_deg[i]; //degree for this iteration is "vertex weight" + actual degree
deg_sorted.insert(i);
}
double iter_max_density = (double)m / n;
int cur_m = m, cur_n = n;
fill(exists.begin(), exists.end(), true);
while (cur_n > 0) {
cur_n--;
int k = *(deg_sorted.begin()); //k = min degree vertex
w[k] = deg[k]; //increment vertex weight for the next iteration (self loops)
deg_sorted.erase(k); //delete k
for (int j : nbrs[k]) { //decrement degrees of k's neighbors
if (exists[j]) {
deg_sorted.erase(j);
deg[j] -= 1;
cur_m --;
if (deg[j] == 0) {
cur_n--;
exists[j] = false;
}
else {
deg_sorted.insert(j);
}
}
exists[k] = false;
}
if (iter_max_density < (double) cur_m / cur_n) {
iter_max_density = (double) cur_m / cur_n;
}
}
if(iter_max_density > mm_density) {
mm_density = iter_max_density;
}
auto enditer = chrono::steady_clock::now();
int elapsed = chrono::duration_cast<chrono::milliseconds>(enditer - startiter).count();
sum_iter_times += elapsed;
cout << "Max density AT iteration " << tt+1 <<": " << iter_max_density << endl;
cout << "Max density until iteration " << tt+1 <<": " << mm_density << endl;
cout << "Avg time per iteration: " << sum_iter_times/(tt+1) << " ms" << endl;
cout << "Total time: " << sum_iter_times + init_time << " ms" << endl;
}
return 0;
} | true |
cbc2b3b9408f29065c2498023c44f94c6737f851 | C++ | msrLi/portingSources | /ACE/ACE_wrappers/TAO/orbsvcs/orbsvcs/PortableGroup/UIPMC_Message_Block_Data_Iterator.cpp | UTF-8 | 2,239 | 2.6875 | 3 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-proprietary-license",
"LicenseRef-scancode-sun-iiop"
] | permissive | #include "orbsvcs/PortableGroup/UIPMC_Message_Block_Data_Iterator.h"
TAO_BEGIN_VERSIONED_NAMESPACE_DECL
UIPMC_Message_Block_Data_Iterator::UIPMC_Message_Block_Data_Iterator (iovec *iov, int iovcnt) :
iov_ (iov),
iovcnt_ (iovcnt),
iov_index_ (0),
iov_ptr_ (0),
iov_len_left_ (0),
state_ (INTER_BLOCK)
{
}
bool
UIPMC_Message_Block_Data_Iterator::next_block (size_t max_length,
iovec &block)
{
if (this->state_ == INTER_BLOCK)
{
// Check that there are some iovec buffers left.
if (this->iov_index_ >= this->iovcnt_)
return false;
if (static_cast<u_long> (this->iov_[this->iov_index_].iov_len) <= max_length)
{
// Return the full data portion.
block.iov_len = this->iov_[this->iov_index_].iov_len;
block.iov_base = this->iov_[this->iov_index_].iov_base;
// Go to the next block.
++this->iov_index_;
return true;
}
else
{
// Let the caller use the first part of this
// message block.
block.iov_len = max_length;
block.iov_base = this->iov_[this->iov_index_].iov_base;
// Break up the block.
this->iov_len_left_ =
this->iov_[this->iov_index_].iov_len - max_length;
this->iov_ptr_ =
reinterpret_cast<char *> (block.iov_base) + max_length;
this->state_ = INTRA_BLOCK;
return true;
}
}
else
{
// Currently scanning a split block.
if (this->iov_len_left_ <= max_length)
{
// Return everything that's left in the block.
block.iov_len = this->iov_len_left_;
block.iov_base = this->iov_ptr_;
// Go to the next block.
++this->iov_index_;
// Update the state.
this->state_ = INTER_BLOCK;
return true;
}
else
{
// Split a little more off the block.
block.iov_len = max_length;
block.iov_base = this->iov_ptr_;
this->iov_len_left_ -= max_length;
this->iov_ptr_ += max_length;
return true;
}
}
}
TAO_END_VERSIONED_NAMESPACE_DECL
| true |
40e579ba5dc7a02db377beebcbe2db34b3243fa5 | C++ | IlVin/stepic-149-final | /include/buffer.h | UTF-8 | 778 | 2.609375 | 3 | [] | no_license | #pragma once
#include <string>
#include <assert.h>
#include <ev.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <cstring>
#define INIT_RAW_SIZE 2048
class TBuffer {
private:
char * raw;
char * hd;
char * tl;
size_t size;
public:
TBuffer() {
size = INIT_RAW_SIZE;
raw = (char *)malloc(size);
tl = hd = raw;
}
virtual ~TBuffer() {
free(raw);
}
char ** head();
char ** tail();
size_t length();
bool space(size_t need_space);
void append(const std::string &str);
int rcv(int fd, size_t sz);
int snd(int fd);
char * c_str();
std::string asString();
};
| true |
0d55b0ef705a785a6b5ca6730540ca1b456df08a | C++ | gm2-pisa/gm2daq | /analyzer/modules/master/master.cpp | UTF-8 | 5,898 | 2.609375 | 3 | [] | no_license | /**
* @file analyzer/modules/master/master.cpp
* @author Vladimir Tishchenko <tishenko@pa.uky.edu>
* @date Tue Jun 5 15:48:21 2012 (-0500)
* @date Last-Updated: Tue Mar 17 13:38:06 2015 (-0500)
* By : Data Acquisition
* Update #: 34
* @version $Id$
*
* @copyright (c) new (g-2) collaboration
*
* @brief Analyzer for fronternd master
*
* @section Changelog
* @verbatim
* $Log$
* @endverbatim
*/
/*-- Include files -------------------------------------------------*/
/* standard includes */
#include <stdio.h>
#include <iostream>
/* midas includes */
#include "../../../analyzer/src/midas.h"
#include "rmana.h"
#include "../../frontends/master/master.h"
/* root includes */
#include <TH1D.h>
//#include <TH2D.h>
/* other header files */
/*-- Function declarations -----------------------------------------*/
static INT module_event(EVENT_HEADER *, void *);
static INT module_init(void);
static INT module_bor(INT run_number);
static INT module_eor(INT run_number);
double saved_time = 0;
/*-- Parameters ----------------------------------------------------*/
/*-- Histogram declaration -----------------------------------------*/
// declare your histograms here
static TH1D *h1_time_total;
static TH1D *h1_time_diff;
//static TH2D *h2_xxx;
/*-- Module declaration --------------------------------------------*/
/* Replace the word 'template' with the actual name of your module */
ANA_MODULE master_module = {
"master" , /* module name */
"Vladimir Tishchenko", /* author - Write your name here */
module_event, /* event routine */
module_bor, /* BOR routine */
module_eor, /* EOR routine */
module_init, /* init routine */
NULL, /* exit routine */
NULL, /* parameter structure */
0, /* structure size */
NULL, /* initial parameters */
};
/*-- module-local variables ----------------------------------------*/
/*-- Doxygen documentation -------------------------------------------*/
/**
@page page_modue_master master
@ingroup group_analyzer_modules
- <b>file</b> : analyzer/modules/master/master.cpp
- <b>Input</b> : Bank [TRIG] produced by frontend master
- <b>Output</b> : Fills histograms
Histograms various timing information for profiling
*/
/*-- init routine --------------------------------------------------*/
/**
* @brief Init routine.
* @details This routine is called when the analyzer starts.
*
* Book your histgorams, gpraphs, etc. here
*
* TH1 objects will be added to the ROOT folder histos/module_name automatically
*
* TGraph and TGraphError objects must be added manually to the module.
* Otherwise graphs will not be written to the output ROOT file and
* will not be cleaned automatically on new run.
*
* @return SUCCESS on success
*/
INT module_init(void)
{
// book your histograms here
// Histograms will be written to the output ROOT file automatically
// They will be in the folder histos/module_name/ in the output root file
//h1_time_total = new TH1D("h1_time_total","event readout time",100000,0.0,1000.0);
h1_time_total = new TH1D("h1_time_total","event readout time",100000,0.0,10000.0);
h1_time_total->SetXTitle("time (ms)");
h1_time_diff = new TH1D("h1_time_diff","#Delta t between events",100000,0.0,1000.0);
h1_time_diff->SetXTitle("#Delta t (ms)");
// h1_xxx = new TH1D("h1_xxx","h1 xxx title", 100, 0.1, 100.);
// h2_xxx = new TH2D("h2_xxx","h2 xxx title", 100, 0.1, 100., 100, 0.1, 100.0);
return SUCCESS;
}
/*-- BOR routine ---------------------------------------------------*/
/**
* @brief BOR routine
* @details This routine is called when run starts.
*
* @param run_number run number
*
* @return SUCCESS on success
*/
INT module_bor(INT run_number)
{
return SUCCESS;
}
/*-- eor routine ---------------------------------------------------*/
/**
* @brief EOR routine
* @details This routine is called when run ends.
*
* @param run_number
*
* @return SUCCESS on success
*/
INT module_eor(INT run_number)
{
return SUCCESS;
}
/*-- event routine -------------------------------------------------*/
/**
* @brief Event routine.
* @details This routine is called on every MIDAS event.
*
* @param pheader pointer to MIDAS event header
* @param pevent pointer to MIDAS event
*
* @return SUCCESS
*/
INT module_event(EVENT_HEADER * pheader, void *pevent)
{
S_TRIGGER_TIME_INFO trig;
DWORD *pdata;
unsigned int bank_len = bk_locate(pevent, "TRIG", &pdata);
if ( bank_len == 0 ) return SUCCESS;
if ( bank_len != 8 )
{
printf("***ERROR! Wrong length of bank [TRIG]: %i\n",bank_len);
return SUCCESS;
}
trig.trigger_nr = *pdata++;
trig.trigger_mask = *pdata++;
trig.time_s = *pdata++;
trig.time_us = *pdata++;
trig.time_recv_s = *pdata++;
trig.time_recv_us = *pdata++;
trig.time_done_s = *pdata++;
trig.time_done_us = *pdata++;
double readout_time = 1.0e3*trig.time_done_s + 1.0e-3*trig.time_done_us
- ( 1.0e3*trig.time_s + 1.0e-3*trig.time_us );
if ( readout_time > h1_time_total->GetXaxis()->GetXmax() )
readout_time = h1_time_total->GetXaxis()->GetXmax() - h1_time_total->GetXaxis()->GetBinWidth(1)*0.5;
h1_time_total->Fill(readout_time);
printf("Trigger time stamp: %i %i\n",trig.time_s,trig.time_us);
printf("Readout time stamp: %i %i\n",trig.time_done_s,trig.time_done_us);
printf("Readout time: %f\n",readout_time);
double new_time = 1.0e3*trig.time_s + 1.0e-3*trig.time_us;
double dt = new_time - saved_time;
if(saved_time != 0) h1_time_diff->Fill(dt);
else std::cout << "no saved time\n";
saved_time = new_time;
return SUCCESS;
}
| true |
ce4bae236c2ca2754a69b28ab977b9cef3b522cf | C++ | narendraumate/piLibs | /src/libSystem/windows/piFileOS.cpp | UTF-8 | 2,449 | 2.734375 | 3 | [
"MIT"
] | permissive | #include <windows.h>
#include <stdio.h>
#include <io.h>
#include <errno.h>
#include "../piTypes.h"
#include "../piFile.h"
namespace piLibs {
bool piFile::Open(const wchar_t *name, const wchar_t *mode)
{
FILE *fp = nullptr;
if( _wfopen_s(&fp, name, mode) != 0 )
return false;
mInternal = (void*)fp;
return true;
}
bool piFile::Seek(uint64_t pos, SeekMode mode)
{
int cmode = 0;
if (mode == CURRENT) cmode = SEEK_CUR;
if (mode == END) cmode = SEEK_END;
if (mode == SET) cmode = SEEK_SET;
return ( _fseeki64( (FILE*)mInternal, pos, cmode ) == 0 );
}
uint64_t piFile::Tell(void)
{
return _ftelli64((FILE*)mInternal);
}
void piFile::Close(void)
{
fclose((FILE*)mInternal);
}
bool piFile::Exists(const wchar_t *name)
{
FILE *fp = _wfopen(name, L"rb");
if (!fp)
return false;
fclose(fp);
return true;
}
bool piFile::DirectoryExists(const wchar_t *dirName_in)
{
DWORD ftyp = GetFileAttributesW(dirName_in);
if (ftyp == INVALID_FILE_ATTRIBUTES)
return false; //something is wrong with your path!
if (ftyp & FILE_ATTRIBUTE_DIRECTORY)
return true; // this is a directory!
return false; // this is not a directory!
}
bool piFile::HaveWriteAccess(const wchar_t *name)
{
if (_waccess(name, 6) == -1)
{
return errno == ENOENT;
}
return true;
}
bool piFile::Copy(const wchar_t *dst, const wchar_t *src, bool failIfexists)
{
if( CopyFile( src, dst, failIfexists)==0 )
{
int res = GetLastError();
return false;
}
return true;
}
uint64_t piFile::GetLength(void)
{
uint64_t p = ftell( (FILE*)mInternal );
_fseeki64((FILE*)mInternal, 0, SEEK_END);
uint64_t l = ftell((FILE*)mInternal);
_fseeki64((FILE*)mInternal, p, SEEK_SET);
return l;
}
bool piFile::DirectoryCreate( const wchar_t *name, bool failOnExists )
{
if( ::CreateDirectory( name, NULL )==0 )
{
int res = GetLastError();
if (res == ERROR_ALREADY_EXISTS )
return !failOnExists;
if (res == ERROR_PATH_NOT_FOUND )
return false;
return false;
}
return true;
}
uint64_t piFile::GetLength(const wchar_t *filename)
{
FILE *fp = nullptr;
if (_wfopen_s(&fp, filename, L"rb") != 0)
return false;
uint64_t p = ftell(fp);
_fseeki64(fp, 0, SEEK_END);
uint64_t l = ftell(fp);
_fseeki64(fp, p, SEEK_SET);
fclose(fp);
return l;
}
} | true |
a9b68e4532353ca5c1a4fec64e01ceb9edbaa547 | C++ | 5trike/robot | /Servo.ino | UTF-8 | 10,557 | 2.578125 | 3 | [] | no_license | /*********
Руи Сантос
Более подробно о проекте на: http://randomnerdtutorials.com
*********/
#include <WiFi.h>
#include <ESP32Servo.h>
#include "soc/soc.h" //disable brownout problems
#include "soc/rtc_cntl_reg.h" //disable brownout problems
Servo myservo1; // создаем экземпляр класса «Servo»,
// чтобы с его помощью управлять сервоприводом;
// большинство плат позволяют
// создать 12 объектов класса «Servo»
Servo myservo2;
Servo myservo3;
Servo myservo4;
Servo myservo5;
// вставьте здесь учетные данные своей сети:
const char* ssid = "NETGEAR09";
const char* password = "bluephoenix200";
// создаем веб-сервер на порте «80»:
WiFiServer server(80);
// переменная для хранения HTTP-запроса:
String header;
// несколько переменных для расшифровки значения в HTTP-запросе GET:
String pos = String(5);
String num = String(5);
int pos1 = 0;
int pos2 = 0;
int pos3 = 0;
int ledState = INPUT; // этой переменной устанавливаем состояние светодиода
long previousMillis = 0; // храним время последнего переключения светодиода
long interval = 1000; // интервал между включение/выключением светодиода (1 секунда)
void setup() {
WRITE_PERI_REG(RTC_CNTL_BROWN_OUT_REG, 0); //disable brownout detector
Serial.begin(115200);
// привязываем сервопривод,
myservo1.attach(12);
myservo2.attach(13);
myservo3.attach(14);
myservo4.attach(15);
// это нажиматели сенсорных кнопок
pinMode(2, OUTPUT);
pinMode(4, OUTPUT); // это еще и светодиод
// подключаемся к WiFi при помощи заданных выше SSID и пароля:
Serial.print("Connecting to "); // "Подключаемся к "
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
// печатаем локальный IP-адрес и запускаем веб-сервер:
Serial.println("");
Serial.println("WiFi connected."); // "WiFi подключен."
Serial.println("IP address: "); // "IP-адрес: "
Serial.println(WiFi.localIP());
server.begin();
}
void loop(){
// здесь будет код, который будет работать постоянно
// и который не должен останавливаться на время между переключениями свето
unsigned long currentMillis = millis();
//проверяем не прошел ли нужный интервал, если прошел то
if(currentMillis - previousMillis > interval) {
// сохраняем время последнего переключения
previousMillis = currentMillis;
// если светодиод не горит, то зажигаем, и наоборот
if (ledState == OUTPUT)
ledState = INPUT;
else
ledState = OUTPUT;
// устанавливаем состояния выхода, чтобы включить или выключить светодиод
pinMode(4,ledState);
//digitalWrite(4, ledState);
}
// начинаем прослушивать входящих клиентов:
WiFiClient client = server.available();
if (client) { // если подключился новый клиент,
Serial.println("New Client."); // печатаем сообщение
// «Новый клиент.»
// в мониторе порта;
String currentLine = ""; // создаем строку для хранения
// входящих данных от клиента;
while (client.connected()) { // цикл while() будет работать
// все то время, пока клиент
// будет подключен к серверу;
if (client.available()) { // если у клиента есть данные,
// которые можно прочесть,
char c = client.read(); // считываем байт, а затем
Serial.write(c); // печатаем его в мониторе порта
header += c;
if (c == '\n') { // если этим байтом является
// символ новой строки
// если получили два символа новой строки подряд,
// то это значит, что текущая строчка пуста;
// это конец HTTP-запроса клиента,
// а значит – пора отправлять ответ:
if (currentLine.length() == 0) {
// HTTP-заголовки всегда начинаются
// с кода ответа (например, «HTTP/1.1 200 OK»)
// и информации о типе контента
// (чтобы клиент понимал, что получает);
// в конце пишем пустую строчку:
client.println("HTTP/1.1 200 OK");
client.println("Content-type:text/html");
client.println("Connection: close");
// "Соединение: отключено"
client.println();
// показываем веб-страницу:
client.println("<!DOCTYPE html><html>");
client.println("<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");
client.println("<link rel=\"icon\" href=\"data:,\">");
client.println("<style>body { text-align: center; font-family: \"Trebuchet MS\", Arial; margin-left:auto; margin-right:auto;}");
client.println(".slider { width: 300px; }</style>");
client.println("<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>");
// веб-страница:
client.println("</head><body><h1>Buttons</h1>");
client.println("<input type=\"button\" id= \"button_1_press\" value=\"Button 1 PRESS\" onClick=servo(1,90)> <input type=\"button\" id= \"button_1_release\" value=\"Button 1 RELEASE\" onClick=servo(1,0)> </br>" );
client.println("<input type=\"button\" id= \"button_2_press\" value=\"Button 2 PRESS\" onClick=servo(2,90)> <input type=\"button\" id= \"button_2_release\" value=\"Button 2 RELEASE\" onClick=servo(2,0)> </br>" );
client.println("<input type=\"button\" id= \"button_3_press\" value=\"Button 3 PRESS\" onClick=servo(3,90)> <input type=\"button\" id= \"button_3_release\" value=\"Button 3 RELEASE\" onClick=servo(3,0)> </br>" );
client.println("<input type=\"button\" id= \"button_4_press\" value=\"Button 4 PRESS\" onClick=servo(4,90)> <input type=\"button\" id= \"button_4_release\" value=\"Button 4 RELEASE\" onClick=servo(4,0)> </br>" );
client.println("<input type=\"button\" id= \"button_5_press\" value=\"Button 5 PRESS\" onClick=servo(5,90)> <input type=\"button\" id= \"button_5_release\" value=\"Button 5 RELEASE\" onClick=servo(5,0)> </br>" );
client.println("<input type=\"button\" id= \"button_10_press\" value=\"Button 10 PRESS\" onClick=servo(10,90)> <input type=\"button\" id= \"button_10_release\" value=\"Button 10 RELEASE\" onClick=servo(10,0)> </br>" );
client.println("<script>$.ajaxSetup({timeout:1000}); function servo(num, pos) { ");
client.println("$.get(\"/?num=\" + num + \"|pos=\" + pos + \"&\"); {Connection: close};}</script>");
client.println("</body></html>");
//GET /?value=180& HTTP/1.1
if(header.indexOf("GET /?num=")>=0) {
pos1 = header.indexOf("num=");
pos2 = header.indexOf("pos=");
pos3 = header.indexOf('&');
num = header.substring(pos1+4, pos2-1);
pos = header.substring(pos2+4, pos3);
// вращаем ось сервомотора:
if(num=="1") {myservo1.write(pos.toInt());}
if(num=="2") {myservo2.write(pos.toInt());}
if(num=="3") {myservo3.write(pos.toInt());}
if(num=="4") {myservo4.write(pos.toInt());}
if(num=="5") {myservo5.write(pos.toInt());}
if(num=="10" and pos=="90") {pinMode(2,INPUT);}
if(num=="10" and pos=="0") {pinMode(2,OUTPUT);}
Serial.println(num + "|" + pos);
}
// конец HTTP-ответа задается
// с помощью дополнительной пустой строки:
client.println();
// выходим из цикла while():
break;
} else { // если получили символ новой строки,
// очищаем текущую строку «currentLine»:
currentLine = "";
}
} else if (c != '\r') { // если получили любые данные,
// кроме символа возврата каретки,
currentLine += c; // добавляем эти данные
// в конец строки «currentLine»
}
}
}
// очищаем переменную «header»:
header = "";
// отключаем соединение:
client.stop();
Serial.println("Client disconnected.");
// "Клиент отключился."
Serial.println("");
}
}
| true |
ce946c1b1af19adf73384a2c554c6f7c645dc9ed | C++ | H-W-Huang/c-codes | /数据结构/排序/OJ/8644堆排序/8644堆排序.cpp | UTF-8 | 2,654 | 3.375 | 3 | [] | no_license | // 8644 堆排序
// 时间限制:1000MS 内存限制:1000K
// 提交次数:1909 通过次数:1257
// 题型: 编程题 语言: G++;GCC
// Description
// 用函数实现堆排序,并输出每趟排序的结果
// 输入格式
// 第一行:键盘输入待排序关键的个数n
// 第二行:输入n个待排序关键字,用空格分隔数据
// 输出格式
// 第一行:初始建堆后的结果
// 其后各行输出交换堆顶元素并调整堆的结果,数据之间用一个空格分隔
// 输入样例
// 10
// 5 4 8 0 9 3 2 6 7 1
// 输出样例
// 9 7 8 6 4 3 2 5 0 1
// 8 7 3 6 4 1 2 5 0 9
// 7 6 3 5 4 1 2 0 8 9
// 6 5 3 0 4 1 2 7 8 9
// 5 4 3 0 2 1 6 7 8 9
// 4 2 3 0 1 5 6 7 8 9
// 3 2 1 0 4 5 6 7 8 9
// 2 0 1 3 4 5 6 7 8 9
// 1 0 2 3 4 5 6 7 8 9
// 0 1 2 3 4 5 6 7 8 9
// 提示
// 作者
// yqm
//堆调整---对 s 到 m 的序列进行堆排序
//使用堆排序时,0号元素不要用。否则不能正确的到其左右孩子。
#include <cstdio>
int Heap_Adjust(int a[],int s,int m)
{
int j,temp;
// 2*s 为 s的左孩子
temp=a[s]; //暂时将a[s]的值存到 temp里
printf("temp===%d\n",temp );
printf("HeapAdjusting...\n");
for(j=2*s;j<=m;j*=2)
{
if(j<m && a[j] < a[j+1]) j++; //将j定位到最大的孩子上;
if(temp>=a[j]){for(int i=1;i<=10;i++) printf("%d ",a[i] );putchar('\n'); break; } //每一次比较的是a[j] 和 原树根,即temp的值
a[s]=a[j]; //将大的孩子的值赋到其双亲上
s=j;
for(int i=1;i<=10;i++) printf("%d ",a[i] );putchar('\n');
}
a[s]=temp;
putchar('\n'); putchar('\n'); putchar('\n');
printf("result:\n");
for(int i=1;i<=10;i++) printf("%d ",a[i] );putchar('\n');
printf("******************************************\n");
}
int Heap_sort(int a[],int n)
{
int i,temp;
for(i=n/2;i>0/*i>=1*/;i--) //对非树叶的结点进行调整
Heap_Adjust(a,i,n);
for(i=n;i>1;i--) //调整的顺序是自下而上的
{temp=a[i]; a[i]=a[1]; a[1]=temp; Heap_Adjust(a,1,i-1);for(int i=1;i<=n;i++) printf("%d ",a[i] );putchar('\n'); }
//第一个元素与第i个元素调换位置
//由之前建立的大顶堆,第一个元素一定是整个数组中最大的一个元素,将其放到最后,对1 ~ i-1 建立调整,从而得到次大的,之后又被房贷最后。如此反复,可得增序的序列
return 0;
}
int main()
{
int a[10000],n;
scanf("%d",&n);
for(int i=1;i<=n;i++) scanf("%d",&a[i]);
Heap_sort(a,n);
return 0;
}
| true |
de6fa45d4d5c412d2720dfaf52d9482b94757f43 | C++ | PierreINP/Projet_Info | /ProjetC/Software/Install/Source/FSM_assignation.cpp | UTF-8 | 2,066 | 3.03125 | 3 | [] | no_license | #include"./../Header/Lexeme.h"
#include <stdlib.h>
#include <stdio.h>
#include <list>
#include <iostream>
#include <string.h>
using namespace std;
extern string keywordList[];
extern char specialList[];
extern string operatorList[];
bool isEntier(string a) {
int i;
for (i; i< a.size(); i++) {
if (not(a[i] >= 48 and a[i] <= 57)) {return false;}
}
return true;
}
int main() {
list<Lexeme> structure;
//List for port test
structure.push_back(Lexeme("a"));
structure.push_back(Lexeme(":"));
structure.push_back(Lexeme("="));
structure.push_back(Lexeme("b"));
structure.push_back(Lexeme("+"));
structure.push_back(Lexeme("c"));
structure.push_back(Lexeme(";"));
list<Lexeme>::iterator it;
list<Lexeme>::iterator it_tmp;
int step = 0;
for(it = structure.begin(); it != structure.end(); it ++)
{
it_tmp = it;
cout << step << " | " << *it <<endl;
///////////////////////////////////////////CHECKSTRUCTURE ASSIGNATION///////////////////////////////////////////
switch(step){
case 0: if((*it).getType()=="id"){
step++;
//GetType ? Futur test de cohérence de type
}
else step=-1; //rentre dans le cas default
break;
case 1 : if((*it).getName()=="<="){step++;}
else if((*it).getName()==":" and (*++it).getName()=="="){step++;}
else step=-1;
break;
//Case 2 et 3 parcourt les Id avant le ":"
case 2 : if((*it).getType()=="id" and (*++it_tmp).getType()=="operator"){
//recuperer id
step++;
}
else if ((*it).getType()=="id" or (*++it_tmp).getName() == ";") {step = 4;}
else step=-1;
break;
case 3 : if((*it).getType() == "operator" and (*++it_tmp).getType()=="id"){
//recuperer opérator
step--;
}
else step=-1;
break;
//Fin de l'assignation
case 4 : if((*it).getName()==";") {
cout << "Structure ASSIGNATION validée" << endl; return true;
}
else step=-1;
break;
default : cout << "error" << endl; //cf gestion d'erreur
return false;
}
}
}
| true |
b6d51ef37b0d07b206d7e82d11853e15bc5050d2 | C++ | yl1019/Lid-Driven-Cavity-Problem | /LidDrivenCavitySolver.cpp | UTF-8 | 2,581 | 2.9375 | 3 | [] | no_license | #include <iostream>
#include <exception>
#include <iomanip>
#include <mpi.h>
using namespace std;
#include "LidDrivenCavity.h"
#include "ProgramOptions.h"
#include "MpiConfig.h"
int main(int argc, char **argv)
{
/** Initialize MPI and retrieve rank & size */
MPI_Init(&argc, &argv);
int rank, size;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &size);
/** Parameters from command input */
double Lx, Ly;
int Nx, Ny;
int Px, Py;
double dt;
double T;
double Re;
po::variables_map vm;
bool status; ///< to decide the input status, 1 for successful input
status = OptionStatus(argc, argv, vm);
/// If help is called or error occurs, terminate the program
if (!status)
{
MPI_Finalize();
return 0;
}
/// Read all parameters
ReadVals(vm, Lx, Ly, Nx, Ny, Px, Py, dt, T, Re);
/** Check if the number of processors are compatible with the size */
double dx = Lx/(Nx - 1);
double dy = Ly/(Ny - 1);
if (!CheckWorkers(size, Px, Py))
{
if (rank == 0)
{
cout << "Number of processores doe not match input Px and Py." << endl;
cout << "Please ensure np = Px * Py." << endl;
}
MPI_Finalize();
return 0;
}
/** Work before operating */
MPI_Comm mygrid;
const int dims = 2;
int sizes[dims] = {Py, Px};
int periods[dims] = {0, 0};
int reorder = 0;
/// Create a new communicator based on Cartesian Topology
MPI_Cart_create(MPI_COMM_WORLD, dims, sizes, periods, reorder, &mygrid);
int coords[dims];
/// Give each rank a coordinate
MPI_Cart_coords(mygrid, rank, dims, coords);
int neighbor[4] = {0};
/// Obtain neighborhood information for each rank
FindNeighbor(mygrid, neighbor);
// cout << "rank " << rank << " 's neighbor is " << neighbor[0] << " "
// << neighbor[1] << " " << neighbor[2] << " " << neighbor[3] << endl;
int nx, ny; ///< number of grids for each rank
double start[2] = {0.0, 0.0};
/// Distribute work to each process
DistributeWork(rank, Nx, Ny, Px, Py, dx, dy, coords, start, nx, ny);
// MPI_Finalize();
// return 0;
/** Solving the main problem */
bool dt_flag;
/// Create a new instance of the LidDrivenCavity class for each rank
LidDrivenCavity* solver = new LidDrivenCavity(mygrid, rank, coords, start, neighbor,
nx, ny, dt, T, Re, dx, dy, dt_flag);
if (!dt_flag)
{
MPI_Finalize();
return 0;
}
/// Run the solver
solver->Solve();
/// Output the result
solver->Output(Px, Py, Lx, Ly);
//solver->Output(Lx, Ly, Px, Py, Nx-2, Ny-2);
/// Exit
MPI_Finalize();
return 0;
}
| true |
d0435eb0d04d0c54a5e8269faf3333a23d778c0e | C++ | cntkillme/Advent-of-Code-2020 | /src/problem-7/main.cpp | UTF-8 | 4,133 | 3.15625 | 3 | [] | no_license | #include <algorithm>
#include <iostream>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include "dataset.hpp"
struct constraint {
std::size_t bag;
std::string name;
std::unordered_set<std::size_t> parents;
std::unordered_map<std::size_t, long> children;
};
using input = std::vector<constraint>;
using mapping = std::unordered_map<std::string, std::size_t>;
static std::size_t part1(const input& input, const mapping& mapping);
static std::size_t part2(const input& input, const mapping& mapping);
/** Grammar
* constraint = bag "contains?" bag_list '\n';
* bag = WORD WORD "bags?";
* bag_list = LONG bag '.' | LONG bag ',' bag_list | "no other bags.";
*/
int main() {
auto stream = open_dataset("data/problem-7.txt");
input input;
mapping mapping;
auto recordBag = [&, id = static_cast<std::size_t>(0)](const std::string& name) mutable {
if (mapping.count(name) == 0) {
input.push_back({ id, name, {}, {} });
mapping[name] = id;
return id++;
} else {
return mapping.at(name);
}
};
// bag = WORD WORD "bags?"
auto parseBag = [&]() {
std::string adjective, color, terminator;
stream >> adjective >> color >> terminator;
std::string name = adjective + " " + color;
char last = terminator.at(terminator.size() - 1);
if (last == ',' || last == '.') {
stream.unget();
}
return recordBag(name);
};
// bag_list = LONG bag '.' | LONG bag ',' bag_list | "no other bags."
auto parseBagList = [&]() {
std::unordered_map<std::size_t, long> children;
std::string count;
stream >> count;
if (count == "no") {
// "no other bags."
stream >> count; // skip "other"
stream >> count; // skip "bags."
} else {
auto bag = parseBag();
while (stream.peek() == ',') {
// LONG bag ','
children[bag] = std::stol(count);
stream.get(); // skip ','
stream >> count;
bag = parseBag();
}
// LONG BAG '.'
children.insert({ bag, std::stol(count) });
children[bag] = std::stol(count);
stream.get(); // skip '.'
}
return children;
};
// constraint = bag "contains?" bag_list '\n';
auto parseConstraint = [&]() {
std::string temp;
auto bag = parseBag();
stream >> temp; // skip "contains?"
input.at(bag).children = parseBagList();
stream.ignore(1, '\n'); // skip '\n'
// assign parents
std::for_each(
input.at(bag).children.begin(),
input.at(bag).children.end(),
[&](const auto& pair) { input.at(pair.first).parents.insert(bag); }
);
};
while (stream.peek() != std::ifstream::traits_type::eof()) {
parseConstraint();
if (stream.peek() == '\n') {
stream.get();
}
}
std::cout << "Part 1 Solution: " << part1(input, mapping) << "\n";
std::cout << "Part 2 Solution: " << part2(input, mapping) << "\n";
return 0;
}
/** Counts the number of bags that eventually contain one shiny gold bag.
* Time complexity: O(n)
* Space complexity: O(n)
*/
std::size_t part1(const input& input, const mapping& mapping) {
std::unordered_set<std::size_t> ancestors;
std::vector<std::size_t> scan;
scan.push_back(mapping.at("shiny gold"));
// get ancestors (no cycles)
while (!scan.empty()) {
const auto& constraint = input.at(scan.back());
scan.pop_back();
for (const auto& parent : constraint.parents) {
if (ancestors.count(parent) == 0) {
ancestors.insert(parent);
scan.push_back(parent);
}
}
}
return ancestors.size();
}
/** Counts the total number of bags that one shiny gold bag will contain.
* Time complexity: O(n)
* Space complexity: O(n)
*/
std::size_t part2(const input& input, const mapping& mapping) {
std::vector<decltype(constraint::children)::value_type> scan;
std::size_t total = 0;
scan.emplace_back(mapping.at("shiny gold"), 1);
// get descendants and count (no cycles)
while (!scan.empty()) {
auto [bag, count] = scan.back();
total += count;
scan.pop_back();
// add children bag count
for (auto [child, childCount] : input.at(bag).children) {
std::size_t totalCount = count * childCount;
scan.emplace_back(child, totalCount);
}
}
// exclude the shiny gold bag itself
return total - 1;
}
| true |
8a9a5fa7ca825ab200ab8585bdaab535fde3ba48 | C++ | hasancuet13/uva | /divisorsV2.cpp | UTF-8 | 935 | 2.71875 | 3 | [] | no_license | #include<bits/stdc++.h>
#define SIZE_N 1000000
using namespace std;
bool status[1000000];
int prime[SIZE_N];
void sieve()
{
int N=1000000,t=0;
for(int i=4;i<=N;i+=2){
status[i]=1;
}
for(int i=3;i*i<=N;i+=2){
if(!status[i]){
for(int j=i*i;j<=N;j+=i){
status[j]=1;
}
}
}
status[1]=1;
for(int i=2;i<=N;i++){
if(!status[i])
prime[t++]=i;
}
}
int divisor(int n)
{
int div=1;
int sq=sqrt(n)+1;
for(int i=0;i<=sq;i++){
if(n%prime[i]==0){
int cnt=1;
while((n%prime[i])==0){
n/=prime[i];
cnt++;
}
div*=cnt;
}
}
if(n>1)div=div*2;
return div;
}
int main()
{
sieve();
int n,d;
while((cin>>n)){
d=divisor(n);
cout<<d<<endl;
}
}
| true |
96f2aacc2460a9cc06d8e0d30f2d272073f1e591 | C++ | Elotod/Sensor-de-corrente-Elotod | /Valor_eficaz_AC_usando_sensor_de_corrente_Elotod_versao14set202.ino | UTF-8 | 5,588 | 2.625 | 3 | [] | no_license | // Editado por prof. Spalding em 09Set2020:
// Para usar com Arduino UNO, ESP32 e outros: Programa adaptado por Carlos Re Signor em Setembro de 2018 para capturar as formas
// de onda do sensor de corrente Elotod.
// O programa calcula o valor eficaz da corrente e mostra o valor na saida serial e a forma de onda na saide serial modo plotter
// MUITO CUIDADO AO USAR 220 V. Não faça este experimento sem um adulto por perto, além de você. Ensine ele a desligar a energia eletrica.
// Este firmware eh usado nos videos 2 e 3 da pagina da Elotod no facebook: https://www.facebook.com/elotod
#if defined(ESP8266) || defined(ESP31B) || defined(ESP32)
#define TOVOLTAGE 3.3 / 1023.0 // o projetista pode escolher o valor de final de escala e o valor de bits do conversor
#define SERIAL_BAUDRATE 115200 // esta eh a taxa de transmissao de dados usual para ESP32
#else
#define TOVOLTAGE 5 / 1023.0 // Para o Arduino, o final de escala padrao eh 5,0V e o conversor eh de 10 bits
#define SERIAL_BAUDRATE 9600 // esta eh a taxa de transmissao de dados usual para Arduino
#endif
#define AMOSTRAS 64 // eh possivel varias este numero de amostras (N). Para Arduino UNO, o maximo eh 147
// quando selecionar o numero de amostras, cuide para a variavel DELAY deve se manter positiva
#define FREQUENCIA 60 // Normalmente, eh 60 ou 50 Hz
#define GANHO_SENSOR_CORRENTE 0.57 // este 0.57 é o valor de calibracao impresso na etiqueta do sensor Elotod. No caso um sensor para 0.8 Apico
#define PIN_A A5 // Pino do conversor analogico/digital escolhido para medir a corrente. Pode ser modificado
#define PRINT_VETOR 0 // "0"(zero) mostra o valor eficaz na serial e "1" mostra os dados na serial e a forma de onda na plotter
float corrente[AMOSTRAS]; // vetor com os dados instantaneos (N AMOSTRAS)da forma de onda da corrente
float DELAY; // DELAY necessario para ajustar o tempo do loop de aquisicao e fazer N AMOSTRAS em um ciclo de 50Hz ou 60Hz
float TEMPO_CONVERSAO_N_AMOSTRAS;
float PERIODO = (1.0/FREQUENCIA);
void setup()
{
pinMode(PIN_A, INPUT);
Serial.begin(SERIAL_BAUDRATE);
Serial.println("Serial initt...");
Serial.println("Set: ");
Serial.print("\tN AMOSTRAS: "); Serial.println(AMOSTRAS);
Serial.print("\tFrequencia do Sinal: "); Serial.print(FREQUENCIA); Serial.println(" Hz");
Serial.print("\tPeriodo do Sinal: "); Serial.print(PERIODO,4);Serial.println(" segundos");
TEMPO_CONVERSAO_N_AMOSTRAS = micros();
for (int i = 0; i < AMOSTRAS; i++) //primeira conversao para calibração do AD e obter o tempo necessário para converter N AMOSTRAS
{
corrente[i] = analogRead(PIN_A);
}
TEMPO_CONVERSAO_N_AMOSTRAS = micros() - TEMPO_CONVERSAO_N_AMOSTRAS;
// O Arduino converte N amostras em um determinado tempo (milisegundos). Eh preciso fazer um DELAY para ter um N AMOSTRAS em um ciclo completo
DELAY = (((1000000*PERIODO) - TEMPO_CONVERSAO_N_AMOSTRAS) / AMOSTRAS); // 1000000 eh para passar o PERIODO para microsegundos
// Observe que DELAY esta em microsegundos e que vc precisa cuidar para fazer N AMOSTRAS EM UM CICLO DE 60 OU 50Hz
// DELAY nao pode ser negativo
Serial.print("\tDELAY NAO PODE SER NEGATIVO = ");Serial.print(DELAY, 4);Serial.println(" microsegundos");
}
void loop()
{
//AQUISIÇÃO E ARMAZENAMENTO DE N AMOSTRAS DO SENSOR DE CORRENTE
for (int i = 0; i < AMOSTRAS; i++)
{
corrente[i] = analogRead(PIN_A);
delayMicroseconds(DELAY);
}
//FIM DA AQUISIÇÃO
// "1" eh a opcao para ver a forma de onda, sugiro comentar todos os "Serial.print" que estao fora do #if PRINT_VETOR == 1 abaixo.
#if PRINT_VETOR == 1
for (int i = 0; i < AMOSTRAS; i++)
{
Serial.println(corrente[i]);
Serial.print(" ");
}
while (1); // voce pode eliminar esta linha ou comentar para que a visualização da forma de onda seja constante
#endif
//CÁLCULO DA MÉDIA ARITMÉTICA DA TENSÃO E CORRENTE. Eh importante calcular o valor medio das amostras para usar na sequencia e eliminar
// o nivel DC da forma de onda, caso sua corrente seja simetrica. A variação de temperatura no sensor pode fazer o nivel DC variar
float media_aritmetica_corrente = 0;
for (int i = 0; i < AMOSTRAS; i++)
{
media_aritmetica_corrente += corrente[i]; //equivale a: media_aritmetica_corrente = media_aritmetica_corrente + corrente[i];
}
media_aritmetica_corrente /= AMOSTRAS;
//FIM CÁLCULO MÉDIA ARITMÉTICA
//REMOVER O NIVEL DC DA FORMA DE ONDA DA CORRENTE ELETRICA
for (int i = 0; i < AMOSTRAS; i++)
{
corrente[i] -= media_aritmetica_corrente;
}
//FIM REMOÇÃO DO NIVEL DC DA FORMA DE ONDA
//CALULO DO VALOR EFICAZ CORRENTE(RMS)
//valor_eficaz = sqrt(sum(amostra[i]^2) / numero de amostras)
float soma_quadrados_corrente = 0;
for (int i = 0; i < AMOSTRAS; i++)
{
soma_quadrados_corrente += corrente[i] * corrente[i];
}
float rms_corrente = sqrt(soma_quadrados_corrente / AMOSTRAS) * TOVOLTAGE; // ajuste para ficar na escala de (0 a 5.0 ou a 3.3)Volts
// FIM CÁLCULO VALOR RMS
// aplicar o ganho para obter o valor correto e calibrado da corrente eletrica.
// O valor do ganho esta impresso na etiqueta do sensor de corrente Elotod
Serial.print("\tCorrente Eficaz: ");
Serial.print(rms_corrente * GANHO_SENSOR_CORRENTE, 3);
Serial.println(" (Arms)");
delay(1000);
}
| true |
80b554e93193fa5a0c4eb993271943fd80957e1b | C++ | Radiation-Physics-Group-of-Alexandria/GeantV | /Nudy/src/TNudyDB.cxx | UTF-8 | 3,229 | 2.609375 | 3 | [] | no_license | #include "TNudyDB.h"
#include "TNudyEndfTape.h"
#include "TFile.h"
#include "TNudyLibrary.h"
#ifdef USE_ROOT
ClassImp(TNudyDB)
#endif
//______________________________________________________________________________
// TNudyDB::TNudyDB(const char *name,const char *title,const char *file){
TNudyDB::TNudyDB(const char *name, const char *title, const char *file)
: fName(name), fTitle(title)
{
// Constructor for TNudyDB, opens database storage file
// Try to open file for update
fDB = new TFile(file, "UPDATE");
if (fDB->IsOpen()) {
// if file exists open for reading
printf("Database Opened\n");
// Create new library hash in memory
} else {
printf("Creating new Database\n");
fDB->Close();
fDB = new TFile(file, "RECREATE");
// **Check if creation is successful
}
// fDB->Close();
}
//______________________________________________________________________________
TNudyDB::~TNudyDB()
{
// Destructor for TNudyDB, Deletes all libraries in memory
// Close open database file
if (fDB->IsOpen()) {
fDB->Close();
}
// Delete database file in memory
delete fDB;
}
//______________________________________________________________________________
void TNudyDB::AddLibrary(const char *name, const char *file)
{
// Open endf root file and store tape
// Check if file exists
TFile *endf = new TFile(file, "OLD");
if (endf->IsZombie()) {
// TNudyManager::Instance()->Log("Error opening ENDF file");
Error("AddLibrary", "Cannot open file %s", file);
return;
}
TNudyEndfTape *newTape = new TNudyEndfTape();
// Check if tape is present
if (newTape) {
newTape->Read(endf->GetListOfKeys()->First()->GetName());
if (!newTape) {
Error("AddLibrary", "Cannot find ENDF Tape in file %s", file);
return;
}
} else {
// TNudyManager::Instance()->Log("Error opening ENDF Tape");
Error("AddLibrary", "Could not create new ENDF Tape");
return;
}
// Create tempory library in memory to process and store data
TNudyLibrary *lib = new TNudyLibrary(name, file);
// Set current file to Database file
gFile = fDB;
gDirectory->cd("/");
if (!fDB->GetDirectory(name)) {
// If library is not stored in database create new library
printf("Creating new Library\n");
fDB->mkdir(name);
} else {
// If library exists open it for updating
printf("Updating Library %s\n", name);
// lib = (TNudyLibrary*)fDB->Get(name);
// lib->Print();
}
// Go to Library folder
fDB->cd(name);
// gDirectory->cd(name);
// printf("%s",fDB->pwd());
// Read and Process tape
lib->ReadTape(newTape);
// Close file
endf->Close();
// Return to root directory of database file
gDirectory->cd("/");
fDB->cd("/");
// Delete endf file , temporary library and tape from memory
delete endf;
delete lib;
printf("Deleting Tape");
delete newTape;
}
//______________________________________________________________________________
TList *TNudyDB::GetEntries()
{
return fDB->GetListOfKeys();
}
//______________________________________________________________________________
void TNudyDB::RemoveLibrary(const char *name)
{
fDB->Delete(Form("%s;*", name));
}
| true |
b4580a304a84b10ac620421ed91193b235d9c9f9 | C++ | Lumos-az/MiniSQL | /src/BufferManager.h | UTF-8 | 4,157 | 2.828125 | 3 | [] | no_license | #ifndef MINISQL_BUFFERMANAGER_H
#define MINISQL_BUFFERMANAGER_H
#include <map>
#include <set>
#include <string>
#include <vector>
#include <ctime>
using namespace std;
#define BUFFER_SIZE 4096
#define BLOCK_SIZE 4096
#define HEAD_SIZE 4
#define TABLE_INFO_PATH "../data/TableInfo.txt"
class Buffer;
class BufferManager;
extern BufferManager bufferManager;
class Block {
public:
//|--4 byte--|---4092 byte---|
// size data
// size = 已用空间
char data[BLOCK_SIZE];
Block(Buffer* _buffer);
int GetSize();
void SetSize(int size);
void SetPin(bool flag);
void SetDirty(bool flag);
void Display();
//Return [n, k) records from block, the number of bytes of a record is h.
vector<string>* GetRecords(int n, int k, int h);
private:
Buffer* buffer;
};
class FreeBuffer{
public:
FreeBuffer(int _bufferIdx, FreeBuffer* _next);
~FreeBuffer();
int bufferIdx;
FreeBuffer* next;
};
class Buffer{
public:
Buffer();
~Buffer();
string fileName;
int idx;
bool used;
bool dirty;
bool pinned;
//If the block in the buffer is not read from disk but created.
bool created;
clock_t lastUsedTime;
Block* block;
};
class BufferManager {
public:
//idx: the index of blocks in file
//bufferIdx: the index of buffers in bufferPool
//Register a existed file in BufferManager
int LoadFile(const string& fileName);
//Get the number of blocks in file
int GetFileSize(const string& fileName);
//Get the idx block of file, must be called after LoadFile or CreateFile. If the block is modified, call SetDirty.
Block* GetFileBlock(const string& fileName, int idx);
//Create a new file, occupy a buffer for the new created file
bool CreateFile(const string& fileName);
//Append the file with a block in its end
void AppendFile(const string& fileName);
//Append the file with n blocks in its end
void AppendFile(const string& fileName, int n);
//Delete the last block of file
void DeleteFileLastBlock(const string& fileName);
//Write all dirty blocks of the file in bufferPool to disk and commit AppendFile or DeleteFileLastBlock. Release all blocks no matter the block is pinned or not.
void SaveFile(const string& fileName);
//The file will be reset with only one empty block resevered.
void ResetFile(const string& fileName);
//Release all blocks no matter the block is pinned or not.
void ClearFileBlock(const string& fileName);
//Delete file. If the file has no block in bufferPool, just delete it. If there are any blocks of the file in bufferPool, free them.
bool DeleteFile(const string& fileName);
//Display buffer state
void DisplayBuffers();
//Check if file is registered in the bufferpool.
bool IsFileRegistered(const string& fileName);
//Check if the file is in the disk.
bool IsFileExist(const string& fileName);
//Display loaded file state
//void DisplayFiles();
//觉得有功能不够的话可以让我加
BufferManager();
~BufferManager();
private:
Buffer** bufferPool;
FreeBuffer* freeBufferList;
map<string, map<int, int>> fileBuffer;
map<string, int> fileSize;
//return the index of the least recently used block, excluding the pinned block
int LRU();
//
int FetchBlockFromDisk(ifstream &is, int idx);
//
void WriteBlockToDisk(fstream &os, int idx, const char* block);
//
void WriteNewBlockToDisk(ofstream &os, int idx, const char* blockData);
//
void FreeBlock(int bufferIdx);
//
int GetFreeBufferIdx();
};
#endif | true |
37cb7943fff601a3e92bbff287e4bec899fe11b3 | C++ | abhirishi7/Algorithmic-Puzzles | /Matrix Multiplication/MatrixMultiplication.cpp | UTF-8 | 1,096 | 3.59375 | 4 | [] | no_license | /*
* MatrixMultiplication.cpp
*
* Created on: 03-Sep-2017
* Author: Abhishek Tripathi
*/
#include "MatrixMultiplication.h"
#include<iostream>
using namespace std;
int** matrixMul(int r1, int c1, int r2, int c2, int** mat1, int** mat2) {
int** result = new int*[r1];
for (int i = 0; i < r1; i++) {
result[i] = new int[c2];
for (int j = 0; j < c2; j++) {
result[i][j] = 0;
for (int k = 0; k < c1; k++) {
result[i][j] += mat1[i][k] * mat2[k][j];
}
}
}
return result;
}
int main() {
int r1, c1, r2, c2;
cin >> r1 >> c1 >> r2 >> c2;
cout << "Enter matrix 1" << endl;
int **mat1 = new int*[r1];
for (int i = 0; i < r1; i++) {
mat1[i] = new int[c1];
for (int j = 0; j < c1; j++)
cin >> mat1[i][j];
}
cout << "Enter matrix 2" << endl;
int **mat2 = new int*[r2];
for (int i = 0; i < r2; i++) {
mat2[i] = new int[c2];
for (int j = 0; j < c2; j++)
cin >> mat2[i][j];
}
int** mul = matrixMul(r1, c1, r2, c2, mat1, mat2);
for (int i = 0; i < r1; i++) {
for (int j = 0; j < c2; j++) {
cout << mul[i][j] << " ";
}
cout << endl;
}
return 0;
}
| true |
e182ea8f32ca3a6fc6772edacfeaaff886d18257 | C++ | mfueller/eventglue | /mcr_robinson_ros/ros/include/mcr_robinson_ros/RosEventGlue.h | UTF-8 | 1,472 | 2.59375 | 3 | [] | no_license | #ifndef ROSEVENTGLUE_H_
#define ROSEVENTGLUE_H_
#include "RosEvent.h"
#include "RosPort.h"
class RosEventGlue
{
public:
static EventPortOutput &ros_event_source(std::string topic_name, std::string event_name)
{
EventPortOutputROS *event_source = new EventPortOutputROS(topic_name, event_name);
//ros_event_sources.push_back(event_source);
return *event_source;
}
static EventPortInput &ros_event_sink(std::string topic_name, std::string event_name)
{
EventPortInputROS *event_sink = new EventPortInputROS(topic_name, event_name);
//ros_event_sinks.push_back(event_sink);
return *event_sink;
}
template<typename ROS_TYPE, typename MY_TYPE>
static typename DataPortOutput<MY_TYPE>::type &port_from_ros_topic(std::string topic_name)
{
DataPortOutputROS<ROS_TYPE, MY_TYPE> *in_port = new DataPortOutputROS<ROS_TYPE, MY_TYPE>(topic_name);
//ros_in_ports.push_back(in_port);
return *in_port;
}
template<typename ROS_TYPE, typename MY_TYPE>
static typename DataPortInput<MY_TYPE>::type &port_to_ros_topic(std::string topic_name)
{
DataPortInputROS<ROS_TYPE, MY_TYPE> *in_port(new DataPortInputROS<ROS_TYPE, MY_TYPE>(topic_name));
//ros_out_ports.push_back(in_port);
return *in_port;
}
};
#endif
| true |
48368f1de872137eecd8ae5e70895c381e645de9 | C++ | DawsonMeyer/UVAProblems | /497.cc | UTF-8 | 1,440 | 2.9375 | 3 | [] | no_license | /*
Dawson Meyer
Problem #497: Strategic Defence Initiative
Need to dynamically allocate the space in the data structure. So use a
Vector.
*/
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
vector<int> M;
//changing Howard's code to work with vectors that get passed in
int sasc_seq(vector<int> v1, int S[])
{
vector<int> last(v1.size()+1), pos(v1.size()+1), pred(v1.size());
if (v1.size() == 0) {
return 0;
}
int len = 1;
last[1] = v1[pos[1] = 0];
for (int i = 1; i < v1.size(); i++) {
int j = lower_bound(last.begin()+1, last.begin()+len+1, v1[i]) -
last.begin();
pred[i] = (j-1 > 0) ? pos[j-1] : -1;
last[j] = v1[pos[j] = i];
len = max(len, j);
}
int start = pos[len];
for (int i = len-1; i >= 0; i--) {
S[i] = v1[start];
start = pred[start];
}
return len;
}
int main()
{
int N;
cin >> N;
cin.ignore();
cin.ignore();
while(N)
{
M.clear();
N--;
string temp;
int alt;
while(getline(cin, temp) && temp != "")
{
alt = stoi(temp, 0, 10);
M.push_back(alt);
}
int ans=0;
int *S = new int[M.size()];
ans = sasc_seq(M, S);
cout << "Max hits: " << ans << endl;
for(int i=0; i < ans; i++)
{
cout << S[i] << endl;
}
delete S;
if(N)
{
cout << endl;
}
}
return 0;
}
| true |
816ccfa16302016b65c2f9179c95ed938bd86183 | C++ | JuntaoLiu01/LeetCode | /Array/FDN.cpp | UTF-8 | 956 | 3.109375 | 3 | [] | no_license | #include <vector>
using namespace std;
class Solution {
public:
int findDuplicate(vector<int>& nums) {
int left = 1,right = nums.size()-1;
while(left < right){
int mid = (left+right)/2;
int cnt = 0;
for(auto a:nums){
if(a <= mid)
cnt++;
}
if(cnt > mid)
right = mid;
else
left = mid + 1;
}
return left;
}
};
// O(n) method
class Solution2 {
public:
int findDuplicate(vector<int>& nums) {
int slow = 0,fast = 0;
while(true){
slow = nums[slow];
fast = nums[nums[fast]];
if(slow == fast)
break;
}
int start = 0;
while(true){
slow = nums[slow];
start = nums[start];
if(slow == start)
break;
}
return slow;
}
}; | true |
ccae11320406fe9ef8ca308a4755e12941e5acf3 | C++ | Rigel09/CRW_2021_Teensy_Data_Record | /src/main.cpp | UTF-8 | 2,230 | 2.671875 | 3 | [
"MIT"
] | permissive | /*
Retrieves sensor data and writes to a csv file on the sd card
Sensors:
Magnetometer x1
Accelerometer x3
Gyroscope x3
Author: Charger Rocket Works 2021/2022 Team
Date: Fall 2021
*/
#include "Arduino.h"
#include "SPI.h"
#include "SdFat.h"
#include "include/ADXL356_Accelerometer.hpp"
//------------------------------------------------------------------------------
// Store error strings in flash to save RAM.
#define error(s) sd.errorHalt(&Serial, F(s))
// Use built-in SD for SPI modes on Teensy 3.5/3.6.
// Teensy 4.0 use first SPI port.
// SDCARD_SS_PIN is defined for the built-in SD on some boards.
#ifndef SDCARD_SS_PIN
const uint8_t SD_CS_PIN = SS;
#else // SDCARD_SS_PIN
// Assume built-in SD is used.
const uint8_t SD_CS_PIN = SDCARD_SS_PIN;
#endif // SDCARD_SS_PIN
// SD_FAT_TYPE = 0 for SdFat/File as defined in SdFatConfig.h,
// 1 for FAT16/FAT32, 2 for exFAT, 3 for FAT16/FAT32 and exFAT.
#define SD_FAT_TYPE 3
// Try to select the best SD card configuration.
#if HAS_SDIO_CLASS
# define SD_CONFIG SdioConfig(FIFO_SDIO)
#elif ENABLE_DEDICATED_SPI
# define SD_CONFIG SdSpiConfig(SD_CS_PIN, DEDICATED_SPI, SPI_CLOCK)
#else // HAS_SDIO_CLASS
# define SD_CONFIG SdSpiConfig(SD_CS_PIN, SHARED_SPI, SPI_CLOCK)
#endif // HAS_SDIO_CLASS
#define testFileName "testFile.csv"
// Sd card class
SdFs sd;
FsFile testFile;
void setup()
{
pinMode(LED_BUILTIN, OUTPUT);
Serial.begin(9600);
Serial.println("Mounting SD Card");
// Initialize the SD.
if (!sd.begin(SD_CONFIG))
{
sd.initErrorHalt(&Serial);
return;
}
Serial.println("SD Card Succesfully mounted");
Serial.print("Attempting to open test file ");
Serial.println(testFileName);
// Create the file.
if (!testFile.open(testFileName, FILE_WRITE))
{
error("open failed");
}
Serial.println("Test file open, writing some data.......");
// Write test data.
testFile.print(F(
"abc,123,456,7.89\r\n"
"def,-321,654,-9.87\r\n"
"ghi,333,0xff,5.55"));
testFile.close();
Serial.println("Example data written and file closed.");
}
void loop()
{
digitalWriteFast(LED_BUILTIN, !digitalReadFast(LED_BUILTIN));
delay(500);
}
| true |
40ec48aab7492b895b16fc9c2cacc27edd992a2d | C++ | pongsh/aizuoj | /volume_1/0100.cpp | UTF-8 | 807 | 2.640625 | 3 | [] | no_license | #include <iostream>
#include <map>
#include <vector>
using namespace std;
int main() {
int N;
while (cin >> N && N != 0) {
cin.get();
map<int, long long> sales;
vector<int> sequence;
int i;
long long p, q;
for (int n = 0; n != N; ++n) {
cin >> i >> p >> q;
if (!sales.count(i)) {
sequence.push_back(i);
}
sales[i] += p * q;
}
bool printNA = true;
for (int i = 0; i != sequence.size(); ++i) {
if (sales[sequence[i]] >= 1000000) {
cout << sequence[i] << endl;
printNA = false;
}
}
if (printNA) {
cout << "NA" << endl;
}
}
return 0;
} | true |
b7988a74157ef9131ce7db5ed76981094192ba51 | C++ | boomitsnoom/ray | /cpp/src/ray/test/cluster/cluster_mode_test.cc | UTF-8 | 2,879 | 2.5625 | 3 | [
"Apache-2.0",
"MIT"
] | permissive |
#include <gtest/gtest.h>
#include <ray/api.h>
#include <ray/api/ray_config.h>
#include <ray/experimental/default_worker.h>
using namespace ::ray::api;
/// general function of user code
int Return1() { return 1; }
int Plus1(int x) { return x + 1; }
/// a class of user code
class Counter {
public:
int count;
Counter(int init) { count = init; }
static Counter *FactoryCreate() { return new Counter(0); }
static Counter *FactoryCreate(int init) { return new Counter(init); }
/// non static function
int Plus1() {
count += 1;
return count;
}
int Add(int x) {
count += x;
return count;
}
};
TEST(RayClusterModeTest, FullTest) {
/// initialization to cluster mode
ray::api::RayConfig::GetInstance()->run_mode = RunMode::CLUSTER;
/// TODO(Guyang Song): add the dynamic library name
ray::api::RayConfig::GetInstance()->lib_name = "";
Ray::Init();
/// put and get object
auto obj = Ray::Put(12345);
auto get_result = *(Ray::Get(obj));
EXPECT_EQ(12345, get_result);
/// common task without args
auto task_obj = Ray::Task(Return1).Remote();
int task_result = *(Ray::Get(task_obj));
EXPECT_EQ(1, task_result);
/// common task with args
task_obj = Ray::Task(Plus1, 5).Remote();
task_result = *(Ray::Get(task_obj));
EXPECT_EQ(6, task_result);
/// actor task without args
ActorHandle<Counter> actor1 = Ray::Actor(Counter::FactoryCreate).Remote();
auto actor_object1 = actor1.Task(&Counter::Plus1).Remote();
int actor_task_result1 = *(Ray::Get(actor_object1));
EXPECT_EQ(1, actor_task_result1);
/// actor task with args
ActorHandle<Counter> actor2 = Ray::Actor(Counter::FactoryCreate, 1).Remote();
auto actor_object2 = actor2.Task(&Counter::Add, 5).Remote();
int actor_task_result2 = *(Ray::Get(actor_object2));
EXPECT_EQ(6, actor_task_result2);
/// actor task with args which pass by reference
ActorHandle<Counter> actor3 = Ray::Actor(Counter::FactoryCreate, 6).Remote();
auto actor_object3 = actor3.Task(&Counter::Add, actor_object2).Remote();
int actor_task_result3 = *(Ray::Get(actor_object3));
EXPECT_EQ(12, actor_task_result3);
Ray::Shutdown();
}
/// TODO(Guyang Song): Separate default worker from this test.
/// Currently, we compile `default_worker` and `cluster_mode_test` in one single binary,
/// to work around a symbol conflicting issue.
/// This is the main function of the binary, and we use the `is_default_worker` arg to
/// tell if this binary is used as `default_worker` or `cluster_mode_test`.
int main(int argc, char **argv) {
const char *default_worker_magic = "is_default_worker";
/// `is_default_worker` is the last arg of `argv`
if (argc > 1 &&
memcmp(argv[argc - 1], default_worker_magic, strlen(default_worker_magic)) == 0) {
default_worker_main(argc, argv);
return 0;
}
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
} | true |
163f1a37757ba6561ea3ebbb4f0f7396f1a26ffa | C++ | MohammadAlhourani/Physics-lab-03 | /square physics/square physics/Game.cpp | UTF-8 | 3,505 | 2.9375 | 3 | [] | no_license | #include "Game.h"
#include <iostream>
#include <SFML/Graphics.hpp>
// Updates per milliseconds
static double const MS_PER_UPDATE = 10.0;
////////////////////////////////////////////////////////////
Game::Game()
: m_window(sf::VideoMode(800, 800, 32), "physics!", sf::Style::Default)
{
Square.setSize(sf::Vector2f(10, 10));
Square.setPosition(sf::Vector2f(400, 645));
Square.setOrigin(5, 5);
Ground.setSize(sf::Vector2f(800, 150));
Ground.setPosition(sf::Vector2f(0,650));
Ground.setFillColor(sf::Color::Green);
gravity = 5.0f * gravity;
if (Font.loadFromFile("ariblk.ttf"))
{
timerText.setFont(Font);
}
timerText.setCharacterSize(15);
timerText.setPosition(10, 20);
timerText.setFillColor(sf::Color::White);
}
void Game::Normalise()
{
normVel.x = Velocity.x / sqrt(Velocity.x * Velocity.x + Velocity.y * Velocity.y);
normVel.y = Velocity.y / sqrt(Velocity.x * Velocity.x + Velocity.y * Velocity.y);
}
sf::Vector2f Game::multiply(sf::Vector2f t_vector1, sf::Vector2f t_vector2)
{
sf::Vector2f temp = sf::Vector2f(t_vector1.x * t_vector2.x, t_vector1.y * t_vector2.y);
return temp;
}
////////////////////////////////////////////////////////////
void Game::run()
{
sf::Clock clock;
sf::Int32 lag = 0;
while (m_window.isOpen())
{
sf::Time dt = clock.restart();
lag += dt.asMilliseconds();
processEvents();
while (lag > MS_PER_UPDATE)
{
update(MS_PER_UPDATE);
lag -= MS_PER_UPDATE;
}
update(MS_PER_UPDATE);
render();
}
}
////////////////////////////////////////////////////////////
void Game::processEvents()
{
sf::Event event;
while (m_window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
{
m_window.close();
}
processGameEvents(event);
}
}
////////////////////////////////////////////////////////////
void Game::processGameEvents(sf::Event& event)
{
// check if the event is a a mouse button release
if (sf::Event::KeyPressed == event.type)
{
switch (event.key.code)
{
case sf::Keyboard::Escape:
m_window.close();
break;
case sf::Keyboard::W:
Velocity = sf::Vector2f(0, 150);
timer = 0;
break;
case sf::Keyboard::D:
Velocity = sf::Vector2f(150, 0);
timer = 0;
break;
case sf::Keyboard::A:
Velocity = sf::Vector2f(-150, 0);
timer = 0;
break;
case sf::Keyboard::S:
Square.setPosition(400, 645);
Velocity = sf::Vector2f(0, 0);
timer = 0;
break;
default:
break;
}
}
}
////////////////////////////////////////////////////////////
void Game::update(double dt)
{
time =dt/10000;
if (Square.getGlobalBounds().intersects(Ground.getGlobalBounds()) == false)
{
Square.setPosition(Square.getPosition() + (Velocity * time) + (0.5f * gravity * (time * time)));
Velocity = Velocity + (gravity * time);
}
else
{
Velocity.y = -(restitiution * Velocity.y);
Normalise();
Acceleration = -restitiution * gravity.y * normVel;
Square.setPosition(Square.getPosition() + (Velocity* time) + (0.5f * Acceleration * (time * time)));
Velocity = Velocity + (Acceleration * time);
}
if (Square.getPosition().x > 800 || Square.getPosition().x < 0)
{
Velocity = -1.0f * Velocity ;
}
if (Velocity.x > 0.1 || Velocity.x < -0.1 )
{
timer += time;
}
timerText.setString("Time = " + (std::to_string(timer)));
}
////////////////////////////////////////////////////////////
void Game::render()
{
m_window.clear(sf::Color(0, 0, 0, 0));
m_window.draw(Ground);
m_window.draw(Square);
m_window.draw(timerText);
m_window.display();
}
| true |
a5e577621f1358f6171eec25225afac6786c268f | C++ | ksmeeks0001/black_jack | /Deck.cpp | UTF-8 | 1,647 | 3.453125 | 3 | [] | no_license | #include <cstdlib>
#include <iostream>
#include <time.h>
#include "Deck.h"
#include "Card.h"
Deck::Deck()
{
srand(time(NULL)); // random seed to time
suits[0] = "Hearts";
suits[1] = "Diamonds";
suits[2] = "Spades";
suits[3] = "Clubs";
denoms[0] = "A";
denoms[1]= "2";
denoms[2]= "3";
denoms[3] = "4";
denoms[4]= "5";
denoms[5]= "6";
denoms[6]="7";
denoms[7]= "8";
denoms[8]="9";
denoms[9]= "10";
denoms[10]="J";
denoms[11]= "Q";
denoms[12] = "K";
//loop through the deck of cards and set suits and denominations
int index = 0;
for (int i=0; i<4; i++) //for each suit in suites array
{
for (int j=0; j<13;j++) //for each denomination in denoms array
{
cards[index].suit = suits[i];
cards[index].denom = denoms[j];
cards[index].set_value();
index += 1;
}
}
cards_left = 52;
shuffle();
shuffle();
}
void Deck::display_cards()
{
for (int i=0; i<52;i++)
{
cout << cards[i].denom << " of " << cards[i].suit << " value is " <<
cards[i].value << endl;
}
}
void Deck::shuffle()
{
for (int x = 0; x < 52; x++)
{
int random_index = (rand() % 52);
Card temp = cards[random_index];
cards[random_index] = cards[x];
cards[x] = temp;
}
}
Card Deck::deal(bool new_game)
{
static int index = 0;
Card deal;
if (new_game == false)
{
deal = cards[index];
index++;
return deal;
}
else
{
index = 0;
deal = cards[index];
index++;
return deal;
}
}
| true |
c7a1ca5ec1df187576bfea743df4eea622d0c688 | C++ | maggie-han/3rd-Polynomial-Fit | /FINAL least squares.cpp | UTF-8 | 2,867 | 3.765625 | 4 | [] | no_license | //Maggie Han
//AP physics assignment 0
//C programming Least Squares
//Accept a set of data then effect 3rd degree polynomial fit
//using least squares and Vandemonde matrix
#include <iostream>
#include <math.h>
#include <iomanip>
#include <cstdlib>
using namespace std;
int main()
{
//**************************************************input**********************************************
int size,ro,co;
cout<<"How many data points are available? ";
cin>>size;
ro=size;
double x[size];
double y[size];
double v[size][4];
double vt[4][size];
double vtv[size][size];
co=4;
cout<<"Key in the x values: \n";
for (int i=0;i<size;i++)
cin>>x[i];
cout<<"Key in the corresponding y values: \n";
for (int i=0;i<size;i++)
cin>>y[i];
//**************************************************processing**********************************************
//now create the vandermonde matrix in the form x^3+x^2+x^1+x^0 as well as its transpose
for (int i=0;i<ro;i++)
{
for (int j=0;j<co;j++)
{
v[i][j]=pow((x[i]),(3-j));
vt[j][i]=v[i][j];
}
}
//Calculate vtv
double temp;
for (int i=0;i<4;i++)
{
for (int j=0;j<4;j++)
{
temp=0; //this allows the value of each term to cumulate to the sum that is vtv in each cell
for (int k=0;k<size;k++)
{
temp= temp+ vt[i][k]*v[k][j];
}
vtv[i][j]=temp; //writes value into vtv matrix
}
}
//**************************************************output**********************************************
system("cls");
cout<<"This is the Vandermonde Matrix: ";
for (int i=0;i<ro;i++)
{
cout<<"\n";
for (int j=0;j<co;j++)
{
cout<<v[i][j]<<setw(15);
}
}
cout<<"\n\nThis is the Transposed Vandermonde Matrix: ";
for (int i=0;i<co;i++)
{
cout<<"\n";
for (int j=0;j<ro;j++)
{
cout<<vt[i][j]<<setw(9);
}
}
cout<<"\n\nThis is VtV: ";
for (int i=0;i<4;i++)
{
cout<<"\n";
for (int j=0;j<4;j++)
{
cout<<vtv[i][j]<<setw(15);
}
}
//display the input data
cout<<"\n\nThese are the data inputted";
cout<<"\nx"<<setw(15)<<"y\n";
for (int i=0;i<size;i++)
cout<<x[i]<<setw(15)<<y[i]<<"\n";
}
| true |
754f4dbbda4bff38364878581001b7d023a415cc | C++ | Nightmare4214/connect_four | /Project1/AlphaBetaPruning.cpp | GB18030 | 16,762 | 2.796875 | 3 | [] | no_license | #include "AlphaBetaPruning.hpp"
#include"TranspositionTable.hpp"
#include<conio.h>
int AlphaBetaPruning::getScore(const uint64_t & currentMove)const
{
uint64_t pos = getWinPositions(bitBoard | currentMove, mask);
int cnt = 0;
while (0 != pos) {
++cnt;
pos &= pos - 1;
}
return cnt;
}
uint64_t AlphaBetaPruning::topMask(const int & col)
{
/*
1ULL << (HEIGHT - 1)1ƵHEIGHT-1λ(Ҳ̵)
ȻƵcol
*/
return (1ULL << (HEIGHT - 1)) << ((HEIGHT + 1)*col);
}
uint64_t AlphaBetaPruning::bottomMask(const int & col)
{
return 1ULL << ((HEIGHT + 1)*col);
}
uint64_t AlphaBetaPruning::columnMask(const int & col)
{
return (((1ULL << HEIGHT) - 1) << (col*(HEIGHT + 1)));
}
uint64_t AlphaBetaPruning::getWinPositions(const uint64_t & position, const uint64_t & boardMask)
{
//ֱ(Ѿγ3)
uint64_t result = (position << 1) & (position << 2) & (position << 3);
//ˮƽ
uint64_t temp = (position << (HEIGHT + 1))&(position << ((HEIGHT + 1) << 1));
//γ3ʤұߵ
result |= temp & (position << (3 * (HEIGHT + 1)));
//xx_x
result |= temp & (position >> (HEIGHT + 1));
temp = (position >> (HEIGHT + 1))&(position >> ((HEIGHT + 1) << 1));
//γ3ʤߵ
result |= temp & (position >> (3 * (HEIGHT + 1)));
//x_xx
result |= temp & (position << (HEIGHT + 1));
//Խ
temp = (position << HEIGHT)&(position << (HEIGHT << 1));
//γ3ʤ·
result |= temp & (position << (3 * HEIGHT));
//бxx_x
result |= temp & (position >> HEIGHT);
temp = (position >> HEIGHT)&(position >> (HEIGHT << 1));
//γ3ʤϷ
result |= temp & (position >> (3 * HEIGHT));
//бx_xx
result |= temp & (position << HEIGHT);
//Խ
temp = (position << (HEIGHT + 2))&(position << ((HEIGHT + 2) << 1));
//γ3ʤϷ
result |= temp & (position << (3 * (HEIGHT + 2)));
//бxx_x
result |= temp & (position >> (HEIGHT + 2));
temp = (position >> (HEIGHT + 2))&(position >> ((HEIGHT + 2) << 1));
//γ3ʤ·
result |= temp & (position >> (3 * (HEIGHT + 2)));
//бx_xx
result |= temp & (position << (HEIGHT + 2));
return result & (boardValidMask ^ boardMask);
}
uint64_t AlphaBetaPruning::getAllValidPositions() const
{
return (mask + allBottomMask)&boardValidMask;
}
uint64_t AlphaBetaPruning::getAllCurrentPlayerWinPositions() const
{
return getWinPositions(bitBoard, mask);
}
uint64_t AlphaBetaPruning::getAllOpponentWinPositions() const
{
return getWinPositions(bitBoard^mask, mask);
}
uint64_t AlphaBetaPruning::getAllNotLosePositions(int & forcedMove)
{
//µλ
uint64_t validMask = getAllValidPositions();
//ֻӮλ
uint64_t opponentWinPositions = getAllOpponentWinPositions();
//ӮĺϷλ
uint64_t forcedMask = validMask & opponentWinPositions;
if (0 != forcedMask) {
//forcedMask-1൱ƻһʤ㣬֮Ϊ0˵˫
if (0 != (forcedMask&(forcedMask - 1))) {
for (int i = 0; i < WIDTH; ++i) {
//˫־Ҹط°
if (0 != (columnMask(i)&forcedMask)) {
forcedMove = i;
return 0;
}
}
return 0;
}//ֻһʤ,
else return forcedMask;
}
//opponentWinPositions >> 1 Ӯλһλ
uint64_t nextPosition = validMask & (~(opponentWinPositions >> 1));
if (0 == nextPosition) {
for (int i = 0; i < WIDTH; ++i) {
//־ӮˣȻûѡ
if (0 != (columnMask(i)&validMask)) {
forcedMove = i;
return 0;
}
}
return 0;
}
else return nextPosition;
}
uint64_t AlphaBetaPruning::getKey() const
{
return bitBoard + mask + allBottomMask;
}
int AlphaBetaPruning::getCorrectCol() const
{
string temp;
int col;
while (cin >> temp) {
try {
col = stoi(temp);
if (col < 0 || col >= WIDTH) {
_cprintf("row ERROR,please enter the correct row\r\n");
}
else if (!canPlay(col)) {
_cprintf("row full,please enter the correct row\r\n");
}
else return col;
}
catch (exception e) {
_cprintf("row ERROR,please enter the correct row\r\n");
}
}
return 0;
}
int AlphaBetaPruning::evaluate(const int & player, const bool& opponentFlag) const
{
int opponent = -player;
int score = 0;
//ŵ
for (int i = 0; i < WIDTH; ++i) {
for (int j = 0; j <= HEIGHT - 4; ++j) {
int playerCnt = 0, opponentCnt = 0;
for (int k = 0; k < 4; ++k) {
int temp = board[i][j + k];
if (temp == player)++playerCnt;
else if (temp == opponent) {
++opponentCnt;
break;
}
}
if (opponentCnt != 0)continue;
else if (4 == playerCnt)score += 1000000;
else if (3 == playerCnt)score += 100000;
else if (2 == playerCnt)score += 100;
else if (1 == playerCnt)score += 50;
}
}
//ֱ
for (int j = 0; j < HEIGHT; ++j) {
for (int i = 0; i <= WIDTH - 4; ++i) {
int playerCnt = 0, opponentCnt = 0;
for (int k = 0; k < 4; ++k) {
int temp = board[i + k][j];
if (temp == player)++playerCnt;
else if (temp == opponent) {
++opponentCnt;
break;
}
}
if (opponentCnt != 0)continue;
else if (4 == playerCnt)score += 1000000;
else if (3 == playerCnt)score += 50000;
else if (2 == playerCnt)score += 100;
else if (1 == playerCnt)score += 50;
}
}
//Խy=-x+bias
for (int bias = 3; bias <= HEIGHT + WIDTH - 5; ++bias) {
int x = 0, y = bias;
if (y >= HEIGHT) {
y = HEIGHT - 1;
x = -y + bias;
}
while (x < WIDTH&&y >= 0 && x + 3 < WIDTH&&y - 3 >= 0) {
int playerCnt = 0, opponentCnt = 0;
for (int k = 0; k < 4; ++k) {
int temp = board[x + k][y - k];
if (temp == player)++playerCnt;
else if (temp == opponent) {
++opponentCnt;
break;
}
}
++x;
--y;
if (opponentCnt != 0)continue;
else if (4 == playerCnt)score += 1000000;
else if (3 == playerCnt)score += 30000;
else if (2 == playerCnt)score += 100;
else if (1 == playerCnt)score += 50;
}
}
//Խy=x+bias
for (int bias = HEIGHT - 4; bias >= 4 - WIDTH; --bias) {
int x = 0, y = bias;
if (y < 0) {
y = 0;
x = -bias;
}
while (x >= 0 && y < HEIGHT&&x + 3 < WIDTH&&y + 3 < HEIGHT) {
int playerCnt = 0, opponentCnt = 0;
for (int k = 0; k < 4; ++k) {
int temp = board[x + k][y + k];
if (temp == player)++playerCnt;
else if (temp == opponent) {
++opponentCnt;
break;
}
}
++x;
++y;
if (opponentCnt != 0)continue;
else if (4 == playerCnt)score += 1000000;
else if (3 == playerCnt)score += 30000;
else if (2 == playerCnt)score += 100;
else if (1 == playerCnt)score += 50;
}
}
return score;
}
int AlphaBetaPruning::alphaBetaPruning(int depth, int alpha, int beta, int player, int & move)
{
move = -1;
++searchedPosition;
bool findedFlag;
//hashֵ
int hashVal = table.probeHash(getKey(), depth, alpha, beta, move, findedFlag);
int hashFlag = TranspositionTableNode::ALPHA_FLAG;
//Ѿѹˣֱӷ
//TranspositionTable::unknown != hashVal || findedFlag
if (findedFlag) {
++ttHitCnt;
return hashVal;
}
//ж֮ʤ
for (const int &i : columnOrder) {
if (!canPlay(i))continue;
if (isWinMove(i, true)) {
move = i;
return (INF >> 1) - HEIGHT * WIDTH - round;
}
}
int twoCnt = 0, forcedMove;
//ԼĻ
for (int i = 0; i < WIDTH; ++i) {
if (!canPlay(i))continue;
uint64_t playedMask = ((mask + bottomMask(i)) & columnMask(i));
uint64_t winTwo = (getWinPositions(bitBoard | playedMask, mask | playedMask)&getAllValidPositions());
if (0 != (winTwo&(winTwo - 1))) {
move = i;
return (INF >> 1) - HEIGHT * WIDTH - round - 2;
}
}
//һµ
uint64_t nextPosition = getAllNotLosePositions(forcedMove);
//˫
if (0 == nextPosition) {
move = forcedMove;
return (INF >> 1) - HEIGHT * WIDTH - round - 1;
}
//ֻ
twoCnt = 0;
for (int i = 0; i < WIDTH; ++i) {
//Ҫµλ
uint64_t playedMask = (nextPosition&columnMask(i));
if (0 == playedMask)continue;
uint64_t opponent = (getWinPositions(((bitBoard^mask) | playedMask), mask | playedMask)&getAllValidPositions());
//ȥǻ3
if (0 != (opponent & (opponent - 1))) {
++twoCnt;
nextPosition = playedMask;
break;
}
}
//ﵽ
if (depth <= 0) {
//÷=Լ-ֵ
int tempVal = evaluate(player) - evaluate(-player);
table.recordHash(getKey(), tempVal, depth, TranspositionTableNode::EXACT_FLAG, -1);
return tempVal;
}
MoveSorter moveSorter;
for (int i = WIDTH - 1; i >= 0; --i) {
uint64_t playedMask = nextPosition & columnMask(columnOrder[i]);
if (0 == playedMask)continue;
moveSorter.addMove(columnOrder[i], getScore(playedMask));
}
//м¼ŷ
if (findedFlag&&-1 != move) {
moveSorter.changeOrder(move);
}
int tempMove;
while (!moveSorter.isEmpty()) {
int i = moveSorter.getNextMove();
//if (0 == (nextPosition & columnMask(i)))continue;
play(i, player);
++currentDepth;
int val;
if (HEIGHT*WIDTH == round)val = 0;
else val = -alphaBetaPruning(depth - 1, -beta, -alpha, -player, tempMove);
undo(i);
--currentDepth;
if (val >= beta) {
table.recordHash(getKey(), beta, depth, TranspositionTableNode::BETA_FLAG, i);
return beta;
}
if (val > alpha) {
hashFlag = TranspositionTableNode::EXACT_FLAG;
move = i;
alpha = val;
}
}
table.recordHash(getKey(), depth, alpha, hashFlag, move);
return alpha;
}
int AlphaBetaPruning::getColByAlphaBetaPruning(const int & player)
{
int opponentWinMove[2];
int size = 0;
for (int i = 0; i < WIDTH; ++i) {
//һӮ
if (isWinMove(i, true))return i;
else if (isWinMove(i, true, true)) {
if (size < 2) {
opponentWinMove[size] = i;
++size;
}
}
}
//Էһ֣
if (0 != size)return opponentWinMove[0];
//table.reset();
int col;
ttHitCnt = 0;
searchedPosition = 0;
alphaBetaPruning(maxDepth, -INF, INF, player, col);
_cprintf("hit:%d\r\n", ttHitCnt);
_cprintf("all:%d\r\n", searchedPosition);
_cprintf("hit rate:%lf%%\r\n", ttHitCnt * 100.0 / searchedPosition);
return col;
}
void AlphaBetaPruning::initSocket()
{
WSAStartup(MAKEWORD(2, 2), &wsaData);
//½ͻsocket
sockClient = socket(AF_INET, SOCK_STREAM, 0);
//Ҫӵķ˵ַ
addrServer.sin_family = AF_INET;
addrServer.sin_port = htons(PORT);//Ӷ˿
addrServer.sin_addr.S_un.S_addr = inet_addr(IP);
if (connect(sockClient, (SOCKADDR*)&addrServer, sizeof(addrServer)) < 0)
{
throw "δӵ\n";
}
}
void AlphaBetaPruning::closeSocket()
{
closesocket(sockClient);
WSACleanup();
}
void AlphaBetaPruning::sendData(const string & msg) const
{
if (send(sockClient, msg.data(), msg.length(), 0) != SOCKET_ERROR) {
_cprintf("Client:%s\r\n", msg.data());
}
else {
_cprintf("send error!!!\r\n");
}
}
string AlphaBetaPruning::recvData() const
{
char message[Len] = { 0 };
if (recv(sockClient, message, Len, 0) < 0)
{
_cprintf("receive error!!!\r\n");
return GameOver;
}
else
{
_cprintf("Server:%s\r\n", message);
string msg(message);
return msg.substr(0, msg.find_first_of('\r'));
}
}
AlphaBetaPruning::AlphaBetaPruning()
{
for (int i = 0; i < WIDTH; i++) {
columnOrder[i] = WIDTH / 2 + (1 - 2 * (i % 2))*(i + 1) / 2;
}
}
void AlphaBetaPruning::printBoard() const
{
_cprintf("***********************\r\n");
for (int j = HEIGHT - 1; j >= 0; --j) {
for (int i = 0; i < WIDTH; ++i) {
_cprintf("|");
if (0 == board[i][j])_cprintf("_");
else if (1 == board[i][j])_cprintf("X");
else _cprintf("O");
}
_cprintf("|\r\n");
}
for (int i = 0; i < WIDTH; ++i)_cprintf(" %d", i);
_cprintf(" \r\n");
_cprintf("***********************\r\n");
}
bool AlphaBetaPruning::canPlay(const int & col) const
{
return 0 == (mask & topMask(col));
}
void AlphaBetaPruning::play(const int & col, const int & player)
{
board[col][currentHeight[col]] = player;
bitBoard ^= mask;
mask |= mask + bottomMask(col);
++currentHeight[col];
++round;
}
void AlphaBetaPruning::undo(const int & col)
{
--currentHeight[col];
board[col][currentHeight[col]] = 0;
mask &= ~((1ULL << currentHeight[col]) << (col*(HEIGHT + 1)));
bitBoard ^= mask;
--round;
}
void AlphaBetaPruning::initPlay(const string & s)
{
int player = 1;
for (const char &c : s) {
play(c - '1', player);
player = -player;
}
}
bool AlphaBetaPruning::isWinMove(const int& lastCol, const bool& predict, const bool& isOpponent) const
{
uint64_t tempBoard = bitBoard;
//Ԥ
if (predict) {
if (isOpponent)tempBoard ^= mask;
//play֮ǰʾԼģԽҪµм1ͺ
tempBoard |= (mask + bottomMask(lastCol))&columnMask(lastCol);
}
else {
//play֮ʾֵģһʾԼ
tempBoard ^= mask;
}
/*
ֱ
tempBorad tempMask tempMask&(tempMask >> 2
1 0 0 0 0
1 1 1 0 0
1 1 1 0 0
1 1 1 1 1
0 1 0 1 0
0 0 0 1 0
*/
uint64_t tempMask = tempBoard & (tempBoard >> 1);
if (0 != (tempMask&(tempMask >> 2)))return true;
//ˮƽ
//height+1൱Ƶǰһͬһ
tempMask = tempBoard & (tempBoard >> (HEIGHT + 1));
if (0 != (tempMask&(tempMask >> ((HEIGHT + 1) << 1))))return true;
//Խ
//height+2൱Ƶǰһͬһеһ
tempMask = tempBoard & (tempBoard >> (HEIGHT + 2));
if (0 != (tempMask&(tempMask >> ((HEIGHT + 2) << 1))))return true;
//Խ
//height+1൱Ƶǰһͬһеһ
tempMask = tempBoard & (tempBoard >> HEIGHT);
return (0 != (tempMask&(tempMask >> (HEIGHT << 1))));
}
bool AlphaBetaPruning::isEnd(const int & lastCol, const int & player) const
{
if (isWinMove(lastCol, false)) {
if (1 == player)_cprintf("X");
else _cprintf("O");
_cprintf("Win\r\n");
return true;
}
else if (HEIGHT*WIDTH == round) {
_cprintf("draw\r\n");
return true;
}
else return false;
}
void AlphaBetaPruning::pvp()
{
printBoard();
int col;
//ǷֵX
int player = 1;
while (true) {
if (player)_cprintf("X turn\r\n");
else _cprintf("O turn\r\n");
col = getCorrectCol();
play(col, player);
printBoard();
if (isEnd(col, player))return;
player = -player;
}
}
void AlphaBetaPruning::pve(const bool & firstFlag)
{
int col;
int player = 1;
printBoard();
while (true) {
if (firstFlag) {
_cprintf("X turn\r\n");
col = getCorrectCol();
play(col, player);
printBoard();
if (isEnd(col, player))return;
player = -player;
_cprintf("O turn\r\n");
col = getColByAlphaBetaPruning(player);
_cprintf("%d\r\n", col);
}
else {
_cprintf("X turn\r\n");
col = getColByAlphaBetaPruning(player);
_cprintf("%d\r\n", col);
play(col, player);
printBoard();
if (isEnd(col, player))return;
player = -player;
_cprintf("O turn\r\n");
col = getCorrectCol();
}
play(col, player);
printBoard();
if (isEnd(col, player))return;
player = -player;
}
}
void AlphaBetaPruning::AI_course_socket()
{
int col;
int player = 1;
try
{
initSocket();
sendData(TeamName);
string msg = recvData();
int out;
if (msg == Success) {
while (true) {
msg = recvData();
if (!(msg == GameOver)) {
if (msg == Begin) {
col = getColByAlphaBetaPruning(player);
play(col, player);
player = -player;
out = col + 1;
}
else {
int in = stoi(msg);
play(in - 1, player);
player = -player;
col = getColByAlphaBetaPruning(player);
play(col, player);
player = -player;
out = col + 1;
}
sendData(to_string(out));
}
else {
break;
}
}
}
closeSocket();
}
catch (exception e)
{
printf(e.what());
}
}
MoveSorter::MoveSorter() :moveSorterSize(0)
{
}
void MoveSorter::addMove(const int & move, const int & score)
{
int pos = moveSorterSize;
++moveSorterSize;
//
while (pos > 0 && container[pos - 1].score > score) {
container[pos] = container[pos - 1];
--pos;
}
container[pos].setData(move, score);
}
int MoveSorter::getNextMove()
{
--moveSorterSize;
return container[moveSorterSize].move;
}
void MoveSorter::changeOrder(const int & move)
{
for (int i = 0; i < AlphaBetaPruning::WIDTH; ++i) {
if (container[i].move == move) {
swap(container[i], container[moveSorterSize - 1]);
break;
}
}
}
bool MoveSorter::isEmpty() const
{
return 0 == moveSorterSize;
}
| true |
81019e106cdb98b3bf06bb109d502e4941d029a7 | C++ | qianzhanwang/libnet | /src/epollctrl.cpp | UTF-8 | 1,204 | 2.5625 | 3 | [] | no_license | #include "epollctrl.h"
#include <unistd.h>
EpollCtrl::EpollCtrl ()
:EpollUserData(EpollUserData::et_ctrlor)
{
m_nfds[0] = 0;
m_nfds[1] = 0;
}
EpollCtrl::~EpollCtrl ()
{
}
bool EpollCtrl::Init(std::functioal<void()> cb)
{
m_cbHandleCmd = cb;
if (pipe(m_nfds) < 0)
{
return false;
}
return true;
}
bool EpollCtrl::Release()
{
if (m_nfds[0] > 0)
{
close(m_nfds[0]);
}
if (m_nfds[1] > 0)
{
close(m_nfds[1]);
}
m_nfds[0] = 0;
m_nfds[1] = 0;
return true;
}
void EpollCtrl::Handle(int nEvent)
{
bool bRead = (nEvent & EPOLLIN);
if (!bRead)
{
// log
return;
}
int len = 0;
char buf[4*1024];
do
{
int ret = read(m_nfds[0], buf, sizeof(buf));
if (ret <= 0)
{
break;
}
len += ret;
} while (true);
if (m_cbHandleCmd)
{
m_cbHandleCmd(len);
}
}
int EpollCtrl::OnPush()
{
do
{
int ret = write(m_nfds[1], "C", 1);
if (ret < 0 && (errno == EINTR))
{
// 中断重试
continue;
}
return ret;
} while (true);
} | true |
5bec85a3cb21727f92c039431ceb981d9e048870 | C++ | juankzero/EjerciciosProgramacion3_P3A20 | /EjemploPolimorfismo/Figura2D.h | UTF-8 | 339 | 2.84375 | 3 | [] | no_license | #pragma once
#ifndef FIGURA2D_H
#define FIGURA2D_H
enum TipoFigura
{
tRectangulo, //0
tTrianguloRectangulo, //1
tCirculo //2
};
//definicion de clase abstracta
class Figura2D
{
public:
virtual float getArea() = 0;
virtual float getPerimetro() = 0;
virtual void imprimirFigura() = 0;
virtual TipoFigura getTipo() = 0;
};
#endif | true |
c31f45ba9370158b3541ab0ebdd12f1bfc5f30ba | C++ | Candlemancer/Freshman-Year | /CS 1410 - Intermediate Computer Science/Recursion/Recursion.cpp | UTF-8 | 5,104 | 3.46875 | 3 | [] | no_license | // Jonathan Petersen
// A01236750
// Recursion Examples
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int cannonball(int);
void printBinary(int);
int sumOfDigits(int);
void maze(string);
void solver(bool&, char**&, int&, int&, int, int);
int main() {
cout << "Cannonball Example ==============================\n"
<< "Pyramid with 1 level : " << cannonball( 1) << " cannonballs.\n"
<< "Pyramid with 42 levels: " << cannonball(42) << " cannonballs.\n"
<< "=================================================\n" << endl;
cout << "Binary Conversion Example =======================\n"
<< "The number 1 in binary is: "; printBinary( 1); cout << ".\n"
<< "The number 42 in binary is: "; printBinary(42); cout << ".\n"
<< "=================================================\n" << endl;
cout << "Sum of Digits Example ===========================\n"
<< "The sum of the digits of 1 is: " << sumOfDigits( 1) << ".\n"
<< "The sum of the digits of 42 is: " << sumOfDigits(42) << ".\n"
<< "=================================================\n" << endl;
cout << "Maze Solver Example =============================\n"
<< "Maze Solution 1 ( maze.txt): --------------------\n";
maze("maze");
cout << "Maze Solution 2 (maze2.txt): --------------------\n";
maze("maze2");
cout << "=================================================\n" << endl;
cout << "maze2.txt will now self-destruct." << endl;
remove("maze2.txt");
return 0;
}
//Count the number of cannonballs in a pyramid based on levels
int cannonball(int level) {
//Base Case
if(level < 1) return 0;
//Alternative Case
return ( (level*level) + cannonball(level - 1) );
}
//Print out the binary representation of a number
void printBinary(int n) {
//Base Case
if(n / 2 == 0) {cout << (n % 2); return;}
//Alternative case
printBinary(n / 2);
cout << n % 2;
return;
}
//Find the sum of all the digits in a number
int sumOfDigits(int num) {
//Base Case
if(num < 10) return num;
//Alternative Case
return ( (num % 10) + sumOfDigits(num / 10) );
}
//Solve a maze. This function only sets up file I/O, see below for the solver.
void maze(string filename) {
ifstream file (filename + ".txt");
ofstream newfile;
char** maze;
int rows, cols;
int xpos, ypos;
bool solved = false; // Defined here so I only need once instance of the variable.
//See if there is a maze file, and if not create a generic one.
if(!file) {
cout << "No file by the name of " + filename + ".txt could be located.\n"
<< "Generating new file.\n";
newfile.open(filename + ".txt");
newfile << "11 10" << endl
<< "9 4" << endl
<< "XXXXXXXXXX" //<< endl
<< "XX...tX..X" //<< endl
<< "XX.XXXX.XX" //<< endl
<< "XX.......X" //<< endl
<< "XXXXXXX.XX" //<< endl
<< "X....XX.XX" //<< endl
<< "X.XX.....X" //<< endl
<< "X...XX.XXX" //<< endl
<< "XXX..XXXXX" //<< endl
<< "XXXX....XX" //<< endl
<< "XXXXXXXXXX";
newfile.close();
file.open(filename + ".txt");
}
//Insure all variables are properly initialized.
if( !(file >> rows) || !(file >> cols) || !(file >> xpos) || !(file >> ypos) ) {
cout << filename + ".txt is not properly formatted. Program will now exit." << endl;
//system("pause");
exit(EXIT_FAILURE);
}
//cout << "SIZE: " << rows << "x" << cols << endl;
//cout << "START: " << xpos << "," << ypos << endl;
file.get();
//Setup the maze array.
maze = new char* [rows];
for(int i=0; i<rows; i++) {
maze[i] = new char [cols];
}
//Form the array
for(int i=0; i<rows; i++) {
for(int j=0; j<cols; j++) {
maze[i][j] = file.get();
}
}
solver(solved, maze, rows, cols, xpos, ypos);
//Print the array
for(int i=0; i<rows; i++) {
for(int j=0; j<cols; j++) {
cout << " " << maze[i][j];
}
cout << endl;
}
//Delete the maze array
for(int i=0; i<rows; i++) {
delete [] maze[i];
}
delete [] maze;
file.close();
return;
}
void solver(bool& solved, char**& maze, int& rows, int& cols, int xpos, int ypos) {
//Base Case
if(maze[xpos][ypos] == 't') {cout << "Treasure found at [" << xpos << ", " << ypos << "]! Congratulations!\n"; solved = true; return;}
if(solved) return;
//Alternative Cases
maze[xpos][ypos] = '!';
if(xpos < rows) if(maze[xpos - 1][ypos] != 'X' && maze[xpos - 1][ypos] != '!') solver(solved, maze, rows, cols, (xpos - 1), ypos);
if(ypos < cols) if(maze[xpos][ypos + 1] != 'X' && maze[xpos][ypos + 1] != '!') solver(solved, maze, rows, cols, xpos, (ypos + 1));
if(ypos > 0) if(maze[xpos][ypos - 1] != 'X' && maze[xpos][ypos - 1] != '!') solver(solved, maze, rows, cols, xpos, (ypos - 1));
if(xpos > 0) if(maze[xpos + 1][ypos] != 'X' && maze[xpos + 1][ypos] != '!') solver(solved, maze, rows, cols, (xpos + 1), ypos);
//Print Correct Path
if(solved) {cout << "Treasure path is: [" << xpos << ", " << ypos << "]\n"; return;}
return;
} | true |
97c244a39f549b5af407e9473c39e71ad8d1237e | C++ | tbobo555/CrazyRat | /Classes/Controller/GameController.cpp | UTF-8 | 25,407 | 2.796875 | 3 | [] | no_license | #include "GameController.h"
namespace Controller
{
GameController* GameController::instance = new GameController::GameController();
GameController::GameController(){}
GameController* GameController::getInstance()
{
return instance;
}
void GameController::loadMenuSceneResource()
{
auto menuScene = new MenuScene();
menuScene->initScene();
SceneManager::getInstance()->setWithKey("MenuScene", menuScene);
}
void GameController::releaseMenuSceneResource()
{
auto menuScene = SceneManager::getInstance()->getByKey("MenuScene");
menuScene->releaseScene();
SceneManager::getInstance()->releaseByKey("MenuScene");
}
void GameController::loadStartSceneResource()
{
StartScene *startScene = new StartScene();
startScene->initScene();
SceneManager::getInstance()->setWithKey("StartScene", startScene);
}
void GameController::releaseStartSceneResource()
{
auto startScene = SceneManager::getInstance()->getByKey("StartScene");
startScene->releaseScene();
SceneManager::getInstance()->releaseByKey("StartScene");
}
void GameController::loadSelectionSceneResource()
{
SelectionScene *selectionScene = new SelectionScene();
selectionScene->initScene();
SceneManager::getInstance()->setWithKey("SelectionScene", selectionScene);
}
void GameController::releaseSelectionSceneResource()
{
auto selectionScene = SceneManager::getInstance()->getByKey("SelectionScene");
selectionScene->releaseScene();
SceneManager::getInstance()->releaseByKey("SelectionScene");
}
void GameController::loadEpisodeSceneResource(int episodeNumber)
{
EpisodeScene *episodeScene = new EpisodeScene(episodeNumber);
episodeScene->initScene();
std::stringstream key;
key << "EpisodeScene_" << episodeNumber;
SceneManager::getInstance()->setWithKey(key.str(), episodeScene);
}
void GameController::releaseEpisodeSceneResource(int episodeNumber)
{
std::stringstream key;
key << "EpisodeScene_" << episodeNumber;
auto episodeScene = SceneManager::getInstance()->getByKey(key.str());
episodeScene->releaseScene();
SceneManager::getInstance()->releaseByKey(key.str());
}
void GameController::loadPlaySceneResource(int episodeNumber, int stageNumber)
{
PlayScene *playScene = new PlayScene(episodeNumber, stageNumber);
playScene->initScene();
std::stringstream key;
key << "PlayScene_" << episodeNumber << "_" << stageNumber;
SceneManager::getInstance()->setWithKey(key.str(), playScene);
}
void GameController::releasePlaySceneResource(int episodeNumber, int stageNumber)
{
std::stringstream key;
key << "PlayScene_" << episodeNumber << "_" << stageNumber;
auto playScene = SceneManager::getInstance()->getByKey(key.str());
playScene->releaseScene();
SceneManager::getInstance()->releaseByKey(key.str());
}
void GameController::loadPlayInfiniteSceneResource()
{
PlayInfiniteScene *playInfiniteScene = new PlayInfiniteScene();
playInfiniteScene->initScene();
SceneManager::getInstance()->setWithKey("PlayInfiniteScene", playInfiniteScene);
}
void GameController::releasePlayInfiniteSceneResource()
{
auto playInfiniteScene = SceneManager::getInstance()->getByKey("PlayInfiniteScene");
playInfiniteScene->releaseScene();
SceneManager::getInstance()->releaseByKey("PlayInfiniteScene");
}
void GameController::loadPauseSceneResource()
{
PauseScene* pauseScene = new PauseScene();
pauseScene->initScene();
SceneManager::getInstance()->setWithKey("PauseScene", pauseScene);
}
void GameController::releasePauseSceneResource()
{
auto pauseScene = SceneManager::getInstance()->getByKey("PauseScene");
pauseScene->releaseScene();
SceneManager::getInstance()->releaseByKey("PauseScene");
}
void GameController::loadVictorySceneResource()
{
VictoryScene* victoryScene = new VictoryScene();
victoryScene->initScene();
SceneManager::getInstance()->setWithKey("VictoryScene", victoryScene);
}
void GameController::releaseVictorySceneResource()
{
auto victoryScene = SceneManager::getInstance()->getByKey("VictoryScene");
victoryScene->releaseScene();
SceneManager::getInstance()->releaseByKey("VictoryScene");
}
void GameController::loadLoseSceneResource()
{
LoseScene* loseScene = new LoseScene();
loseScene->initScene();
SceneManager::getInstance()->setWithKey("LoseScene", loseScene);
}
void GameController::releaseLoseSceneResource()
{
auto loseScene = SceneManager::getInstance()->getByKey("LoseScene");
loseScene->releaseScene();
SceneManager::getInstance()->releaseByKey("LoseScene");
}
void GameController::loadFinalScoreScene(std::string score)
{
FinalScoreScene* finalScoreScene = new FinalScoreScene(score);
finalScoreScene->initScene();
SceneManager::getInstance()->setWithKey("FinalScoreScene", finalScoreScene);
}
void GameController::releaseFinalScoreScene()
{
auto finalScoreScene = SceneManager::getInstance()->getByKey("FinalScoreScene");
finalScoreScene->releaseScene();
SceneManager::getInstance()->releaseByKey("FinalScoreScene");
}
void GameController::addMenuSceneToCurrentScene()
{
auto scene = SceneManager::getInstance()->getCurrent();
// 僅放上settingButton,其餘的物件會在settingButton被點擊後加至目前的場景
auto settingButton = SpriteManager::getInstance()->getByKey("MenuScene_SettingButton");
scene->addChild(settingButton, 1);
}
void GameController::removeMenuSceneFromCurrentScene()
{
auto scene = SceneManager::getInstance()->getCurrent();
scene->removeChild(SpriteManager::getInstance()->getByKey("MenuScene_SettingButton"));
scene->removeChild(SpriteManager::getInstance()->getByKey("MenuScene_SettingBackground"));
scene->removeChild(SpriteManager::getInstance()->getByKey("MenuScene_SettingBackButton"));
scene->removeChild(SpriteManager::getInstance()->getByKey("MenuScene_MusicButton"));
scene->removeChild(SpriteManager::getInstance()->getByKey("MenuScene_SoundsButton"));
scene->removeChild(SpriteManager::getInstance()->getByKey("MenuScene_SettingMask"));
scene->removeChild(SpriteManager::getInstance()->getByKey("MenuScene_CreditMask"));
}
void GameController::addPauseSceneToCurrentScene()
{
auto scene = SceneManager::getInstance()->getCurrent();
// 與addMenuScene不同,此方法將所有相關物件加至目前的場景
// 但是只顯示pauseButton,其餘物件會在pauseButton被點擊後顯示
Manager::SpriteManager* spriteManager = Manager::SpriteManager::getInstance();
auto pauseButton = spriteManager->getByKey("PauseScene_PauseButton");
auto pauseBackground = spriteManager->getByKey("PauseScene_PauseBackground");
auto pauseBackButton = spriteManager->getByKey("PauseScene_PauseBackButton");
auto musicButton = spriteManager->getByKey("PauseScene_MusicButton");
auto soundsButton = spriteManager->getByKey("PauseScene_SoundsButton");
auto backHomeButton = spriteManager->getByKey("PauseScene_BackHomeButton");
auto retryButton = spriteManager->getByKey("PauseScene_RetryButton");
auto pauseMask = spriteManager->getByKey("PauseScene_PauseMask");
scene->addChild(pauseButton, 20);
scene->addChild(pauseBackground, -100);
scene->addChild(pauseMask, -100);
pauseBackground->addChild(pauseBackButton, -100);
pauseBackground->addChild(musicButton, -100);
pauseBackground->addChild(soundsButton, -100);
pauseBackground->addChild(backHomeButton, -100);
pauseBackground->addChild(retryButton, -100);
}
void GameController::removePauseSceneFromCurrentScene()
{
auto scene = SceneManager::getInstance()->getCurrent();
Manager::SpriteManager* spriteManager = Manager::SpriteManager::getInstance();
auto pauseBackground = spriteManager->getByKey("PauseScene_PauseBackground");
scene->removeChild(SpriteManager::getInstance()->getByKey("PauseScene_PauseButton"));
scene->removeChild(SpriteManager::getInstance()->getByKey("PauseScene_PauseBackground"));
scene->removeChild(SpriteManager::getInstance()->getByKey("PauseScene_PauseMask"));
pauseBackground->GameScene::BaseScene::removeChild(SpriteManager::getInstance()->getByKey("PauseScene_PauseBackButton"));
pauseBackground->GameScene::BaseScene::removeChild(SpriteManager::getInstance()->getByKey("PauseScene_MusicButton"));
pauseBackground->GameScene::BaseScene::removeChild(SpriteManager::getInstance()->getByKey("PauseScene_SoundsButton"));
pauseBackground->GameScene::BaseScene::removeChild(SpriteManager::getInstance()->getByKey("PauseScene_BackHomeButton"));
pauseBackground->GameScene::BaseScene::removeChild(SpriteManager::getInstance()->getByKey("PauseScene_RetryButton"));
}
void GameController::addVictorySceneToCurrentScene(int newScores)
{
auto victoryScene = static_cast<VictoryScene*>(SceneManager::getInstance()->getByKey("VictoryScene"));
auto scene = SceneManager::getInstance()->getCurrent();
Manager::SpriteManager* spriteManager = Manager::SpriteManager::getInstance();
auto victoryBackground = spriteManager->getByKey("VictoryScene_VictoryBackground");
auto nextButton = spriteManager->getByKey("VictoryScene_NextButton");
auto starLeft = static_cast<GameSprite::Star*>(spriteManager->getByKey("VictoryScene_StarLeft"));
auto starRight = static_cast<GameSprite::Star*>(spriteManager->getByKey("VictoryScene_StarRight"));
auto starMiddle = static_cast<GameSprite::Star*>(spriteManager->getByKey("VictoryScene_StarMiddle"));
// 依據不同的分數(星星數)來決定勝利畫面的樣式
if (newScores == 2) {
starRight->setBlank();
}
if (newScores == 1) {
starRight->setBlank();
starMiddle->setBlank();
}
scene->addChild(victoryBackground, 200);
scene->addChild(nextButton, 201);
scene->addChild(starLeft, 201);
scene->addChild(starRight, 201);
scene->addChild(starMiddle, 201);
victoryScene->runAnimation(newScores);
}
void GameController::removeVictorySceneFromCurrentScene()
{
auto scene = SceneManager::getInstance()->getCurrent();
scene->removeChild(SpriteManager::getInstance()->getByKey("VictoryScene_VictoryBackground"));
scene->removeChild(SpriteManager::getInstance()->getByKey("VictoryScene_NextButton"));
scene->removeChild(SpriteManager::getInstance()->getByKey("VictoryScene_StarLeft"));
scene->removeChild(SpriteManager::getInstance()->getByKey("VictoryScene_StarRight"));
scene->removeChild(SpriteManager::getInstance()->getByKey("VictoryScene_StarMiddle"));
}
void GameController::addLoseSceneToCurrentScene()
{
auto loseScene = static_cast<LoseScene*>(SceneManager::getInstance()->getByKey("LoseScene"));
auto scene = SceneManager::getInstance()->getCurrent();
Manager::SpriteManager* spriteManager = Manager::SpriteManager::getInstance();
auto loseBackground = spriteManager->getByKey("LoseScene_LoseBackground");
auto nextButton = spriteManager->getByKey("LoseScene_NextButton");
auto loseTitle = spriteManager->getByKey("LoseScene_LoseTitle");
scene->addChild(loseBackground, 200);
scene->addChild(loseTitle, 201);
scene->addChild(nextButton, 201);
loseScene->runAnimation();
}
void GameController::removeLoseSceneFromCurrentScene()
{
auto scene = SceneManager::getInstance()->getCurrent();
scene->removeChild(SpriteManager::getInstance()->getByKey("LoseScene_LoseBackground"));
scene->removeChild(SpriteManager::getInstance()->getByKey("LoseScene_NextButton"));
scene->removeChild(SpriteManager::getInstance()->getByKey("LoseScene_LoseTitle"));
}
void GameController::addFinalScoreSceneToCurrentScene(std::string score)
{
auto finalScoreScene = static_cast<FinalScoreScene*>(SceneManager::getInstance()->getByKey("FinalScoreScene"));
auto scene = SceneManager::getInstance()->getCurrent();
finalScoreScene->setScore(score);
Manager::SpriteManager* spriteManager = Manager::SpriteManager::getInstance();
auto finalScoreBackground = spriteManager->getByKey("FinalScoreScene_FinalScoreBackground");
auto nextButton = spriteManager->getByKey("FinalScoreScene_NextButton");
auto scoreLabel = finalScoreScene->getScoreLabel();
scene->addChild(finalScoreBackground, 200);
scene->addChild(nextButton, 201);
scene->addChild(scoreLabel, 201);
finalScoreScene->runAnimation();
}
void GameController::removeFinalScoreSceneFromCurrentScene()
{
auto scene = SceneManager::getInstance()->getCurrent();
auto finalScoreScene = static_cast<FinalScoreScene*>(SceneManager::getInstance()->getByKey("FinalScoreScene"));
scene->removeChild(SpriteManager::getInstance()->getByKey("FinalScoreScene_FinalScoreBackground"));
scene->removeChild(SpriteManager::getInstance()->getByKey("FinalScoreScene_NextButton"));
scene->removeChild(finalScoreScene->getScoreLabel());
}
void GameController::runStartScene()
{
this->loadMenuSceneResource();
this->loadStartSceneResource();
this->loadSelectionSceneResource();
StartScene *scene = static_cast<StartScene*>(
SceneManager::getInstance()->getByKey("StartScene"));
SceneManager::getInstance()->setCurrent(scene);
this->addMenuSceneToCurrentScene();
Director::getInstance()->runWithScene(scene);
scene->runAnimation();
}
void GameController::startSceneToSelectionScene()
{
SelectionScene *scene = static_cast<SelectionScene*>(
SceneManager::getInstance()->getByKey("SelectionScene"));
this->removeMenuSceneFromCurrentScene();
SceneManager::getInstance()->setCurrent(scene);
this->addMenuSceneToCurrentScene();
Director::getInstance()->replaceScene(scene);
scene->runConstantAnimation();
}
void GameController::selectionSceneToStartScene()
{
StartScene *scene = static_cast<StartScene*>(
SceneManager::getInstance()->getByKey("StartScene"));
this->removeMenuSceneFromCurrentScene();
SceneManager::getInstance()->setCurrent(scene);
this->addMenuSceneToCurrentScene();
Director::getInstance()->replaceScene(scene);
}
void GameController::selectionSceneToEpisodeScene(int episodeNumber)
{
this->loadEpisodeSceneResource(episodeNumber);
std::stringstream key;
key << "EpisodeScene_" << episodeNumber;
EpisodeScene *scene = static_cast<EpisodeScene*>(
SceneManager::getInstance()->getByKey(key.str()));
this->removeMenuSceneFromCurrentScene();
SceneManager::getInstance()->setCurrent(scene);
this->addMenuSceneToCurrentScene();
Director::getInstance()->replaceScene(scene);
}
void GameController::EpisodeSceneToSelectionScene(int episodeNumber)
{
this->releaseEpisodeSceneResource(episodeNumber);
SelectionScene *scene = static_cast<SelectionScene*>(
SceneManager::getInstance()->getByKey("SelectionScene"));
this->removeMenuSceneFromCurrentScene();
SceneManager::getInstance()->setCurrent(scene);
this->addMenuSceneToCurrentScene();
Director::getInstance()->replaceScene(scene);
scene->runConstantAnimation();
}
void GameController::EpisodeSceneToPlayScene(int episodeNumber, int stageNumber)
{
this->releaseStartSceneResource();
this->releaseMenuSceneResource();
this->releaseEpisodeSceneResource(episodeNumber);
this->releaseSelectionSceneResource();
// 將一些被cocos2d核心程式快取,殘留在記憶體沒有被釋放的物件做記憶體釋放
Director::getInstance()->purgeCachedData();
this->loadPauseSceneResource();
this->loadVictorySceneResource();
this->loadLoseSceneResource();
this->loadPlaySceneResource(episodeNumber, stageNumber);
std::stringstream key;
key << "PlayScene_" << episodeNumber << "_" << stageNumber;
std::string a = key.str();
PlayScene *scene = static_cast<PlayScene*>(
SceneManager::getInstance()->getByKey(key.str()));
SceneManager::getInstance()->setCurrent(scene);
this->addPauseSceneToCurrentScene();
Director::getInstance()->replaceScene(scene);
scene->play();
}
void GameController::PlaySceneToEpisodeScene(int episodeNumber, int stageNumber)
{
// 若玩家完成某章節的最後一關,那麼PlayScene將返回至下一章節的關卡選擇畫面。
int newEpisodeNumber = episodeNumber;
auto current = static_cast<GameScene::PlayScene*>(SceneManager::getInstance()->getCurrent());
// 是否有突破新高分(較多的星星數)
bool isNewHighscore = current->getIsNewHighScore();
// 新分數與舊有分數的差距
int newHighScorediff = current->getNewHighScoreDiff();
bool isUnlockedEpisode = false;
// 如果勝利且是第一次完成此關卡
if (current->getIsVictory() && current->getAlreadyComplete() == false) {
// 取得每個章節最多的關卡數,-1是為了與關卡編號做比較,關卡編號從0開始
int maxStage = DB::StageSetting::getInstance()->getMax() - 1;
// 取得app的總章節數,-1是為了與章節編號做比較,章節編號從0開始
int maxEpisode = DB::EpisodeSetting::getInstance()->getMax() - 1;
// 如果完成的關卡是章節裡的最後一關,場景將切至章節選擇畫面
if (stageNumber == maxStage) {
newEpisodeNumber++;
isUnlockedEpisode = true;
}
// 如果章節是最後一個章節(沒有下一章節),場景將切回原章節的關卡選擇畫面(既最後一章節)
if (newEpisodeNumber > maxEpisode) {
isUnlockedEpisode = false;
newEpisodeNumber = episodeNumber;
}
}
if (isUnlockedEpisode) {
this->PlaySceneToSelectionScene(episodeNumber, stageNumber, newEpisodeNumber);
return;
}
this->removePauseSceneFromCurrentScene();
this->removeLoseSceneFromCurrentScene();
this->removeVictorySceneFromCurrentScene();
this->releasePauseSceneResource();
this->releaseVictorySceneResource();
this->releaseLoseSceneResource();
this->releasePlaySceneResource(episodeNumber, stageNumber);
// 將一些被cocos2d核心程式快取,殘留在記憶體沒有被釋放的物件做記憶體釋放
Director::getInstance()->purgeCachedData();
this->loadMenuSceneResource();
this->loadStartSceneResource();
this->loadSelectionSceneResource();
this->loadEpisodeSceneResource(newEpisodeNumber);
std::stringstream key;
key << "EpisodeScene_" << newEpisodeNumber;
EpisodeScene *scene = static_cast<EpisodeScene*>(SceneManager::getInstance()->getByKey(key.str()));
// 將是否為新高分與分差,傳入EpisodeScene,目的是用來播放星星的動畫
scene->isNewHighScore = isNewHighscore;
scene->newHighScoreDiff = newHighScorediff;
scene->newHighScoreStage = stageNumber;
SceneManager::getInstance()->setCurrent(scene);
this->addMenuSceneToCurrentScene();
Director::getInstance()->replaceScene(scene);
scene->runStarAnimation();
}
void GameController::RetryPlayScene(int episodeNumber, int stageNumber)
{
this->removePauseSceneFromCurrentScene();
this->removeLoseSceneFromCurrentScene();
this->removeVictorySceneFromCurrentScene();
this->releasePauseSceneResource();
this->releaseVictorySceneResource();
this->releaseLoseSceneResource();
this->releasePlaySceneResource(episodeNumber, stageNumber);
this->loadPauseSceneResource();
this->loadVictorySceneResource();
this->loadLoseSceneResource();
this->loadPlaySceneResource(episodeNumber, stageNumber);
std::stringstream key;
key << "PlayScene_" << episodeNumber << "_" << stageNumber;
PlayScene *scene = static_cast<PlayScene*>(SceneManager::getInstance()->getByKey(key.str()));
SceneManager::getInstance()->setCurrent(scene);
this->addPauseSceneToCurrentScene();
Director::getInstance()->replaceScene(scene);
scene->play();
}
void GameController::PlaySceneToSelectionScene(int episodeNumber, int stageNumber, int unlockedEpisodeNumber)
{
this->removePauseSceneFromCurrentScene();
this->removeLoseSceneFromCurrentScene();
this->removeVictorySceneFromCurrentScene();
this->releasePauseSceneResource();
this->releaseVictorySceneResource();
this->releaseLoseSceneResource();
this->releasePlaySceneResource(episodeNumber, stageNumber);
// 將一些被cocos2d核心程式快取,殘留在記憶體沒有被釋放的物件做記憶體釋放
Director::getInstance()->purgeCachedData();
this->loadMenuSceneResource();
this->loadStartSceneResource();
this->loadSelectionSceneResource();
SelectionScene* selectionScene = static_cast<SelectionScene*>(SceneManager::getInstance()->getByKey("SelectionScene"));
SceneManager::getInstance()->setCurrent(selectionScene);
this->addMenuSceneToCurrentScene();
Director::getInstance()->replaceScene(selectionScene);
selectionScene->runConstantAnimation();
selectionScene->runUnlockedEpisodeAnimation(unlockedEpisodeNumber);
}
void GameController::startSceneToPlayInfiniteScene()
{
this->releaseStartSceneResource();
this->releaseMenuSceneResource();
this->releaseSelectionSceneResource();
// 將一些被cocos2d核心程式快取,殘留在記憶體沒有被釋放的物件做記憶體釋放
Director::getInstance()->purgeCachedData();
this->loadPauseSceneResource();
this->loadFinalScoreScene("0");
this->loadPlayInfiniteSceneResource();
PlayInfiniteScene *scene = static_cast<PlayInfiniteScene*>(SceneManager::getInstance()->getByKey("PlayInfiniteScene"));
SceneManager::getInstance()->setCurrent(scene);
this->addPauseSceneToCurrentScene();
Director::getInstance()->replaceScene(scene);
}
void GameController::retryPlayInfiniteScene()
{
this->removePauseSceneFromCurrentScene();
this->releasePauseSceneResource();
this->releaseFinalScoreScene();
this->releasePlayInfiniteSceneResource();
// 將一些被cocos2d核心程式快取,殘留在記憶體沒有被釋放的物件做記憶體釋放
Director::getInstance()->purgeCachedData();
this->loadPauseSceneResource();
this->loadFinalScoreScene("0");
this->loadPlayInfiniteSceneResource();
PlayInfiniteScene *scene = static_cast<PlayInfiniteScene*>(SceneManager::getInstance()->getByKey("PlayInfiniteScene"));
SceneManager::getInstance()->setCurrent(scene);
this->addPauseSceneToCurrentScene();
scene->hideTipBlock();
Director::getInstance()->replaceScene(scene);
scene->play();
}
void GameController::playInfiniteSceneToStartScene()
{
this->removePauseSceneFromCurrentScene();
this->releasePauseSceneResource();
this->releaseFinalScoreScene();
this->releasePlayInfiniteSceneResource();
// 將一些被cocos2d核心程式快取,殘留在記憶體沒有被釋放的物件做記憶體釋放
Director::getInstance()->purgeCachedData();
this->loadMenuSceneResource();
this->loadStartSceneResource();
this->loadSelectionSceneResource();
StartScene* startScene = static_cast<StartScene*>(SceneManager::getInstance()->getByKey("StartScene"));
SceneManager::getInstance()->setCurrent(startScene);
this->addMenuSceneToCurrentScene();
Director::getInstance()->replaceScene(startScene);
}
}
| true |
d3e3b988e25b9a3fff123e0324bfc1f88f2fee1b | C++ | rsahara/whip | /src/lib/Formats/KotlinFormat/StateMachineGenerator.cpp | UTF-8 | 10,830 | 2.6875 | 3 | [] | no_license | //
// StateMachineGenerator.cpp
// Whip
//
// Copyright © 2019 Runo Sahara. All rights reserved.
//
#include "StateMachineGenerator.hpp"
#include <sstream>
#include "Document/Document.hpp"
#include "PseudoCode/PseudoCode.hpp"
#include "Util/Text.hpp"
namespace Whip::KotlinFormat {
StateMachineGenerator::StateMachineGenerator(const Document& document, std::ostream& output)
: document(document)
, output(output)
, pseudoCodeGenerator(document) {
}
bool StateMachineGenerator::loadDocument() {
delegateClassName.clear();
for (auto it = document.metas.begin(); it != document.metas.end(); it++) {
const MetaData& metaData = *it;
if (metaData.key == MetaDataKey::defineDelegateClass) {
delegateClassName = metaData.value + "Impl";
stateMachineClassName = metaData.value;
stateClassName = metaData.value + "State";
}
else if (metaData.key == MetaDataKey::defineInitialState) {
initialStateName = metaData.value;
}
else if (metaData.key == MetaDataKey::definePackage) {
packageName = metaData.value;
}
}
if (delegateClassName.empty()) {
errorLog() << "delegate class name undetermined." << std::endl;
return false;
}
for (auto it = document.states.begin(); it != document.states.end(); it++) {
const State& state = *it;
stateNameMap[state.name] = state.stateID;
}
for (auto it = document.transitions.begin(); it != document.transitions.end(); it++) {
const Transition& transition = *it;
transitionNameSet.emplace(transition.name);
}
return true;
}
bool StateMachineGenerator::generate() {
loadDocument();
generateInterfaceCode();
for (auto it = document.states.begin(); it != document.states.end(); it++) {
generateStateCode(*it);
}
return true;
}
void StateMachineGenerator::generateInterfaceCode() {
std::string invalidStateClassName = stateClassName + "Invalid";
// Declaration of the package.
if (!packageName.empty()) {
output << "package " << packageName << std::endl;
output << std::endl;
}
// Imports.
output << "import android.util.SparseArray" << std::endl;
// State machine class.
output << "class " << stateMachineClassName << "(val delegate: " << delegateClassName << ") {" << std::endl;
output << indentation(1) << "var currentState: " << stateClassName << " = " << invalidStateClassName << std::endl;
output << indentation(2) << "private set" << std::endl;
if (stateNameMap.find(initialStateName) != stateNameMap.end()) {
output << indentation(1) << "fun enterInitialState() { " << std::endl;
output << indentation(2) << "enterState(" << upperCamelCaseIdentifier(stateClassName + initialStateName) << ")" << std::endl;
output << indentation(1) << "}" << std::endl;
}
output << indentation(1) << "fun exitState() {" << std::endl;
output << indentation(2) << "currentState.exitState(delegate)" << std::endl;
output << indentation(2) << "currentState = " << invalidStateClassName << std::endl;
output << indentation(1) << "}" << std::endl;
output << indentation(1) << "fun enterState(state: " << stateClassName << ") {" << std::endl;
output << indentation(2) << "currentState = state" << std::endl;
output << indentation(2) << "currentState.enterState(delegate)" << std::endl;
output << indentation(1) << "}" << std::endl;
for (auto it = transitionNameSet.begin(); it != transitionNameSet.end(); it++) {
output << indentation(1) << "fun " << *it << "() {" << std::endl;
output << indentation(2) << "currentState." << *it << "(this, delegate)" << std::endl;
output << indentation(1) << "}" << std::endl;
}
output << "}" << std::endl;
// State class.
output << std::endl;
output << "abstract class " << stateClassName << " {" << std::endl;
output << indentation(1) << "abstract val name: String" << std::endl;
output << indentation(1) << "abstract val id: Int" << std::endl;
for (auto it = transitionNameSet.begin(); it != transitionNameSet.end(); it++) {
output << indentation(1) << "open fun " << *it << "(owner: " << stateMachineClassName << ", delegate: " << delegateClassName << ") {" << std::endl;
output << indentation(2) << "delegate.defaultTransition(this, \"" << *it << "\")" << std::endl;
output << indentation(1) << "}" << std::endl;
}
output << indentation(1) << "open fun enterState(delegate: " << delegateClassName << ") {" << std::endl;
output << indentation(1) << "}" << std::endl;
output << indentation(1) << "open fun exitState(delegate: " << delegateClassName << ") {" << std::endl;
output << indentation(1) << "}" << std::endl;
output << indentation(1) << "companion object {" << std::endl;
output << indentation(2) << "private val idToStateMap: SparseArray<" << stateClassName << "> by lazy {" << std::endl;
output << indentation(3) << "SparseArray<" << stateClassName << ">().apply {" << std::endl;
output << indentation(4) << "append(" << std::endl;
output << indentation(5) << invalidStateClassName << ".id," << std::endl;
output << indentation(5) << invalidStateClassName << std::endl;
output << indentation(4) << ")" << std::endl;
for (auto it = document.states.begin(); it != document.states.end(); it++) {
std::string thisClassName(upperCamelCaseIdentifier(stateClassName + it->name));
output << indentation(4) << "append(" << std::endl;
output << indentation(5) << thisClassName << ".id," << std::endl;
output << indentation(5) << thisClassName << std::endl;
output << indentation(4) << ")" << std::endl;
}
output << indentation(3) << "}" << std::endl;
output << indentation(2) << "}" << std::endl;
output << indentation(2) << "fun valueOf(id: Int) = idToStateMap.get(id, " << invalidStateClassName<< ")" << std::endl;
output << indentation(1) << "}" << std::endl;
output << "}" << std::endl;
// State class for an invalid state.
output << std::endl;
output << "object " << invalidStateClassName << " : " << stateClassName << "() {" << std::endl;
output << indentation(1) << "override val name = \"" << upperCamelCaseIdentifier("Invalid") << "\"" << std::endl;
output << indentation(1) << "override val id = -1" << std::endl;
output << "}" << std::endl;
}
void StateMachineGenerator::generateStateCode(const State& state) {
output << std::endl;
output << "object " << upperCamelCaseIdentifier(stateClassName + state.name) << " : " << stateClassName << "() {" << std::endl;
output << indentation(1) << "override val name = \"" << upperCamelCaseIdentifier(state.name) << "\"" << std::endl;
output << indentation(1) << "override val id = " << state.stateID << std::endl;
// Entry function.
if (state.entryPseudoCodeID != invalidPseudoCodeID) {
output << indentation(1) << "override fun enterState(delegate: " << delegateClassName << ") {" << std::endl;
output << indentation(2);
const PseudoCode& pseudoCode = document.pseudoCodes[state.entryPseudoCodeID];
pseudoCodeGenerator.generate(pseudoCode, output);
output << std::endl;
output << indentation(1) << "}" << std::endl;
}
// Exit function.
if (state.exitPseudoCodeID != invalidPseudoCodeID) {
output << indentation(1) << "override fun exitState(delegate: " << delegateClassName << ") {" << std::endl;
output << indentation(2);
const PseudoCode& pseudoCode = document.pseudoCodes[state.exitPseudoCodeID];
pseudoCodeGenerator.generate(pseudoCode, output);
output << std::endl;
output << indentation(1) << "}" << std::endl;
}
// Transition functions.
TransitionEnumerator enumerator(document, state.stateID, *this);
enumerator.enumerate();
output << "}" << std::endl;
}
void StateMachineGenerator::enumerateTransition(const Transition& transition,
bool sameTransitionNameAsPrevious,
bool sameTransitionNameAsNext) {
if (!sameTransitionNameAsPrevious) {
output << indentation(1) << "override fun " << transition.name << "(owner: " << stateMachineClassName << ", delegate: " << delegateClassName << ") {" << std::endl;
}
int indentationSize = 2;
bool hasCondition = transition.conditionPseudoCodeID != invalidPseudoCodeID;
if (hasCondition) {
if (!sameTransitionNameAsPrevious) {
output << indentation(2);
}
output << "if (";
const PseudoCode& pseudoCode = document.pseudoCodes[transition.conditionPseudoCodeID];
pseudoCodeGenerator.generate(pseudoCode, output);
output << ") {" << std::endl;
indentationSize = 3;
}
else if (sameTransitionNameAsPrevious) {
output << "{" << std::endl;
indentationSize = 3;
}
bool changeState = transition.dstStateID != invalidStateID;
if (changeState) {
output << indentation(indentationSize) << "owner.exitState()" << std::endl;
}
if (transition.transitionPseudoCodeID != invalidPseudoCodeID) {
output << indentation(indentationSize);
const PseudoCode& pseudoCode = document.pseudoCodes[transition.transitionPseudoCodeID];
pseudoCodeGenerator.generate(pseudoCode, output);
output << std::endl;
}
if (changeState) {
const State& dstState = document.states[transition.dstStateID];
output << indentation(indentationSize) << "owner.enterState(" << upperCamelCaseIdentifier(stateClassName + dstState.name) << ")" << std::endl;
}
if (hasCondition || sameTransitionNameAsPrevious) {
output << indentation(2) << "}" << std::endl;
}
if (sameTransitionNameAsNext) {
output << indentation(2) << "else ";
}
else {
output << indentation(1) << "}" << std::endl;
}
}
}
| true |
d4ce81fa70bcdae1987e4efd2877fc8d4dfdb916 | C++ | chandan0904/coding | /coding/subset_sum.cpp | UTF-8 | 685 | 3.171875 | 3 | [] | no_license | #include<iostream>
#include<vector>
using namespace std;
void subset_sum(vector<int> &set,vector<bool> &ex,int sum,int m,int i,int j)
{
if(sum<m || i>j)
{
return ;
}
if(sum == m)
{
for(int k=0;k<j;k++)
{
if(ex[k])
cout<<set[k]<<" ";
}
cout<<endl;
return ;
}
subset_sum(set,ex,sum,m,i+1,j);
m += set[i];
ex[i]=1;
subset_sum(set,ex,sum,m,i+1,j);
ex[i]=0;
}
int main()
{
int n,e,s;
vector<int> set;
cout<<"Enter no. of elements in set : ";
cin>>n;
for(int i=0; i<n;i++)
{
cin>>e;
set.push_back(e);
}
vector<bool> ex(n,0);
cout<<"enter SuM : ";
cin>>s;
subset_sum(set,ex,s,0,0,n);
}
| true |
b2e50dc1680ab259aa82b2f6afcd845f4c0233b3 | C++ | HRNaudZ/CppSolutions | /ThreeNumbers.cpp | UTF-8 | 990 | 3.40625 | 3 | [] | no_license | /**** Code by WOANA Yao Renaud *****/
/*---------woanayr@gmail.com------*/
#include <iostream>
#include <vector>
bool isEndThree(int a){
return a%10==3;
}
bool isPrime(int a){
if(a<=1) return false;
if(a<=3) return true;
if(a%2==0 || a%3==0) return false;
for(int i(5); i*i<=a; i+=6){
if(a%i==0 || a%(i+2)==0) return false;
}
return true;
}
bool isTHREE(int a){
if(isPrime(a)){
if(isEndThree(a)) return true;
else return false;
}
std::vector<int> factors;
for(int i(2); i<=(a/2); i++){
if(a%i==0 && isPrime(i)) factors.push_back(i);
}
for(int i(0); i<factors.size(); i++) if(!isEndThree(factors[i])) return false;
return true;
}
int main(){
int a;
do{
std::cin>>a;
if(a==-1) break;
if(isTHREE(a)) std::cout<<a<<" "<<"YES"<<std::endl;
else std::cout<<a<<" "<<"NO"<<std::endl;
}while(a!=-1);
}
/**This code checks if a number is a Three number :
-prime and last digit is 3
-or all it's prime factors last digits are 3
**/
| true |
0f15b7dd003b4e11998161c9e07d9a78f8548228 | C++ | kumasento/VELVET-PROGRAMMING | /OJ/POJ/POJ_DS_61.cpp | UTF-8 | 1,876 | 3.078125 | 3 | [] | no_license | #include <iostream>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <string>
using namespace std;
struct node {
node *ch, *sb;
int v, k;
};
void Insert(node *&o, string st, int i){
int n = st[i]-'0';
if(o->ch == NULL){
// build a new child
o->ch = new node();
(o->ch)->ch = (o->ch)->sb = NULL;
(o->ch)->v = n; (o->ch)->k = 1;
if(i == st.length()-1)
return;
Insert(o->ch, st, i+1); return ;
}
node *w = o->ch;
while(w != NULL){
if(w->v == n)
break;
if(w->sb == NULL)
break;
w = w->sb;
}
if(w->sb == NULL && w->v != n){
(w)->sb = new node();
((w)->sb)->ch = ((w)->sb)->sb = NULL;
((w)->sb)->v = n; ((w)->sb)->k = 1;
if(i == st.length()-1)
return;
Insert((w)->sb, st, i+1); return ;
}
w->k ++;
if(i == st.length()-1)
return;
Insert(w, st, i+1);
return ;
}
void Print(node *o){
if( o == NULL) return ;
cout << o->v <<' ' << o->k<<endl;;
node *t = o->ch;
while(t != NULL){
Print(t);
t = t->sb;
}
//cout << endl;
return;
}
int Check(node *o){
if(o==NULL) return 1;
node * w = o->ch; int cnt = 0;
while(w != NULL){
//cout << w->v << ' ' << w->k << endl;
cnt += w->k;
w = w->sb;
}
//cout << o->v << ' ' << o->k << ' ' << cnt << endl;
if(cnt < o->k && cnt)
return 0;
else{
w = o->ch; int ok = 1;
while(w != NULL && ok){
ok = Check(w);
w = w->sb;
}
return ok;
}
}
int main(){
freopen("data_61.in","r",stdin);
int t; scanf("%d", &t);
while(t --){
int n; scanf("%d", &n);
node * t = new node();
t->ch = t->sb = NULL;
while(n--){
string st; cin >> st;
Insert(t, st, 0);
}
//Print(t);
//cout << endl;
node *w = t->ch;
int ok = 1;
while( w != NULL && ok ){
ok = Check(w);
//cout << w->v << ' ' << ok << endl;
w = w->sb;
}
if(!ok) cout << "NO" << endl;
else cout << "YES" << endl;
}
return 0;
} | true |
7b7b31015b4127b651c2e7e25b9487fe98f5e84d | C++ | nolanjian/Parametric-Furniture-Designer | /Component/Axis.cpp | UTF-8 | 846 | 2.53125 | 3 | [] | no_license | #include <Component/Axis.h>
#include <osg/Geode>
#include <osg/Shape>
#include <osg/ShapeDrawable>
namespace PFD
{
namespace Component
{
Axis::Axis(Dim dim, unsigned int uLen)
: m_dim(dim), m_uLen(uLen)
{
Init();
}
void Axis::Init()
{
removeChildren(0, getNumChildren());
osg::ref_ptr<osg::Geode> geode = new osg::Geode;
geode->addDrawable(new osg::ShapeDrawable(new osg::Cylinder(osg::Vec3(0.0, 0.0, 0.0), 0.1, m_uLen * 1.0)));
geode->addDrawable(new osg::ShapeDrawable(new osg::Cone(osg::Vec3(0.0, 0.0, m_uLen * 1.0), 0.15, 0.4)));
osg::Matrixd mat;
switch (m_dim)
{
case Axis::X:
mat.rotate(90, osg::Y_AXIS);
break;
case Axis::Y:
mat.rotate(-90, osg::X_AXIS);
break;
case Axis::Z:
break;
default:
break;
}
setMatrix(mat);
addChild(geode);
}
}
} | true |
e9f5df151ccfaade0df440d830ad68a4c0f5312a | C++ | GuillaumeSmaha/sleepyogre3d | /include/Core/ClassRootSingleton.h | UTF-8 | 1,985 | 3.328125 | 3 | [
"BSD-2-Clause"
] | permissive | /*!
* \file ClassRootSingleton.h
* \brief Ce fichier contient la déclaration de la classe ClassRootSingleton.
*/
#ifndef __CLASS_ROOT_SINGLETON_H__
#define __CLASS_ROOT_SINGLETON_H__
#ifndef DOXYGEN_SKIP
#include <stddef.h>
#endif
#include "Core/ClassRoot.h"
/*!
* \class ClassRootSingleton
* \brief Permet de créer une classe singleton
*/
template <typename T>
class ClassRootSingleton : public ClassRoot
{
private:
/*!
* \brief Explicit private copy constructor. This is a forbidden operation.
*/
ClassRootSingleton(const ClassRootSingleton<T> &);
/*!
* \brief Private operator= . This is a forbidden operation.
*/
ClassRootSingleton& operator=(const ClassRootSingleton<T> &);
protected:
/*!
* \brief Instance de ClassRootSingleton pour le singleton
*/
static T * _instance;
public:
/*!
* \brief Constructor
*/
ClassRootSingleton() : ClassRoot()
{
if(_instance == 0)
{
_instance = static_cast<T *>(this);
}
}
/*!
* \brief Destructor
*/
~ClassRootSingleton()
{
_instance = 0;
}
/*!
* \brief Créé le singleton
*/
static void createSingleton()
{
if (_instance == 0)
{
new T();
}
}
/*!
* \brief Retourne un pointeur sur l'instance du singleton
* \return Le pointeur sur le singleton
*/
static T * getSingletonPtr()
{
if (_instance == 0)
{
T::createSingleton();
}
return _instance;
}
/*!
* \brief Retourne une référence sur l'instance du singleton
* \return La référence sur le singleton
*/
static T & getSingleton()
{
if (_instance == 0)
{
T::createSingleton();
}
return *_instance;
}
/*!
* \brief Retourne une référence sur l'instance du singleton
* \return La référence sur le singleton
*/
static void destroySingleton()
{
if(_instance != 0)
{
delete _instance;
}
}
};
#endif // __CLASS_ROOT_SINGLETON_H__
| true |
a9e7b0dcc4b67008dcd703b2261f8e9de09559e5 | C++ | MargaretBarseghayn/OA_Hashing | /OA_HashTable.h | UTF-8 | 915 | 3.296875 | 3 | [] | no_license | #pragma once
//*** THE REPETITIONS ARE NOT ALLOWED ***//
class OA_HashTable
{
enum Status { FREE, OCCUPIED, DELETED };
struct Node {
int key_;
Status status_;
Node(int key = 0, Status status = FREE) :key_(key), status_(status) {}
};
//the values of these functions should be taken modulo size_
static int firstFunction(int key) { return key * key + 1; }
static int secondFunction(int key) { return (key << 1) + 1; }
public:
OA_HashTable(int size);
~OA_HashTable(void);
/*1*/ bool search(int key)const; //. . . should be implemented . . .
//precondition: search(key)==false
/*2*/ void insert(int key); //. . . should be implemented . . .
//precondition: search(key)==true
/*3*/ void remove(int key); //. . . should be implemented . . .
void print()const;
private:
Node * table_;
int size_; //should be a power of 2
};
| true |
549d349e8b213c831cdf6fbbba72be816d4f61d6 | C++ | zfu/codejam | /FairandSquare/Solution.cpp | UTF-8 | 3,338 | 2.953125 | 3 | [] | no_license | #include <vector>
#include <list>
#include <map>
#include <set>
#include <queue>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <fstream>
using namespace std;
class Solution {
public:
Solution() {
input = freopen("data.in", "r" , stdin);
output = freopen("data.out", "w" , stdout);
}
void solve() {
int T;
cin >> T;
for(int i = 1; i <= T; i++) {
cout << "Case #" << i << ": " << solveCase() << endl;
}
}
private:
int solveCase() {
long long A, B;
cin >> A >> B;
int res = 0;
long long root = sqrt(A);
if (isPalindrome(root) && isPalindrome(A) && root*root == A)
res++;
ostringstream os;
os << root;
string str = os.str();
while (true) {
nextPalindrome(str);
istringstream is(str);
is >> root;
long long prod = root*root;
if (prod > B)
break;
if (isPalindrome(prod))
res++;
}
return res;
}
long long sqrt(long long x) {
if(x < 2) return x;
long long l = 0;
long long u = 1 + (x / 2);
while(l+1 < u) {
long long m = l + (u - l) / 2;
long long p = m * m;
if (p == x)
return m;
if(p > x)
u = m;
else
l = m;
}
return l;
}
bool isPalindrome(long long x) {
if (x < 0) return false;
long long d = 1;
while (x / d >= 10) d *= 10;
while (x != 0) {
long long l = x / d;
long long r = x % 10;
if (l != r) return false;
x = (x % d) / 10;
d /= 100;
}
return true;
}
void nextPalindrome(string & num) {
string org(num);
int begin = 0;
int end = num.size() - 1;
while (begin < end)
num[end--] = num[begin++];
if (begin > end)
begin--, end++;
if (!isGreater(num, org))
increase(num, begin, end);
}
bool isGreater(string & v1, string & v2) {
if (v1.size() != v2.size())
return v1.size() > v2.size();
for (size_t i = 0; i < v1.size(); i++)
if (v1[i] != v2[i])
return v1[i] > v2[i];
return false;
}
void increase(string & num, int begin, int end) {
if (begin < 0) {
num[num.size() - 1] = '1';
num.insert(num.begin(), '1');
return;
}
if (num[begin] < '9') {
num[begin] = num[end] = num[begin] + 1;
return;
}
num[begin] = num[end] = '0';
increase(num, begin-1, end+1);
return;
}
FILE * input;
FILE * output;
};
int main() {
Solution sol;
sol.solve();
}
| true |
f10249daa6df6342932d6000a78e4d3f9749dfe1 | C++ | apple/foundationdb | /fdbclient/TupleVersionstamp.cpp | UTF-8 | 1,592 | 2.65625 | 3 | [
"Apache-2.0"
] | permissive | #include "fdbclient/TupleVersionstamp.h"
TupleVersionstamp::TupleVersionstamp(StringRef str) {
if (str.size() != VERSIONSTAMP_TUPLE_SIZE) {
throw invalid_versionstamp_size();
}
data = str;
}
TupleVersionstamp::TupleVersionstamp(int64_t version, uint16_t batchNumber, uint16_t userVersion) {
data = makeString(VERSIONSTAMP_TUPLE_SIZE);
uint8_t* buf = mutateString(data);
*reinterpret_cast<int64_t*>(buf) = bigEndian64(version);
*reinterpret_cast<uint16_t*>(buf + sizeof(int64_t)) = bigEndian16(batchNumber);
*reinterpret_cast<uint16_t*>(buf + sizeof(int64_t) + sizeof(uint16_t)) = bigEndian16(userVersion);
}
int16_t TupleVersionstamp::getBatchNumber() const {
const uint8_t* begin = data.begin();
begin += 8;
int16_t batchNumber = *(int16_t*)(begin);
batchNumber = bigEndian16(batchNumber);
return batchNumber;
}
int16_t TupleVersionstamp::getUserVersion() const {
const uint8_t* begin = data.begin();
begin += 10;
int16_t userVersion = *(int16_t*)(begin);
userVersion = bigEndian16(userVersion);
return userVersion;
}
const uint8_t* TupleVersionstamp::begin() const {
return data.begin();
}
int64_t TupleVersionstamp::getVersion() const {
const uint8_t* begin = data.begin();
int64_t version = *(int64_t*)begin;
version = bigEndian64(version);
return version;
}
size_t TupleVersionstamp::size() const {
return VERSIONSTAMP_TUPLE_SIZE;
}
bool TupleVersionstamp::operator==(const TupleVersionstamp& other) const {
return getVersion() == other.getVersion() && getBatchNumber() == other.getBatchNumber() &&
getUserVersion() == other.getUserVersion();
} | true |
95f24b1f505a7cc05f76c35785c964502b26fd45 | C++ | joss31/ada | /1/cutRod.cpp | UTF-8 | 2,745 | 3.171875 | 3 | [] | no_license | #include <iostream>
#include <time.h>
#include <random>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
// esta funcion es muy ineficiente ya que tarda mucho tiempo en ejecutarse,
//tambien por su llamada recursiva se llama varias veces los mismos parametros
//por eso es su tiempo de ejecucion es 2ˆ(n-1).
int cutRod(int* p, int n){
if(n==0){
return 0;
}
int q=-9999;
for(int i=0; i<n;i++){
q= max(q,p[i]+cutRod(p,n-(i+1)));
}
return q;
}
//Aqui se utiliza una programacion dinamica, y tambien se llama a recursividad
//y eso hace que no sea tan eficiente aunque es mejor que la funcion cutRod.
int memoized_cutRod_aux(int* p, int n, int* r){
if(n!=0 and r[n-1]>=0){
return r[n-1];
}
int q=-9999;
if(n==0){
q=0;
}
else
{
for(int i=0; i<n;i++){
q=max(q,p[i]+memoized_cutRod_aux(p,n-(i+1),r));
}
}
r[n-1]=q;
return q;
}
int memoized_cutRod(int* p, int n){
int* r=new int [n];
for(int i=0;i<n;i++){
r[i]=-9999;
}
return memoized_cutRod_aux(p,n,r);
}
// Aqui el tiempo de ejecucion es de nˆ2, y es el mas eficiente que
//los otros dos anteriores ya que en la parte del bucle hace menos operaciones
//que en las otras funciones que se llama hasta la recursividad.
int bottom_up_cutRod(int* p, int n){
int* r=new int [n+1];
r[0]=0;
for(int j=0;j<n;j++){
int q=-9999;
for(int i=0;i<=j;i++)
q=max(q,p[i]+r[j-i]);
r[j+1]=q;
}
return r[n];
}
int main()
{
int var_size;
cin>>var_size;
int * a=new int[var_size];
for(unsigned int i=0;i<var_size;++i)
a[i]=10*i+rand()%10;
cout<<"start"<<endl;
clock_t start, end1;
double joss_time;
start = clock();
//El cut rod esta comentado porque al momento de hacer las pruebas demora mucho por eso es muy ineficiente.
//cutRod(a,var_size);
end1 = clock();
joss_time=end1-start;
cout<<"cutRod: "<<joss_time/CLOCKS_PER_SEC<<endl;
start = clock();
memoized_cutRod(a,var_size);
end1 = clock();
joss_time=end1-start;
cout<<"memorized cutRod: "<<joss_time/CLOCKS_PER_SEC<<endl;
start = clock();
bottom_up_cutRod(a,var_size);
end1 = clock();
joss_time=end1-start;
cout<<"bottom cutRod: "<<joss_time/CLOCKS_PER_SEC<<endl;
delete a;
//------------------------
//var size = 70
//cutRod - 0.00006
//Memoized_CutRod - 0.00005
//Bottom_up_cutRod - 0.00005
//------------------------
//var size = 1800
//cutRod - 0.00006
//Memoized_CutRod -0.01746
//Bottom_up_cutRod -0.008951
system("pause");
return 0;
}
| true |
89a2870d785a1f1a34a44a5a70b3e6922fb74a9e | C++ | winielson/CS435 | /Proj1/RecBST/RecBST/RecBST.cpp | UTF-8 | 6,102 | 3.78125 | 4 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <sstream>
using namespace std;
#define MAX_SIZE_OF_ARR 256
struct node {
int key;
struct node *l, *r;
};
// Create new node
struct node *newNode(int item) {
struct node *temp = (struct node *)malloc(sizeof(struct node)); // Allocates appropriate amount of space for node
temp->key = item;
temp->l = temp->r = NULL;
return temp;
}
// Inorder traversal of BST to produce output
void inorder(node *root) {
if (root != NULL) {
inorder(root->l);
printf("%d ", root->key);
inorder(root->r);
}
}
// Inserts node into BST recursively
struct node* insertRec(node* node, int key) {
// Base case, BST at position is empty
if (node == NULL) {
return newNode(key);
}
// Recursively find correct position of new node (Assumes no duplicate inputs)
if (key < node->key) { // Traverse left if newNode less than current
node->l = insertRec(node->l, key);
}
else { // Traverse right if newNode greater than current
node->r = insertRec(node->r, key);
}
return node;
}
// Find minimum key recursively in BST (Also used in deleteRec())
struct node * findMinRec(node* node) {
if (node && node->l != NULL) {
node = findMinRec(node->l);
}
return node;
}
// Find maximum key recursively in BST
struct node * findMaxRec(node* node) {
if (node && node->r != NULL) {
node = findMaxRec(node->r);
}
return node;
}
void inOrdertoVec(node *node, vector<int> &vec, int i) {
if (node == NULL) { // recursion anchor: when the node is null an empty leaf was reached (doesn't matter if it is left or right, just end the method call
return;
}
inOrdertoVec(node->l, vec, i); // first do every left child tree
vec.push_back(node->key); // then write the data in the array
i++;
inOrdertoVec(node->r, vec, i); // do the same with the right child
}
// Find next node of node in BST inorder vec
void findNextRec(vector<int> vec, int key) {
for (int i = 0; i < vec.size(); i++) {
if (vec[i] == key) {
printf("\nNext of node with key %d is %d\n", key, vec[++i]);
return;
}
}
}
// Find next node of node in BST inorder vec
void findPrevRec(vector<int> vec, int key) {
for (int i = 0; i < vec.size(); i++) {
if (vec[i] == key) {
printf("\nPrev of node with key %d is %d\n", key, vec[--i]);
return;
}
}
}
// Deletes key and returns new root
struct node* deleteRec(node* root, int key) {
// Base case, BST at position is empty
if (root == NULL) {
return root;
}
if (key < root->key) { // Traverse left if newNode less than current
root->l = deleteRec(root->l, key);
}
else if (key > root->key) { // Traverse right if newNode greater than current
root->r = deleteRec(root->r, key);
}
else { // Node to be deleted is found (key == root->key)
// Case: Node with only one child or no child
if (root->l == NULL) {
struct node *temp = root->r;
free(root);
return temp;
}
else if (root->r == NULL) {
struct node *temp = root->l;
free(root);
return temp;
}
// Case node with two children
struct node* temp = findMinRec(root->r); //Get the inorder successor (smallest in the right subtree)
root->key = temp->key; // Copy the inorder successor's content to this node
root->r = deleteRec(root->r, temp->key); // Delete the inorder successor
}
return root;
}
int main() {
struct node *root = NULL; // Initialize root
// INPUT ORDER: numCommands, commands
unsigned int numCommands = 0;
cout << "Commands:\n insert (int)\n delete (int)\n findnext (int)\n findprev (int)\n findmin\n findmax\n\n";
cout << "Enter number of commands desired: ";
cin >> numCommands;
cout << "Enter commands:\n";
string commands[MAX_SIZE_OF_ARR];
// Input handling
for (int i = 0; i < numCommands + 1; i++) {
getline(cin, commands[i]); // Takes entire line as input string
if (commands[i].find("insert") != string::npos) { // Checks if delete is in string
int insVal = 0;
int q = 0;
// Split string
string arr[2];
stringstream ssin(commands[i]);
while (ssin.good() && q < 2){
ssin >> arr[q];
++q;
}
insVal = atoi(arr[1].c_str()); // Converts string to int
root = insertRec(root, insVal); // assigns new root after insert
printf("Inorder traversal of the given tree: ");
inorder(root);
cout << endl;
}
else if (commands[i].find("delete") != string::npos) { // Checks if delete is in string
int delVal = 0;
int q = 0;
// Split string
string arr[2];
stringstream ssin(commands[i]);
while (ssin.good() && q < 2){
ssin >> arr[q];
++q;
}
delVal = atoi(arr[1].c_str()); // Converts string to int
deleteRec(root, delVal);
printf("Current Inorder Traversal of BST: ");
inorder(root);
cout << endl;
}
else if (commands[i].find("findnext") != string::npos) { // Checks if delete is in string
vector<int> inOrderArrVec;
int findVal = 0;
int q = 0;
// Split string
string arr[2];
stringstream ssin(commands[i]);
while (ssin.good() && q < 2){
ssin >> arr[q];
++q;
}
findVal = atoi(arr[1].c_str()); // Converts string to int
inOrdertoVec(root, inOrderArrVec, 0); // Fill new inorder vec
findNextRec(inOrderArrVec, findVal);
}
else if (commands[i].find("findprev") != string::npos) { // Checks if delete is in string
vector<int> inOrderArrVec;
int findVal = 0;
int q = 0;
// Split string
string arr[2];
stringstream ssin(commands[i]);
while (ssin.good() && q < 2){
ssin >> arr[q];
++q;
}
findVal = atoi(arr[1].c_str()); // Converts string to int
inOrdertoVec(root, inOrderArrVec, 0); // Fill new inorder vec
findPrevRec(inOrderArrVec, findVal);
}
else if (commands[i].find("findmin") != string::npos) { // Checks if delete is in string
printf("Find min: %d\n", findMinRec(root)->key);
}
else if (commands[i].find("findmax") != string::npos) { // Checks if delete is in string
printf("Find max %d\n", findMaxRec(root)->key);
}
else {
//printf("INVALID COMMAND\n");
}
}
return 0;
}
| true |
4259989d82c0d9a23713ddbcfb99cb06d3a90032 | C++ | kurochan/OASIS | /v1.1/source/system/graphic/sheet.cpp | UTF-8 | 10,202 | 2.765625 | 3 | [] | no_license | //=========================================
// OASIS Kernel source code
// Copyright (C) 2010 soS.A
//=========================================
/*シート関係*/
#include "kernel.h"
SHTCTL shtctl ;
bool SHTCTL::alreadyExist = 0;
/*
シートシステム初期化関数
シートを一枚作って、シートシステムを確立します。
シート関係の関数を使う場合は最初にこの関数を必ず呼び出すこと。
引数、戻り値:create_sheet関数と同じ
*/
struct SHEET *SHTCTL::init(short vx, short vy, short xsize, short ysize) {
if(alreadyExist)
panic();
alreadyExist = 1;
SHEET *sheet=g_sheet(vx, vy, xsize, ysize) ;
top=sheet ;
back=sheet ;
bottom=sheet ;
return sheet ;
}
/*
シート作成関数
戻り値:シート構造体へのポインタ
*/
struct SHEET *SHTCTL::create(short vx, short vy, short xsize, short ysize) {
_using.Lock();
SHEET *sheet=g_sheet(vx, vy, xsize, ysize) ;
top->next_sheet=sheet;
top=sheet ;
_using.Free();
return sheet ;
}
/*
シート作成関数
create_sheet関数とsheet_init関数の共通部を関数化したもの
*/
struct SHEET *SHTCTL::g_sheet(short vx, short vy, short xsize, short ysize){
SHEET *sheet = (SHEET *)new char[xsize*ysize*4+sizeof(SHEET)] ;
//引数代入
sheet->vx=vx ;
sheet->vy=vy ;
sheet->xsize=xsize ;
sheet->ysize=ysize ;
//フラグセット、透過情報なし、表示
sheet->flag=1 ;
sheet->buffer=(int *)sheet+sizeof(SHEET) ;
return sheet ;
}
/*
ウィンドウシート作成関数
戻り値:シート構造体へのポインタ
*/
//これ、マウスの次にウィンドウが来ちゃうから、修正する必要がある・・・
struct WINDOW *SHTCTL::wincreate(short vx, short vy, short xsize, short ysize) {
_using.Lock();
WINDOW *window=g_winsheet(vx, vy, xsize, ysize) ;
top->next_sheet=&(window->this_s);
top=&(window->this_s) ;
_using.Free();
return window ;
}
/*
ウィンドウシート作成関数
*/
struct WINDOW *SHTCTL::g_winsheet(short vx, short vy, short xsize, short ysize){
WINDOW *window=(WINDOW *)new char[xsize*ysize*4+sizeof(WINDOW)] ;
window->this_s_p=&(window->this_s) ;
//引数代入
window->this_s.vx=vx ;
window->this_s.vy=vy ;
window->this_s.xsize=xsize ;
window->this_s.ysize=ysize ;
//フラグセット、透過情報なし、表示
window->this_s.flag=1 ;
window->this_s.buffer=(int *)window->this_s_p+sizeof(SHEET) ;
return window ;
}
/*
シート破棄関数
引数
対象シートへのポインタ
*/
void SHTCTL::del(SHEET *sheet) {
_using.Lock();
_del(sheet) ;
_using.Free();
delete [] sheet ;
return ;
}
void SHTCTL::_del(SHEET *sheet) {
if (sheet==bottom) {
bottom=sheet->next_sheet ;
}else{
SHEET *c_sheet=back ;
for(;;) {
if (c_sheet->next_sheet==sheet)
break ;
c_sheet=c_sheet->next_sheet ;
if (c_sheet==top)
return ; //無効なシート指定
}
c_sheet->next_sheet=sheet->next_sheet ;
if (sheet==top)
top=c_sheet ;
}
return ;
}
/*
シート非表示化関数
実際には非表示にするのではなく、背景シートの後ろへ持ってくる
*/
void SHTCTL::hide(SHEET *sheet) {
_using.Lock();
_hide(sheet) ;
_using.Free();
refresh(back,sheet->vx,sheet->vy,sheet->xsize,sheet->ysize) ;
return ;
}
void SHTCTL::_hide(SHEET *sheet) {
SHEET *c_sheet=back ;
for(;;) {
if (c_sheet->next_sheet==sheet)
break ;
c_sheet=c_sheet->next_sheet ;
if (c_sheet==top)
return ;
}
c_sheet=sheet->next_sheet ;
sheet->next_sheet=back->next_sheet ;
back->next_sheet=sheet ;
return ;
}
/*
シート最前面化関数
戻り値:なし
*/
void SHTCTL::set_top(SHEET *sheet) {
if (sheet==top)
return;
_using.Lock();
set_top_m(sheet, top) ;
top=sheet ;
_using.Free();
all_refresh(sheet) ;
return ;
}
/*
シート最前面化関数(ただし、マウス、タスクバーなどよりは後ろ)
主にウィンドウの最前面化用
*/
void SHTCTL::set_wintop(SHEET *sheet, SHEET *active) {
if (sheet==active)
return;
_using.Lock();
set_top_m(sheet, active) ;
_using.Free();
all_refresh(sheet) ;
return ;
}
/*
set_top, set_wintop関数から呼び出す実際の処理ルーチン
*/
void SHTCTL::set_top_m(SHEET *sheet, SHEET *c_top) {
if (sheet==bottom) {
bottom=sheet->next_sheet ;
}else{
for ( SHEET *c_sheet=bottom; c_sheet!=c_top; c_sheet=c_sheet->next_sheet ) {
if (c_sheet->next_sheet==sheet) {
c_sheet->next_sheet=sheet->next_sheet ;
break ;
}
}
}
sheet->next_sheet=c_top->next_sheet ;
c_top->next_sheet=sheet;
return ;
}
/*
二つの四角形の重なってる部分の値をもとめる関数
全く重なっていない場合は値がおかしくなるため、チェックし、戻り値を1にする
lx1,ly1:x1とvx1のうちの大きい方の値が代入される
lx2,ly2:x2とvx2のうちの小さい方の値が代入される
*/
char SHTCTL::cmp(short *lx1, short x1, short vx1, short *ly1, short y1, short vy1, short *lx2, short x2, short vx2, short *ly2, short y2, short vy2) const {
if (x1>vx1)
*lx1=x1 ;
else
*lx1=vx1 ;
if (y1>vy1)
*ly1=y1 ;
else
*ly1=vy1 ;
if (x2<vx2)
*lx2=x2 ;
else
*lx2=vx2 ;
if (y2<vy2)
*ly2=y2 ;
else
*ly2=vy2 ;
//シートが重なっていない場合を弾く。
if (*lx1>*lx2 || *ly1>*ly2)
return 1 ;
return 0 ;
}
//シートを描画
void SHTCTL::all_refresh(SHEET *t_sheet) {
refresh(t_sheet, t_sheet->vx, t_sheet->vy, t_sheet->xsize, t_sheet->ysize) ;
return ;
}
//スクリーン上の任意の短径を再描画する関数(絶対座標で指定)
//t_sheetより上のシートは描画されない(t_sheetは含める)
void SHTCTL::refresh(SHEET *t_sheet, short vx, short vy, short xsize, short ysize) {
int nt_sheet_num=0, cnt1, cnt2, num_smat=0, o_num_smat ;
short lx1, ly1, lx2, ly2, y ;
char flag=0;
UCHAR num_r;
//指定箇所がVRAM外の場合は補正
if ((vx+xsize-1)>=sinfo->scrnx)
xsize=sinfo->scrnx-vx ;
if ((vy+ysize-1)>=sinfo->scrny)
ysize=sinfo->scrny-vy ;
if (vx<0) {
xsize+=vx;
vx=0;
}
if (vy<0) {
ysize+=vy;
vy=0;
}
if (xsize<=0||ysize<=0)
return ; //値が不正だった時以外にも、範囲すべてがVRAM外に存在する場合はここに来る事もアリ
_using.Lock();
SHEET *sheet=back ;
//透明度を持たず、非表示でもないシートの数を調べる
for(;;sheet=sheet->next_sheet) {
if (sheet->flag==1)
nt_sheet_num++ ;
if (sheet==top)
break ;
}
//smat構造体のメモリ確保
SMAT *alloc_smat=new SMAT [nt_sheet_num*(nt_sheet_num+1)-1] ;
SMAT *smat1=alloc_smat, *b_smat=alloc_smat, *smat2, *osmat1 ;
sheet=back ;
//シートマップテーブルを作成
for(cnt1=0; cnt1<nt_sheet_num; cnt1++) {
if (sheet->flag!=1) {
sheet=sheet->next_sheet ;
cnt1-- ;
continue ; //透過属性あり、もしくは非表示
}
if (cmp(&lx1,sheet->vx,vx,
&ly1,sheet->vy,vy,
&lx2,sheet->vx+sheet->xsize-1,vx+xsize-1,
&ly2,sheet->vy+sheet->ysize-1,vy+ysize-1)
==1) {
sheet=sheet->next_sheet ;
continue ; //重なりがなかった
}
//現在のシートのマップを作る
smat1->sheet=sheet ;
smat1->x1=lx1 ;
smat1->y1=ly1 ;
smat1->x2=lx2 ;
smat1->y2=ly2 ;
smat1->flag=flag ;
if (sheet==t_sheet)
flag=1 ;
num_smat++ ;
//現在のシート(osmat1)とそれまで作ったすべてのシート(smat2)との当たり判定をする
osmat1=smat1 ;
smat2=b_smat ;
o_num_smat=num_smat ;
smat1=&smat1[1] ;
for(cnt2=0; cnt2<o_num_smat-1; cnt2++) {
if (smat2->sheet==(SHEET *)0) {
smat2=&smat2[1];
continue ; //無効なマップデータ
}
num_r=divide_smat(smat1, osmat1, smat2) ;
smat1=&smat1[num_r] ; //シート分割
num_smat+=num_r ;
smat2=&smat2[1] ;
}
sheet=sheet->next_sheet ;
}
//シートマップテーブルを参考に、実描画
smat1=b_smat ;
for(cnt2=0; cnt2<num_smat; cnt2++) {
if (smat1->sheet==(SHEET *)0 || smat1->flag==1) {
//ここに問題有り
smat1=&smat1[1] ;
continue ;
}
sheet=smat1->sheet ;
int *scrnbuf=&(sinfo->vram[smat1->y1*sinfo->scrnx + smat1->x1]);
int *sheetbuf=&(sheet->buffer[(smat1->y1 - sheet->vy)*sheet->xsize + smat1->x1 - sheet->vx]);
int size=(smat1->x2 - smat1->x1 + 1)<<2;
for(y=smat1->y1; y<=smat1->y2; y++) {
ssememcpy(scrnbuf, sheetbuf , size);
scrnbuf+=sinfo->scrnx;
sheetbuf+=sheet->xsize;
// for(short x=smat1->x1; x<=smat1->x2; x++)
// sinfo->vram[y*sinfo->scrnx+x]=sheet->buffer[(y - sheet->vy)*sheet->xsize + x - sheet->vx] ;
}
smat1=&smat1[1] ;
}
_using.Free();
delete [] alloc_smat ;
return ;
}
char SHTCTL::divide_smat( SMAT *smat1, SMAT *osmat1, SMAT *smat2) const {
short lx1, ly1, lx2, ly2 ;
char num_r=0 ;
if (shtctl.cmp(&lx1,osmat1->x1,smat2->x1,
&ly1,osmat1->y1,smat2->y1,
&lx2,osmat1->x2,smat2->x2,
&ly2,osmat1->y2,smat2->y2)
==1)
return 0 ; //重なりがなかった
if (smat2->y1!=ly1) {
smat1->sheet=smat2->sheet ;
smat1->x1=smat2->x1 ;
smat1->y1=smat2->y1 ;
smat1->x2=smat2->x2 ;
smat1->y2=ly1-1 ;
smat1->flag=smat2->flag ;
smat1=&smat1[1] ;
num_r++ ;
}
if (smat2->x1!=lx1) {
smat1->sheet=smat2->sheet ;
smat1->x1=smat2->x1 ;
smat1->y1=ly1 ;
smat1->x2=lx1-1 ;
smat1->y2=ly2 ;
smat1->flag=smat2->flag ;
smat1=&smat1[1] ;
num_r++ ;
}
if (lx2!=smat2->x2) {
smat1->sheet=smat2->sheet ;
smat1->x1=lx2+1 ;
smat1->y1=ly1 ;
smat1->x2=smat2->x2 ;
smat1->y2=ly2 ;
smat1->flag=smat2->flag ;
smat1=&smat1[1] ;
num_r++ ;
}
if (ly2!=smat2->y2) {
smat2->y1=ly2+1 ;
}else{
smat2->sheet=(SHEET *)0 ;
}
return num_r;
}
| true |
d7b960822e6d7d80afde7e17e6c2a8f17fd70b39 | C++ | Anirgb00/gfg-Covid-codes | /unqueprime.cpp | UTF-8 | 1,203 | 3 | 3 | [] | no_license | #include <bits/stdc++.h>
#include <vector>
#include <string.h>
#include <math.h>
using namespace std;
void sieve(long long int n){
bool isprime[n+1];
int flag = 0;
for(int i=0;i<=n;i++)
isprime[i] = true;
isprime[0] = false;
isprime[1] = false;
for(int i=2;i*i<=n;i++){
if(isprime[i] == true){
for(int j = i*i;j<=n;j += i)
isprime[j] = false; }
}
for(int i=0;i<n;i++){
if(isprime[i] == true && n%i == 0){
flag = 1;
cout<<i<<" "; }
}
if(flag == 0) cout<<n<<endl;
cout<<"\n";
}
int prime(int n){
int c=0;
for(int i = 2;i<=n;i++){
if(n%i == 0){
c = 1;
break; }
if(c == 0) cout<<Indian Institute of Technology Varanasi (IIT BHU)
}
cout<<endl;
return 0;
}
void print(int n){
while(n%2 ==0)
cout<<"2"<<endl(
for(int j = 3;j<=sqrt(n);i = i+2){
while(n%i == 0){
cout<<i<<" ";
n = n/i; }
}
if(n>2) cout<<n<<endl;
}
int main() {
int t;
long long int num;
cin>>t;
while(t--){
cin>>num;
sieve(num);
//prime(num);
print(num)l
}
return 0;
}
| true |
0692143634ddf43520132eac327ff30aab05d5b7 | C++ | alexandraback/datacollection | /solutions_2645486_0/C++/swda289346/B.cpp | UTF-8 | 1,375 | 2.65625 | 3 | [] | no_license | #include <stdio.h>
#define N 10000
inline long long max(long long a, long long b)
{
return a>b?a:b;
}
inline long long min(long long a, long long b)
{
return a<b?a:b;
}
long long _calc(long long *v, int e, int r, int n, int se, int ee)
{
if (n<=0)
return 0;
int maxpos = 0;
long long ans = 0;
for (int i=1;i<n;++i)
if (v[i]>v[maxpos])
maxpos = i;
long long canGetBefore = maxpos, canGetAfter = n-maxpos-1;
canGetBefore *= r;
canGetAfter *= r;
long long has = min(canGetBefore+se, e), reserved = max(ee-canGetAfter, 0);
ans += (has-reserved)*v[maxpos];
// fprintf(stderr, "%lld %lld %lld\n", has, reserved, v[maxpos]);
ans += _calc(v, e, r, maxpos, se, max(has-r, 0));
ans += _calc(v+maxpos+1, e, r, n-maxpos-1, min(reserved+r, e), ee);
return ans;
}
long long calc(long long *v, int e, int r, int n)
{
int maxpos = 0;
long long ans = 0;
for (int i=1;i<n;++i)
if (v[i]>v[maxpos])
maxpos = i;
ans += v[maxpos]*e;
ans += _calc(v, e, r, maxpos, e, max(e-r, 0));
ans += _calc(v+maxpos+1, e, r, n-maxpos-1, min(e, r), 0);
return ans;
}
int main()
{
int t;
int e, r, n;
long long v[N];
scanf("%d", &t);
for (int i=1;i<=t;++i)
{
scanf("%d%d%d", &e, &r, &n);
for (int j=0;j<n;++j)
scanf("%lld", &v[j]);
printf("Case #%d: %lld\n", i, calc(v, e, r, n));
}
return 0;
}
| true |
644c7ea7b6636da5f9baf043aa5dcc2e0c7b25e5 | C++ | jishnusen/cs32-hw | /homework2/mazestack.cpp | UTF-8 | 1,196 | 3.578125 | 4 | [] | no_license | #include <iostream>
#include <stack>
#include <string>
using namespace std;
class Coord {
public:
Coord(int rr, int cc) : m_row(rr), m_col(cc) {}
int r() const { return m_row; }
int c() const { return m_col; }
private:
int m_row;
int m_col;
};
bool pathExists(string maze[], int nRows, int nCols, int sr, int sc, int er,
int ec) {
stack<Coord> coordStack;
coordStack.push(Coord(sr, sc)); // Push starting coord;
maze[sr][sc] = 'D';
while (!coordStack.empty()) {
Coord top = coordStack.top();
coordStack.pop();
// cout << "R: " << top.r() << "\tC: " << top.c() << endl;
if (top.r() == er && top.c() == ec) {
return true;
}
const int r = top.r();
const int c = top.c();
if (maze[r - 1][c] == '.') {
coordStack.push(Coord(r - 1, c));
maze[r - 1][c] = 'D';
}
if (maze[r][c + 1] == '.') {
coordStack.push(Coord(r, c + 1));
maze[r][c + 1] = 'D';
}
if (maze[r + 1][c] == '.') {
coordStack.push(Coord(r + 1, c));
maze[r + 1][c] = 'D';
}
if (maze[r][c - 1] == '.') {
coordStack.push(Coord(r, c - 1));
maze[r][c - 1] = 'D';
}
}
return false;
}
| true |
bed6e4d7253afcb2c7e8b70cd5da89687d57e98b | C++ | Eradan94/Tangram | /include/View/Menu.h | UTF-8 | 2,177 | 3.296875 | 3 | [] | no_license | /*!
* \file Menu.h
* \brief Defines a representation of menu.
* \author Biguenet Denis & Gosset Severin
* \date 22/02/2020
*/
#pragma once
#include "../../include/View/Drawable.h"
#include "../../include/View/Button.h"
#include "../../include/Model/Shape.h"
#include "../../include/Model/Piece.h"
#include <list>
#include <memory>
/*! \class Menu
* \brief Representation of menu
*
* A menu is represented by a vector of buttons and a vector of pieces (decorations)
*/
class Menu: public Drawable {
public :
/*!
* \brief default constructor
*
*/
Menu();
/*!
* \brief menu initialization
* \return a pointer to the new menu
*
*/
static std::shared_ptr<Menu> init();
/*!
* \brief Adds a button in the menu's vector of buttons
* \param button : the button added into the vector
*
*/
void addButton(std::unique_ptr<Button> button);
/*!
* \brief Sets an input button for the menu
* \param inputBox the button to sets as input
*/
void setInputBox(std::unique_ptr<Button> inputBox);
/*!
* \brief Draw method
* \param window : the window chre the button is draw
*
*/
void draw(sf::RenderWindow & window);
/*!
* \brief Checks if a button is clicked by the user
* \param event : a point (position of the mouse cursor the the user clicked)
*
*/
void select(const Point<double> & event);
/*!
* \brief Clears the vectors
*
*/
void clear();
/*!
* \brief Adds a shape in the menu's vector of decoration shapes
* \param piece : the piece added into the vector
*
*/
void addDecorationPiece(std::shared_ptr<Shape<double>> piece);
/*!
* \brief Adds a character to the input button of the menu, if it exists
* \param c the character to add
*/
void setText(char c);
/*!
* \brief Returns the input text of the input button
* \return the input text
*/
std::string getInputBoxText();
private :
std::vector<std::unique_ptr<Button>> buttons; /*!Vector of buttons */
std::shared_ptr<Button> inputBox; /*!Input box*/
std::vector<std::shared_ptr<Shape<double>>> decorationPieces; /*!Vector of decoration pieces */
};
| true |
0d93944f6fd52aeb7593befab6b59d15e970bbe8 | C++ | SebiCoroian/pbinfo-sources | /primeintreele.cpp | UTF-8 | 336 | 3.328125 | 3 | [] | no_license | #include<iostream>
using namespace std;
int euclid(int a, int b)
{
int c;
while (b)
{
c = a % b;
a = b;
b = c;
}
return a;
}
int main()
{
int a,b;
cin>>a>>b;
if(euclid(a,b)==1)
{
cout<<"PIE";
}
else
{
cout<<"NOPIE";
}
} | true |
68fe604a4903a5949caf8132a39e7e85e17f740c | C++ | 1001root/SEM4_lab_codes | /c++/DSA/lab5/oppQueue_linklist.cpp | UTF-8 | 1,363 | 3.84375 | 4 | [] | no_license | #include<iostream>
using namespace std;
class list{
public:
int data;
list * next;
list * previous;
};
class queue{
public:
list * head;
list * tail;
public:
queue(){
head = NULL;
tail = NULL;
}
bool is_empty(){
return(head == NULL || tail == NULL);
}
void enqueue(int a){
list * temp;
temp = new list;
if(is_empty()){
head=temp;
tail= temp;
temp->next=NULL;
temp->previous=NULL;
}
else{
head->next=temp;
temp->previous=head;
// temp->previous=head;
head=temp;
head->next=NULL;
}
temp->data=a;
}
int deque(){
if(! is_empty()){
list * tmp;
tmp = tail;
cout<<tmp->data<<endl;
tail=tail->next;
if(tail != NULL)
tail->previous=NULL;
else{
head=NULL;
delete head;
}
delete tmp;
}
else {
cout<<"Empty"<<endl;
}
}
int display(){
list * tem;
tem = head;
while(tem != NULL){
cout<<tem->data<<" ";
tem = tem->previous;
}
cout<<endl;
return 0;
}
};
int main(){
queue one;
bool con= true;
cout<<"You have a Queue"<<endl;
cout<<"1.Enque. 2.Deque 3.Display 9.Quit"<<endl;
while(con){
cout<<"?? : ";
int a;
cin>>a;
if(a==1){
int b;
cout<<"value"<<endl;
cin>>b;
one.enqueue(b);
}
else if(a==2){
one.deque();
}
else if(a==3){
one.display();
}
else if(a==9){
con=false;
}
}
return 0;
}
| true |
2c9712900f91666eaf071047b953234e94440403 | C++ | qawbecrdtey/BOJ-sol | /problems/acmicpc_22952.cpp | UTF-8 | 199 | 2.59375 | 3 | [
"MIT"
] | permissive | #include <cstdio>
int main() {
int n; scanf("%d", &n);
if(n & 1) printf("%d ", n);
for(int i = 1; i <= n / 2; i++) {
if(i * 2 == n) printf("%d %d", i, n);
else printf("%d %d ", i, n - i);
}
} | true |
a9bbb6c09aaf75a2fedad536c756b461e5612a0d | C++ | parthc-rob/tictactoe-game | /include/gameboard.h | UTF-8 | 3,086 | 2.875 | 3 | [] | no_license | //Console-based Tic-Tac-Toe Game. Can be played vs a random bot
// Copyright (C) 2019, Parth Chopra [parthchopra93@gmail.com]
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
#ifndef GAMEBOARD_H
#define GAMEBOARD_H
#define GAME_NOT_OVER 999
#include <array>
#include <string>
#include <cstdlib>
#include <ctime>
#include <algorithm>
#include <list>
#include <iterator>
#include <map>
#include <vector>
enum class player_enum{
none = 0, player_0 = 1, player_x = -1
};
enum class line_type{
row, column, lr_diagonal, rl_diagonal
};
namespace ticTacUtils {
std::map<player_enum, std::string>
player_name
= {
{player_enum::player_0 , "Player 0"},
{player_enum::player_x , "Player X"},
{player_enum::none , "No One"},
};
std::map<player_enum, char>
player_symbol
= {
{player_enum::player_0 , '0'},
{player_enum::player_x , 'X'},
{player_enum::none , ' '},
};
typedef std::vector <player_enum>
board_type_t;
typedef std::array <int,2>
cell_t;
typedef std::vector <player_enum>
line_list_t;
void reset_board(
board_type_t& current_board, line_list_t& line_occupancy,
int size
);
int random(int min, int max);
template<typename T> typename T::iterator get_random_from_list(T & list);
cell_t convertIndexToCell(int index, int board_size);
int convertCellToIndex(cell_t rowCol, int board_size);
int convertRowColToIndex(int row, int column, int board_size);
void printRowSeparator(int board_size);
bool promptReplay();
int promptBoardSize();
}
class GameBoard {
int board_size;
ticTacUtils::board_type_t current_board;
ticTacUtils::board_type_t player_0_board;
ticTacUtils::board_type_t player_X_board;
player_enum who_won;
int is_game_over;
ticTacUtils::line_list_t line_occupancy;
char colStart = 'A';
std::list<ticTacUtils::cell_t> emptyCells;
bool visualize = true;
public:
GameBoard(bool vis = true, int board_size = 3);
void resetBoard();
void resetEmptyCells();
player_enum checkFilledLine(line_type line);
player_enum checkFilledLine(line_type line,
ticTacUtils::cell_t rowCol);
bool isBoardFilled();
int isGameOver();
ticTacUtils::cell_t processKeyboardInput(std::string userInput);
bool playMove(ticTacUtils::cell_t inputCell,
bool is_player_0);
bool playMove(std::string userInput,
bool is_player_0);
bool playRandomMove(bool is_player_0);
void showBoard(bool visualize = false);
std::string whoWon();
void activateVisualization();
};
#endif
| true |
c005fe0a5a3bdcf9f25125326468692d1e1d87ba | C++ | JulienFiant/arcade | /games/PACMAN/include/clyde.hpp | UTF-8 | 1,245 | 2.53125 | 3 | [] | no_license | /*
** EPITECH PROJECT, 2019
** OOP_arcade_2018
** File description:
** clyde
*/
#ifndef CLYDE_HPP_
#define CLYDE_HPP_
#include "../../../core/IEntity.hpp"
class clyde : public IEntity
{
public:
clyde();
~clyde();
void setBonus(int = 0);
int getBonus();
void setSpriteSFML(sf::Sprite sprite);
sf::Sprite getSpriteSFML() const;
void changePosSpriteSFML(float x, float y);
void setSpriteNCURSES(std::string sprite);
std::string getSpriteNCURSES() const;
void setNameSprite(std::string name_sprite);
std::string getNameSprite() const;
int getColorChar() const;
void setName(std::string name);
std::string getName() const;
void setPos(float *pos);
const float *getPos() const;
std::vector<std::string> move(Event &evt, std::vector<std::string> _map_carac, std::vector<IObject *> &bonus);
void check_bonus(std::vector<IObject *> &bonus);
int getScore() const;
void destroy_sprite();
protected:
int _tileSize;
int _mapStartX;
int _mapStartY;
sf::Sprite _sprite_sfml;
std::string _sprite_ncurses;
bool _SFMLSetup;
std::vector<std::string> _name_sprite;
std::vector<int> _color;
size_t _sprite_idx;
std::string _name;
int _score;
Clock timer;
};
#endif /* !CLYDE_HPP_ */
| true |
74871d89152babb98d4681f52c5ded1b261b1a91 | C++ | epsilon-phase/logo | /tests/lexer2.cpp | UTF-8 | 5,670 | 3.265625 | 3 | [] | no_license | #include "catch2.hpp"
#include <iostream>
#include <logo/errors/syntaxexception.hpp>
#include <logo/language/lexer/lexer.hpp>
#include <string>
#ifdef TEST_PRINTING
#define PRINT_ERROR(X) std::cerr << X
#define PRINT_OUT(X) std::cout << X
#else
#define PRINT_ERROR(X)
#define PRINT_OUT(X)
#endif
using namespace logo::language;
using namespace logo::language::tokens;
static void list_tokens(const logo::language::TranslationUnit &);
TEST_CASE("lex2 can find anything", "[lex2]") {
WHEN("a string is present in the input") {
const std::string basic = "\"hi\"";
auto tu = TranslationUnit();
tu.contents = basic;
try {
lex2(tu);
} catch (const logo::error::SyntaxException &se) {
PRINT_ERROR(<< se.get_context() << std::endl);
throw se;
}
if (tu.tokens.size() != 1)
list_tokens(tu);
THEN("A token is found") { REQUIRE(tu.tokens.size() == 1); }
THEN("It is identified as a string") {
REQUIRE(tu.tokens[0].type == String);
}
}
WHEN("a number is present") {
const std::string num = "12.23";
auto tu = TranslationUnit();
tu.contents = num;
lex2(tu);
THEN("They are found") { REQUIRE(tu.tokens.size() == 1); }
THEN("It is identified") { REQUIRE(tu.tokens[0].type == Number); }
THEN("It looks right") { REQUIRE(tu.tokens[0].content == "12.23"); }
}
WHEN("Multiple numbers are present") {
const std::string num = "12.3 5.4e5";
auto tu = TranslationUnit();
tu.contents = num;
lex2(tu);
THEN("They are found") { REQUIRE(tu.tokens.size() == 2); }
THEN("They are identified as numbers") {
REQUIRE(tu.tokens[0].type == Number);
REQUIRE(tu.tokens[1].type == Number);
}
}
WHEN("Multiple numbers are present and have signs mixed with operators") {
const std::string num = "12.3 - -13 - 5";
auto tu = LexString(num);
THEN("They are found") { REQUIRE(tu.tokens.size() == 5); }
THEN("They are correctly identified") {
REQUIRE(tu.tokens[0].type == Number);
REQUIRE(tu.tokens[1].type == Minus);
REQUIRE(tu.tokens[2].type == Number);
REQUIRE(tu.tokens[3].type == Minus);
REQUIRE(tu.tokens[4].type == Number);
}
}
WHEN("There is an identifier") {
const std::string ident = "hello";
auto tu = TranslationUnit();
tu.contents = ident;
lex2(tu);
THEN("It is found") { REQUIRE(tu.tokens.size() == 1); }
THEN("It is labeled as such") { REQUIRE(tu.tokens[0].type == Identifier); }
}
WHEN("There are several identifiers") {
const std::string ident = "hello world";
auto tu = TranslationUnit();
tu.contents = ident;
lex2(tu);
THEN("They are found") { REQUIRE(tu.tokens.size() == 2); }
THEN("They are labeled as such") {
REQUIRE(tu.tokens[0].type == Identifier);
REQUIRE(tu.tokens[1].type == Identifier);
}
THEN("They appear right") {
REQUIRE(tu.tokens[0].content == "hello");
REQUIRE(tu.tokens[1].content == "world");
}
}
WHEN("Operators are present") {
const std::string operators = "hello+3";
auto tu = TranslationUnit();
tu.contents = operators;
lex2(tu);
THEN("They are found") { REQUIRE(tu.tokens.size() == 3); }
THEN("They are correctly identified") {
REQUIRE(tu.tokens[0].type == Identifier);
REQUIRE(tu.tokens[1].type == Plus);
REQUIRE(tu.tokens[2].type == Number);
}
}
WHEN("Operators are present and weird") {
const std::string operators = "hello+-3";
auto tu = TranslationUnit();
tu.contents = operators;
lex2(tu);
THEN("They are found") { REQUIRE(tu.tokens.size() == 3); }
THEN("They are correctly identified") {
REQUIRE(tu.tokens[0].type == Identifier);
REQUIRE(tu.tokens[1].type == Plus);
REQUIRE(tu.tokens[2].type == Number);
}
}
WHEN("Keywords are present") {
const std::string keywords = "while endwhile";
auto tu = TranslationUnit();
tu.contents = keywords;
lex2(tu);
THEN("They are found") { REQUIRE(tu.tokens.size() == 2); }
THEN("They are correctly identified") {
REQUIRE(tu.tokens[0].type == While);
REQUIRE(tu.tokens[1].type == EndDo);
}
}
}
TEST_CASE("Comments", "[lex2]") {
WHEN("Comments are present") {
try {
const std::string comment = "//This is fine\n"
"//Right?";
auto tu = LexString(comment);
THEN("They are found") { REQUIRE(tu.tokens.size() == 2); }
THEN("They are identified as comments") {
REQUIRE(tu.tokens[0].type == Comment);
REQUIRE(tu.tokens[1].type == Comment);
}
THEN("They appear correct") {
REQUIRE(tu.tokens[0].content == "This is fine");
REQUIRE(tu.tokens[1].content == "Right?");
}
} catch (logo::error::SyntaxException &s) {
PRINT_OUT(<< s.get_context() << std::endl);
throw s;
}
}
WHEN("The comments are multiline") {
try {
const std::string comment = "/*This is cool huh\n"
"Well, we think it is at least :) */";
auto tu = LexString(comment);
THEN("It is found") { REQUIRE(tu.tokens.size() == 1); }
THEN("They are identified as comments") {
REQUIRE(tu.tokens[0].type == Comment);
}
} catch (logo::error::SyntaxException &s) {
PRINT_OUT(<< "On line " << s.line << ": " << s.get_context()
<< std::endl);
throw s;
}
}
}
static void list_tokens(const logo::language::TranslationUnit &tu) {
using namespace logo::language::tokens;
for (const auto &i : tu.tokens)
PRINT_OUT(<< "'" << i.content << "' " << TokenToString(i.type)
<< std::endl);
} | true |
5fc0b8592fe5e3855aedbc662ce63b0c123e5239 | C++ | olendvcook/TinyMaze | /Enemy.h | UTF-8 | 738 | 2.8125 | 3 | [] | no_license | #pragma once
#include "animatedsprite.h"
//Example of extended Animated Sprite class to create simple enemies
//update depending on what state enemy is in
//TODO: is states for enemies as dumb as states for player?
enum ENEMYSTATE { eLEFT, eRIGHT, eNONE };
//extends AnimatedSprite so it has all of AnimatedSprites vars and methods
class Enemy :
public AnimatedSprite
{
private:
ENEMYSTATE mEnemyState;
public:
Enemy(sf::Vector2f pPosition,
sf::Vector2f pVelocity,
sf::Vector2i pSize,
sf::Texture *pTexture,
float pAngle = 0,
float pAngularVelocity = 0);
virtual ~Enemy(void);
//override animated sprite update method
void update();
void setEnemyState(ENEMYSTATE pEnemyState) { mEnemyState = pEnemyState; }
};
| true |
76610bd434861a44d9a056d597e527f3a5b521b4 | C++ | tongchiyang/PSS | /purenessscopeserver/purenessscopeserver/PurenessScopeServer/PacketParse/PacketParse.h | GB18030 | 3,000 | 2.578125 | 3 | [] | no_license | #ifndef _PACKETPARSE_H
#define _PACKETPARSE_H
//ȫʹõ
//↑ֻҪȥʵ5ӿڣͿһݰ
//һӣֻģʽĻҪٹ캯ָm_u1PacketModeΪPACKET_WITHSTREAM
//ȻʵGetPacketStream()һдСӡ
//ʵģʽֻްͷЭ飬аͷЭ飬㲻SetPacketHeadSetPacketBody
//ҲԼȥGetPacketStreamʵ
//ԼϲãһƼǰߣΪЧʱȽϸߡ
//add by freeeyes
#include "PacketParseBase.h"
#ifdef WIN32
#if defined PACKETPARSE_BUILD_DLL
#define DLL_EXPORT __declspec(dllexport)
#else
#define DLL_EXPORT __declspec(dllimport)
#endif
#else
#define DLL_EXPORT
#endif
#ifdef WIN32
class DLL_EXPORT CPacketParse : public CPacketParseBase
#else
class CPacketParse : public CPacketParseBase
#endif
{
public:
CPacketParse(void);
virtual ~CPacketParse(void);
//ʼPacketParsed
void Init();
//õݰͷݿ飬u4ConnectIDIDpmbHeadݿ飬pMessageBlockManagerݿأýЧ
bool SetPacketHead(uint32 u4ConnectID, ACE_Message_Block* pmbHead, IMessageBlockManager* pMessageBlockManager);
//õݰݿ飬u4ConnectIDIDpmbHeadݿ飬pMessageBlockManagerݿأýЧ
bool SetPacketBody(uint32 u4ConnectID, ACE_Message_Block* pmbBody, IMessageBlockManager* pMessageBlockManager);
//רŶӦ ModeΪ0IJͷݰ,Ǵͷģʽʲô
//ΪõڴأpHeadpBodyɿṩɿܻգnewpHeadpBodyڴй¶
//Ҫעһ°ȻǰĽӿڷҲӿʵĹǰm_u1PacketModePACKET_WITHSTREAM
uint8 GetPacketStream(uint32 u4ConnectID, ACE_Message_Block* pCurrMessage, IMessageBlockManager* pMessageBlockManager);
//ƴݷذеķݰ
bool MakePacket(uint32 u4ConnectID, const char* pData, uint32 u4Len, ACE_Message_Block* pMbData, uint16 u2CommandID = 0);
//õݰij
uint32 MakePacketLength(uint32 u4ConnectID, uint32 u4DataLen, uint16 u2CommandID = 0);
//ӵһνʱصĽӿԼĴ
bool Connect(uint32 u4ConnectID, _ClientIPInfo objClientIPInfo, _ClientIPInfo objLocalIPInfo);
//ӶϿʱԼĴ
void DisConnect(uint32 u4ConnectID);
//õǰݰͷϢ
void GetPacketHeadInfo(_PacketHeadInfo& objPacketHeadInfo);
};
#endif
| true |