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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
5bd532a50f7c75328b69b24ec3b8116ccfd9d624 | C++ | neurohazardous/hyperSynch | /hM_blackBox/hM_blackBox.ino | UTF-8 | 1,588 | 3.234375 | 3 | [] | no_license | //This will send 3 TTL pulses to the selected outputsof the Arduino
// https://www.arduino.cc/en/Tutorial/Switch
const int switchPin = 4; //Switch Connected to PIN 4
const int TTLpinP1 = 8; //Output parallel 1
const int TTLpinP2 = 7; //Output parallel 2
const int TTLpinJ1 = 6; //Output jack 1
int switchState = 0; //Variable for reading switch status
void setup()
{
pinMode(TTLpinP1, OUTPUT);
pinMode(TTLpinP2, OUTPUT);
pinMode(TTLpinJ1, OUTPUT);
pinMode(switchPin, INPUT_PULLUP); //Switch PIN is Input
}
void loop()
{
switchState = digitalRead(switchPin); //Read the status of the Switch
if (switchState == LOW) //If the switch is pressed
{
digitalWrite(TTLpinP1, HIGH); //ON
digitalWrite(TTLpinP2, HIGH);
digitalWrite(TTLpinJ1, HIGH);
delay(50); //50ms Pulse
digitalWrite(TTLpinP1, LOW); //OFF
digitalWrite(TTLpinP2, LOW);
digitalWrite(TTLpinJ1, LOW);
delay(500); // ISI 500ms
digitalWrite(TTLpinP1, HIGH); //ON
digitalWrite(TTLpinP2, HIGH);
digitalWrite(TTLpinJ1, HIGH);
delay(50); //50ms Pulse
digitalWrite(TTLpinP1, LOW); //OFF
digitalWrite(TTLpinP2, LOW);
digitalWrite(TTLpinJ1, LOW);
delay(500); // ISI 500ms
digitalWrite(TTLpinP1, HIGH); //ON
digitalWrite(TTLpinP2, HIGH);
digitalWrite(TTLpinJ1, HIGH);
delay(50); //50ms Pulse
digitalWrite(TTLpinP1, LOW); //OFF
digitalWrite(TTLpinP2, LOW);
digitalWrite(TTLpinJ1, LOW);
delay(500); // ISI 500ms
}
}
| true |
c8baefbd9ae76bbac48185c8b0500fb6e6e9a254 | C++ | morell5/HSE-Course | /seminars/seminar13/variadic/array.cpp | UTF-8 | 1,805 | 3.828125 | 4 | [] | no_license | #include <algorithm>
#include <iostream>
template<typename T, std::size_t Size>
class array {
public:
typedef T value_type;
typedef T* pointer;
typedef T& reference;
template<typename... U>
array(U... elem) : arr{elem...} { }
class iterator;
reference operator[](int index) {
return arr[index];
}
reference operator[](int index) const {
return arr[index];
}
iterator begin() {
pointer p = &arr[0];
auto x = iterator(p);
return iterator(&arr[0]);
}
iterator end() {
return iterator(&arr[Size - 1]);
}
class iterator {
public:
using value_type = array::value_type;
using reference = array::reference;
using pointer = array::pointer;
iterator(pointer _ptr) : ptr(_ptr) {}
iterator(const iterator& iterator) : ptr(iterator.ptr) {}
iterator& operator++() {
ptr++;
return *this;
}
iterator operator++(int) {
iterator it(*this);
ptr++;
return it;
}
pointer operator->() const {
return ptr;
}
reference operator*() const {
return *ptr;
}
bool operator==(const iterator& rhs ) {
return ptr == rhs.ptr;
}
bool operator!=(const iterator& rhs ) {
return !(*this == rhs);
}
bool operator-(const iterator& rhs ) {
return ptr - rhs.pt;
}
private:
pointer ptr;
};
private:
T arr[Size];
};
int main() {
array<int, 4> arr = {0, 1, 2};
for (auto it = arr.begin(); it != arr.end(); it++) {
std::cout << *it;
}
return 0;
} | true |
04a14757bb1de62f68cfbafd2dd2c4f8ba965ece | C++ | dmitri-mcguckin/Weather-Log | /tools.cpp | UTF-8 | 1,882 | 3.25 | 3 | [
"MIT"
] | permissive | #include "tools.h"
/*void menu() // DEPRECATED
{
cout << "What would you like to do?" << endl;
cout << "[A]dd song" << endl;
cout << "[L]ist songs" << endl;
cout << "[E]dit song" << endl;
cout << "[R]emove song" << endl;
cout << "[S]earch songs" << endl;
cout << "[C]hange library" << endl;
cout << "[Q]uit" << endl;
cout << "?: ";
}*/
void clear()
{
#if defined(windows) || defined(__windows__) || defined(__windows)
system("cls");
#elif defined(unix) || defined(__unix__) || defined(__unix)
system("clear");
#else
cout << "Your operating system is not supported!" << endl;
pause();
#endif
}
void printFile(char *fileName)
{
int x = 48;
cout << setw(x) << setfill('-') << "-" << endl;
cout << setw(x/2) << setfill(' ') << left << "Current Selected File: " << setw(x/2) << right << fileName << endl;
cout << setw(x) << setfill('-') << "-" << endl;
cout << setfill(' ') << left << endl;
}
void fixTime(int &min, int &sec)
{
int addM;
int addS;
if(sec >= 60)
{
addM = sec / 60;
addS = sec % 60;
min += addM;
sec = addS;
}
cout << right << setw(3);
cout << min << ":";
if(sec < 10)
cout << "0";
cout << left << setw(4);
cout << sec;
}
bool error(istream &buffer)
{
if(!buffer)
{
cout << endl << endl << "There was a problem with your input somewhere!" << endl;
return true;
}
else
{
return false;
}
}
void handle(istream &buffer)
{
cout << endl << endl << "Please Wait while we handle it!" << endl << endl;
buffer.clear();
buffer.ignore();
}
void pause()
{
cout << endl << "<Press Enter To Continue>" << endl;
cin.get();
cin.ignore(9999,'\n');
}
| true |
b52b145437285a1cb6b9199483d3d7173d72f58c | C++ | autyinjing/OJ | /nowcoder/PAT/1001_A+B和C.cc | UTF-8 | 419 | 2.875 | 3 | [] | no_license | #include <iostream>
int main()
{
uint32_t cnt = 0;
int64_t a = 0, b = 0, c = 0;
std::cin >> cnt;
for (uint32_t i = 0; i < cnt; ++i)
{
std::cin >> a >> b >> c;
std::cout << "Case #";
if (a + b > c)
std::cout << i+1 << ": true" << std::endl;
else
std::cout << i+1 << ": false" << std::endl;
}
return 0;
} | true |
496a0f0f910ee309cbb5a073034a982df843c1ce | C++ | chang-s/astro | /ant.cpp | UTF-8 | 3,130 | 3.4375 | 3 | [] | no_license | /*******************************************************************
* Program Name: CS 162 - Group Project - Predator-Prey Sim
* Author: Group 8 (Astro)
* Date: November 4, 2018
* Description: Source file for Ant class, which models the
* prey in the predator-prey simulation. This
* class is a derived class of Critter, establshing
* an IS-A relationship with Critter (i.e. every
* Ant IS-A Critter).
*******************************************************************/
#include "critter.hpp"
#include "ant.hpp"
/*******************************************************************
* Description: Method that moves an ant to one of the four
* adjacent cells
* Arguments: A Direction enum value that specifies where the
* new ant object should be placed on the board
* Returns: A pointer to a Critter object holding a new ant
*******************************************************************/
Critter* Ant::move(Direction dir) {
Critter* crit = nullptr;
// Increment tracker variables
++this->critSteps;
++this->lastBreed;
// Create a new DB in the specified direction
switch(dir) {
case (Direction::UP) : {
crit = new Ant(this->row-1, this->col,
this->critSteps, this->lastBreed);
break;
}
case (Direction::RIGHT) : {
crit = new Ant(this->row, this->col+1,
this->critSteps, this->lastBreed);
break;
}
case (Direction::DOWN) : {
crit = new Ant(this->row+1, this->col,
this->critSteps, this->lastBreed);
break;
}
case (Direction::LEFT) : {
crit = new Ant(this->row, this->col-1,
this->critSteps, this->lastBreed);
break;
}
case (Direction::NONE) : {
crit = new Ant(this->row, this->col,
this->critSteps, this->lastBreed);
break;
}
}
return crit;
}
/*******************************************************************
* Description: Method that allows an ant to breed if it meets the
* requirements for doing so
* Arguments: A Direction enum value that specifies where the
* ant object should breed on the board
* Returns: A pointer to a Critter object holding a new ant;
* note: the return value will be a null pointer if
* the breed would take the ant out of bounds
*******************************************************************/
Critter* Ant::breed(Direction dir) {
Critter* crit = nullptr;
// Only breed if more than 3 steps since last breed
if (this->lastBreed >= 3) {
// Breed a new critter in the specified direction
switch(dir) {
case (Direction::UP) :
this->lastBreed = 0;
crit = new Ant(row-1, col);
break;
case (Direction::RIGHT) :
this->lastBreed = 0;
crit = new Ant(row, col+1);
break;
case (Direction::DOWN) :
this->lastBreed = 0;
crit = new Ant(row+1, col);
break;
case (Direction::LEFT) :
this->lastBreed = 0;
crit = new Ant(row, col-1);
break;
// Don't reset breed counter
case (Direction::NONE) :
break;
}
}
return crit;
}
| true |
ded6ca1dfe9b9750a9e39a79225ea5ffe8aec685 | C++ | hasnainclub/school | /18 spring NIU/csci241 intermediate c++/Assign2/old/BookStore.h | UTF-8 | 1,665 | 3.125 | 3 | [] | no_license | #ifndef BOOKSTORE_H
#define BOOKSTORE_H
#include "Book.h"
#include <iostream>
#include <string>
#include <cstring>
//*****************************************************************
// FILE: BookStore.h
// AUTHOR: Hasnain Attarwala
// LOGON ID: z1697740
// DUE DATE: Feb 13 2018
//
// PURPOSE: Contains the declaration for the BookStore class.
//*****************************************************************
/*
The BookStore class should have the following two private data members:
An array of 30 Book objects
An integer that specifies the number of Book objects actually stored in the array
*/
class BookStore
{
private:
Book bookArray[30];
int numBookObjects;
public:
BookStore(); //BookStore default constructor - This "default" constructor for the BookStore class takes no parameters.
//Like all C++ constructors, it does not have a return data type.
BookStore(const std::string&); // alt constructor a reference to a constant string object (data type const string&),
//that will contain the name of an existing database file.
void print(); // print stuff
void sortByISBN(); //This will be a method, not a function. Change the parameters for the method to
// those described above.
int searchForISBN(const char*); //searching for isbn method , made constant lecture pending
//value of char pointer can't be changed, even in scope even if it's a pointer
//power of const
void processOrders(const std::string& ) ;//passing filename wishing to open, because it's in string
};
#endif
| true |
27e373c049cdc80e3061a57457e0f7e0640e54bd | C++ | MLXXXp/StarHonor | /Vector2d.cpp | UTF-8 | 1,646 | 3.25 | 3 | [
"MIT"
] | permissive | #include "Vector2d.h"
#include <Arduboy2.h>
//#define Deg2Rad( Deg ) { Deg * PI / 180 };
Vector2d::Vector2d()
{
x = 0;
y = 0;
}
Vector2d::Vector2d( int PosX, int PosY )
{
x = PosX;
y = PosY;
}
Vector2d::~Vector2d()
{
}
float Vector2d::Magnitude()
{
return sqrt( MagnitudeSquared() );
}
float Vector2d::MagnitudeSquared()
{
return ( x * x + y * y );
}
void Vector2d::Normalize()
{
float mag = this->Magnitude();
x = x / mag;
y = y / mag;
}
Vector2d Vector2d::operator*( const Vector2d &rhs )
{
Vector2d result;
result.x = x * rhs.x;
result.y = y * rhs.y;
return result;
}
Vector2d Vector2d::operator*( const float rhs )
{
Vector2d result;
result.x = x * rhs;
result.y = y * rhs;
return result;
}
Vector2d Vector2d::operator*=( const Vector2d &rhs )
{
x = x * rhs.x;
y = y * rhs.y;
}
Vector2d Vector2d::operator+( const Vector2d &rhs )
{
Vector2d result;
result.x = x + rhs.x;
result.y = y + rhs.y;
return result;
}
Vector2d Vector2d::operator+=( const Vector2d &rhs )
{
x = x + rhs.x;
y = y + rhs.y;
}
Vector2d Vector2d::operator-( const Vector2d &rhs )
{
Vector2d result;
result.x = x - rhs.x;
result.y = y - rhs.y;
return result;
}
Vector2d Vector2d::operator-=( const Vector2d &rhs )
{
x = x - rhs.x;
y = y - rhs.y;
}
float Vector2d::Dot( Vector2d b )
{
return ( x * b.x + y * b.y );
}
Vector2d Vector2d::Rotate( float angle )
{
float radian = Deg2Rad(angle);
float cs = cos( radian );
float sn = sin( radian );
float px = x * cs - y * sn;
float py = x * sn + y * cs;
x = px;
y = py;
}
float Deg2Rad( float Deg )
{
return ( Deg * PI / 180 );
}
| true |
06afa9be6d7a5170f6d8d07f0176fe3b76e6ef22 | C++ | cms-externals/tkonlinesw | /TrackerOnline/Fed9U/Fed9USoftware/Fed9UDevice/include/Fed9UMoFO.hh | UTF-8 | 3,708 | 2.625 | 3 | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | #ifndef Fed9UMoFO_HH_
#define Fed9UMoFO_HH_
#include "Fed9UUtils.hh"
//
// class Fed9UMoFO
// Author: Matt Noy
// Date: June 2004
// Purpose: Provides a configurable monitoring
// handle that enables monitoring of the Fed.
//
//
namespace Fed9U
{
class Fed9UDevice;
class Fed9UMoFO
{
public:
//
// Hardware monitor bit field
//
enum MONITOR_FLAGS{COUNTERS=1, TEMPS=2, VOLTAGES=4, TTC=8, CLOCKSRC=16, BE_STATUS=32};
//
// constructor for the Fed9UMoFO class.
// Counters, Temperature, and Voltage are all
// monitored by default. The class doesn't assume
// ownership of the Fed9UDevice it points to
//
// Fed9UMoFO(Fed9UDevice * pFed, DATA_DESTINATION dest, bool MonCounters=true,
// bool MonTemp=true, bool MonVolt=true);
Fed9UMoFO(Fed9UDevice * pFed,
u32 Flags=COUNTERS|TEMPS|VOLTAGES|TTC|CLOCKSRC|BE_STATUS);
~Fed9UMoFO(){}
//
// populates the containers with data from the fed passed to the class
//
void Load();
//
//
//
void Send(std::ostream * os);
// <NAC date="08/05/2007"> made all const
//<JEC date=05-02-07> add get methods for private member variables for monitoring interface to Fed9USupervisor
inline Fed9UCounters getCounterValue() const{return mFedCounters;}
inline std::vector<Fed9UTempControlInfo> getTemperatureValues() const{return mTempInfo;}
inline Fed9UVoltageControlInfo getVoltageValues() const{return mVoltageInfo;}
inline Fed9UTtcrxDescriptionInfo getTTCRxInfo() const{return mTtcInfo;}
inline Fed9UClockSource getClockSourceInfo() const{return mClkSource;}
//</JEC>
// </NAC>
// <NAC date="07/05/2007"> added get method to get TempControlInfo for an FPGA by giving its address
Fed9UTempControlInfo getTemperatureValues(const Fed9UAddress& fpga) const;
// </NAC>
//
// get the monitor state
//
inline bool getCountersFlag()const{return mMonitorFlags&COUNTERS;}
inline bool getTemperatureFlag()const{return mMonitorFlags&TEMPS;}
inline bool getVoltageFlag()const{return mMonitorFlags&VOLTAGES;}
inline bool getTtcFlag()const{return mMonitorFlags&TTC;}
inline bool getClockSrcFlag()const{return mMonitorFlags&CLOCKSRC;}
//
// get all the flags at once
//
inline u32 getMonitorFlags()const{return mMonitorFlags;}
//
// set the monitor state individually
//
inline void setCountersFlag(bool c){c?mMonitorFlags|=COUNTERS:mMonitorFlags&=~COUNTERS;}
inline void setTemperatureFlag(bool t){t?mMonitorFlags|=TEMPS:mMonitorFlags&=~TEMPS;}
inline void setVoltageFlag(bool v){v?mMonitorFlags|=VOLTAGES:mMonitorFlags&=~VOLTAGES;}
inline void setTtcFlag(bool ttc){ttc?mMonitorFlags|=TTC:mMonitorFlags&=~TTC;}
inline void setClockSrcFlag(bool cs){cs?mMonitorFlags|=CLOCKSRC:mMonitorFlags&=~CLOCKSRC;}
//
// set all flag at once
//
inline void setMonitorFlags(u32 Flags){mMonitorFlags=Flags;}
private:
Fed9UMoFO(){}
Fed9UMoFO(const Fed9UMoFO & m){}
//operator=();
private:
//
// configuration parameters
//
Fed9UDevice * mpFed;
u32 mMonitorFlags;
bool mHasNewData;
//
// data containers
//
Fed9UCounters mFedCounters;
//Vector of Fed9UTempControlInfos. First FEUNITS_PER_FED are for FE units ordered by internal numbering. Next is BE them VME. (NAC 09/05/2007)
std::vector<Fed9UTempControlInfo> mTempInfo;
Fed9UVoltageControlInfo mVoltageInfo;
Fed9UTtcrxDescriptionInfo mTtcInfo;
Fed9UClockSource mClkSource;
u32 mBeStatus;
};
} // namespace Fed9U
#endif // Fed9UMoFO_HH_
| true |
68ec1dfc6140cbc75d0062698f2f2455623cad71 | C++ | sidsrivastavasks/CP-Programs | /PRACTICE/anand.cpp | UTF-8 | 1,206 | 3.140625 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
void print_matrix(int arr[100][100],int n,int m);
int main(){
int n ,m, k=0 ;
int i,j;
int arr[100][100];
printf("\nEnter number of rows and columns : ");
scanf ("%d%d",&n,&m);
int matrix[n][m];
for (i=0;i<n;i++){
for(j=0;j<m;j++){
matrix[i][j] = 0;
}
}
srand(time(0));
for(i=0;i<n;i++){
int a = rand()%n, b = rand()%m, c =rand()%100;
printf("%d %d %d %d\n",i,a,b,c);
matrix[a][b] = c;
print_matrix(matrix,n,m);
}
// for (i=0;i<n;i++){
// for(j=0;j<m;j++){
// if (matrix[i][j] != 0){
// arr[k][0]=i;
// arr[k][1]=j;
// arr[k][2]=matrix[i][j];
// }
// k++;
// }
// }
// printf("\n");
// print_matrix(arr,k,3);
return 0;
}
void print_matrix(int matrix[100][100],int n,int m){
int i,j;
if (n == 0){
printf("\nMatrix empty");
return;
}
for (i=0;i<n;i++){
for (j=0;j<m;j++){
printf("%d ",matrix[i][j]);
}
printf("\n");
}
}
| true |
bd25a046c59bf139e6e666d1ba75db844b330ead | C++ | chenghu17/Algorithm | /Leetcode/c_202_Happy_Number.cpp | UTF-8 | 1,938 | 3.78125 | 4 | [] | no_license | //
// Created by Mr.Hu on 2018/5/12.
//
// leetcode 202 happy number
// 题目要求对于给定的数字,计算数字上每一位的平方和,对结果继续上述操作,如果存在平方和等于1,则该数为happy number。
//
// 根据题目要求可以发现,这是一个多次迭代的过程,如果当前平方和为1,则return true,
// 如果不等于1,则继续结果各个位数的平方和。在这个过程中,可能会出现平方和不等于1,且在之前出现过,
// 则说明出现了"死循环",这个数是一定不可能称为happy number,此时就要结束迭代,return false。
// 根据这个思路,则需要把之前出现的数字记录下来,所以使用map进行存储,如果key所对应的value值为1,则说明出现过。
//
// 写完这个代码之后没有像之前那样直接提交,先自己审查了一遍,发现自己在编写的时候有结果小问题,比如拼写问题。
// 测试的时候出现了一个错误,就是我将mapname直接写成了map,糊涂了...更改后顺利通过测试,并且超过了85%的答案
//
#include <iostream>
#include <map>
#include <cmath>
using namespace std;
class Solution {
public:
bool isHappy(int n) {
map<int, int> tmp;
tmp[n] = 1;
while (1) {
int m = 0;
int result = 0;
while (n != 0) {
m = n % 10;
n /= 10;
result += pow(m, 2);
}
if (result == 1) {
return true;
} else {
if (tmp[result] == 1) {
return false;
} else {
tmp[result] = 1;
n = result;
}
}
}
}
};
int main() {
int n = 10;
Solution solution;
bool isHappyNumber = solution.isHappy(n);
cout << isHappyNumber << endl;
return 0;
} | true |
91fd482c3500cfca0765a55aa48e20c377a84a77 | C++ | LittleD3092/bottle_and_cap_problem | /main.cpp | UTF-8 | 431 | 3.046875 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
int main(int argc, char const *argv[])
{
//input
int x;
scanf("%d", &x);
//change money to bottle and cap
int bottle = x;
int cap = x;
//process
while(cap >= 3)
{
if(cap == 3)
{
cap = 0;
bottle ++;
break;
}
int new_bottle = cap/4;
bottle += new_bottle;
cap = cap%4 + new_bottle;
}
//output
printf("%d\n", bottle);
//end
system("pause");
return 0;
} | true |
892340b5fef014da573179b01d564c0e4ccfb6b3 | C++ | DJJ547/Sudoku-Solver | /main.cpp | UTF-8 | 3,293 | 3.40625 | 3 | [] | no_license | #include <iostream>
#include<vector>
using namespace std;
void printSudoku(int arr[9][9]){
cout << "-----------------------" << endl;
for(int r = 0; r < 9; r++){
if(r != 0 && r % 3 == 0){
cout << "-----------------------" << endl;
}
for(int c = 0; c < 9; c++){
if(c != 0 && c % 3 == 0){
cout << "| ";
}
if(arr[r][c] == 0){
cout << ". ";
}else{
cout << arr[r][c] << " ";
}
}
cout << endl;
}
cout << "-----------------------" << endl;
}
bool canPlace9x9(int arr[9][9], int row, int col, int n)
{
if (arr[row][col] != 0) return false;
bool status = true;
int gridx = (col / 3) * 3;
int gridy = (row / 3) * 3;
for (int i = 0; i < 9; i++) {
if (arr[row][i] == n) { status = false; break; }
if (arr[i][col] == n) { status = false; break; }
if (arr[gridy + i / 3][gridx + i % 3] == n) { status = false; break; }
}
return status;
}
void nextEmpty(int arr[9][9], int row, int col, int& rowNext, int& colNext)
{
int indexNext = 9 * 9 + 1;
for (int i = row * 9 + col + 1; i < 9 * 9; i++) {
if (arr[i / 9][i % 9] == 0) {
indexNext = i;
break;
}
}
rowNext = indexNext / 9;
colNext = indexNext % 9;
//cout << row << "," << col << "|" << rowNext << "," << colNext << endl;
}
void copyArray(int arr[9][9], int arrCpy[9][9]) {
for (int y = 0; y < 9; y++)
for (int x = 0; x < 9; x++)
arrCpy[y][x] = arr[y][x];
}
std::vector<int> findPlaceables(int arr[9][9], int row, int col) {
vector<int> placebles = {};
for (int n = 1; n <= 9; n++)
if (canPlace9x9(arr, row, col, n)) placebles.push_back(n);
return placebles;
}
bool solveSudoku9x9(int arr[9][9], int row, int col)
{
//system("cls");
//printSudoku9x9(arr);
if (row > 8) return true;
if (arr[row][col] != 0) {
int rowNext, colNext;
nextEmpty(arr, row, col, rowNext, colNext);
return solveSudoku9x9(arr, rowNext, colNext);
}
std::vector<int> placebles = findPlaceables(arr, row, col);
if (placebles.size() == 0) {
return false;
};
bool status = false;
for (int i = 0; i < placebles.size(); i++) {
int n = placebles[i];
int arrCpy[9][9];
copyArray(arr, arrCpy);
//cout << "(" << row << "," << col << ") =>" << n << endl;
arrCpy[row][col] = n;
int rowNext = row;
int colNext = col;
nextEmpty(arrCpy, row, col, rowNext, colNext);
if (solveSudoku9x9(arrCpy, rowNext, colNext)) {
copyArray(arrCpy, arr);
status = true;
break;
}
}
return status;
}
int main(int argc, char** argv)
{
int board[9][9] = {
{5,3,0,0,7,0,0,0,0},
{6,0,0,1,9,5,0,0,0},
{0,9,8,0,0,0,0,6,0},
{8,0,0,0,6,0,0,0,3},
{4,0,0,8,0,3,0,0,1},
{7,0,0,0,2,0,0,0,6},
{0,6,0,0,0,0,2,8,0},
{0,0,0,4,1,9,0,0,5},
{0,0,0,0,8,0,0,7,9}
};
int board2[9][9] = {
{8,0,0,0,0,0,0,0,0},
{0,0,3,6,0,0,0,0,0},
{0,7,0,0,9,0,2,0,0},
{0,5,0,0,0,7,0,0,0},
{0,0,0,0,4,5,7,0,0},
{0,0,0,1,0,0,0,3,0},
{0,0,1,0,0,0,0,6,8},
{0,0,8,5,0,0,0,1,0},
{0,9,0,0,0,0,4,0,0}
};
if (solveSudoku9x9(board, 0, 0)) cout << "successfully solved board 1!" << std::endl;
printSudoku(board);
if (solveSudoku9x9(board2, 0, 0)) cout << "successfully solved board 2!" << std::endl;
printSudoku(board2);
return 0;
}
| true |
a821fe12cdaa5f5e47c2f49242a39945a12363b7 | C++ | hazamayuji/170813_lit_add_hmw | /src/ofApp.cpp | UTF-8 | 3,032 | 2.671875 | 3 | [] | no_license | #include "ofApp.h"
//動的配列でscreeenを追加
vector <BaseScreen *> screens;
using namespace std;
void ofApp::changeScreen(AppScreen screen){
switch (screen) {
case AppScreen::showScreen1:
currentScreen = 0;
break;
case AppScreen::showScreen2:
currentScreen = 1;
break;
// case AppScreen::EndScreen:
// currentScreen = 2;
// break;
}
}
//--------------------------------------------------------------
void ofApp::setup(){
ofBackground(0, 0, 0);
//番号:0
//start_screen
BaseScreen *showSc1 = new showScreen1();
showSc1 -> setup();
screens.push_back(showSc1);
//番号:1
//main_screen_01
BaseScreen *showSc2 = new showScreen2();
showSc2 -> setup();
screens.push_back(showSc2);
// //番号:2
// //end_screen
// BaseScreen *end_sc = new end_screen();
// end_sc -> setup();
// screens.push_back(end_sc);
}
//--------------------------------------------------------------
void ofApp::update(){
getCurrentScreen() -> update();
}
//--------------------------------------------------------------
void ofApp::draw(){
getCurrentScreen() -> draw();
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
if(key == ' '){
currentScreen++;
currentScreen = currentScreen % 2;
}
getCurrentScreen() -> keyPressed(key);
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
getCurrentScreen() -> keyReleased();
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y){
getCurrentScreen() -> mouseMoved(x,y);
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
getCurrentScreen() -> mouseDragged();
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
getCurrentScreen() -> mousePressed(x, y, button);
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
getCurrentScreen() -> mouseReleased();
}
//--------------------------------------------------------------
void ofApp::mouseEntered(int x, int y){
}
//--------------------------------------------------------------
void ofApp::mouseExited(int x, int y){
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){
}
BaseScreen *ofApp::getCurrentScreen() {
return screens[currentScreen];
}
| true |
1a19ca3f830ab78bb46c3e19f56bfd422b73052d | C++ | okanogutlu/Numerical-Analysis | /lagrange(1306170013).cpp | ISO-8859-9 | 993 | 2.859375 | 3 | [] | no_license | //1306170013 Talha Agez
#include<iostream>
#include<fstream>
#include<vector>
using namespace std;
int main() {
ifstream inClientFile("veri.txt", ios::in);
if (!inClientFile) {
cerr << "File could not be opened" << endl;
exit(EXIT_FAILURE);
}
double a, b;
vector<double> x_i;
vector<double> fx_i;
int i = 0;
//Aralk belirleme...
double x = 0.45;
cout << "Ara degeri giriniz: ";
cin >> x;
//Dosya Okuma
while (inClientFile >> a >> b){
x_i.push_back(a); fx_i.push_back(b);
i++;
}
//Lagrance metodu....
vector<double> lagrance_katsays;
double temp = 1;
int z = 0;
for (int j = 0; j < i; j++) {
z = 0;
for (z = 0; z < i; z++) {
if (z != j) {
temp = ((x - x_i[z]) / (x_i[j] - x_i[z])) * temp;
}
}
cout << j << ": Lagrance katsayss: " << temp << endl;
lagrance_katsays.push_back(temp);
temp = 1;
}
temp = 0;
for (int i = 0; i < lagrance_katsays.size(); i++) {
temp = lagrance_katsays[i] * fx_i[i] + temp;
}
cout << temp;
} | true |
1bd70e4a6956d5f3f8b7feeca38dae3be9179d8a | C++ | pthom/BabylonCpp | /src/Extensions/src/extensions/navigationmesh/channel.cpp | UTF-8 | 2,964 | 2.828125 | 3 | [
"Apache-2.0",
"LicenseRef-scancode-free-unknown"
] | permissive | #include <babylon/extensions/navigationmesh/channel.h>
namespace BABYLON {
namespace Extensions {
Channel::Channel()
{
}
Channel::~Channel()
{
}
void Channel::push(const Vector3& p)
{
portals.emplace_back(Portal{p, p});
}
void Channel::push(const Vector3& p1, const Vector3& p2)
{
portals.emplace_back(Portal{p1, p2});
}
bool Channel::_vequal(const Vector3& a, const Vector3& b)
{
return Vector3::DistanceSquared(a, b) < 0.00001f;
}
float Channel::_triarea2(const Vector3& a, const Vector3& b, const Vector3& c)
{
const float ax = b.x - a.x;
const float az = b.z - a.z;
const float bx = c.x - a.x;
const float bz = c.z - a.z;
return bx * az - ax * bz;
}
std::vector<Vector3>& Channel::stringPull()
{
std::vector<Vector3> pts;
// Init scan state
size_t apexIndex = 0, leftIndex = 0, rightIndex = 0;
auto& portalApex = portals[0].left;
auto& portalLeft = portals[0].left;
auto& portalRight = portals[0].right;
// Add start point.
pts.emplace_back(portalApex);
for (size_t i = 1; i < portals.size(); ++i) {
const auto& left = portals[i].left;
const auto& right = portals[i].right;
// Update right vertex.
if (_triarea2(portalApex, portalRight, right) >= 0.f) {
if (_vequal(portalApex, portalRight)
|| _triarea2(portalApex, portalLeft, right) < 0.f) {
// Tighten the funnel.
portalRight = right;
rightIndex = i;
}
else {
// Right over left, insert left to path and restart scan from portal
// left point.
pts.emplace_back(portalLeft);
// Make current left the new apex.
portalApex = portalLeft;
apexIndex = leftIndex;
// Reset portal
portalLeft = portalApex;
portalRight = portalApex;
leftIndex = apexIndex;
rightIndex = apexIndex;
// Restart scan
i = apexIndex;
continue;
}
}
// Update left vertex.
if (_triarea2(portalApex, portalLeft, left) <= 0.f) {
if (_vequal(portalApex, portalLeft)
|| _triarea2(portalApex, portalRight, left) > 0.f) {
// Tighten the funnel.
portalLeft = left;
leftIndex = i;
}
else {
// Left over right, insert right to path and restart scan from portal
// right point.
pts.emplace_back(portalRight);
// Make current right the new apex.
portalApex = portalRight;
apexIndex = rightIndex;
// Reset portal
portalLeft = portalApex;
portalRight = portalApex;
leftIndex = apexIndex;
rightIndex = apexIndex;
// Restart scan
i = apexIndex;
continue;
}
}
}
if ((pts.empty()) || (!_vequal(pts.back(), portals.back().left))) {
// Append last point to path.
pts.emplace_back(portals.back().left);
}
path = std::move(pts);
return path;
}
} // end of namespace Extensions
} // end of namespace BABYLON
| true |
785f3cdc5af763c0938bf490b6f3b2cda24b5545 | C++ | harshil93/Competitive-Programming | /codechef/bytecode/savemum.cpp | UTF-8 | 1,141 | 2.703125 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <vector>
#include <algorithm>
#include <utility>
#include <queue>
#include <stack>
#include <map>
#include <set>
using namespace std;
#define PR(x) cout << #x " = " << x << "\n";
int main(){
int64_t t;cin>>t;
while(t--){
int64_t visited[255]={0};
string s;
cin>>s;
std::vector<char> distinctChars;
for (int64_t i = 0; i < s.size(); ++i)
{
if(visited[s[i]] == 0 ){
visited[s[i]] = 1;
distinctChars.push_back(s[i]);
}
}
int64_t n = distinctChars.size();
std::map<char, int64_t> maping;
for (int64_t i = 0; i < distinctChars.size(); ++i)
{
if(i==0){
maping[distinctChars[i]] = 1;
}
else if(i==1) {
maping[distinctChars[i]] = 0;
}
else{
maping[distinctChars[i]] = i;
}
}
int64_t ans = 0;
int64_t base;
if(distinctChars.size() == 1){ base = 2;}else {base = distinctChars.size();}
for (int64_t i = 0; i < s.size(); ++i)
{
ans = ans*base + maping[s[i]];
}
cout<<ans<<endl;
maping.clear();
distinctChars.clear();
}
return 0;
} | true |
a8f968ff15ab5ee76d40229723c3de99c07f5e41 | C++ | pavel-zeman/CodeChef | /CodeChef/src/y2015/m09/challenge/CrackingTheCode.cpp | UTF-8 | 3,058 | 2.984375 | 3 | [] | no_license | // The key idea is that the square of the multiplication matrix is 16 (2^4). Then it's enough to calculate the first element and its exponent of 2.
// https://www.codechef.com/SEPT15/problems/CODECRCK
#include <bits/stdc++.h>
using namespace std;
#define FOR(c, m) for(int c=0;c<(int)(m);c++)
#define FORE(c, f, t) for(int c=(f);c<(t);c++)
char ccc = 0;
int getInt() {
int r = 0;
while (!(ccc >= '0' && ccc <= '9')) ccc = getc_unlocked(stdin);
while (ccc >= '0' && ccc <= '9') {
r = r * 10 + (ccc - '0');
ccc = getc_unlocked(stdin);
}
return r;
}
int getSignedInt() {
int r = 0;
while (!(ccc == '-' || (ccc >= '0' && ccc <= '9'))) ccc = getc_unlocked(stdin);
bool minus = ccc == '-';
if (minus) ccc = getc_unlocked(stdin);
while (ccc >= '0' && ccc <= '9') {
r = r * 10 + (ccc - '0');
ccc = getc_unlocked(stdin);
}
return minus ? -r : r;
}
long long int getLongLongInt() {
long long int r = 0;
while (!(ccc >= '0' && ccc <= '9')) ccc = getc_unlocked(stdin);
while (ccc >= '0' && ccc <= '9') {
r = r * 10 + (ccc - '0');
ccc = getc_unlocked(stdin);
}
return r;
}
long long int getSignedLongLongInt() {
long long int r = 0;
while (!(ccc == '-' || (ccc >= '0' && ccc <= '9'))) ccc = getc_unlocked(stdin);
bool minus = ccc == '-';
if (minus) ccc = getc_unlocked(stdin);
while (ccc >= '0' && ccc <= '9') {
r = r * 10 + (ccc - '0');
ccc = getc_unlocked(stdin);
}
return minus ? -r : r;
}
template <class type> void print(type a) {
if (a < 0) {
putc_unlocked('-', stdout);
a = -a;
}
if (a == 0) {
putc_unlocked('0', stdout);
} else {
char result[20];
int resSize = 0;
while (a > 0) {
result[resSize++] = '0' + a % 10;
a /= 10;
}
while (--resSize >= 0) putc_unlocked(result[resSize], stdout);
}
putc_unlocked('\n', stdout);
}
void printString(const char *str) {
while (*str) putc_unlocked(*str++, stdout);
putc_unlocked('\n', stdout);
}
void fail() {
*((char *)0) = 0;
}
template <class type> type mx(type a, type b) {
return a > b ? a : b;
}
template <class type> type mn(type a, type b) {
return a < b ? a : b;
}
#define S6 sqrt(6)
#define S3 sqrt(3)
#define S2 sqrt(2)
int main(void) {
int i = getInt();
int k = getInt();
long long int s = getSignedLongLongInt();
int ai = getInt();
int bi = getInt();
double a0, b0;
if ((i & 1) == 0) {
a0 = ai;
b0 = bi;
} else {
a0 = (-(S6 - S2) * ai - (-S2 - S6) * bi) / 16;
b0 = (2 + S3) * ai / 4 / S2 / (1 + S3) - (S2 - S6) * bi / 16;
}
int e0 = -((i >> 1) << 2);
double ak = a0, bk = b0;
if ((k & 1) == 1) {
ak = (S2 - S6) * a0 + (S2 + S6) * b0;
bk = (S2 + S6) * a0 + (S6 - S2) * b0;
}
int ek = e0 + ((k >> 1) << 2);
int sk = ek - s;
double result = (ak + bk) * pow(2, sk);
printf("%lf\n", result);
}
| true |
b799cf6f105e4a47647e2024076e35a84d828bb6 | C++ | pjsaksa/swd | /src/utils/path.cc | UTF-8 | 1,333 | 2.671875 | 3 | [
"MIT"
] | permissive | /* swd - Scripts with Dependencies
* Copyright (C) 2020 Pauli Saksa
*
* Licensed under The MIT License, see file LICENSE.txt in this source tree.
*/
#include "path.hh"
#include <cstring>
#include <stdexcept>
#include <sys/stat.h>
#include <sys/types.h>
using namespace std;
//
utils::OpenDir::OpenDir(const string &path)
: m_dir(opendir(path.c_str()))
{
if (!m_dir) {
throw runtime_error("opendir(" + path + "): " + strerror(errno));
}
}
utils::OpenDir::~OpenDir()
{
closedir(m_dir);
}
struct dirent *utils::OpenDir::readdir()
{
return ::readdir(m_dir);
}
// ------------------------------------------------------------
void utils::safeMkdir(const std::string& path)
{
if (mkdir(path.c_str(), 0777) != 0)
{
switch (errno) {
case EEXIST:
{
struct stat st;
if (stat(path.c_str(), &st) != 0) {
throw runtime_error("mkdir(" + path + "): stat: " + strerror(errno));
}
if (!S_ISDIR(st.st_mode)) {
throw runtime_error("mkdir(" + path + "): path already exists but is not a directory");
}
}
break;
default:
throw std::runtime_error("mkdir(" + path + ") failed: " + strerror(errno));
}
}
}
| true |
0d22f6754c88b0244afb67a6a78a306ec9e623d9 | C++ | Furgl/CS-368-A6 | /ConsoleApplication1/main.cpp | UTF-8 | 636 | 3.3125 | 3 | [] | no_license | #include "Vector.hpp"
#include <iostream>
using namespace std;
void printVector(const Vector<int> &v) {
for (int i = 0; i < v.size(); i++) {
cout << v[i] << ", ";
}
cout << endl;
}
int main() {
Vector<int> v1;
v1.pushBack(1);
v1.pushBack(2);
v1.pushBack(3);
printVector(v1);
cout << "SELF ASSIGNMENT TEST" << endl;
v1 = v1;
Vector<int> v2;
v2 = v1;
printVector(v2);
v2[0] = 4;
printVector(v2);
printVector(v1);
v1.pushBack(4);
v1.pushBack(5);
printVector(v1);
int *i1 = v1.begin();
cout << *i1 << endl;
v1.popBack();
printVector(v1);
v1.erase(i1+1);
printVector(v1);
cin.get();
return 0;
}
| true |
dfc4b906b20bae1ffe7ee84c472332545e5469e8 | C++ | leag37/BuffaloEngine | /BuffaloEngine/Include/Rendering/BuffMaterialReader.h | UTF-8 | 3,361 | 2.84375 | 3 | [] | no_license | // Filename: BuffMaterialReader.h
// Author: Gael Huber
#ifndef __BUFFMATERIALREADER_H__
#define __BUFFMATERIALREADER_H__
#include "Core\BuffPrerequisites.h"
#include "Rendering\BuffConstantBuffer.h"
#include "Rendering\BuffMaterial.h"
#include <fstream>
#include <vector>
namespace BuffaloEngine
{
/** \addtogroup Rendering
* @{
*/
class Material::MaterialReader : public SimpleAlloc
{
public:
/**
* Default constructor
*/
MaterialReader();
/**
* Destructor
*/
~MaterialReader();
/**
* Read and initialize data for this material
* @param
* Material* The material to populate
* @return
* bool Returns true if successful
*/
bool Read(Material* material);
private:
/**
* Read and tokenize a line from the material
* @param
* std::vector<std::string>& The tokens of the line
* @return
* bool True if successful
*/
bool ReadLine(std::vector<std::string>& tokens);
/**
* Check if this line is a block start indicator
* @param
* const std::vector<std::string>& The tokens of the line
* @return
* bool True if block start
*/
bool IsBlockStart(std::vector<std::string>& tokens);
/**
* Check if this line is a block end indicator
* @param
* const std::vector<std::string>& The tokens of the line
* @return
* bool True if block end
*/
bool IsBlockEnd(std::vector<std::string>& tokens);
/**
* Tokenize a line into individual strings
* @param
* const std::string& The string to tokenize
* @return
* std::vector<std::string> The vector of tokens
*/
std::vector<std::string> Tokenize(const std::string& line);
/**
* Read a layout block. Layouts describe the input layout and semantic types of vertices being
* passed into the material
*/
void ReadLayoutBlock();
/**
* Read an input layout parameter
* @param
* InputLayoutParameter& The input layout parameter to populate
* @param
* const std::vector<std::string>& The tokens for this line
* @return
* bool Returns true if successful
*/
bool ReadInputLayoutParameter(InputLayoutParameter& param, const std::vector<std::string>& tokens);
/**
* Read a constant buffer block for a "per frame" buffer
*/
void ReadCBFrameBlock();
/**
* Read a constant buffer block for a "per material" buffer
*/
void ReadCBMaterialBlock();
/**
* Read a constant buffer block for a "per object" buffer
*/
void ReadCBObjectBlock();
/**
* Read in configuration for a constant buffer block
* @param
* ConstantBufferType The type of buffer to create
*/
void ReadConstantBuffer(ConstantBufferType bufferType);
/**
* Read a technique description. Techniques describe a series of passes that pair
* rendering pipeline stages to various shaders
*/
void ReadTechniqueBlock();
/**
* Read a pass block description. Passes contain information about the particular
* rendering pass.
* @param
* Technique& The technique to which the pass will be attached
*/
void ReadPassBlock(Technique& technqiue);
private:
/**
* The material being read
*/
Material* _material;
/**
* A handle to the file stream
*/
std::fstream _stream;
};
/** @} */
} // Namespace
#endif // __BUFFMATERIALREADER_H__ | true |
b638f5d8ce52aa89c763f2534b4d2aa1eb8bb1cb | C++ | taylor-jones/Fly-Away-Home | /Slider.hpp | UTF-8 | 864 | 2.90625 | 3 | [] | no_license | /**********************************************************
** Program Name: final project
** Author: Taylor Jones
** Date: 3/6/2018
** Description: Slider.hpp is the Slider class
** specification file. This file contains declarations
** for the member variables and member functions of
** the Slider class.
**********************************************************/
#ifndef SLIDER_HPP
#define SLIDER_HPP
#include "Space.hpp"
#include "Element.hpp"
class Slider: public Space {
private:
Direction slideDirection = RIGHT;
void init() override;
public:
Slider();
explicit Slider(Direction slideDirection);
~Slider() override;
SpaceType spaceType() override;
void experience(Element* experiencer) override;
Direction getSlideDirection() const;
void setSlideDirection(Direction slideDirection);
};
#endif //SLIDER_HPP
| true |
7dad9dbe10d30131ae901cb25b4c0fcc652336d9 | C++ | MannyOsorio/legendary-enigma | /Allele.cpp | UTF-8 | 502 | 2.890625 | 3 | [
"Apache-2.0"
] | permissive | #include <iostream>
#include "Allele.h"
#include <string>
using namespace std;
Allele::Allele()
{
this->nucleotideSequence = "";
this->variantName = "";
this->variantType = "";
}
Allele::Allele(string nucleotideSquence, string variantName, string variantType)
{
this->nucleotideSequence = nucleotideSquence;
this->variantName = variantName;
this->variantType = variantType;
}
string Allele::getName()
{
return variantName;
}
void Allele::setName(string newName)
{
variantName = newName;
}
| true |
803b5959c292125a2fb05ab8084fad96744e01c6 | C++ | dotnet/dotnet-api-docs | /snippets/cpp/VS_Snippets_CLR/MethodBody/cpp/source.cpp | UTF-8 | 4,887 | 3.4375 | 3 | [
"MIT",
"CC-BY-4.0"
] | permissive | // 1 - (entire sample) MethodBody class
// 2 - (everything through GetMethodBody and displaying InitLocals & MaxStackSize)
// 3 - (displaying locals)
// 4 - (displaying exception clauses)
// 5 - (end of Main, example method, beginning of output through output for snippet 2)
// 6 - (output for snippet 3 (locals))
// 7 - (output for snippet 4 (clauses))
// 2,5 - InitLocals, MaxStackSize
// 2,3,5,6 - lvis property, lviInfo class
// 2,4,5,7 - ExceptionHandlingClauses property, ExceptionHandlingClause class, ExceptionHandlingClauseFlags enum
//
//<Snippet1>
//<Snippet2>
#using <System.dll>
using namespace System;
using namespace System::Reflection;
public ref class Example
{
//<Snippet5>
// The Main method contains code to analyze this method, using
// the properties and methods of the MethodBody class.
public:
void MethodBodyExample(Object^ arg)
{
// Define some local variables. In addition to these variables,
// the local variable list includes the variables scoped to
// the catch clauses.
int var1 = 42;
String^ var2 = "Forty-two";
try
{
// Depending on the input value, throw an ArgumentException or
// an ArgumentNullException to test the Catch clauses.
if (arg == nullptr)
{
throw gcnew ArgumentNullException("The argument cannot " +
"be null.");
}
if (arg->GetType() == String::typeid)
{
throw gcnew ArgumentException("The argument cannot " +
"be a string.");
}
}
// There is no Filter clause in this code example. See the Visual
// Basic code for an example of a Filter clause.
// This catch clause handles the ArgumentException class, and
// any other class derived from Exception.
catch (ArgumentException^ ex)
{
Console::WriteLine("Ordinary exception-handling clause caught:" +
" {0}", ex->GetType());
}
finally
{
var1 = 3033;
var2 = "Another string.";
}
}
//</Snippet5>
};
int main()
{
// Get method body information.
MethodInfo^ mi =
Example::typeid->GetMethod("MethodBodyExample");
MethodBody^ mb = mi->GetMethodBody();
Console::WriteLine("\r\nMethod: {0}", mi);
// Display the general information included in the
// MethodBody object.
Console::WriteLine(" Local variables are initialized: {0}",
mb->InitLocals);
Console::WriteLine(" Maximum number of items on the operand " +
"stack: {0}", mb->MaxStackSize);
//</Snippet2>
//<Snippet3>
// Display information about the local variables in the
// method body.
Console::WriteLine();
for each (LocalVariableInfo^ lvi in mb->LocalVariables)
{
Console::WriteLine("Local variable: {0}", lvi);
}
//</Snippet3>
//<Snippet4>
// Display exception handling clauses.
Console::WriteLine();
for each(ExceptionHandlingClause^ exhc in mb->ExceptionHandlingClauses)
{
Console::WriteLine(exhc->Flags.ToString());
// The FilterOffset property is meaningful only for Filter
// clauses. The CatchType property is not meaningful for
// Filter or Finally clauses.
switch(exhc->Flags)
{
case ExceptionHandlingClauseOptions::Filter:
Console::WriteLine(" Filter Offset: {0}",
exhc->FilterOffset);
break;
case ExceptionHandlingClauseOptions::Finally:
break;
default:
Console::WriteLine(" Type of exception: {0}",
exhc->CatchType);
break;
}
Console::WriteLine(" Handler Length: {0}",
exhc->HandlerLength);
Console::WriteLine(" Handler Offset: {0}",
exhc->HandlerOffset);
Console::WriteLine(" Try Block Length: {0}", exhc->TryLength);
Console::WriteLine(" Try Block Offset: {0}", exhc->TryOffset);
}
//</Snippet4>
}
//This code example produces output similar to the following:
//
//Method: Void MethodBodyExample(System.Object)
// Local variables are initialized: False
// Maximum number of items on the operand stack: 4
//
//<Snippet6>
//Local variable: System.ArgumentException (0)
//Local variable: System.String (1)
//Local variable: System.Int32 (2)
//</Snippet6>
//<Snippet7>
//Clause
// Type of exception: System.ArgumentException
// Handler Length: 29
// Handler Offset: 78
// Try Block Length: 65
// Try Block Offset: 13
//Finally
// Handler Length: 13
// Handler Offset: 113
// Try Block Length: 100
// Try Block Offset: 13
//</Snippet7>
//</Snippet1>
| true |
805a7bf5d5f1f566fb38f4012c1f48922a330414 | C++ | rlorigro/pytorch | /aten/src/ATen/core/op_registration/infer_schema.h | UTF-8 | 3,223 | 2.96875 | 3 | [
"BSD-3-Clause",
"LicenseRef-scancode-generic-cla",
"Apache-2.0",
"BSD-2-Clause"
] | permissive | #pragma once
/**
* This file contains functionality to take a C++ function and infer its
* c10::FunctionSchema.
*/
#include <ATen/core/function_schema.h>
#include <c10/util/C++17.h>
#include <c10/util/Metaprogramming.h>
namespace c10 {
namespace detail {
/// Checks the static C++ type `T` for correctness to catch common error cases.
template <typename T>
void checkStaticTypes() {
// Give nice error messages for some of the common error cases.
// Use a LOUD ERROR MESSAGE SO USERS SEE THE STATIC_ASSERT
static_assert(
!std::is_integral<T>::value || std::is_same<T, int64_t>::value,
"INVALID TYPE: Only int64_t is supported as an integral argument type");
static_assert(
!std::is_same<T, float>::value,
"INVALID TYPE: float is not supported as an argument type, use double instead");
}
template <typename First, typename Second, typename... Rest>
void checkStaticTypes() {
checkStaticTypes<First>();
checkStaticTypes<Second, Rest...>();
}
template <typename... Ts, size_t... Is>
::std::vector<Argument> createArgumentVectorFromTypes(guts::index_sequence<Is...>) {
checkStaticTypes<guts::decay_t<Ts>...>();
// Arguments are named "_<index>"
return {Argument("_" + std::to_string(Is), getTypePtr<guts::decay_t<Ts>>())...};
}
template <typename... Ts, size_t... Is>
::std::vector<Argument> createReturns(guts::index_sequence<Is...>) {
return createArgumentVectorFromTypes<Ts..., Is...>();
}
/// Unpack a tuple return type into a vector of return types, one per tuple
/// element.
template <typename... Ts>
::std::vector<Argument> createReturns(std::tuple<Ts...>* tuple) {
return createReturns<Ts...>(guts::make_index_sequence<sizeof...(Ts)>());
}
/// Create a single-element `vector` for simple (non-tuple) return types.
template <typename ReturnType>
::std::vector<Argument> createReturns(ReturnType*) {
checkStaticTypes<guts::decay_t<ReturnType>>();
return {Argument("_1", getTypePtr<guts::decay_t<ReturnType>>())};
}
/// Creates a vector of `Argument` from `FunctionTraits` and a pack of indices
/// into the argument list.
template <typename FunctionTraits, size_t... Is>
::std::vector<Argument> createArgumentVectorFromTraits(guts::index_sequence<Is...> indices) {
using ArgumentTypes = typename FunctionTraits::parameter_types;
return createArgumentVectorFromTypes<
c10::guts::typelist::element_t<Is, ArgumentTypes>...>(indices);
}
/// Creates a `FunctionSchema` object from a `FunctionTraits` type for a
/// function.
template <typename FunctionTraits>
FunctionSchema createFunctionSchemaFromTraits(std::string name, std::string overload_name) {
using ReturnType = typename FunctionTraits::return_type;
auto arguments = createArgumentVectorFromTraits<FunctionTraits>(
guts::make_index_sequence<FunctionTraits::number_of_parameters>());
auto returns = createReturns(static_cast<ReturnType*>(nullptr));
return {std::move(name), std::move(overload_name), std::move(arguments), std::move(returns)};
}
}
template<class FuncType>
FunctionSchema inferFunctionSchema(std::string name, std::string overload_name) {
return detail::createFunctionSchemaFromTraits<guts::infer_function_traits_t<FuncType>>(std::move(name), std::move(overload_name));
}
}
| true |
d4117c4827b4b791e2f68dac5e33bcd41daa953d | C++ | anandaditya444/LEETCODE | /MaximumXorOfTwoNumbersInAnArray.cpp | UTF-8 | 983 | 3.140625 | 3 | [] | no_license | //Q.421
class Solution {
public:
//http://www.ritambhara.in/maximum-xor-value-of-two-elements/
typedef struct data
{
data* bit[2];
int cnt = 0;
}trie;
trie* head;
void insert(int x)
{
trie* cur = head;
for(int i=30;i>=0;i--)
{
int b = (x>>i) & 1;
if(!cur->bit[b])
cur->bit[b] = new trie();
cur = cur->bit[b];
cur->cnt++;
}
}
// void remove(int x)
// {
// trie* cur = head;
// for(int i=30;i>=0;i--)
// {
// int b = (x>>i) & 1;
// cur = cur->bit[b];
// cur->cnt--;
// }
// }
int maxxor(int x)
{
trie* cur = head;
int ans = 0;
for(int i=30;i>=0;i--)
{
int b = (x>>i)&1;
if(cur->bit[!b] && cur->bit[!b]->cnt>0)
{
ans += (1LL<<i);
cur = cur->bit[!b];
}
else
cur = cur->bit[b];
}
return ans;
}
int findMaximumXOR(vector<int>& nums) {
int res = -1;
head = new trie();
for(int i=0;i<nums.size();i++)
{
insert(nums[i]);
res = max(res,maxxor(nums[i]));
}
return res;
}
}; | true |
e6f22d1ca2300041509cae58f08f48de5e1f2617 | C++ | Ivanova475/cplusplus-tasks | /Hash_Table/Hash_Table/hash_table.h | UTF-8 | 422 | 2.796875 | 3 | [] | no_license | #pragma once
#include <vector>
#include <string>
class HashTable
{
public:
HashTable();
void Add(const std::string& new_string);
bool Has(const std::string& new_string) const;
void Remove(const std::string& new_string);
int GetHash(const std::string& new_string) const;
const std::vector<std::vector<std::string>>& GetData() const;
private:
std::vector<std::vector<std::string>> data_;
};
| true |
307a374cb7548779a84ecff57cd15bcf61126528 | C++ | jhwang7628/aero_cfd | /src/sourcefunction.cpp | UTF-8 | 2,153 | 2.890625 | 3 | [] | no_license | #include "sourcefunction.h"
#include "parameters.h"
#include <stdio.h>
SourceFunction::SourceFunction(const double bs, const SHAPE s, const Eigen::MatrixXd * g, const int textureIndex) : _baseSpeed(bs),
_shape(s),
_g(postProcessG(g)),
_textureIndex(textureIndex),
maxTimeStep(_g->rows())
{
cout << "New source function initialized for shape ";
printf("\"%s\"\n", getShapeName());
cout << "textureIndex = " << textureIndex << endl;
cout << "maxTimeStep = " << maxTimeStep << endl;
computeLocalAbsMax();
}
SourceFunction::~SourceFunction()
{
if (_g)
delete _g;
}
Eigen::MatrixXd * SourceFunction::postProcessG(const Eigen::MatrixXd *g) const
{
Eigen::MatrixXd * gProcessed = new Eigen::MatrixXd();
/* Linear interpolation */
gProcessed->setZero(g->rows()*PARAMETERS::UPSAMPLE_RATIO, g->cols());
for (int ii=0; ii<g->rows(); ii++)
{
double count = 0;
for (int jj=ii*PARAMETERS::UPSAMPLE_RATIO; jj<(ii+1)*PARAMETERS::UPSAMPLE_RATIO; jj++)
{
double alpha = count/(double)PARAMETERS::UPSAMPLE_RATIO;
int thisTS = ii;
int nextTS = ii+1;
if (ii+1 == g->rows())
nextTS = 0; // wrap-around
gProcessed->row(jj) = g->row(thisTS)*(1.0-alpha) + g->row(nextTS)*alpha;
count += 1.0;
}
}
printf("The source source function was upsampled by a factor of %u\n", PARAMETERS::UPSAMPLE_RATIO);
FILE* fp = fopen("out/ginterpolated.txt", "w");
for (int ii=0; ii<gProcessed->rows(); ii++)
{
fprintf(fp,"%.12f %.12f %.12f\n", (*gProcessed)(ii,0),
(*gProcessed)(ii,1),
(*gProcessed)(ii,2));
}
fclose(fp);
return gProcessed;
}
const char * SourceFunction::getShapeName() const
{
switch (_shape)
{
case cylinder : return "2D cylinder"; break;
case square : return "2D square"; break;
case sword_aniso : return "2D sword (anisotropic)"; break;
}
return NULL;
}
| true |
eb2b5f20381c312b1661b3befa66c87a564b2f2c | C++ | dvtrunggg/OOP | /Seminar/Nhom10/Sourcecode_Adapter/adapter_plug.cpp | UTF-8 | 1,056 | 3.34375 | 3 | [] | no_license | #include <iostream>
#include <string>
using namespace std;
class Plug_2
{
public:
virtual int numPin()
{
return 0;
}
virtual string namePlug()
{
return "";
}
};
class twoPin : public Plug_2
{
public:
int numPin()
{
return 2;
}
string namePlug()
{
return "two_pin plug!";
}
};
class Plug_3
{
public:
virtual int numPin()
{
return 0;
}
virtual string namePlug()
{
return "";
}
};
class threePin : public Plug_3
{
public:
int numPin()
{
return 3;
}
string namePlug()
{
return "three_pin plug!";
}
};
class Adapter : public Plug_2
{
public:
Adapter(Plug_3* plug) {}
Adapter(Plug_2* plugg) {}
int numPin()
{
return 2;
}
string namePlug()
{
return "two_pin plug!";
}
};
int main()
{
Plug_2* plug2 = new twoPin();
Plug_3* plug3 = new threePin();
Plug_2* adapter = new Adapter(plug2);
cout << adapter->numPin();
return 0;
}
| true |
6e35ad201572c4f4ff79b9a14546875daf11d76f | C++ | magallonphil/Experiment-2 | /Problem-4.cpp | UTF-8 | 674 | 4.125 | 4 | [] | no_license | //Create a program that will accept three numbers as input and display the LARGEST number
//of the three.
#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
float n1, n2, n3;
cout << "Enter three numbers: ";
cin >> n1 >> n2 >> n3;
if (n1 >= n2)
{
if (n1 >= n3)
cout << "The LARGEST number of three: " << n1;
else
cout << "The LARGEST number of three: " << n3;
}
else
{
if (n2 >= n3)
cout << "The LARGEST number of three: " << n2;
else
cout << "The LARGEST number of three: " << n3;
}
return 0;
}
| true |
0e885d8877bcd96466459ac47a12011586c02e9d | C++ | a-kashirin-official/spbspu-labs-2018 | /vasekha.irina/A1/rectangle.hpp | UTF-8 | 561 | 2.9375 | 3 | [] | no_license | #ifndef RECTANGLE_HPP
#define RECTANGLE_HPP
#include <cmath>
#include <iostream>
#include "shape.hpp"
class Rectangle: public Shape
{
public:
Rectangle(const point_t & pos, const double width, const double height);
virtual double getArea() const override;
virtual rectangle_t getFrameRect() const override;
virtual void move(const point_t & point) override;
virtual void move(const double dx, const double dy) override;
private:
point_t pos_;
double width_;
double height_;;
virtual void print(std::ostream & out) const override;
};
#endif
| true |
155a73e6ab15e826a80f390064c30d80e46011d4 | C++ | Subhammodi/coding | /Sorting/practice/insersort.cpp | UTF-8 | 472 | 3.3125 | 3 | [] | no_license | #include<stdio.h>
using namespace std;
void swapp(int *p, int *q) {
int temp = *p;
*p = *q;
*q = temp;
}
void insersort(int *arr, int n) {
int j;
for(int i=0; i<n; i++) {
j=i;
while(j>0) {
if(arr[j] < arr[j-1])
swapp(&arr[j], &arr[j-1]);
j--;
}
}
}
int main()
{
int n;
scanf("%d", &n);
int *arr = new int[n];
for(int i=0; i<n; i++)
scanf("%d", &arr[i]);
insersort(arr, n);
for(int i=0; i<n; i++)
printf("%d\n", arr[i]);
return 0;
}
| true |
0f13196fb086ea197b1408fe1b0e2eb3d23b8633 | C++ | SachinGunjal001/Data-Structures-And-Algorithms | /LinkedList/LinkedList_Deletion.cpp | UTF-8 | 2,548 | 4.09375 | 4 | [] | no_license | #include<stdio.h>
#include<stdlib.h>
struct Node{
int data;
struct Node * next;
};
void linkedListTraversal(struct Node *ptr)
{
while (ptr != NULL)
{
printf("Element: %d\n", ptr->data);
ptr = ptr->next;
}
}
// Case 1 : delete the first element
struct Node * deleteFirst(struct Node * head){
struct Node * ptr = head;
head = head->next;
free(ptr);
return head;
}
// Case 2 : delete in element at given index
struct Node * deleteAtIndex(struct Node *head, int index){
struct Node * p = head;
struct Node * q = head->next;
int i = 0;
for(i = 0; i < index-1;i++) {
p = p->next;
q = q->next;
}
p->next = q->next;
free(q);
return head;
}
// Case 3: Deleting the last element
struct Node * deleteAtLast(struct Node * head){
struct Node *p = head;
struct Node *q = head->next;
while(q->next !=NULL)
{
p = p->next;
q = q->next;
}
p->next = NULL;
free(q);
return head;
}
// Case 4 : delete in element with given value from linked list
struct Node * deleteAtGivenIndex(struct Node *head, int index, int value){
struct Node * p = head;
struct Node * q = head->next;
while(q->data!=value && q->next!=NULL){
p = p->next;
q = q->next;
}
if(q->data == value){
p->next = q->next;
free(q);
}
return head;
}
int main(){
struct Node *head;
struct Node *second;
struct Node *third;
struct Node *fourth;
// Allocate memory for nodes in the linked list in Heap
head = (struct Node *)malloc(sizeof(struct Node));
second = (struct Node *)malloc(sizeof(struct Node));
third = (struct Node *)malloc(sizeof(struct Node));
fourth = (struct Node *)malloc(sizeof(struct Node));
// Link first and second nodes
head->data = 17;
head->next = second;
// Link second and third nodes
second->data = 11;
second->next = third;
// Link third and fourth nodes
third->data = 44;
third->next = fourth;
// Terminate the list at the third node
fourth->data = 26;
fourth->next = NULL;
printf("Linked list before insertion\n");
linkedListTraversal(head);
// head = deleteFirst(head); //delete first element
// head = deleteFirst(head); //delete second element
//head = deleteAtIndex(head, 2);
// head = deleteAtLast(head);
head = deleteAtGivenIndex(head,2,44);
printf("\nLinked list after insertion\n");
linkedListTraversal(head);
return 0;
}
| true |
300a52f0ab4e2d542e13274d0c8f62f6c4b55b21 | C++ | hamzasclone2/EECS-560 | /Lab08/maxMin.h | UTF-8 | 577 | 2.9375 | 3 | [] | no_license | #ifndef MAXMIN_H
#define MAXMIN_H
class maxMin{
public:
maxMin(); //constructor
~maxMin(); //destructor
void buildHeap(); //takes in data file to populate array
void insert(int val); //inserts value at last+1
void deleteMin(); //deletes min value, replaces with last
int findMin(); //returns one of the children of the root
int findMax(); //returns the root
void deleteMax(); //deletes max value, replaces with last
void levelOrder(); //prints out array in order
private:
int* heap;
int size;
int lastIdx;
};
#endif
| true |
72694fb80efd5f79305c2b0d2ce7e1d7ddcc678a | C++ | Andrewnetwork/CS170 | /Work/textBasedRpg/textBasedRpg/playerClass.h | UTF-8 | 816 | 3.328125 | 3 | [] | no_license | /*
The player class must have the following features:
1.)[]An array to hold invintory information.
2.)[]Health variable and functions that can change the health such as:
-[]Dammage function
-[]Healing function
3.)[]A way to determine if the player is dead.
4.)[]An array to hold information about player attacks.
5.)[]An array to hold information about the players progression in the game.
-[]And the ability to write and read that information from a data file.
6.)[]A variable that holds the players level.
-[]And functions to change level.
7.)[]A variable that holds the players armor.
-[]And functions that can change players armor.
8.)[]An attack menu.
9.)[]A defenceive menu.
*/
class player
{
public:
private:
int playerHealth;
int playerArmor;
int playerLevel;
}
//Functions | true |
6c8bdadfdd8ec738a71a7d29072774017cda36ad | C++ | cowtony/ACM | /C++ Fundamental/09 OOP - Polymorphim/Dog.h | UTF-8 | 333 | 3.125 | 3 | [] | no_license | #pragma once
#include <iostream>
#include "Animal.h"
class Dog : public Animal {
public:
void animalSound() const override {
std::cout << "The dog says: bow wow \n";
}
};
class Teddy : public Dog {
public:
void animalSound() const override {
std::cout << "The Teddy says: I'm a teddy dog \n";
}
};
| true |
dd3eb542cc30cd771951a7cb24e4a7098a436666 | C++ | emakryo/cmpro | /src/tenkei90/d025.cpp | UTF-8 | 1,438 | 2.53125 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
template<typename T>
ostream& operator<<(ostream &os, vector<T> &v){
string sep = " ";
if(v.size()) os << v[0];
for(int i=1; i<v.size(); i++) os << sep << v[i];
return os;
}
template<typename T>
istream& operator>>(istream &is, vector<T> &v){
for(int i=0; i<v.size(); i++) is >> v[i];
return is;
}
#ifdef DBG
void debug_(){ cout << endl; }
template<typename T, typename... Args>
void debug_(T&& x, Args&&... xs){
cout << x << " "; debug_(forward<Args>(xs)...);
}
#define dbg(...) debug_(__VA_ARGS__)
#else
#define dbg(...)
#endif
ll n, b;
int check(vector<int> &v){
ll p = 1;
for(int i=0; i<10; i++){
for(int j=0; j<v[i]; j++) p*=i;
}
ll m = b+p;
if(m>n) return 0;
vector<int> z(10);
while(m){
z[m%10]++;
m/=10;
}
bool ok = true;
for(int i=0; i<10; i++){
if(v[i]!=z[i]) ok = false;
}
return ok?1:0;
}
ll dfs(int k, vector<int> &v){
if(reduce(v.begin(), v.end())>11) return 0;
if(k==10){
dbg(v);
return check(v);
}
ll ans = 0;
for(int i=0; i<=10; i++){
v[k] = i;
ans += dfs(k+1, v);
}
v[k] = 0;
return ans;
}
int main() {
ios_base::sync_with_stdio(false);
cout << setprecision(20) << fixed;
cin >> n >> b;
vector<int> v(10);
cout << dfs(0, v) << endl;
return 0;
} | true |
290fc81f9ac36ad59b5589e2350e8959022818d5 | C++ | XiangqianMa/Aim-At-Offer | /35_clone_complex_list/clone_complex_list.cpp | UTF-8 | 1,909 | 3.25 | 3 | [] | no_license | //
// Created by mxq on 2020/2/18.
//
#include "clone_complex_list.h"
/**
* @brief 复制复杂链表
* @param list_head
* @return
*/
ComplexListNode* CloneComplexList(ComplexListNode* list_head){
if (list_head == nullptr)
return nullptr;
CloneNodes(list_head);
ConnectSiblingNodes(list_head);
return SplitNodes(list_head);
}
/**
* @brief 在原始链表的基础上进行节点复制
* @param list_head
*/
void CloneNodes(ComplexListNode* list_head){
ComplexListNode* temp_node = list_head;
while (temp_node != nullptr){
auto new_node = new ComplexListNode;
new_node->val = temp_node->val;
new_node->next = temp_node->next;
new_node->sibling = nullptr;
temp_node->next = new_node;
temp_node = new_node->next;
}
}
/**
* @brief 连接复制节点与其silbing节点
* @param list_head
*/
void ConnectSiblingNodes(ComplexListNode* list_head){
ComplexListNode* temp_node = list_head;
while (temp_node != nullptr){
if (temp_node->sibling != nullptr){
temp_node->next->sibling = temp_node->sibling->next;
}
else {
temp_node->next->sibling = nullptr;
}
temp_node = temp_node->next->next;
}
}
/**
* @brief 将原链表和复制的链表拆分开
* @param list_head
* @return 复制的链表的表头指针
*/
ComplexListNode* SplitNodes(ComplexListNode* list_head){
ComplexListNode* temp_node = list_head;
ComplexListNode* cloned_head= list_head->next;
ComplexListNode* temp_cloned_node = cloned_head;
while (temp_node != nullptr){
temp_node->next = temp_node->next->next;
if (temp_cloned_node->next != nullptr)
temp_cloned_node->next = temp_cloned_node->next->next;
temp_node = temp_node->next;
temp_cloned_node = temp_cloned_node->next;
}
return cloned_head;
}
| true |
ea5804b9214a3d59a28091734d30f3c29c371202 | C++ | ahmedkrmn/Competitive-Programming | /Codeforces/313A.cpp | UTF-8 | 569 | 2.75 | 3 | [] | no_license | #include <iostream>
#include <cmath>
using namespace std;
int main()
{
long long int n;
cin >>n;
int last,beforelast;
if (n>=0)
{
cout << n << endl;
}
else
{
n=abs(n);
last = n%10;
beforelast=(n/10)%10;
if (last>beforelast)
{
n/=10;
cout << "-"<<n;
}
else
{
if(n<=99)
{
if (last==0)
{
cout <<"0";
}
else
{
cout<<"-"<<last;
}
}
else if (last==beforelast)
{
cout <<"-"<<n/10;
}
else
{
cout<<"-"<<n/100<<last;
}
}
}
} | true |
34141a9212a9e9c2f329f83cd0657b09f86814e9 | C++ | srisaipasupuleti/interviewbit | /arrays/largest_number_s.cpp | UTF-8 | 484 | 3.078125 | 3 | [] | no_license | int compare(string a,string b){
string pre=a.append(b);
string suc=b.append(a);
return pre.compare(suc)>0?1:0;
}
string Solution::largestNumber(const vector<int> &A) {
vector<string> B;
for(auto x:A){
B.push_back(to_string(x));
}
sort(B.begin(),B.end(),compare);
string result;
for(auto x:B){
result+=x;
}
int index=0;
while(result[index]=='0')index++;
if(index==result.length())result="0";
return result;
}
| true |
9f55303adbc20feb6bfbc6a85abb6745179f7945 | C++ | georgidimov/FileSystem | /FileSystem/directory.cpp | UTF-8 | 6,743 | 3.3125 | 3 | [] | no_license | #include "directory.h"
Directory :: Directory(Value newName, size_t size, Directory * newParent) : File(newName, size){
parent = newParent;
}
Directory :: Directory(Value newName, size_t position, size_t newSize, size_t newSizeInFS, Directory *nParent) :
File(newName, position, newSize, newSizeInFS)
{
parent = nParent;
}
Directory :: Directory(Value serializedString) : File("", 0){
deserialize(serializedString);
}
Directory :: ~Directory(){
clear();
}
void Directory :: clear(){
for(List<File *> :: Iterator it = files.begin(); it; it++){
delete *it;
}
for(List<Directory *> :: Iterator it = directories.begin(); it; it++){
delete *it;
}
size_t size = files.getSize();
while(size){
files.removeAt(0);
--size;
}
size = directories.getSize();
while(size){
directories.removeAt(0);
--size;
}
}
void Directory :: addFile(File * file){
files.addAt(0, file);
}
void Directory :: addDirectory(Directory * dir){
directories.addAt(0, dir);
}
File * Directory :: getFile(Value name){
List<File *> :: Iterator it = files.begin();
for(; it; it++){
if((*it)->getName() == name){
return *it;
}
}
return *it;
}
Directory * Directory :: getDirectory(Value name){
List<Directory *> :: Iterator it = directories.begin();
for(; it; it++){
if((*it)->getName() == name){
return *it;
}
}
throw std :: runtime_error("invalid directory name or path");
}
void Directory :: deleteFile(Value name){
//FIX US!
size_t size = files.getSize();
for(size_t i = 0; i < size; ++i){
if(files.getAt(i)->getName() == name){
delete files[i];
files.removeAt(i);
return;
}
}
}
void Directory :: deleteDirectory(Value name){
size_t size = directories.getSize();
for(size_t i = 0; i < size; ++i){
if(directories.getAt(i)->getName() == name){
delete directories[i];
directories.removeAt(i);
return;
}
}
}
Directory * Directory :: detachDirectory(Value name){
size_t size = directories.getSize();
for(size_t i = 0; i < size; ++i){
if(directories.getAt(i)->getName() == name){
return directories.removeAt(i);
}
}
throw std :: runtime_error("wrong directory name or path");
}
File * Directory :: detachFile(Value name){
//FIX US!
size_t size = files.getSize();
for(size_t i = 0; i < size; ++i){
if(files.getAt(i)->getName() == name){
return files.removeAt(i);
}
}
throw std :: runtime_error("wrong file name or path");
}
void Directory :: setParent(Directory * newParent){
parent = newParent;
}
Directory * Directory :: getParent() const{
return parent;
}
Directory * Directory :: getCopy() const{
Directory * newDirectory = new Directory(name, positionInFile, size, sizeInFileSystem, NULL);
newDirectory->setCreationTime(creationTime);
newDirectory->setLastModifiedTime(lastModifiedTime);
Directory * tempChild = NULL;
for(List<Directory *> :: Iterator it = directories.begin(); it; it++){
tempChild = (*it)->getCopy();
tempChild->setParent(newDirectory);
newDirectory->addDirectory(tempChild);
}
File * tempFile = NULL;
for(List<File *> :: Iterator it = files.begin(); it; it++){
tempFile = (*it)->getCopy();
newDirectory->addFile(tempFile);
}
return newDirectory;
}
Value Directory :: serialize() const{
Value serialized = File :: serialize();
serialized = serialized + ":" + Value(files.getSize());
for(List<File *> :: Iterator it = files.begin(); it; it++){
serialized = serialized + (*it)->serialize();
}
serialized = serialized + ":" + Value(directories.getSize());
for(List<Directory *> :: Iterator it = directories.begin(); it; it++){
serialized = serialized + (*it)->serialize();
}
//return Value(":") + Value(serialized.length() + 1) + serialized;
return Value(":") + Value(serialized.length()) + serialized;
}
Value Directory::deserialize(Value serialized){
//remove current content
clear();
//define part of the string for this folder
size_t length = serialized.length();
size_t i = 1;
for(; i < length; ++i){
if(serialized[i] < '0' || serialized[i] > '9'){
break;
}
}
size_t serializedStringLength = Value(serialized, 1, i).toNumber();
//split part of the string that is not needed
Value restOfTheString = Value(serialized, serializedStringLength + i, length);
//load information for the current folder - name, size and etc.
serialized = Value(serialized, i, serializedStringLength + i);
serialized = File :: deserialize(serialized);
//read part for the files in the folder
for(i = 1; i < length; ++i){
if(serialized[i] < '0' || serialized[i] > '9'){
break;
}
}
size_t delimiter = serialized.find(':', 1);
size_t filesCount = Value(serialized, 1, i).toNumber();
serialized = Value(serialized, delimiter, serialized.length());
File * tempFile = NULL;
//add files in the folder
for(i = 0; i < filesCount; ++i){
tempFile = new File("", 0);
serialized = tempFile->deserialize(serialized) + Value(":");
addFile(tempFile);
}
tempFile = NULL;
//read part for the subfolders
for(i = 1; i < length; ++i){
if(serialized[i] < '0' || serialized[i] > '9'){
break;
}
}
delimiter = serialized.find(':', 1);
size_t directoriesCount = Value(serialized, 1, i).toNumber();
serialized = Value(serialized, delimiter, serialized.length());
//std :: cout <<"\n\n s"<< serialized << "d " << delimiter << "l " << serialized.length() << "\n";
//add subfolders
Directory * tempDir = NULL;
for(i = 0; i < directoriesCount; ++i){
tempDir = new Directory("", 0, NULL);
serialized = tempDir->deserialize(serialized);
addDirectory(tempDir);
}
tempDir = NULL;
//return the part of the string that is for the other folders
return restOfTheString;
}
void Directory :: printContent() const{
File :: printContent();
std :: cout << "\nFiles:" << files.getSize() << "\n";
for(List<File *> :: Iterator it = files.begin(); it; it++){
std :: cout << (*it)->getName() << "\n";
}
std :: cout << "\nDirectories:" <<directories.getSize() << "\n";
for(List<Directory *> :: Iterator it = directories.begin(); it; it++){
std :: cout << (*it)->getName() << "\n";
}
}
| true |
36765b4c11f98f55a86c073ec6b25b07ac658d7c | C++ | Ameyyy4/Problem-Solving | /Array/Count Inversion/Brute.cpp | UTF-8 | 647 | 3.3125 | 3 | [] | no_license | // TC : O(n*n) SC : O(n) - For a single Test Case
// SC is due to the input size
#include <iostream>
#include <vector>
using namespace std;
int count_inv(vector<int> &vec, int n)
{
int count = 0;
for(int i=0;i<n;i++)
{
for(int j=i+1;j<n;j++)
{
if(vec[i]>vec[j])
count++;
}
}
return count;
}
int main()
{
int testcases;
cin>>testcases;
for(int i=0;i<testcases;i++)
{
int n;
cin>>n;
vector<int> vec(n);
for(int i=0;i<n;i++)
{
cin>>vec[i];
}
cout<<count_inv(vec,n)<<endl;
}
return 0;
}
| true |
afd838a72747bf786c517012b7de548602cadb08 | C++ | Graphics-Physics-Libraries/Tiny3D | /Win32Project1/mesh/sphere.cpp | UTF-8 | 3,701 | 2.609375 | 3 | [] | no_license | #include "sphere.h"
#include "../constants/constants.h"
#include <stdlib.h>
#include <string.h>
Sphere::Sphere(int m,int n):Mesh() {
longitude=m;
latitude=n;
vertexCount = (m - 1) * n + 2;
vertices=new VECTOR4D[vertexCount];
normals=new VECTOR3D[vertexCount];
texcoords=new VECTOR2D[vertexCount];
indexCount = (m - 2) * n * 6 + 2 * n * 3;
indices = (int*)malloc(indexCount*sizeof(int));
materialids = NULL;
initFaces();
caculateExData();
}
Sphere::Sphere(const Sphere& rhs) {
vertexCount=rhs.vertexCount;
vertices=new VECTOR4D[vertexCount];
normals=new VECTOR3D[vertexCount];
texcoords=new VECTOR2D[vertexCount];
if (rhs.materialids)
materialids = new int[vertexCount];
for(int i=0;i<vertexCount;i++) {
vertices[i]=rhs.vertices[i];
normals[i]=rhs.normals[i];
texcoords[i]=rhs.texcoords[i];
if (rhs.materialids)
materialids[i] = rhs.materialids[i];
}
indexCount = rhs.indexCount;
indices = (int*)malloc(indexCount*sizeof(int));
memcpy(indices, rhs.indices, indexCount*sizeof(int));
caculateExData();
}
Sphere::~Sphere() {
}
void Sphere::initFaces() {
float stepAngZ=PI/longitude;
float stepAngXY=PI2/latitude;
uint current = 0;
float x0 = 0; float y0 = 0; float z0 = 1;
float v0 = 0; float u0 = 0;
vertices[current].x = x0; vertices[current].y = y0; vertices[current].z = z0; vertices[current].w = 1;
normals[current].x = x0; normals[current].y = y0; normals[current].z = z0;
texcoords[current].x = u0; texcoords[current].y = v0;
current++;
for (int i = 1; i < longitude; i++) {
for (int j = 0; j < latitude; j++) {
float x = sin(i * stepAngZ) * cos(j * stepAngXY);
float y = sin(i * stepAngZ) * sin(j * stepAngXY);
float z = cos(i * stepAngZ);
float v = (i * stepAngZ) / PI;
float u = (j * stepAngXY) / PI2;
vertices[current].x = x; vertices[current].y = y; vertices[current].z = z; vertices[current].w = 1;
normals[current].x = x; normals[current].y = y; normals[current].z = z;
texcoords[current].x = u; texcoords[current].y = v;
current++;
}
}
z0 = -1;
v0 = 1; u0 = 0;
vertices[current].x = x0; vertices[current].y = y0; vertices[current].z = z0; vertices[current].w = 1;
normals[current].x = x0; normals[current].y = y0; normals[current].z = z0;
texcoords[current].x = u0; texcoords[current].y = v0;
uint curIndex = 0, baseVertex = 0;
for (int i = 0; i < latitude; i++) {
indices[curIndex] = 0; curIndex++;
indices[curIndex] = i + 1; curIndex++;
if (i != latitude - 1)
indices[curIndex] = i + 2;
else
indices[curIndex] = 1;
curIndex++;
}
baseVertex = 1;
for (int i = 1; i < longitude - 1; i++) {
for (int j = 0; j < latitude; j++) {
indices[curIndex] = baseVertex + j; curIndex++;
indices[curIndex] = baseVertex + latitude + j; curIndex++;
if (j != latitude - 1)
indices[curIndex] = baseVertex + latitude + (j + 1);
else
indices[curIndex] = baseVertex + latitude;
curIndex++;
if (j != latitude - 1) {
indices[curIndex] = baseVertex + latitude + (j + 1); curIndex++;
indices[curIndex] = baseVertex + (j + 1); curIndex++;
} else {
indices[curIndex] = baseVertex + latitude; curIndex++;
indices[curIndex] = baseVertex; curIndex++;
}
indices[curIndex] = baseVertex + j; curIndex++;
}
baseVertex += latitude;
}
for (int i = 0; i < latitude; i++) {
indices[curIndex] = baseVertex + i; curIndex++;
indices[curIndex] = baseVertex + latitude; curIndex++;
if (i != latitude - 1)
indices[curIndex] = baseVertex + i + 1;
else
indices[curIndex] = baseVertex;
curIndex++;
}
}
| true |
bdc76be272f82cd97d36d7423143802d25ae0d1a | C++ | HeenaRajput/DS-A-Assignments | /week1/Day4/heightchecker.cpp | UTF-8 | 562 | 2.875 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int heightChecker(vector<int>& heights) {
vector<int> v=heights;
sort(v.begin(),v.end());
int i,count=0;
int n=heights.size();
for(i=0;i<n;i++){
if(heights[i]!=v[i])
count++;
}
return count;
}
int main(){
vector<int> v;
int n,vt;
cin>>n;
for(int i=0;i<n;i++){
cin>>vt;
v.push_back(vt);
}
int v2=heightChecker(v);
cout<<v2<<" ";
return 0;
}
| true |
d94faeaed0d1c1a25d48c943a9a483a4c5d4e296 | C++ | RoberttyFreitas/Grupo-OBI-2020 | /Exercícios Aula/Aula 2/PremiodoMilhao.cpp | UTF-8 | 228 | 2.703125 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main(){
int N, A, soma = 0, dia = 1;
cin >> N;
while(N--){
cin >> A;
soma += A;
if(soma >= 1000000){
break;
}
dia++;
}
cout << dia << endl;
return 0;
}
| true |
c29d0e8a5b66da8aeec784f08c51611f51cc18a9 | C++ | sergey-pashaev/practice | /cpp/dbg/include/dbg/breakpoint.h | UTF-8 | 613 | 2.78125 | 3 | [] | no_license | #ifndef BREAKPOINT_H
#define BREAKPOINT_H
#include <cstdint>
#include <sys/types.h>
class Breakpoint {
public:
Breakpoint() = default;
Breakpoint(pid_t pid, std::intptr_t addr);
void Enable();
void Disable();
bool IsEnabled() const;
std::intptr_t GetAddress() const;
private:
pid_t pid_ = 0;
std::intptr_t addr_ = 0;
bool enabled_ = false;
std::uint8_t saved_data_ = 0; // Data which used to be at the
// breakpoint address (before replaceing
// it with 'int 3' instruction).
};
#endif /* BREAKPOINT_H */
| true |
8c4d162397adce698de73e58a1270369e557081d | C++ | xSofter/workflow_annotation | /demos/12_counter/counter_intro.cc | UTF-8 | 1,400 | 2.890625 | 3 | [
"MIT"
] | permissive | // 计数器是我们框架中一种非常重要的基础任务,计数器本质上是一个不占线程的信号量。
// 计数器主要用于工作流的控制,包括匿名计数器和命名计数器两种,可以实现非常复杂的业务逻辑。
// 每个计数器都包含一个target_value,当计数器的计数到达target_value,callback被调用。
// 匿名计数器直接通过WFCounterTask的count方法来增加计数
// 命名计数器,可以通过count, count_by_name函数来增加计数
#include <spdlog/spdlog.h>
#include <workflow/WFTaskFactory.h>
#include <workflow/WFHttpServer.h>
#include <workflow/WFFacilities.h>
#include <signal.h>
int main()
{
const int cnt = 3;
WFFacilities::WaitGroup wait_group(1);
WFCounterTask *counter =
WFTaskFactory::create_counter_task("counter",
cnt,
[&wait_group](WFCounterTask *counter)
{
spdlog::info("counter callback");
wait_group.done();
});
counter->count();
counter->start();
spdlog::info("counter start");
WFTaskFactory::count_by_name("counter");
WFTaskFactory::count_by_name("counter", 1);
wait_group.wait();
} | true |
f4dd5c5a9f30b8b4692c6a2c5d4ec2cf26863297 | C++ | gourav13/c-_code | /mpp/main.cpp | UTF-8 | 490 | 3.015625 | 3 | [] | no_license | #include <iostream>
#include <map>
using namespace std;
map<long long,long long > m;
int main()
{
map<long long,long long>::iterator it;
m[2]=1;
m[8]=1;
m[4]=1;
m[10]=1;
m[12]=1;
m[15]=1;
long long k=1;
for(it=m.begin();it!=m.end();++it)
{
it->second=k++;
cout<<it->first<<" ";
cout<<it->second<<" ";
cout<<endl;
}
cout<<endl<<endl;
for(int i=1;i<100;i++)
cout<<m[i]<<" ";
cout << "Hello world!" << endl;
return 0;
}
| true |
a2a40c42f40aa468783b378d35e26c9476456dc5 | C++ | andreibratu/bachelor | /sem5/pdp/lab5/Polynomial.cpp | UTF-8 | 1,668 | 3.328125 | 3 | [] | no_license | //
// Created by bratu on 11/14/2020.
//
#include <iostream>
#include "Polynomial.h"
std::ostream &operator<<(std::ostream &os, const Polynomial &dt) {
std::vector<int> number = dt.coefficients;
for(int i = number.size() - 1; i >= 0; i--){ // NOLINT(cppcoreguidelines-narrowing-conversions)
if(i == number.size() - 2 && number[i + 1] == 0){
if(number[i] > 0){
os << number[i] << "x^" << std::to_string(i);
}else{
os << std::abs(number[i]) << "x^" << std::to_string(i);
}
}
if(number[i] != 0 && i != 0) {
if(i == number.size() - 1) {
if (number[i] > 0) {
os << number[i] << "x^" << std::to_string(i);
}
else {
os << "-" << std::abs(number[i]) << "x^" << std::to_string(i);
}
}
else {
if(number[i] > 0) {
os << " + " << number[i] << "x^" << std::to_string(i);
}
else {
os << " - " << std::abs(number[i]) << "x^" << std::to_string(i);
}
}
}
else if(i == 0 && number[i] != 0) {
if (number[i] > 0) {
os << " + " << number[i];
}
else{
os << " - " << std::abs(number[i]);
}
}
}
return os;
}
const std::vector<int> &Polynomial::getCoefficients() const {
return this->coefficients;
}
void Polynomial::setCoefficients(std::vector<int> &newCoefficients) {
this->coefficients = newCoefficients;
}
| true |
22c7b22d787978bba88d8e5e1fe86fbd240c3032 | C++ | flylofty/coding_test_study | /210304_BOJ_16398 - 02.cpp | UTF-8 | 1,070 | 2.859375 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <queue>
using namespace std;
typedef pair<int, int> pii;
int N;
vector<pii> v[1001];
vector<bool> visit(1001, false);
void input() {
cin >> N;
for (int i = 0; i < N; ++i) {
for (int j = 0; j < N; ++j) {
int c; cin >> c;
if (c == 0)
continue;
v[i].push_back({ j, c });
v[j].push_back({ i, c });
}
}
}
void prim(int start) {
visit[start] = true;
priority_queue<pii, vector<pii>, greater<pii>> pq;
for (int i = 0; i < v[start].size(); ++i) {
int x = v[start][i].first;
int cost = v[start][i].second;
pq.push({ cost, x });
}
long long sum = 0;
while (!pq.empty()) {
int cost1 = pq.top().first;
int x = pq.top().second;
pq.pop();
if (visit[x])
continue;
visit[x] = true;
sum += cost1;
for (int i = 0; i < v[x].size(); ++i) {
int y = v[x][i].first;
if (visit[y])
continue;
int cost2 = v[x][i].second;
pq.push({ cost2, y });
}
}
cout << sum << "\n";
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0), cout.tie(0);
input();
prim(1);
} | true |
94a5cfea663a589c1a459e17ddc7fb27e87310f9 | C++ | adityanjr/code-DS-ALGO | /CCDSAP/STACKS AND QUEUES/HISTO/main.cpp | UTF-8 | 1,068 | 2.625 | 3 | [
"MIT"
] | permissive | #include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
int main()
{
ll a;
while(cin>>a && a!=0){
vector<ll>vec(a);
for(int i=0;i<a;i++){
cin>>vec[i];
}
ll max_area = LLONG_MIN;
ll i = 0;
stack<ll>ss;
while(i<a){
if(ss.empty() || vec[ss.top()]<=vec[i]){
ss.push(i++);
}
else{
while(!ss.empty() && vec[ss.top()]>vec[i] ){
ll top = ss.top();
ss.pop();
ll area = vec[top]*(ss.empty()?i:i-ss.top()-1);
max_area = max(max_area,area);
}
ss.push(i);
i++;
}
}
while(!ss.empty()){
ll top = ss.top();
ss.pop();
ll area = vec[top]*(ss.empty()?i:(i-ss.top()-1));
max_area = max(max_area,area);
}
cout<<max_area<<endl;
}
return 0;
}
| true |
dbc7116631e83d687dd7ed7ca99da0c6669d9f12 | C++ | npazderov/OOP_2017 | /Battleship_2inter/Ship.cpp | UTF-8 | 4,662 | 3.078125 | 3 | [] | no_license | #include "Ship.h"
Ship::Ship()
{
hp = 0;
ID = '.';
positionX = 0;
positionY = 0;
}
Ship::Ship( int newHp, char newID, int newPositionX, int newPositionY)
{
hp = newHp;
ID = newID;
positionX = newPositionX;
positionY = newPositionY;
}
Ship::Ship(const Ship& other)
{
hp = other.hp;
ID = other.ID;
positionX = other.positionX;
positionY = other.positionY;
}
Ship& Ship::operator=(const Ship& rhs)
{
if (this == &rhs)
{
hp = rhs.hp;
ID = rhs.ID;
positionX = rhs.positionX;
positionY = rhs.positionY;
}
return *this;
}
int Ship::getHp() const
{
return hp;
}
char Ship::getID()const
{
return ID;
}
int Ship::getPositionX() const
{
return positionX;
}
int Ship::getPositionY() const
{
return positionY;
}
void Ship::setHP(int _HP)
{
hp = _HP;
}
void Ship::setID(char _ID)
{
ID = _ID;
}
void Ship::place(int _positionX, int _positionY)
{
char userOrientation;
if ((_positionX >= 0 && _positionX <= 7) && (_positionY >= 0 && _positionY <= 7))
{
do
{
cout << "Enter U / D / L / R for orientation of the Ship:";
cin >> userOrientation;
if (userOrientation == 'U')
{
if (_positionY >= this->getHp())
{
if(collisionU(_positionX, _positionY, this->getHp() == false))
{
for (size_t i = _positionY; i < this->getHp(); i++)
{
setAt(_positionX, _positionY - i, this->getID());
}
}
else
{
cout << "There is a ship on one of the positions. Try again..." << endl;
}
}
}
if (userOrientation == 'D')
{
if (_positionY <= this->getHp())
{
if(collisionD(_positionX, _positionY, this->getHp() == false))
{
for (size_t i = _positionY; i < this->getHp(); i++)
{
setAt(_positionX, _positionY + i, this->getID());
}
}
else
{
cout << "There is a ship on one of the positions. Try again..." << endl;
}
}
}
if (userOrientation == 'L')
{
if (_positionX >= this->getHp())
{
if(collisionL(_positionX, _positionY, this->getHp() == false))
{
for (size_t i = _positionX; i < this->getHp(); i++)
{
setAt(_positionX - i, _positionY, this->getID());
}
}
else
{
cout << "There is a ship on one of the positions. Try again..." << endl;
}
}
}
if (userOrientation == 'R')
{
if (_positionX <= this->getHp())
{
if(collisionR(_positionX, _positionY, this->getHp() == false))
{
for (size_t i = _positionX; i < this->getHp(); i++)
{
setAt(_positionX + i, _positionY, this->getID());
}
}
else
{
cout << "There is a ship on one of the positions. Try again..." << endl;
}
}
}
break;
}
while (true);
}
}
void Ship::attack(Map& _map, Map & _map2, int _playerHP)
{
int _positionX, _positionY;
cout<< "Please enter coordinate for attack"<<endl;
cin >> _positionX >> _positionY;
if(_map.checkAt(_positionX,_positionY))
{
cout<<"It's a miss"<<endl;
_map2.setAt('O', _positionX, _positionY);
}
else if(!_map.checkAt(_positionX,_positionY))
{
cout << "You hit a ship!"<<endl;
_map2.setAt('X', _positonX, _positionY);
hit(_playerHP);
}
}
void Ship::hit(int _playerHP)
{
_playerHP--;
}
| true |
558e2214b44d7fb9a58a90d69158d4947049f5d0 | C++ | geova-25/Vector-Processor-Simulation | /src/alu.h | UTF-8 | 658 | 2.65625 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <stdio.h>
class Alu
{
public:
Alu();
char result;
unsigned char sum (unsigned char op1, unsigned char op2);
unsigned char sub (unsigned char op1, unsigned char op2);
unsigned char xxor(unsigned char op1, unsigned char op2);
unsigned char shfl(unsigned char op1, unsigned char op2);
unsigned char shfr(unsigned char op1, unsigned char op2);
unsigned char shflc(unsigned char op1, unsigned char op2);
unsigned char shfrc(unsigned char op1, unsigned char op2);
unsigned char mult(unsigned char op1, unsigned char op2);
unsigned char div (unsigned char op1, unsigned char op2);
private:
}; | true |
8e7f3fc2a0fc03618cb378511fddb46ef7660932 | C++ | rahulnusiss/ImageMatrixOptimize | /source/TestSearch.cpp | UTF-8 | 2,727 | 2.796875 | 3 | [] | no_license | #include "TestSearch.h"
#include "ISearch.h"
#include "Sequence.h"
#include "Unordered.h"
#include "BestMatch.h"
#include <iostream>
#include <chrono>
#include <vector>
#include <random>
#include <functional>
using namespace std;
TestSearch::TestSearch()
{
m_search_type_map["searchSequence"] = new Sequence();
m_search_type_map["searchUnordered"] = new Unordered();
m_search_type_map["searchBestMatch"] = new BestMatch();
}
TestSearch::~TestSearch()
{
//dtor
map_type::iterator it;
for ( it = m_search_type_map.begin(); it != m_search_type_map.end(); ++it)
{
//cout << "Deleted: " << it->first << endl;
delete (it->second);
}
}
void TestSearch::setMatrix(const vector< vector<int> >& iMatrix)
{
m_original_matrix = iMatrix;
}
void TestSearch::testSearch(const vector<int>& iSeq, const string& iStrArg)
{
cout << "====================" << iStrArg << "=====================" << endl;
m_search = m_search_type_map[iStrArg];
m_search->setMatrices(m_original_matrix, iSeq);
m_search->search();
cout << "====================" << iStrArg << "=====================" << endl;
}
void TestSearch::benchMark(const vector<int>& iSeq, const string& iStrArg, int iter)
{
m_search = m_search_type_map[iStrArg];
// RNG
default_random_engine generator;
// Ginve range for random number
uniform_int_distribution<int> distribution(1,100);
auto rng = bind( distribution, generator );
cout << "====================Benchmarking " << iStrArg << "=====================" << endl;
long int micro_time = 0;
for ( int t = 0; t < iter; ++t)
{
vector< vector<int> > matrix_benchmark;
for (int i =0; i < 10; ++i)
{
vector<int> temp;
for ( int j =0; j < 1000; ++j)
{
// Random number = num
int num = rng();
//int num = rand() % 1000 + 1;
temp.push_back(num);
}
matrix_benchmark.push_back(temp);
}
m_search->setMatrices(matrix_benchmark, iSeq);
// Initial time
chrono::steady_clock::time_point start = chrono::steady_clock::now() ;
m_search->search();
// Final time
chrono::steady_clock::time_point end = chrono::steady_clock::now() ;
// 10^-6 seconds(microseconds)
typedef chrono::duration<int,micro> microsecs_t ;
microsecs_t duration( chrono::duration_cast<microsecs_t>(end-start) ) ;
micro_time += duration.count();
}
long int total_avg_time = micro_time/iter;
cout << "Total avg time = " << total_avg_time << endl;
} | true |
495be596b4bc35c20ce47ebc61ac67c9926cd923 | C++ | porvaznikmichal/ETH-ACM-Lab | /Week 5 - Graphs 2/wild wild west train network/www_train_network.cpp | UTF-8 | 1,769 | 3.375 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <set>
#include <limits>
#include <map>
#include <queue>
using namespace std;
const int MAX_INT = numeric_limits<int>::max();
struct edge
{
int to, length;
};
int dijkstra(vector< vector<edge> > &graph, int source, int target) {
int n = graph.size();
// initialize distance structure and 'priority que'
vector<int> distance(n, MAX_INT);
set< pair<int, int> > priority;
// add source
distance[source] = 0;
priority.insert(make_pair(0, source));
int current;
int alt;
while (!priority.empty()) {
current = priority.begin()->second;
// if we reached target, we have the shortest distance
if (current == target) return distance[current];
// erase current
priority.erase( priority.begin() );
// check neighbourhood
for (vector<edge>::iterator vi = graph[current].begin(); vi != graph[current].end(); vi++) {
alt = distance[current] + vi->length;
if (alt < distance[vi->to]) {
// decrease key
priority.erase(make_pair(distance[vi->to], vi->to));
priority.insert(make_pair(alt, vi->to));
distance[vi->to] = alt;
}
}
}
// if not found, return max
return MAX_INT;
}
void testcase() {
int n, m, y, i; cin >> n >> m >> y >> i;
vector< vector<edge> > graph(n, vector<edge>());
// read graph and weights
int u, v, c;
edge e;
for (int i = 0; i < m; i++) {
cin >> u >> v >> c;
// push edge there
e.to = v;
e.length = c;
graph[u].push_back(e);
//push edge back
e.to = u;
graph[v].push_back(e);
}
int shortest = dijkstra(graph, y, i);
if (shortest == MAX_INT) {
cout << "Need a horse" << endl;
}
else {
cout << shortest << endl;
}
}
int main(int argc, char const *argv[])
{
int c; cin >> c;
while (c--) {
testcase();
}
return 0;
} | true |
54af1bf7a9238134e27563af16613eb7d58cdfce | C++ | ankitsaini84/DS-Algos | /Uncategorized/Implement_Trie.cpp | UTF-8 | 2,208 | 4.09375 | 4 | [] | no_license | /**
* Implement a trie with insert, search, and startsWith methods.
*/
#include <iostream>
#include <string>
#include <vector>
class Trie {
struct Node {
Node* val[26] {nullptr, };
bool eow {false};
};
Node* db {nullptr};
int getVal(char c) {
return c - 'a';
}
public:
/** Initialize your data structure here. */
Trie() {
if(db == nullptr) {
db = new Node();
}
}
/** Inserts a word into the trie. */
void insert(std::string word) {
int c;
Node* curr {db};
int len = static_cast<int>(word.length());
for(int i {0}; i < len; ++i) {
c = getVal(word[i]);
if(curr->val[c] == nullptr) {
curr->val[c] = new Node();
}
curr = curr->val[c];
}
curr->eow = true;
}
/** Returns if the word is in the trie. */
bool search(std::string word) {
int c;
Node* curr {db};
for(int i {0}; i < static_cast<int>(word.length()); ++i) {
c = getVal(word[i]);
if(curr->val[c] == nullptr) {
return false;
}
curr = curr->val[c];
}
return curr->eow;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
bool startsWith(std::string prefix) {
int c;
Node* curr {db};
for(int i {0}; i < static_cast<int>(prefix.length()); ++i) {
c = getVal(prefix[i]);
if(curr->val[c] == nullptr) {
return false;
}
curr = curr->val[c];
}
return true;
}
};
/**
* Your Trie object will be instantiated and called as such:
* Trie* obj = new Trie();
* obj->insert(word);
* bool param_2 = obj->search(word);
* bool param_3 = obj->startsWith(prefix);
*/
int main() {
Trie* trie = new Trie();
trie->insert("apple");
trie->search("apple"); // returns true
trie->search("app"); // returns false
trie->startsWith("app"); // returns true
trie->insert("app");
trie->search("app"); // returns true
return 0;
} | true |
fa346f3dcf77c6ebccb04ccfb790b77d924cf720 | C++ | erwanmarchand/LOG4705-Labs | /TP3/Program/main.cpp | UTF-8 | 3,219 | 2.765625 | 3 | [] | no_license | #include "parc.h"
// Fonction pour lire un fichier
void readFile(string path, vector<pointDInteret*>& listPI){
int numberPointsDinteret = 0;
string delimiter = " ";
string token1;
string token2;
string line;
string line2;
ifstream myfile(path);
if (myfile.is_open())
{
getline(myfile, line);
numberPointsDinteret = atoi(line.c_str());
getline(myfile, line);
getline(myfile, line2);
size_t pos = 0;
size_t pos2 = 0;
int id = 0;
while ((pos = line.find(delimiter)) != std::string::npos && (pos2 = line2.find(delimiter)) != std::string::npos) {
token1 = line.substr(0, pos);
token2 = line2.substr(0, pos);
pointDInteret* tempPI = new pointDInteret(id, atoi(token1.c_str()), atoi(token2.c_str()));
line.erase(0, pos + delimiter.length());
line2.erase(0, pos2 + delimiter.length());
listPI.push_back(tempPI);
id++;
}
pointDInteret* tempPI = new pointDInteret(id, atoi(line.c_str()), atoi(line2.c_str()));
listPI.push_back(tempPI);
for (auto &pi : listPI) // access by reference to avoid copying
{
getline(myfile, line);
for (auto &pi2 : listPI) // access by reference to avoid copying
{
pos = line.find(delimiter);
token1 = line.substr(0, pos);
double cout = stod(token1.c_str());
pi->addCout(pi2, cout);
line.erase(0, pos + delimiter.length());
}
}
myfile.close();
}
else cout << "Unable to open file";
}
int main(int argc, const char * argv[]) {
vector<pointDInteret*> listPI;
std::chrono::time_point<std::chrono::system_clock> departChargement, departTri, finChargement, finTri;
/*if (argc >= 3){
string choixAlgorithme = argv[1];
string chemin = argv[2];
bool afficherNbExtensions = false;
bool afficherTemps = false; */
//DEBUG
string chemin = "C:\\Users\\erwan\\Desktop\\boulot\\session_8\\INF4705\\TPs\\TP3\\TP3Data\\Parc1-10Zones.txt";
bool afficherNbExtensions = true;
bool afficherTemps = true;
//FIN DEBUG
for (int i = 3; i < argc; i++){
if (strncmp(argv[i], "-p", 2) == 0)
afficherNbExtensions = true;
else if (strncmp(argv[i], "-t", 2) == 0)
afficherTemps = true;
}
/*cout << "Algorithme : " << choixAlgorithme << endl;
cout << "Chemin vers serie : " << chemin << endl;
cout << "Afficher Resultat trie : " << afficherArray << endl;
cout << "Afficher temps : " << afficherTemps << endl;
cout << "Le fichier possede : " << nombredElements << " nombres" << endl;*/
//departChargement = std::chrono::high_resolution_clock::now();
unsigned long dureeExecution = 0;
readFile(chemin, listPI);
parc* Parc = new parc(listPI);
Parc->addSentier(listPI[0], listPI[1]);
Parc->addSentier(listPI[1], listPI[2]);
Parc->addSentier(listPI[2], listPI[3]);
Parc->addSentier(listPI[3], listPI[9]);
Parc->addSentier(listPI[0], listPI[4]);
Parc->addSentier(listPI[4], listPI[5]);
Parc->addSentier(listPI[5], listPI[6]);
Parc->addSentier(listPI[6], listPI[7]);
Parc->addSentier(listPI[6], listPI[8]);
Parc->executeAllVerifications();
delete(Parc);
finChargement = std::chrono::high_resolution_clock::now();
long dureeChargement = std::chrono::duration_cast<std::chrono::milliseconds>(finChargement - departChargement).count();
//}
//return 0;
getchar();
} | true |
6240c292d71cf1c3b9280bbc2d4f65664bc91327 | C++ | Hui-hsiang/Information_Security_Class | /hw1/Information_Security_Class/Information_Security_Class/Encrypt.cpp | UTF-8 | 6,852 | 2.796875 | 3 | [] | no_license | #include <stdio.h>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
string caesar(string key, string plaintext);
string playfair(string key, string plaintext);
string vernam(string key, string plaintext);
string row(string key, string plaintext);
string rail_fence(string key, string plaintext);
int main() {
while (1) {
string cipher;
string key;
string plaintext;
cin >> cipher >> key >> plaintext;
if (cipher == "caesar") {
cout << caesar(key, plaintext);
}
else if (cipher == "playfair") {
cout << playfair(key, plaintext);
}
else if (cipher == "vernam") {
cout << vernam(key, plaintext);
}
else if (cipher == "row") {
cout << row(key, plaintext);
}
else if (cipher == "rail_fence") {
cout << rail_fence(key, plaintext);
}
else {
cout << "input erro";
}
}
}
string caesar(string key, string plaintext) {
int shift = 0;
for (int i = 0; i < key.length(); i++) {
shift *= 10;
shift += key[i] - '0';
}
for (int i = 0; i < plaintext.length(); i++) {
plaintext[i] += shift;
if (plaintext[i] > 'z') {
plaintext[i] -= 26;
}
plaintext[i] = toupper(plaintext[i]);
}
return plaintext;
}
string playfair(string key, string plaintext) {
string ciphertext;
int shift = 0;
vector <char> c_table = {
'a','b','c','d','e',
'f','g','h','i','k',
'l','m','n','o','p',
'q','r','s','t','u',
'v','w','x','y','z' };
vector <vector<char>> table;
vector <char> tmp;
bool find = 0;
int char_counter = 0;
char c;
for (int i = 0; i < key.length(); i++) {
c = tolower(key[i]);
if (c == 'i' || c == 'j') {
for (int j = 0; j < c_table.size(); j++) {
if (c_table[j] == 'i') {
find = 1;
c_table.erase(c_table.begin() + j);
}
}
if (find == 1) {
tmp.push_back('i');
char_counter++;
find = 0;
}
}
else {
for (int j = 0; j < c_table.size(); j++) {
if (c_table[j] == c) {
find = 1;
c_table.erase(c_table.begin() + j);
}
}
if (find == 1) {
tmp.push_back(c);
char_counter++;
find = 0;
}
}
if (char_counter == 5) {
table.push_back(tmp);
char_counter = 0;
tmp.clear();
}
}
for (int i = 0; i < c_table.size(); i++) {
tmp.push_back(c_table[i]);
char_counter++;
if (char_counter == 5) {
table.push_back(tmp);
char_counter = 0;
tmp.clear();
}
}
char_counter = 0;
char pre_char;
int pr, pc, nr, nc;
bool ls = 0;
for (int i = 0; i < plaintext.length(); i++) {
if (i == plaintext.length() - 1) {
ls = 1;
}
if (plaintext[i] == 'j') {
plaintext[i] = 'i';
}
if (char_counter == 0) {
if (ls) {
pre_char = plaintext[i];
for (int col = 0; col < 5; col++) {
for (int row = 0; row < 5; row++) {
if (table[col][row] == pre_char) {
pc = col;
pr = row;
}
if (table[col][row] == 'x') {
nc = col;
nr = row;
}
}
}
if (pc == nc) {
if (pr + 1 < 5)
ciphertext += table[pc][pr + 1];
else
ciphertext += table[pc][0];
if (nr + 1 < 5)
ciphertext += table[nc][nr + 1];
else
ciphertext += table[nc][0];
}
else if (pr == nr) {
if (pc + 1 < 5)
ciphertext += table[pc + 1][pr];
else
ciphertext += table[0][pr];
if (nc + 1 < 5)
ciphertext += table[nc + 1][nr];
else
ciphertext += table[0][nr];
}
else {
ciphertext += table[pc][nr];
ciphertext += table[nc][pr];
}
}
pre_char = plaintext[i];
char_counter++;
}
else if (char_counter == 1) {
if (plaintext[i] == pre_char) {
for (int col = 0; col < 5; col++) {
for (int row = 0; row < 5; row++) {
if (table[col][row] == pre_char) {
pc = col;
pr = row;
}
if (table[col][row] == 'x') {
nc = col;
nr = row;
}
}
}
pre_char = plaintext[i];
char_counter = 1;
}
else {
for (int col = 0; col < 5; col++) {
for (int row = 0; row < 5; row++) {
if (table[col][row] == pre_char) {
pc = col;
pr = row;
}
if (table[col][row] == plaintext[i]) {
nc = col;
nr = row;
}
}
}
char_counter = 0;
}
if (pc == nc) {
if (pr + 1 < 5)
ciphertext += table[pc][pr+1];
else
ciphertext += table[pc][0];
if (nr + 1 < 5)
ciphertext += table[nc][nr + 1];
else
ciphertext += table[nc][0];
}
else if (pr == nr) {
if (pc + 1 < 5)
ciphertext += table[pc + 1][pr];
else
ciphertext += table[0][pr];
if (nc + 1 < 5)
ciphertext += table[nc + 1][nr];
else
ciphertext += table[0][nr];
}
else {
ciphertext += table[pc][nr];
ciphertext += table[nc][pr];
}
}
}
for (int i = 0; i < ciphertext.length(); i++) {
ciphertext[i] = toupper(ciphertext[i]);
}
return ciphertext;
}
string vernam(string key, string plaintext) {
string autokey = key;
string ciphertext;
autokey += plaintext;
for (int i = 0; i < plaintext.length(); i++) {
ciphertext += ((plaintext[i] - 'a') ^ (toupper(autokey[i]) - 'A')) + 'A';
}
for (int i = 0; i < ciphertext.length(); i++) {
ciphertext[i] = toupper(ciphertext[i]);
}
return ciphertext;
}
string row(string key, string plaintext) {
int counter = 0;
string ciphertext;
vector<char> tmp;
vector<vector<char>> table;
while (counter < plaintext.length()) {
for (int i = 0; i < key.length(); i++) {
tmp.push_back(plaintext[counter]);
counter++;
if (counter == plaintext.length()) {
break;
}
}
table.push_back(tmp);
tmp.clear();
}
counter = 1;
int col;
while (counter <= key.length())
{
for (int i = 0; i < key.length(); i++) {
if (key[i] - '0' == counter) {
counter++;
col = i;
break;
}
}
for (int i = 0; i < table.size(); i++) {
if (col < table[i].size()) {
ciphertext += table[i][col];
}
}
}
for (int i = 0; i < ciphertext.length(); i++) {
ciphertext[i] = toupper(ciphertext[i]);
}
return ciphertext;
}
string rail_fence(string key, string plaintext) {
int r = 0;
int counter = 0;
string ciphertext;
for (int i = 0; i < key.length(); i++) {
r *= 10;
r += key[i] - '0';
}
vector<vector<char>> table;
vector<char> tmp;
for (int i = 0; i < r; i++) {
table.push_back(tmp);
}
while (counter < plaintext.length()) {
for (int i = 0; i < r; i++) {
table[i].push_back(plaintext[counter]);
counter++;
if (counter == plaintext.length()) {
break;
}
}
if (counter == plaintext.length()) {
break;
}
for (int i = r - 2; i > 0; i--) {
table[i].push_back(plaintext[counter]);
counter++;
if (counter == plaintext.length()) {
break;
}
}
}
for (int i = 0; i < table.size(); i++) {
for (int j = 0; j < table[i].size(); j++) {
ciphertext += toupper(table[i][j]);
}
}
return ciphertext;
}
| true |
6d80708a10ff039feda0b773a43d73546e2fac7b | C++ | Isanti2016/QtLearning | /NotePad/ReplaceDialog.cpp | UTF-8 | 1,835 | 2.578125 | 3 | [] | no_license | #include "ReplaceDialog.h"
ReplaceDialog::ReplaceDialog(QWidget *parent, QPlainTextEdit* pText)
: FindDialog(parent, pText)
{
InitControl();
ConnectSlot();
setWindowTitle("Replace");
}
void ReplaceDialog::InitControl()
{
m_replaceLbl.setText("Replace To:");
m_replaceBtn.setText("Replace");
m_replaceAllBtn.setText("Replace ALL");
m_layout.removeWidget(&m_matchCheckBox);
m_layout.removeWidget(&m_radioGrpBx);;
m_layout.removeWidget(&m_closeBtn);
m_layout.addWidget(&m_replaceLbl, 1, 0);
m_layout.addWidget(&m_replaceEdit, 1, 1);
m_layout.addWidget(&m_replaceBtn, 1, 2);
m_layout.addWidget(&m_matchCheckBox, 2, 0);
m_layout.addWidget(&m_radioGrpBx, 2, 1);
m_layout.addWidget(&m_replaceAllBtn, 2, 2);
m_layout.addWidget(&m_closeBtn, 3, 2);
}
void ReplaceDialog::ConnectSlot()
{
connect(&m_replaceBtn, SIGNAL(clicked()), this, SLOT(onReplaceClicked()));
connect(&m_replaceAllBtn, SIGNAL(clicked()), this, SLOT(OnReplaceAllClicked()));
}
void ReplaceDialog::onReplaceClicked()
{
QString strFrom = m_findEdit.text();
QString strTo = m_replaceEdit.text();
if( (m_pText != NULL) && (strFrom != "") )
{
QString strSelect = m_pText->textCursor().selectedText();
if(strSelect == strFrom)
{
m_pText->insertPlainText(strTo);
}
OnFindClick();
}
}
void ReplaceDialog::OnReplaceAllClicked()
{
QString strFrom = m_findEdit.text();
QString strTo = m_replaceEdit.text();
if( (m_pText != NULL ) && (strFrom != "") )
{
QString strText = m_pText->toPlainText();
strText.replace( strFrom, strTo, m_matchCheckBox.isChecked() ? Qt::CaseSensitive : Qt::CaseInsensitive );
m_pText->clear();
m_pText->insertPlainText(strText);
}
}
| true |
0dbff4fafae3a73aba8c89443df297fa4ecbe55a | C++ | blinker-iot/blinker-library | /src/modules/base64/Base64.cpp | UTF-8 | 2,671 | 2.828125 | 3 | [
"MIT"
] | permissive | #include "Base64.h"
#if (defined(__AVR__))
#include <avr/pgmspace.h>
#elif defined(ESP8266) || defined(ESP32)
#include <pgmspace.h>
#endif
const char PROGMEM b64_alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789+/";
/* 'Private' declarations */
inline void a3_to_a4(unsigned char * a4, unsigned char * a3);
inline void a4_to_a3(unsigned char * a3, unsigned char * a4);
inline unsigned char b64_lookup(char c);
int base64_encode(char *output, char *input, int inputLen) {
int i = 0, j = 0;
int encLen = 0;
unsigned char a3[3];
unsigned char a4[4];
while(inputLen--) {
a3[i++] = *(input++);
if(i == 3) {
a3_to_a4(a4, a3);
for(i = 0; i < 4; i++) {
output[encLen++] = pgm_read_byte(&b64_alphabet[a4[i]]);
}
i = 0;
}
}
if(i) {
for(j = i; j < 3; j++) {
a3[j] = '\0';
}
a3_to_a4(a4, a3);
for(j = 0; j < i + 1; j++) {
output[encLen++] = pgm_read_byte(&b64_alphabet[a4[j]]);
}
while((i++ < 3)) {
output[encLen++] = '=';
}
}
output[encLen] = '\0';
return encLen;
}
int base64_decode(char * output, char * input, int inputLen) {
int i = 0, j = 0;
int decLen = 0;
unsigned char a3[3];
unsigned char a4[4];
while (inputLen--) {
if(*input == '=') {
break;
}
a4[i++] = *(input++);
if (i == 4) {
for (i = 0; i <4; i++) {
a4[i] = b64_lookup(a4[i]);
}
a4_to_a3(a3,a4);
for (i = 0; i < 3; i++) {
output[decLen++] = a3[i];
}
i = 0;
}
}
if (i) {
for (j = i; j < 4; j++) {
a4[j] = '\0';
}
for (j = 0; j <4; j++) {
a4[j] = b64_lookup(a4[j]);
}
a4_to_a3(a3,a4);
for (j = 0; j < i - 1; j++) {
output[decLen++] = a3[j];
}
}
output[decLen] = '\0';
return decLen;
}
int base64_enc_len(int plainLen) {
int n = plainLen;
return (n + 2 - ((n + 2) % 3)) / 3 * 4;
}
int base64_dec_len(char * input, int inputLen) {
int i = 0;
int numEq = 0;
for(i = inputLen - 1; input[i] == '='; i--) {
numEq++;
}
return ((6 * inputLen) / 8) - numEq;
}
inline void a3_to_a4(unsigned char * a4, unsigned char * a3) {
a4[0] = (a3[0] & 0xfc) >> 2;
a4[1] = ((a3[0] & 0x03) << 4) + ((a3[1] & 0xf0) >> 4);
a4[2] = ((a3[1] & 0x0f) << 2) + ((a3[2] & 0xc0) >> 6);
a4[3] = (a3[2] & 0x3f);
}
inline void a4_to_a3(unsigned char * a3, unsigned char * a4) {
a3[0] = (a4[0] << 2) + ((a4[1] & 0x30) >> 4);
a3[1] = ((a4[1] & 0xf) << 4) + ((a4[2] & 0x3c) >> 2);
a3[2] = ((a4[2] & 0x3) << 6) + a4[3];
}
inline unsigned char b64_lookup(char c) {
if(c >='A' && c <='Z') return c - 'A';
if(c >='a' && c <='z') return c - 71;
if(c >='0' && c <='9') return c + 4;
if(c == '+') return 62;
if(c == '/') return 63;
return -1;
}
| true |
787f99072a58993fc96ac0da79b788155250f5ab | C++ | royks07/plankesorteringsanlegg-simulator-styringssystem | /PlankesorteringsAnlegg/Plankesorteringsanlegg/Conveyor.h | UTF-8 | 3,787 | 3.078125 | 3 | [
"Zlib"
] | permissive | /** \file Conveyor.h
* \brief Contains the Conveyor-class and the classes needed to build it.
*
* \author Roy Kollen Svendsen
*/
#ifndef CONVEYOR_H_
#define CONVEYOR_H_
#include <vector>
#include "Sensors.h"
typedef enum{ingen,knott,krok} t_medbringerType;
/** \brief The conveyors wheels.
*/
class Wheel{
public:
Wheel(b2Vec2 p,float32 r,int cmBits,b2World* world);
inline void setSpeed(float32 speed){m_speed=speed;}
void run();
inline b2Body* getBody(){return m_body;}
private:
b2Body* m_body;
float32 m_speed;
};
/** \brief The beam which the wheels are attached to and which the belt runs along.
*/
class Beam{
public:
Beam(b2Vec2 p1,b2Vec2 p2,float32 width,int cmBits,b2World* world);
inline b2Vec2& getLocalAnchor1(){return m_localAnchor1;}
inline b2Vec2& getLocalAnchor2(){ return m_localAnchor2;}
inline b2Body* getBody(){return m_body;}
private:
b2Body* m_body;
b2Vec2 m_localAnchor1;
b2Vec2 m_localAnchor2;
};
/** \brief The conveyorbelt
*/
class ConveyorBelt{
public:
/** \brief Create the conveyorbelt.
* @param p1 Center position of first wheel.
* @param p2 Center position of second wheel.
* @param beamThickness Thickness of the beam.
* @param beltThickness Thickness of the belt.
* @param N Number of links.
* @param M Number of links between every "medbringer"
* @param medbringerType The type of "medbringers" which are connected to the belt.
* @param sensorPos The number of the link which the sensor is placed at.
* @param sensorAdjustment
* @param cmBits Category- and mask-bits.
* @param world Pointer to the world in which you want to create a conveyorbelt.
*/
ConveyorBelt(b2Vec2 p1,b2Vec2 p2,float32 beamThickness,float32 beltThickness,int N,int M,t_medbringerType medbringerType,int sensorPos,float32 sensorAdjustment,int cmBits,b2World* world);
float32 getAngleAt(b2Vec2 p);/**< Get the angle of the nearest belt-tangent*/
void pause();/**< Pause the belt*/
void play();/**< Restart the belt in the same state as when paused.*/
inline ContactSensor* getSensor(){return m_contactSensorCircular; }/**< Return the synchronization sensor*/
b2Vec2 m_p1;
b2Vec2 m_p2;
vector<b2Body*> link;
vector<b2Vec2> linkSpeed;/**< List of all the links velocity- vectors*/
bool m_paused;
ContactSensor_Sync* m_contactSensorCircular;
t_medbringerType m_medbringerType;
};
/** \brief Hinder the conveyorbelt in falling off.
*/
class ConveyorBeltShield{
public:
ConveyorBeltShield(b2Vec2 p1,b2Vec2 p2,float32 beamThickness,float32 beltThickness,int cmBits,b2World* world);
b2Vec2 m_p1;
b2Vec2 m_p2;
float32 m_beamThickness;
float32 m_beltThickness;
};
/** \brief Assemble the conveyor and expose an interface through which controlling the conveyor is possible.
*/
class Conveyor{
public:
Conveyor(b2Vec2 p1, b2Vec2 p2, float32 beamThickness,float32 beltThickness,int N,int M,t_medbringerType medbringerType,int sensorPos,float32 sensorAdjustment,int cmBits, b2World* world);
void setSpeed(float32 speed);/**< \brief Set the speed of the conveyorbelt.*/
void pause();/**< \brief Pause the conveyor*/
void play();/**< \brief Run the conveyor*/
inline bool isPaused(){return m_bPaused;}/**< \brief Check if conveyor is paused.*/
void run();/**< \brief You need to call this function iteratively.*/
inline Wheel* getWheel1() const { return m_wheel1;}
inline Wheel* getWheel2() const { return m_wheel2;}
ContactSensor* getSensor();/**< \brief Return the synchronization-sensor.*/
bool isSensorActivated();/**< \brief Check state of synchronization-sensor*/
Wheel* m_wheel1;
Wheel* m_wheel2;
b2Vec2 m_p1;
b2Vec2 m_p2;
float32 m_beltThickness;
float32 m_beamThickness;
float32 m_speed;
ConveyorBelt* m_conveyorBelt;
ConveyorBeltShield* m_conveyorBeltShield;
bool m_bPaused;
};
#endif /* CONVEYOR_H_ */
| true |
74624341af919e7f063a7f2fa5cb1f35b6da2fac | C++ | rohit9123/mycodes | /combination.cpp | UTF-8 | 2,365 | 2.734375 | 3 | [] | no_license | #include<iostream>
#include<vector>
#include<map>
using namespace std;
vector<vector<int> > combination;
vector<vector<int> > combinationSum(vector<int>& candidates, int target) {
map<int,int> find;
map<int,int> check;
sort(candidates.begin(),candidates.end());
if(target<candidates[0]){
return combination;
}
for(int i=0;i<candidates.size();i++){
find[candidates[i]]++;
}
for(int i=0;i<candidates.size();i++){
if(candidates[i]==target){
vector<int>p;
p.push_back(candidates[i]);
combination.push_back(p);
}else if(candidates[i]<target){
int minus=target-candidates[i];
cout<<check[candidates[i]]<<" "<<minus<<endl;
if(find[minus]&&(check[candidates[i]]!=minus)){
vector<int> p;
p.push_back(candidates[i]);
p.push_back(minus);
combination.push_back(p);
check[minus]==candidates[i];
};
int count=2;
int sum=count*candidates[i];
// cout<<sum<<endl;
while(sum<target){
vector<int> p;
int mini=target-sum;
if(find[mini]){
// cout<<count<<" ";
for(int j=0;j<count;j++){
p.push_back(candidates[i]);
}
p.push_back(mini);
// for(int j:p){
// cout<<j<<" ";
// }
combination.push_back(p);
}
count+=1;
sum=count*candidates[i];
}
}
}
return combination;
}
int main(){
vector<int> candidates;
candidates.push_back(2);
candidates.push_back(3);
candidates.push_back(5);
candidates.push_back(7);
int target=10;
combinationSum(candidates,target);
for(int i=0;i<combination.size();i++){
for(int j:combination[i]){
cout<<j;
}
cout<<endl;
}
return 0;
} | true |
44587fa83ea51d2fa110daef81ce3320a4618ae5 | C++ | Ju5tK1ng/codes | /leetcode/leetcode474.cpp | UTF-8 | 866 | 2.859375 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
class Solution {
public:
pair<int, int> count(string& str)
{
int c0 = 0, c1 = 0;
for (char c : str)
{
if (c == '0')
{
c0++;
}
else
{
c1++;
}
}
return pair<int, int>{c0, c1};
}
int findMaxForm(vector<string>& strs, int m, int n) {
int dp[m + 1][n + 1];
memset(dp, 0, sizeof(dp));
for (string& str : strs)
{
auto t = count(str);
for (int i = m; i >= t.first; i--)
{
for (int j = n; j >= t.second; j--)
{
dp[i][j] = max(dp[i][j], dp[i - t.first][j - t.second] + 1);
}
}
}
return dp[m][n];
}
};
| true |
2976aae9b6efe727aed1e1f414296731a3d73360 | C++ | keyclicker/labs | /Term2/Lab3/С/main.cpp | UTF-8 | 2,794 | 3.109375 | 3 | [] | no_license | #include "sorting.hpp"
#include <algorithm>
#include <iostream>
#include <iomanip>
#include <vector>
#include <random>
#include <thread>
#include <future>
using namespace std;
int main() {
random_device rd;
default_random_engine re(rd());
uniform_real_distribution<double> drand(-100, 100);
uniform_int_distribution<int> rand(0, 100);
//------------------------- Work test ----------------------------------------
cout << "--------------- Work test ---------------" << endl;
cout << "100 sorting tests of random generated array (size = 1000):\n" << endl;
int aq = 0, q = 0, am = 0, m = 0, t = 0, at = 0;
for (int j = 0; j < 100; ++j) {
std::vector<double> a;
for (int i = 0; i < 1000; ++i)
a.emplace_back(drand(re));
sorting::quicksort(a.begin(), a.end());
if (std::is_sorted(a.begin(), a.end())) q++;
a.clear();
for (int i = 0; i < 1000; ++i)
a.emplace_back(drand(re));
sorting::quicksort_async(a.begin(), a.end());
if (std::is_sorted(a.begin(), a.end())) aq++;
a.clear();
for (int i = 0; i < 1000; ++i)
a.emplace_back(drand(re));
sorting::merge(a.begin(), a.end());
if (std::is_sorted(a.begin(), a.end())) m++;
a.clear();
for (int i = 0; i < 1000; ++i)
a.emplace_back(drand(re));
sorting::merge_async(a.begin(), a.end());
if (std::is_sorted(a.begin(), a.end())) am++;
a.clear();
for (int i = 0; i < 1000; ++i)
a.emplace_back(drand(re));
sorting::timsort(a.begin(), a.end());
if (std::is_sorted(a.begin(), a.end())) t++;
}
cout << "Async Quicksort: " << setw(4) << aq << " tests passed" << endl;
cout << "Quicksort: " << setw(4) << q << " tests passed" << endl;
cout << "Async Merge Sort: " << setw(4) << am << " tests passed" << endl;
cout << "Merge Sort: " << setw(4) << m << " tests passed" << endl;
cout << "Tim Sort: " << setw(4) << t << " tests passed" << endl;
cout << endl;
cout << "----------------- Demo -----------------" << endl;
cout << "Generating random array A with 20 integer values\n" << endl;
std::vector<int> A;
for (int i = 0; i < 20; ++i)
A.emplace_back(rand(re));
cout << " A = {";
for (auto a : A) {
cout << setw(3) << a;
}
cout << " }\n" << endl;
cout << "Async Quicksort: {";
auto B = A;
sorting::quicksort_async(B.begin(), B.end());
for (auto a : B) {
cout << setw(3) << a;
}
cout << " }\n" << endl;
cout << "Async Merge Sort: {";
B = A;
sorting::merge_async(B.begin(), B.end());
for (auto a : B) {
cout << setw(3) << a;
}
cout << " }\n" << endl;
cout << "Tim Sort: {";
B = A;
sorting::timsort(B.begin(), B.end());
for (auto a : B) {
cout << setw(3) << a;
}
cout << " }\n" << endl;
return 0;
} | true |
cbe6da21db90a65f7c061dfd4f79d3a5af5e64ab | C++ | SOSpacebar/DATA-ASSIGNEMNT-1 | /Assignment01_164108J_NgJingJie/Assignment01_164108J_NgJingJie/Weapon.h | UTF-8 | 266 | 2.609375 | 3 | [] | no_license | #ifndef WEAPON_H
#define WEAPON_H
#include "Item.h"
class Weapon : public Item
{
public:
Weapon(const string&, const int&, const int&);
virtual ~Weapon();
const int getAttackDmg();
void receiveDamage(const int&);
protected:
const int kAttackDmg;
};
#endif
| true |
16172a72e924efd80eba33a902bac86363696b93 | C++ | imulan/procon | /codeforces/gym/2015ICLFinals_Div1/g.cpp | UTF-8 | 1,098 | 2.515625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define rep(i,n) for(int i=0; i<(int)n; ++i)
#define all(x) (x).begin(),(x).end()
#define pb push_back
#define fi first
#define se second
ll cv(ll h, ll m, ll s)
{
return 1000000000000LL*h + 1000000LL*m + s;
}
void p(ll t)
{
ll a[3];
a[0] = t/1000000000000LL;
t -= 1000000000000LL*a[0];
a[1] = t/1000000LL;
t -= 1000000LL*a[1];
a[2] = t;
printf("%lld %lld %lld\n", a[0],a[1],a[2]);
}
int main()
{
int n;
scanf(" %d", &n);
vector<ll> t(n);
rep(i,n)
{
int h,m,s;
scanf(" %d %d %d", &h, &m, &s);
t[i] = cv(h,m,s);
}
sort(all(t));
ll mod = cv(12,0,0);
// printf("mod %lld\n", mod);
ll ans = 0;
for(int i=1; i<n; ++i)
{
ll d = t[0]+mod-t[i];
ans += d;
}
ll T = ans;
for(int i=1; i<n; ++i)
{
T -= mod+t[i-1]-t[i];
// printf("MINUS %lld\n", mod+t[i-1]-t[i]);
// p(T);
T += (n-1)*(t[i]-t[i-1]);
// p(T);
ans = min(ans, T);
}
p(ans);
}
| true |
b490abf68864314c4901d5d70030d84cc2328b34 | C++ | victor-armegioiu/Algo-stuff | /1213.cpp | UTF-8 | 947 | 2.640625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
const int N = 2000;
const int K = 15;
vector<int> primes;
int n, k;
int pos;
int dp[N][K][N];
inline void sieve()
{
vector<bool> is_prime(N, true);
int lim = sqrt(N);
for (int i = 2; i <= lim; i++)
{
if (is_prime[i])
{
for (int j = i * i; j <= N; j += i)
is_prime[j] = false;
}
}
for (int i = 2; i < N; i++)
if (is_prime[i]) primes.push_back(i);
}
inline int ways(int sum, int left, int curr)
{
if (left == 0)
{
if (sum == 0)
return 1;
return 0;
}
if (left < 0 || sum < 0 || primes[curr] > n)
return 0;
int &ans = dp[sum][left][curr];
if (ans != -1)
return ans;
ans = ways(sum - primes[curr], left - 1, curr + 1)
+ ways(sum, left, curr + 1);
return ans;
}
int main()
{
ios_base::sync_with_stdio(false);
sieve();
while (cin >> n >> k && !(n == 0 && k == 0))
{
memset(dp, -1, sizeof dp);
cout << ways(n, k, 0) << endl;
}
return 0;
} | true |
5d24461cd9090cb69b9dff52208a037d76e331a8 | C++ | lavinrp/NNComs | /Code/src/GameDataReader.cpp | UTF-8 | 13,170 | 2.515625 | 3 | [] | no_license | #include <sstream>
#include "ts3_functions.h"
#include "teamspeak/public_errors.h"
#include "plugin_definitions.h"
#include "GameDataReader.h"
#pragma region Constructors / destructor
/*
initializes GameDataReader values.TS functions must be passed to allow for initialization
of user
@param ts3Functions: pointer functions from the ts3 plugin SDK
@param serverConnectionHandlerID : id of the server the user is connected to*/
GameDataReader::GameDataReader(const TS3Functions ts3Functions, const uint64 serverConnectionHandlerID){
setConnectedStatus(false);
continueDataCollection = true;
this->ts3Functions = ts3Functions;
this->serverConnectionHandlerID = serverConnectionHandlerID;
pttLastValue = false;
}
/*Constructor for game data reader. server connection handler
defaults to 0 and must be set at a later time.
@param ts3Functions: pointer functions from the ts3 plugin SDK*/
GameDataReader::GameDataReader(const TS3Functions ts3Functions) : GameDataReader(ts3Functions, 1) {}
GameDataReader::~GameDataReader() {
//radio memory automatically freed
//player memory automatically freed
}
#pragma endregion
#pragma region Getters / setters
/*Returns true if a pipe has connected to the specified location.
Returns false otherwise*/
bool GameDataReader::isConnected() {
return connectedStatus;
}
/*setConnectedStatus
!!!!!!!PROTECTED FUNCTION!!!!!!!!
Thread safe way to set connectedStatus
@param status: set to true if the connected to a pipe
set to false otherwise*/
void GameDataReader::setConnectedStatus(bool status) {
//wait until the connected status can be modified
connectedStatusMutex.lock();
//set and unlock connectedStatus
connectedStatus = status;
connectedStatusMutex.unlock();
}
/*getPlayer
finds the player with the passed gameID
@param gameID: in game ID of the player to find
@return: Return a shared_ptr to the player with the passed gameID if one exists. Return null shared_ptr otherwise.*/
shared_ptr<Player> GameDataReader::getPlayer(GameID gameID) {
unordered_map<GameID, shared_ptr<Player>>::iterator playerIterator;
playerIterator = players.find(gameID);
if ( playerIterator != players.end() ) {
return playerIterator->second;
} else {
return shared_ptr<Player>();
}
}
/*getRadio
returns the requested radio
@param position: the position of the radio to return
@return: Pointer to the radio at the passed position in GameDataReaders radio vector. null shared_ptr if
the requested radio does not exist.*/
shared_ptr<Radio> GameDataReader::getRadio(unsigned int position) {
if (radios.size() > position) {
return radios[position];
} else {
return shared_ptr<Radio>();
}
}
/*setServerConnectionHandlerID
sets the serverConnectionHandlerID
@param serverConnectionHandlerID: new serverConnectionHandlerID*/
void GameDataReader::setServerConnectionHandlerID(const uint64 serverConnectionHandlerID) {
this->serverConnectionHandlerID = serverConnectionHandlerID;
}
/*getSelfGameID
returns the gameID of the selfClient*/
int GameDataReader::getSelfGameID() {
return selfGameID;
}
/*setPttStatus
Toggles the TS INPUT_ACTIVE property. Should be used to turn on self client microphone
in conjunction with in game radio broadcasts. Does nothing if value is set to previous value.
sets pttLastValue to the passed status.
@param status: true to toggle talking on. False to toggle talking off.*/
void GameDataReader::setPttStatus(bool status) {
if (status != pttLastValue) {
//get myID
anyID myID;
if (ts3Functions.getClientID(serverConnectionHandlerID, &myID) != ERROR_ok) {
//handle error
ts3Functions.logMessage("Error querying own client id", LogLevel_ERROR, "Plugin", serverConnectionHandlerID);
return;
}
//set players talking status to the passed value
unsigned int error;
bool shouldTalk;
shouldTalk = status;
if ((error = ts3Functions.setClientSelfVariableAsInt(myID, CLIENT_INPUT_DEACTIVATED,
shouldTalk ? INPUT_ACTIVE : INPUT_DEACTIVATED))
!= ERROR_ok) {
//handle error
char* errorMsg;
if (ts3Functions.getErrorMessage(error, &errorMsg) != ERROR_ok) {
ts3Functions.logMessage(errorMsg, LogLevel_ERROR, "Plugin", serverConnectionHandlerID);
ts3Functions.freeMemory(errorMsg);
}
return;
}
//update other users
if (ts3Functions.flushClientSelfUpdates(myID, NULL) != ERROR_ok) {
//handle error
char* errorMsg;
if (ts3Functions.getErrorMessage(error, &errorMsg) != ERROR_ok) {
ts3Functions.logMessage(errorMsg, LogLevel_ERROR, "Plugin", serverConnectionHandlerID);
ts3Functions.freeMemory(errorMsg);
}
}
pttLastValue = status;
}
}
/*Determines if the GameDataReader will continue to collect data
@param continueCollection: collection continues if true, stops if false*/
void GameDataReader::setContinueDataCollection(bool continueCollection) {
continueDataCollection = continueCollection;
}
/*Determines if the GameDataReader will continue to collect data.
@return: True if data collection should continue, false otherwise.*/
bool GameDataReader::getContinueDataCollection() {
return continueDataCollection;
}
#pragma endregion
#pragma region Member Functions
/*connectToPipe
connects pipeHandle to the pipe with a name defined by pipeName
@return: true if the connection is successful. Returns false otherwise.*/
bool GameDataReader::connectToPipe() {
while (true) {
//create file
pipeHandle = CreateFile(
pipeName,
GENERIC_READ,
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL,
OPEN_EXISTING,
0,
NULL);
//pipe found break connection loop
if (pipeHandle != INVALID_HANDLE_VALUE) {
break;
}
//unexpected pipe error
if (GetLastError() != ERROR_PIPE_BUSY) {
return false;
}
}
//If pipe is somehow still invalid throw error
if (pipeHandle == INVALID_HANDLE_VALUE) {
return false;
}
return true;
}
/*readFromPipe
Reads data from game pipe.
Stores game pipe data.
Only exits on bad read.*/
void GameDataReader::readFromPipe() {
//initialize this users in game ID and display in metadata
bool goodData = initializePlayer();
//continually read from pipe
while (goodData && continueDataCollection) {
//find the number of each type of voice source to read
VoiceSourceCounts voiceSourceCounts = readVoiceSourceCounts();
//read and create players and radios
gameDataMutex.lock();
bool radioSuccess = readRadios(voiceSourceCounts.radioCount);
bool playerSuccess = readPlayers(voiceSourceCounts.playerCount);
gameDataMutex.unlock();
goodData = radioSuccess && playerSuccess;
}
}
/*initializePlayer
Sets current users Teamspeak metadata to the value passed by
@return: true if data successfully set. False otherwise.
*/
bool GameDataReader::initializePlayer() {
//initialize pipe variables
double buffer[INIT_BUFFER_SIZE];
DWORD bytesRead = 0;
bool readResult = false;
readResult = ReadFile(
pipeHandle, //pipe
buffer, //Write location
sizeof(double), //number of bytes to read
&bytesRead, //bytes read
NULL); //Overlapped
//return on bad read
if (!readResult) {
return false;
}
selfGameID = buffer[0];
//set metadata to value read from pipe
ts3Functions.setClientSelfVariableAsInt(serverConnectionHandlerID, CLIENT_META_DATA, (int)buffer[0]);
ts3Functions.flushClientSelfUpdates(serverConnectionHandlerID, NULL);
selfGameID = (int)buffer[0];
////get myID
//anyID myID;
//if (ts3Functions.getClientID(serverConnectionHandlerID, &myID) != ERROR_ok) {
// ts3Functions.logMessage("Error querying own client id", LogLevel_ERROR, "Plugin", serverConnectionHandlerID);
//}
////USE THIS FOR DEBUG IF YOU NEED IT
//stringstream testOutput;
//testOutput << "Server ID is: " << serverConnectionHandlerID << " the player ID is: " << buffer[0];
//if (ts3Functions.requestSendPrivateTextMsg(serverConnectionHandlerID, testOutput.str().c_str(), myID, NULL) != ERROR_ok) {
// ts3Functions.logMessage("Error requesting send text message", LogLevel_ERROR, "Plugin", serverConnectionHandlerID);
//}
//good read. All data set.
return true;
}
/*readVoiceSourceCounts
reads data from the pipe to determine how many of each VoiceSource will be in the next read
@return: VoiceSourceCounts struct holding the number of each voiceSource that will
be in the next read*/
VoiceSourceCounts GameDataReader::readVoiceSourceCounts() {
//read enough values to fill VoiceSourceCounts
double buffer[VOICE_SOURCE_COUNT_BUFFER_SEIZE];
DWORD bytesRead = 0;
bool readResult = false;
while (!readResult) {
readResult = ReadFile(
pipeHandle, //pipe
buffer, //Write location
VOICE_SOURCE_COUNT_BUFFER_SEIZE * sizeof(double), //number of bytes to read
&bytesRead, //bytes read
NULL); //Overlapped
}
//Create and return a VoiceSourceCounts with the data from the pipe
VoiceSourceCounts voiceSourceCounts;
voiceSourceCounts.playerCount = (UINT64)buffer[0];
voiceSourceCounts.radioCount = (UINT64)buffer[1];
return voiceSourceCounts;
}
/*readRadio
reads the radios passed through the pipe.
@param radioCount the number of radios that is expected to be sent by the pipe
@return: true if all reads and operations successful. False otherwise. */
bool GameDataReader::readRadios(const INT64 radioCount) {
for (unsigned int i = 0; i < radioCount; i++) {
//read enough values to fill a radio
double buffer[DOUBLES_PER_RADIO];
DWORD bytesRead = 0;
bool readResult = false;
readResult = ReadFile(
pipeHandle, //pipe
buffer, //Write location
DOUBLES_PER_RADIO * sizeof(double), //number of bytes to read
&bytesRead, //bytes read
NULL); //Overlapped
//return with false on bad read
if (!readResult) {
return false;
}
//values from pipe
double xpos = buffer[0];
double ypos = buffer[1];
double zpos = buffer[2];
double voiceLevel = buffer[3];
double frequency = buffer[4];
double volume = buffer[5];
bool on = (bool)buffer[6];
bool broadcasting = (bool)buffer[7];
//update or create radio
shared_ptr<Radio> readRadio = getRadio(i);
if (readRadio) {
readRadio->setX(xpos);
readRadio->setY(ypos);
readRadio->setZ(zpos);
readRadio->setFrequency(frequency);
} else {
//create radio and store it
readRadio = make_shared<Radio>(xpos, ypos, zpos, frequency);
radios.push_back(readRadio);
}
readRadio->setVoiceLevel(voiceLevel);
readRadio->setVolume(volume);
readRadio->setOn(on);
readRadio->setBroadcasting(broadcasting);
}
//crop radios vector to fit new number of radios
if (radioCount < radios.size()) {
//erase radios at position radioCount to end
radios.erase(radios.begin() + radioCount, radios.end());
}
//return true if all reads and operations successful
return true;
}
/*readPlayers
reads the players pass through the pipe.
@param playerCount: number of players that is expected to be sent by the pipe
@return: true if successful with all reads. False otherwise.*/
bool GameDataReader::readPlayers(const INT64 playerCount) {
for (unsigned int i = 0; i < playerCount; i++) {
//read enough values to fill a player
double buffer[DOUBLES_PER_PLAYER];
DWORD bytesRead = 0;
bool readResult = false;
readResult = ReadFile(
pipeHandle, //pipe
buffer, //Write location
DOUBLES_PER_PLAYER * sizeof(double), //number of bytes to read
&bytesRead, //bytes read
NULL); //Overlapped
//return if bad read
if (!readResult) {
return false;
}
double xpos = buffer[0];
double ypos = buffer[1];
double zpos = buffer[2];
double voiceLevel = buffer[3];
unsigned int radioPosition = (unsigned int) buffer[4];
GameID gameID = (GameID)buffer[5];
//update or create player
shared_ptr<Player> readPlayer = getPlayer(gameID);
if (readPlayer) {
readPlayer->setX(xpos);
readPlayer->setY(ypos);
readPlayer->setZ(zpos);
} else {
//create and store player
readPlayer = make_shared<Player>(xpos, ypos, zpos);
players.emplace(gameID, readPlayer);
}
readPlayer->setVoiceLevel(voiceLevel);
shared_ptr<Radio> selectedRadio = getRadio(radioPosition);
readPlayer->setRadio(selectedRadio);
}
//Handel radio push to talk for self player
shared_ptr<Radio> selfPlayersRadio = players[selfGameID]->getRadio();
if (selfPlayersRadio) {
setPttStatus(selfPlayersRadio->isBroadcasting());
} else {
setPttStatus(false);
}
//return true if all reads good
return true;
}
/*collectGameData
Searches for and maintains connection to game pipe.
Stores data from game pipe.
Thread safe.*/
void GameDataReader::collectGameData() {
while (continueDataCollection) {
//Connect to the game pipe
//will go on indefinitely until connection is established or an error occurs
bool connection = connectToPipe();
setConnectedStatus(connection);
if (connection) {
//read from pipe until bad read
readFromPipe();
//set connectedStatus and begin connection process again after bad read
setConnectedStatus(false);
}
}
}
/*begin
starts thread in charge of pipe connection and reading*/
void GameDataReader::begin() {
thread readingThread(&GameDataReader::collectGameData, this);
readingThread.detach();
}
#pragma endregion | true |
43107b95e224e8554cb14eebe68530e315aae46e | C++ | dorOren/ElectionsProcess-CollegeProject-CPP | /Provinces.h | UTF-8 | 2,286 | 3.328125 | 3 | [] | no_license | #pragma once
#include "dynamicArrTemplate.h"
namespace elections {
class provinces {
private:
string name; //The name of the represented province
int provNum = 0; //holds the number of the represented province
float perecent = 0; //holds vote precentage in province specifically to the party that contain the class
int electorsSelected = 0; //number of selected electors to the party in this province
int voteNumbers = 0; //The number of votes for this party in this province
DynamicArray<int> memArr; //holds all the members of the party in this province
public:
provinces (string _name = "\0", int _provNum = 0); //constructor
~provinces() {} //destructor
provinces (const provinces& other) { *this = other; } //copy construct
//getters
const string get_name ()const { return name ; }
const int get_provNum ()const { return provNum ; }
const float get_perecent ()const { return perecent ; }
const int get_electorsSelected ()const { return electorsSelected ; }
const int get_voteNumbers ()const { return voteNumbers ; }
const int get_memPhySize ()const { return memArr.capacity(); }
const int get_memLogSize ()const { return memArr.size() ; }
const int get_memID (const int idx)const { return memArr[idx] ; }
//setters
void set_Name (const string _name);
void set_provNum (const int num);
void set_electorsSelected (const int val);
void add_elector (const int val);
void set_voteNumbers (const int votes);
void set_precet (const int provinceVotes);
void addToTail (const int _id);
void add_vote (const int val);
//operators
const provinces& operator=(const provinces& other);
//save & load
void save(ostream& out)const;
void load(istream& in);
};
}
| true |
c1c08dba6aa9f8a89aa07e4a0e455cd7ca73e415 | C++ | cedricplouvier/Highway-Racer | /CarGame2/SDLfact.cpp | UTF-8 | 1,458 | 2.796875 | 3 | [] | no_license | //
// Created by Cedric Plouvier on 2019-03-04.
//
#include <iostream>
#include "SDLfact.h"
using namespace std;
// Contructor that initialises the window and renderer for all our object to be visualized on
SDLfact::SDLfact() {
SDL_Init(SDL_INIT_VIDEO);
SDL_SetHint( SDL_HINT_RENDER_SCALE_QUALITY, "1" );
window = SDL_CreateWindow( "Best Cargame ever", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN );
renderer = SDL_CreateRenderer( window, -1, SDL_RENDERER_ACCELERATED );
}
// Destroy the window and the renderer only when the game gets quit
SDLfact::~SDLfact() {
SDL_DestroyWindow(window);
SDL_DestroyRenderer(renderer);
cout << "renderer and window destroyed" << endl;
}
SDLcar* SDLfact :: createCar(){
return new SDLcar(renderer);
}
SDLHighWay* SDLfact :: createHighWay(){
return new SDLHighWay(renderer);
}
SDLEnemyCar* SDLfact ::createEnemyCar() {
return new SDLEnemyCar(renderer);
}
SDLMenu* SDLfact :: createMenu(){
return new SDLMenu(renderer);
}
SDLPlayer* SDLfact :: createPlayer(){
return new SDLPlayer(renderer);
}
Bullet* SDLfact :: createBullet(){
return new SDLBullet(renderer);
}
EventHandler* SDLfact ::createEventHandler() {
return new SDLEventHandler();
}
PowerUpAmmo* SDLfact :: createPowerUpAmmo(){
return new SDLPowerUpAmmo(renderer);
}
PowerUpCoin* SDLfact ::createPowerUpCoin() {
return new SDLPowerUpCoin(renderer);
} | true |
25c44a337bad83fd178a2804e627918f0e154360 | C++ | dandycheung/dandy-twl | /TWL/include/util/findwnd.h | UTF-8 | 4,180 | 2.515625 | 3 | [] | no_license | #ifndef __FINDWINDOW_H__
#define __FINDWINDOW_H__
#define WFF_CLASSNAME 0x00000001
#define WFF_WINDOWNAME 0x00000002
#define WFF_MATCHMASK (WFF_CLASSNAME | WFF_WINDOWNAME)
#define WFF_SKIPCHILDREN 0x00000004
#define WFF_SKIPHIDDEN 0x00000008
#define WFF_SKIPDISABLED 0x00000010
#define WFF_FIRSTONLY 0x00000020
class CWindowFind
{
typedef CWindowFind thisClass;
LPCTSTR _pszClass;
LPCTSTR _pszName;
UINT _uFlags;
WNDENUMPROC _wep;
LPARAM _lParam;
HWND _hwndFind;
public:
CWindowFind()
{
_pszClass = NULL;
_pszName = NULL;
_uFlags = 0;
_wep = NULL;
_lParam = 0;
_hwndFind = NULL;
}
BOOL Find(LPCTSTR pszClass, LPCTSTR pszName, UINT uFlags)
{
_pszClass = pszClass;
_pszName = pszName;
_uFlags = uFlags;
_hwndFind = NULL;
BOOL bRet = EnumWindows(EnumWindowsProc, (LPARAM)this);
return bRet || (GetLastError() == ERROR_SUCCESS);
}
void SetWindowFindCallback(WNDENUMPROC wep, LPARAM lParam)
{
_wep = wep;
_lParam = lParam;
}
HWND GetFirstWindow() const
{
return _hwndFind;
}
protected:
#ifdef _WIN32_WCE
// Enumerate all children, this can be done via calling EnumChildWindows() on PC,
// but it's absent on Windows CE...
static
BOOL WINAPI EnumChildWindows(HWND hWndParent, WNDENUMPROC lpEnumFunc, LPARAM lParam)
{
if(!lpEnumFunc)
return TRUE;
BOOL bContinue = TRUE;
BOOL bRet;
HWND hwndChild = GetWindow(hWndParent, GW_CHILD);
while(hwndChild && bContinue)
{
bRet = lpEnumFunc(hwndChild, lParam);
bContinue = bRet || (GetLastError() == ERROR_SUCCESS);
if(!bContinue)
break;
if(GetWindow(hwndChild, GW_CHILD))
{
bRet = EnumChildWindows(hwndChild, lpEnumFunc, lParam);
bContinue = bRet || (GetLastError() == ERROR_SUCCESS);
if(!bContinue)
break;
}
hwndChild = GetWindow(hwndChild, GW_HWNDNEXT);
}
return bContinue;
}
#endif // _WIN32_WCE
static BOOL CALLBACK EnumWindowsProc(HWND hwnd, LPARAM lParam)
{
thisClass* pThis = (thisClass*)lParam;
if(!pThis)
{
SetLastError(ERROR_SUCCESS); // ERROR_INVALID_PARAMETER
return FALSE;
}
// we allow the callback is NULL if only the first matched window
// was requested. But, if you request all, and supply a NULL callback,
// we think you are wasting time...
if(!pThis->_wep && !(pThis->_uFlags & WFF_FIRSTONLY))
{
SetLastError(ERROR_SUCCESS); // ERROR_PROC_NOT_FOUND
return FALSE; // no callback, bail out
}
DWORD dwStyle = GetWindowLong(hwnd, GWL_STYLE);
if(!(dwStyle & WS_VISIBLE) && (pThis->_uFlags & WFF_SKIPHIDDEN))
return TRUE;
if(!IsWindowEnabled(hwnd) && (pThis->_uFlags & WFF_SKIPDISABLED))
return TRUE;
BOOL bClassMatched = TRUE;
BOOL bNameMatched = TRUE;
TCHAR szText[MAX_PATH];
if(pThis->_uFlags & WFF_CLASSNAME)
{
GetClassName(hwnd, szText, MAX_PATH);
bClassMatched = (lstrcmpi(szText, pThis->_pszClass) == 0);
}
if(pThis->_uFlags & WFF_WINDOWNAME)
{
GetWindowText(hwnd, szText, MAX_PATH);
bNameMatched = (lstrcmpi(szText, pThis->_pszClass) == 0);
}
BOOL bContinue = TRUE;
if(bClassMatched && bNameMatched)
{
if(pThis->_wep)
bContinue = (pThis->_wep)(hwnd, pThis->_lParam);
if(pThis->_uFlags & WFF_FIRSTONLY)
{
pThis->_hwndFind = hwnd;
SetLastError(ERROR_SUCCESS); // ERROR_CANCELLED
return FALSE;
}
}
if(!bContinue)
{
SetLastError(ERROR_SUCCESS); // ERROR_CANCELLED
return FALSE;
}
if(!(pThis->_uFlags & WFF_SKIPCHILDREN) && GetWindow(hwnd, GW_CHILD))
{
BOOL bRet = EnumChildWindows(hwnd, EnumWindowsProc, lParam);
bContinue = bRet || (GetLastError() == ERROR_SUCCESS);
}
return bContinue;
}
};
class CChildWindowFind : public CWindowFind
{
public:
BOOL Find(HWND hwndParent, LPCTSTR pszClass, LPCTSTR pszName, UINT uFlags)
{
if(!GetWindow(hwndParent, GW_CHILD))
return TRUE;
BOOL bRet = EnumChildWindows(hwndParent, EnumWindowsProc, (LPARAM)this);
return bRet || (GetLastError() == ERROR_SUCCESS);
}
};
#endif // __FINDWINDOW_H__
| true |
844dd0756a21d20f60a65391504fd1b0ea77ee6a | C++ | mmalenta/bitsnbobs | /paf/pafftw.cpp | UTF-8 | 2,057 | 2.6875 | 3 | [] | no_license | #include <chrono>
#include <fftw3.h>
#include <iostream>
#include <random>
#include <time.h>
using std::cout;
using std::endl;
#define UINS 1000000
#define NINS 1000
#define RUNS 50
void poweradd(fftw_complex *in, float* out, unsigned int size)
{
for (int ii = 0; ii < size / 2; ii++)
{
out[ii] = (in[ii][0] * in[ii][0] + in[ii][1] * in[ii][1]) + (in[ii+size/2][0] * in[ii+size/2][0] + in[ii+size/2][1] * in[ii+size/2][1]);
}
}
int main(int argc, char* argv[])
{
size_t elapsed;
struct timespec start, end;
unsigned int fftsize = 32;
unsigned int batchsize = 1152;
unsigned int timesamp = 2;
unsigned int fullsize = fftsize * batchsize * timesamp;
int sizes[1] = {(int)fftsize};
fftw_complex *inarray; //, *outarray;
inarray = (fftw_complex*)fftw_malloc(fullsize * sizeof(fftw_complex));
//outarray = (fftw_complex*)fftw_malloc(fullsize * sizeof(fftw_complex));
float *outarray = new float[fullsize / 2];
unsigned long seed = std::chrono::system_clock::now().time_since_epoch().count();
std::mt19937 arreng{seed};
std::normal_distribution<float> arrdis(0.0, 1.0);
for (int ii = 0; ii < fullsize; ii++) {
inarray[ii][0] = arrdis(arreng);
inarray[ii][1] = arrdis(arreng);
}
fftw_plan plan = fftw_plan_many_dft(1, sizes, batchsize * timesamp, inarray, NULL, 1, fftsize, inarray, NULL, 1, fftsize, FFTW_FORWARD, FFTW_MEASURE);
clock_gettime(CLOCK_MONOTONIC, &start);
for (int run = 0; run < RUNS; run++) {
fftw_execute(plan);
}
clock_gettime(CLOCK_MONOTONIC, &end);
elapsed = (end.tv_sec - start.tv_sec) * UINS / RUNS + (end.tv_nsec - start.tv_nsec) / NINS / RUNS;
cout << "FFT run took: " << elapsed << "\xC2\xB5s\n";
clock_gettime(CLOCK_MONOTONIC, &start);
for (int run = 0; run < RUNS; run++) {
poweradd(inarray, outarray, fullsize);
}
clock_gettime(CLOCK_MONOTONIC, &end);
elapsed = (end.tv_sec - start.tv_sec) * UINS / RUNS + (end.tv_nsec - start.tv_nsec) / NINS / RUNS;
cout << "Power/add run took: " << elapsed << "\xC2\xB5s\n";
fftw_destroy_plan(plan);
fftw_free(inarray);
return 0;
}
| true |
ee4ab93ac3ec4759e1e2cc7d1eb7b15201f42d6e | C++ | dovotori/Murmurations | /src/Camera.h | UTF-8 | 1,508 | 3.03125 | 3 | [] | no_license | #ifndef CAMERA_H
#define CAMERA_H
#include "ofMain.h"
class Camera
{
public:
Camera();
virtual ~Camera();
void setup();
void updateView();
void updateProjection();
void updateRotation();
inline void setPosition(float x, float y, float z){ this->position.set(x, y, z); this->updateView(); };
inline void setNearFar(float n, float f){ this->near = n; this->far = f; this->updateProjection(); };
inline void setTarget(float x, float y, float z){ this->target.set(x, y, z); };
inline void setAngle(float valeur){ this->angle = valeur; this->updateProjection(); };
inline void setAnglesRotation(float x, float y){ this->anglesRotation.set(x, y); this->updateRotation(); };
inline void setZoomRotation(float valeur){ this->zoomRotation = valeur; this->updateRotation(); };
inline ofMatrix4x4 getIdentityMatrix(){ return this->identity; }
inline ofMatrix4x4 getViewMatrix(){ return this->view; }
inline ofMatrix4x4 getProjectionMatrix(){ return this->projection; }
inline float getAngle(){ return this->angle; };
inline ofVec3f getPosition(){ return this->position; };
inline float getDistanceFocale(){ return this->near; };
protected:
private:
ofMatrix4x4 view, projection, identity;
ofVec3f position, target;
float angle, near, far;
ofVec2f anglesRotation;
float zoomRotation;
};
#endif // CAMERA_H
| true |
08c4f0d8ceed1e0c742dcfed00af89c068222102 | C++ | BorisVelichkov/fmi-se-oop-2021 | /01 Introduction to OOP and Classes/Solutions/Timestamp/Timestamp.cpp | UTF-8 | 2,049 | 3.90625 | 4 | [
"MIT"
] | permissive | #include <iostream>
#include "Timestamp.hpp"
Timestamp::Timestamp(const unsigned seconds)
: SECONDS_IN_HOUR(3600)
, SECONDS_IN_MINUTE(60)
//, hours(seconds / SECONDS_IN_HOUR)
{
this->hours = seconds / SECONDS_IN_HOUR;
unsigned remainingSeconds = seconds % SECONDS_IN_HOUR;
this->minutes = remainingSeconds / SECONDS_IN_MINUTE;
remainingSeconds %= SECONDS_IN_MINUTE;
this->seconds = remainingSeconds;
}
// void Timestamp::convertToTimestamp(const unsigned seconds)
// {
// const unsigned SECONDS_IN_HOUR = 3600;
// this->hours = seconds / SECONDS_IN_HOUR;
// unsigned remainingSeconds = seconds % SECONDS_IN_HOUR;
// const unsigned SECONDS_IN_MINUTE = 60;
// this->minutes = remainingSeconds / SECONDS_IN_MINUTE;
// remainingSeconds %= SECONDS_IN_MINUTE;
// this->seconds = remainingSeconds;
// }
void Timestamp::print() const
{
this->printHours();
this->printMinutes();
this->printSeconds();
}
void Timestamp::add(const Timestamp& other)
{
this->hours += other.hours;
this->minutes += other.minutes;
this->seconds += other.seconds;
}
unsigned Timestamp::convertToSeconds() const
{
unsigned seconds = 0;
const unsigned SECONDS_IN_HOUR = 3600;
seconds += this->hours * SECONDS_IN_HOUR;
const unsigned SECONDS_IN_MINUTE = 60;
seconds += this->minutes * SECONDS_IN_MINUTE;
seconds += this->seconds;
return seconds;
}
void Timestamp::printHours() const
{
if (this->hours < 10)
{
std::cout << "0" << this->hours;
}
else
{
std::cout << this->hours;
}
std::cout << ":";
}
void Timestamp::printMinutes() const
{
if (this->minutes < 10)
{
std::cout << "0" << this->minutes;
}
else
{
std::cout << this->minutes;
}
std::cout << ":";
}
void Timestamp::printSeconds() const
{
if (this->seconds < 10)
{
std::cout << "0" << this->seconds;
}
else
{
std::cout << this->seconds;
}
std::cout << std::endl;
} | true |
46efae7de4d8dc00c52e7b68f27ec25b8d67e844 | C++ | Brinews/jacky | /C/C-MAP/minesweep/minesweeper/bonus.h | UTF-8 | 1,913 | 2.796875 | 3 | [] | no_license | #include <string>
#include "minesweeper.h"
#ifndef bonus_H
#define bonus_H
class bonus : public minesweeper {
public:
bonus();
bonus(int col, int row, int numOfMines);
int saveGame(std::string path); //Save minesweeper object state to file
int loadGame(std::string path); //Load minesweeper object state from file
int saveStatistics(std::string path); //Save overall game statistics to file
int loadStatistics(std::string path); //Load overall game statistics from file
int getWins(); //Returns # of wins
void setWins(); //Modify # of wins
int getLoss(); //Returns # of losses
void setLoss(); //Modify # of losses
double getRatio(); //Returns Win/loss Ratio
int getWinStreak(); //Returns current Win Streak (consecutive wins)
void setWinStreak(); //Modifies current Win Streak # (consecutive wins)
int getLongestWinStreak(); //Returns longest Win Streak (largest win streak seen)
void setLongestWinStreak(); //Modifies longest Win Streak (largest win streak seen)
//void initialMineField(int fpX, int fpY); //Initialize game board given first revealed tile.
//Overrides minesweeper.initialMineField(fpX,fpY)
protected:
int wins; // # of total wins
int loss; // # of total losses
double ratio; // Win/Loss ratio
int winStreak; // Current win streak count
int longestWinStreak; // Longest win streak count
void calcRatio(); //Calculates Win/loss Ratio
};
#endif /* BONUS_H */
| true |
5837112d60cfecdd4e2eee72e0d0709d6bdc4ee7 | C++ | JohnataDavi/uri-online-judge | /solutions/1217.cpp | UTF-8 | 938 | 2.796875 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <iomanip>
#include <vector>
using namespace std;
int main()
{
int n;
float v, avg = 0, kg = 0;
string str;
char split_char = ' ';
vector<int> vI;
vector<float> vV;
cin >> n;
for (int i = 0; i < n; i++)
{
cin >> v;
avg += v;
getline(cin, str);
while (str.length() == 0)
getline(cin, str);
int count = 0;
istringstream split(str);
for (string each; getline(split, each, split_char); count++);
vI.push_back(count);
}
for (int i = 1; i <= vI.size(); i++)
{
cout << "day " << i << ": " << vI[i-1] << " kg" << endl;
kg += vI[i-1];
}
cout << fixed;
cout << setprecision(2);
cout << (float)(kg / n) << " kg by day" << endl;
cout << "R$ " << (float)(avg / n) << " by day" << endl;
return 0;
}
| true |
b4f89f6f3d2a2a52413fc2caa9e4759fcbd69f3c | C++ | ThimotheeV/GSpace | /tests/random_generator_test.cpp | UTF-8 | 2,627 | 3.0625 | 3 | [] | no_license | #define CATCH_CONFIG_MAIN
#include "catch.hpp"
#include <array>
#include "random_generator.hpp"
TEST_CASE("random_generator_test")
{
SECTION("construct_rand_gen_c")
{
rand_gen_c rand_gen;
rand_gen.put_seed(3);
REQUIRE(rand_gen.rand_bool() == 1);
REQUIRE(rand_gen.int_0_PRECISION_rand() == Approx(0.19576 * PRECISION).margin(0.00001 * PRECISION));
}
SECTION("rand_seed")
{
rand_gen_c rand_gen;
rand_gen.put_seed(3);
std::mt19937_64 rand(3);
REQUIRE(rand() == (rand_gen.Seed_gen)());
std::uniform_int_distribution distrib(0, 1000);
REQUIRE(distrib(rand) == distrib(rand_gen.Seed_gen));
rand_gen.put_seed(3);
rand.seed(3);
REQUIRE(distrib(rand) == distrib(rand_gen.Seed_gen));
}
SECTION("rand_seed_pointer")
{
rand_gen_c rand_gen;
rand_gen.put_seed(3);
auto rand_ptr = &rand_gen;
std::mt19937_64 rand(3);
REQUIRE(rand() == (rand_ptr->Seed_gen)());
std::uniform_int_distribution distrib(0, 1000);
REQUIRE(distrib(rand) == distrib(rand_ptr->Seed_gen));
rand_ptr->put_seed(3);
rand.seed(3);
REQUIRE(distrib(rand) == distrib(rand_ptr->Seed_gen));
}
SECTION("rand_bool")
{
rand_gen_c rand_gen;
rand_gen.put_seed(7);
std::array<int, 2> count = {0, 0};
for (int i = 0; i < 10000; ++i)
{
if (rand_gen.rand_bool())
{
++count.at(0);
}
else
{
++count.at(1);
}
}
REQUIRE(count.at(0) == Approx(5000).margin(50));
REQUIRE(count.at(1) == Approx(5000).margin(50));
}
SECTION("rand_nucl")
{
rand_gen_c rand_gen;
rand_gen.put_seed(7);
std::array<int, 4> count = {0, 0, 0, 0};
for (int i = 0; i < 100000; ++i)
{
switch (rand_gen.rand_nucl())
{
case 0:
++count.at(0);
break;
case 1:
++count.at(1);
break;
case 2:
++count.at(2);
break;
case 3:
++count.at(3);
break;
default:
break;
}
}
REQUIRE(count.at(0) == Approx(25000).margin(250));
REQUIRE(count.at(1) == Approx(25000).margin(250));
REQUIRE(count.at(2) == Approx(25000).margin(250));
REQUIRE(count.at(3) == Approx(25000).margin(250));
}
} | true |
df43102140046dec72a3367cb59e08cc92350c4a | C++ | sudoHub/Snake-Game-with-console-input-output | /main.cpp | UTF-8 | 3,541 | 3.265625 | 3 | [
"Unlicense"
] | permissive | /*
* File: main.cpp
* Author: Brandon West
*
* Created on November 26, 2017, 1:59 PM
* Purpose: Snake game. Player must eat the 'Z' or '8' without eating
* themselves.
*/
#include "Game.h"
#include "Snake.h"
#include "SaveScr.h"
#include <cstdlib>
#include <iostream>
#include <iomanip>
#include <vector>
#include <termios.h> // Terminal attributes
using namespace std;
//Function Prototype for input without pause
void stInput();
void outro(const Snake &ref);
int main(int argc, char** argv) {
char input;
bool gameOn = true;
int i = 0;
int num = 0;
cout << setw(10) << "Snake" << endl;
cout <<"Directions: \nYou must move the snake and eat either the standard " << endl
<< "token 'Z' for points, or eat '8' token for mega-points!" << endl;
cout << " For every token eaten your snake tail grows in length." << endl
<< " If you eat your tail, you Lose." << endl << endl;
cout << "Snake play Y/N" << endl;
cin >> input;
cout << "Enter number of players:" << endl;
cin >> num;
//Snake *user = {new Snake[num],new SaveScr[num]};
Snake *user = new Snake[num];
stInput(); //enable input
for(i = 0;i < num;i++)
{
while(gameOn)
{
user[i].sBoard(); //display board
user[i].input(); //check input buffer from player
user[i].logic(); //Game logic
cout << user[i]; //overload << and display score
gameOn = user[i].gmStop();//check win
}
//output result
cout << "\nThanks for playing" << endl;
cout << "Your final " << user[i] << endl;
if(num > 1)
{
//the way terminos removes the wait for input, if there is more
//than one player, I cannot get program to pause for enter.
//once rtInput() is called Program immediately goes to next
//game, this method was the longest I could get it to pause,
//and then run as expected.
gameOn = true;
cout << "Player " << i + 1 << " it's your turn!" << endl;
cout << "Press enter when ready" << endl;
int foo;
do
{
foo = getchar();
}while(foo != '\n' && foo != EOF);
}
}
SaveScr *print = new SaveScr[num];
int val = 0; //transfer score
for(i = 0;i < num;i++)
{
val = user[i].getScr();
print[i].setScr(val);
outro(user[i]);
outro(print[i]);
}
for(i = 0;i < num;i++)
{
//write score to bin
user[i].finWrte();
//delete objects
user[i].~Snake();
}
delete[] user;
delete[] print;
return 0;
}
/*Function Definition:
* Terminal interface for serial communication ports.
* Purpose: real-time input
*/
void stInput() {
struct termios t;
// Remove the wait for user input
fcntl(0, F_SETFL, fcntl(0, F_GETFL) | O_NONBLOCK);
// Remove the wait for a newline and echoing
tcgetattr(0, &t);
t.c_lflag &= ~ICANON;
t.c_lflag &= ~ECHO;
t.c_lflag &= ~NOFLSH;
tcsetattr(0, TCSANOW, &t);
}
void outro(const Snake &ref)
{
//example polymorphism
cout << "This is polymorphism for two different objects!" << endl;
cout << "Thank you for playing" << endl;
ref.disScr();
} | true |
265939b5f5003ca2b2e77908550513fb1d1b2e79 | C++ | ThomasKeil/Uhr | /src/handleinput.cpp | UTF-8 | 3,307 | 2.765625 | 3 | [] | no_license | #include <Arduino.h>
#include "Time.h"
#include "handleinput.h"
#include "displayinfos.h"
extern struct datum hochzeitstag;
extern unsigned int next_update;
void printCurrentTime() {
char current_time[40];
sprintf(current_time, "Bekannte Zeit: %02i.%02i.%04i %02i:%02i:%02i", day(), month(), year(), hour(), minute(), second());
Serial.println(current_time);
}
void handleInput() {
const uint16_t inputLength = 512;
if (Serial.available() > 0) {
static char input[inputLength];
static uint16_t i;
char c = Serial.read();
Serial.print(c);
if ( c != '\r' && c != '\n' && i < inputLength - 1) {
input[i++] = c;
} else {
input[i] = '\0';
i = 0;
handleInput_auswertung(input);
}
}
}
void handleInput_auswertung(char input[]) {
Serial.println();
if (!strncmp(input, "setdate", 7)) {
char delimiter[] = " .:";
char *ptr;
int dummy = 0, day = 0, month = 0, year = 0;
// initialisieren und ersten Abschnitt erstellen, den werfen wir gleich weg
ptr = strtok(input, delimiter);
// Serial.println(ptr);
ptr = strtok(NULL, delimiter);
while(ptr != NULL) {
// Serial.println(ptr);
dummy = atoi(ptr);
// Serial.printf("Found: %i\n", dummy);
if (day == 0) {
day = dummy;
} else if (month == 0) {
month = dummy;
} else if (year == 0) {
year = dummy;
setTime(hour(),minute(),second(),day,month,year);
time_is_present = 1;
// Serial.println("Date was set");
}
ptr = strtok(NULL, delimiter);
}
next_update = 0;
}
if (!strncmp(input, "help", 5)) {
Serial.println("help: Print this help");
Serial.println("hello: Say hi!");
Serial.println("currenttime: Prints the currently known time");
Serial.println("setdate DD.MM.YYYY");
Serial.println("clear: Clear the display.");
Serial.println("refresh: Refreshes the display");
Serial.println("drawverheiratetseit: Display the info \"Verheiratet seit\"");
Serial.println("ht X: Display info about Hochzeitstag 0-25" );
if (wifi_wlan) {
Serial.println("ip: Anzeige der IP-Addresse" );
}
Serial.println();
}
if ( !strncmp(input, "ip", 3) ) {
Serial.print("ip = ");
Serial.println(wifiip);
}
if ( !strncmp(input, "currenttime", 11) ) {
printCurrentTime();
}
if (!strncmp(input, "clear", 5)) {
clearDisplay();
}
if (!strncmp(input, "refresh", 7)) {
Serial.println("OK, reseting cyle");
next_update = 0;
}
if (!strncmp(input, "drawverheiratetseit", 19)) {
struct datum today = getNow();
struct periode elapsed = calculatePeriode(hochzeitstag, today);
screenVerheiratetSeit(elapsed);
}
if ( !strncmp(input, "hello", 5) ) {
Serial.println("hi");
}
if ( !strncmp(input, "ht", 2) ) {
char delimiter[] = " .:";
char *ptr;
int dummy = 0;
// initialisieren und ersten Abschnitt erstellen, den werfen wir gleich weg
ptr = strtok(input, delimiter);
// Serial.println(ptr);
ptr = strtok(NULL, delimiter);
while(ptr != NULL) {
// Serial.println(ptr);
dummy = atoi(ptr);
if (dummy >= 0 && dummy < 26) {
screenHochzeitstaginfo(dummy);
}
ptr = strtok(NULL, delimiter);
}
}
}
| true |
05cf2b2738c00f8020b046ff71071ffef3cad150 | C++ | SashiRin/protrode | /atcoder/abc102/B.cpp | UTF-8 | 371 | 2.859375 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <climits>
#include <algorithm>
using namespace std;
int main()
{
int n;
cin >> n;
int num_min = INT_MAX;
int num_max = INT_MIN;
int x;
for (int i = 0; i < n; ++i)
{
cin >> x;
num_min = min(num_min, x);
num_max = max(num_max, x);
}
cout << num_max - num_min << endl;
return 0;
}
| true |
631f36b7da0682234aa0a8f777213d2da423ddbd | C++ | hacchacc42/Platformer | /S2DPlatformer/S2DPlatformer/S2DPlatformer/Animation.cpp | UTF-8 | 686 | 3.0625 | 3 | [] | no_license | #include "Animation.h"
Animation::Animation(Texture2D* texture, float frameTime, bool isLooping)
: _texture(texture), _frameTime(frameTime), _isLooping(isLooping)
{
}
Animation::~Animation(void)
{
delete _texture;
}
const Texture2D* Animation::GetTexture() const
{
return _texture;
}
const float Animation::GetFrameTime() const
{
return _frameTime;
}
const bool Animation::IsLooping() const
{
return _isLooping;
}
const int Animation::GetFrameCount() const
{
return _texture->GetWidth() / _texture->GetHeight();
}
const int Animation::GetFrameWidth() const
{
return _texture->GetHeight();
}
const int Animation::GetFrameHeight() const
{
return _texture->GetHeight();
} | true |
3cce703f3032ef457ecabab8f582701e5d746335 | C++ | CJHMPower/Fetch_Leetcode | /data/Submission/145 Binary Tree Postorder Traversal/Binary Tree Postorder Traversal_1.cpp | UTF-8 | 1,219 | 3.140625 | 3 | [] | no_license | //-*- coding:utf-8 -*-
// Generated by the Fetch-Leetcode project on the Github
// https://github.com/CJHMPower/Fetch-Leetcode/
// 145 Binary Tree Postorder Traversal
// https://leetcode.com//problems/binary-tree-postorder-traversal/description/
// Fetched at 2018-07-24
// Submitted 2 years ago
// Runtime: 0 ms
// This solution defeats 100.0% cpp solutions
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> result;
stack<TreeNode*> Q;
if (root == nullptr) {
return result;
}
Q.push(root);
while (!Q.empty()) {
if (Q.top()->left == nullptr && Q.top()->right == nullptr) {
result.push_back(Q.top()->val);
Q.pop();
} else if (Q.top()->left != nullptr) {
TreeNode* temp = Q.top();
Q.push(temp->left);
temp->left = nullptr;
} else if (Q.top()->right != nullptr) {
TreeNode* temp = Q.top();
Q.push(temp->right);
temp->right = nullptr;
}
}
return result;
}
}; | true |
2c2c02ce32b07cb28262e8065eac984cd170af51 | C++ | liuslevis/leetcode | /Minimum Path Sum.cpp | UTF-8 | 1,244 | 2.890625 | 3 | [
"MIT"
] | permissive | // Redo!
// 30 min
// Recursive method TLE (but python okay)
// Iterative method 1WA 1AC
// Notice: DP speed up.
#include <iostream>
#include <vector>
#include <unordered_map>
#include <deque>
#include <assert.h>
#include <algorithm>
#include <locale>
using namespace std;
class Solution {
private:
int f(vector<vector<int>> grid) {
int m = grid.size();
int n = grid[0].size();
for (int j = 1; j < n; j++)
grid[0][j] += grid[0][j-1];
for (int i = 1; i < m; i++)
grid[i][0] += grid[i-1][0];
if (m==1) return grid[0][n-1];
if (n==1) return grid[m-1][0];
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
grid[i][j] += min(grid[i-1][j], grid[i][j-1]);
}
}
return grid[m-1][n-1];
}
public:
int minPathSum(vector<vector<int>>& grid) {
if (grid.size() < 0) return 0;
return f(grid);
}
};
void run() {
vector<vector<int> > v = {{0}};
vector<vector<int> > &rv = v;
Solution s;
s.minPathSum(rv);
}
int main(int argc, char const *argv[])
{
run();
return 0;
} | true |
d444bef0790a3e6e610222a705c11c7c6de723f4 | C++ | alexandru-dinu/competitive-programming | /leetcode/maximum_sum_circular_subarray.cpp | UTF-8 | 549 | 3.546875 | 4 | [
"MIT"
] | permissive | // https://leetcode.com/problems/maximum-sum-circular-subarray
class Solution
{
public:
int maxSubarraySumCircular(vector<int> &A)
{
int max_eh = 0, max_sf = INT_MIN;
int min_eh = 0, min_sf = INT_MAX;
int sum = 0;
for (int x : A) {
max_eh = max(x, max_eh + x);
max_sf = max(max_sf, max_eh);
min_eh = min(x, min_eh + x);
min_sf = min(min_sf, min_eh);
sum += x;
}
return max_sf > 0 ? max(max_sf, sum - min_sf) : max_sf;
}
}; | true |
77446fa3b3955f361119d782667a4e7766ee13b4 | C++ | skn123/jgt-code | /Volume_10/Number_3/Singh2005/IBar/Rn_Point3_i.H | UTF-8 | 2,409 | 3.171875 | 3 | [
"MIT"
] | permissive | // =========================================================
//
// Methods for R3PointTC template class
//
// =========================================================
// -------------------------------------
// constructors
// -------------------------------------
template<class Coord>
inline
R3PointTC<Coord>::R3PointTC ( const Coord& _x, const Coord& _y, const Coord& _z )
{
x = _x; y = _y; z = _z;
}
template<class Coord>
inline R3PointTC<Coord>::R3PointTC ( const Coord& _x )
{
x = y = z = _x;
}
template<class Coord>
R3PointTC<Coord>::R3PointTC ( const R3PointTC<Coord> & in_p )
{
x = in_p.x; y = in_p.y; z = in_p.z;
}
template<class Coord>
R3PointTC<Coord>::R3PointTC ( const R2PointTC<Coord> & in_p )
{
x = in_p[0]; y = in_p[1];
z = 1.0;
}
// -------------------------------------
// constructors
// -------------------------------------
template<class Coord>
inline R3PointTC<Coord>&
R3PointTC<Coord>::operator += ( const R3VectorTC<Coord>& vDelta )
{
x += vDelta[0];
y += vDelta[1];
z += vDelta[2];
return *this;
}
template<class Coord>
inline R3PointTC<Coord>&
R3PointTC<Coord>::operator -= (const R3VectorTC<Coord>& vDelta )
{
x -= vDelta[0];
y -= vDelta[1];
z -= vDelta[2];
return *this;
}
// -------------------------------------
// binary operators
// -------------------------------------
// -------------------------------------
// point dominance
// -------------------------------------
template<class Coord>
inline WINbool
R3PointTC<Coord>::operator < ( const R3PointTC<Coord>& p ) const
{
return (x < p.x && y < p.y && z < p.z) ? TRUE : FALSE;
}
template<class Coord>
inline WINbool
R3PointTC<Coord>::operator<= ( const R3PointTC<Coord>& p ) const
{
return (x <= p.x && y <= p.y && z <= p.z) ? TRUE : FALSE;
}
// -------------------------------------
// Read/write/print functions
// -------------------------------------
template<class Coord>
inline void R3PointTC<Coord>::Write(ofstream &out) const
{
out << x << " " << y << " " << z << " ";
}
template<class Coord>
inline WINbool R3PointTC<Coord>::Read(ifstream &in)
{
in >> x >> y >> z;
return in.good() ? TRUE : FALSE;
}
template<class Coord>
inline void R3PointTC<Coord>::Print( const WINbool in_bDoReturn ) const
{
TRACE("(%f, %f, %f)", x,y,z);
if ( in_bDoReturn == TRUE )
TRACE("\n");
else
TRACE("\n");
}
| true |
b2cf49813e4727310ae5bd292a003042cd251843 | C++ | ShabnamMRad/DataStructure | /cpp/LinkedList/src/LinkedList/LinkedList.cpp | UTF-8 | 2,071 | 3.59375 | 4 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include "LinkedList.hpp"
using namespace std;
LinkedList::LinkedList()
{
head = NULL;
tail = NULL;
size = 0;
};
int LinkedList::getSize()
{
return size;
};
void LinkedList::append(int data)
{
Node *n = new Node(data);
if ( head == NULL)
{
head = n;
tail = n;
}
else
{
tail->next = n;
tail = n;
}
size++;
};
void LinkedList::prepend(int data)
{
Node *n = new Node(data);
if ( head == NULL )
{
head = n;
tail = n;
}
else
{
Node *temp = head;
head = n;
n->next = temp;
}
size++;
};
void LinkedList::tostring()
{
Node *temp = head;
while ( temp != NULL)
{
std::cout<< temp->data << " ";
temp = temp->next;
}
std::cout<<std::endl;
};
void LinkedList::removefirst()
{
if ( head != NULL )
{
Node *temp = head;
head = head->next;
delete temp;
size--;
}
};
void LinkedList::removelast()
{
if( head->next == NULL )
removefirst();
else if ( head != NULL )
{
Node *cur = head;
Node *prev;
while ( cur->next != NULL )
{
prev = cur;
cur = cur->next;
}
tail = prev;
prev->next = NULL;
delete cur;
size--;
}
};
void LinkedList::removeat(int pos)
{
if( pos > size || pos < 1 )
return;
else if ( pos == 1 )
removefirst();
else if ( pos == size )
removelast();
else if ( head != NULL )
{
Node *cur = head;
Node *prev;
for( int i = 1; i < pos; i++ )
{
prev = cur;
cur = cur->next;
}
prev->next = cur->next;
delete cur;
size--;
}
};
void LinkedList::insertat(int pos, int data)
{
if( pos > size + 1 || pos < 1 )
return;
else if ( pos == 1 )
prepend(data);
else if ( pos == size + 1 )
append(data);
else if ( head != NULL )
{
Node *cur = head;
Node *prev;
for( int i = 1; i < pos; i++ )
{
prev = cur;
cur = cur->next;
}
Node *n = new Node(data);
prev->next = n;
n->next = cur;
size++;
}
};
LinkedList::~LinkedList()
{
Node *next;
while( head != NULL )
{
next = head->next;
delete head;
head = next;
}
};
| true |
74e508392598517cc4cdc49f52724d9308543e52 | C++ | goby/150-problems | /04_01.cpp | UTF-8 | 410 | 3.125 | 3 | [] | no_license | #include <vector>
typedef struct _Node Node;
struct _Node{
int data;
std::vector<Node*> children;
};
int length = 0;
bool is_balance(Node * tree, int high) {
if(tree->children.size() > 0) {
for(int i = 0; i <tree->children.size(); i++) {
if(!is_balance(tree->children.at(i), high+1))
return false;
}
} else if (length == 0) {
length = high;
}
return length == high;
}
| true |
67bcab4f85d6cdd9cff37e400d1e900e00b21b15 | C++ | janfas/Techniki-programowania | /Lista 3/Zadanie 1/main.cpp | UTF-8 | 662 | 3.625 | 4 | [] | no_license | #include <iostream>
#include <vector>
bool match(const std::string& pattern, const std::string& s)
{
if(pattern == s)
return true;
else
return false;
}
int main()
{
std::cout << "Program sprawdzajacy, czy lancuch znakow pasuje do wzorca:" << std::endl;
std::string wzorzec, lancuch;
std::cout << "Podaj wzorzec:" << std::endl;
std::cin >> wzorzec;
std::cout << std::endl;
std::cout << "Podaj lancuch znakow:" << std::endl;
std::cin >> lancuch;
std::cout << std::endl;
if(match(wzorzec, lancuch) == true)
std::cout << "Lancuch pasuje do wzorca." << std::endl;
else
std::cout << "Lancuch nie pasuje do wzorca" << std::endl;
}
| true |
5412af914726b8f29c10cceafa99827d64e33365 | C++ | ibrahimovshamil/AVL-Tree | /AVLTree.cpp | UTF-8 | 3,260 | 3.109375 | 3 | [] | no_license |
#include "AVLTree.h"
#include<iostream>
#include<cstdio>
#include<sstream>
#include<algorithm>
#include <ctime>
#define pow2(n) (1 << (n))
using namespace std;
AVLTree::AVLTree()
{
}
AVLTree::~AVLTree()
{
}
AVLTree::AVLTree(const AVLTree & tree)
{
copyTree(tree.root, root);
}
void AVLTree::copyTree(AVLTreeNode *treePtr, AVLTreeNode *& newTreePtr) const {
if (treePtr != NULL) { // copy node
newTreePtr = new AVLTreeNode(treePtr->item, NULL, NULL);
copyTree(treePtr->leftChildPtr, newTreePtr->leftChildPtr);
copyTree(treePtr->rightChildPtr, newTreePtr->rightChildPtr);
}
else
newTreePtr = NULL; // copy empty tree
}
void AVLTree::insert(int val)
{
insert(val, root);
}
// this part of the code is ispired from the https://users.cs.fiu.edu/~weiss/dsaajava/code/DataStructures/AvlTree.java
AVLTreeNode* AVLTree::insert(const int &val , AVLTreeNode *&treePtr)// throw(TreeException)
{
int a = 5;
int b=4;
if (treePtr == NULL){
treePtr = new AVLTreeNode(val, NULL, NULL);
}
else if (treePtr != NULL && (treePtr->item) > val) //
{
//cout<<"asdas"<<endl;
treePtr->leftChildPtr = insert(val, treePtr->leftChildPtr);
if (calcHeight(treePtr->leftChildPtr) - calcHeight(treePtr->rightChildPtr) > 1)
if (val - (treePtr->leftChildPtr->item) < 0)
treePtr = right(treePtr); //
else
treePtr = leftRight(treePtr); //
}
else if (treePtr != NULL && val > (treePtr->item)) //val > (treePtr->item) val > (treePtr->item)
{ //cout<< "e"<< endl;
treePtr->rightChildPtr = insert(val, treePtr->rightChildPtr);
if (calcHeight(treePtr->rightChildPtr) - calcHeight(treePtr->leftChildPtr) > 1)
if (val - (treePtr->rightChildPtr->item) > 0)
treePtr = left(treePtr); //treePtr = left(treePtr);
else
treePtr = rightLeft(treePtr); //;
}
return treePtr;
}
AVLTreeNode* AVLTree::right(AVLTreeNode *& node)
{
AVLTreeNode* temp;
temp= node->leftChildPtr;
node->leftChildPtr = temp->rightChildPtr;
temp->rightChildPtr = node;
return temp;
}
AVLTreeNode* AVLTree::left(AVLTreeNode *& node)
{
AVLTreeNode* temp;
temp= node->rightChildPtr;
node->rightChildPtr = temp->leftChildPtr;
temp->leftChildPtr = node;
return temp;
}
AVLTreeNode* AVLTree::rightLeft(AVLTreeNode *& node)
{
node->rightChildPtr = right(node->rightChildPtr);
return left(node);
}
AVLTreeNode* AVLTree::leftRight(AVLTreeNode *& parent)
{
parent->leftChildPtr = left(parent->leftChildPtr);
return right(parent);
}
int AVLTree::getHeight()
{
if (root == NULL)
{
return -1;
}
else return calcHeight(root);
}
int AVLTree::calcHeight(AVLTreeNode* node)
{
int height = 0;
if (node != NULL)
{
int max_height = std::max(calcHeight(node->leftChildPtr), calcHeight(node->rightChildPtr));
height = max_height + 1;
}
return height;
}
int AVLTree::heightD(AVLTreeNode *temp)
{
int a = calcHeight(temp->leftChildPtr) - calcHeight(temp->rightChildPtr);
return a;
}
void AVLTree::printInorder(AVLTreeNode* tree)
{
if (tree == NULL)
return;
printInorder(tree->leftChildPtr);
cout << tree->item << " ";
printInorder(tree->rightChildPtr);
}
| true |
17a07190439c78f254d4998f1535bea7dae7ebeb | C++ | 260058433/libnet | /src/EventLoop.cc | UTF-8 | 755 | 2.578125 | 3 | [] | no_license | #include "EventLoop.h"
#include "Channel.h"
#include "Poller.h"
#include "EpollPoller.h"
namespace libnet
{
EventLoop::EventLoop() :
quit_(false),
activeChannels_(),
poller_(new EpollPoller(this))
{
}
EventLoop::~EventLoop()
{
}
const int kPollTimeMs = 1000;
void EventLoop::loop()
{
while (!quit_)
{
activeChannels_.clear();
poller_->poll(kPollTimeMs, activeChannels_);
for (auto p = activeChannels_.begin(); p != activeChannels_.end(); ++p)
(*p)->handleEvent();
}
}
void EventLoop::updateChannel(Channel *channel)
{
poller_->updateChannel(channel);
}
void EventLoop::addChannel(Channel *channel)
{
poller_->addChannel(channel);
}
void EventLoop::quit()
{
quit_ = true;
}
}
| true |
f288a34a9e3c9bd18aeaad3b195e24a31a0fcc79 | C++ | JosephCHS/Arcade | /src/games/lib_arcade_solarfox/src/Game.cpp | UTF-8 | 15,113 | 2.59375 | 3 | [
"MIT"
] | permissive | /*
** EPITECH PROJECT, 2018
** Game.cpp
** File description:
** Game Class
*/
#include <fstream>
#include <iostream>
#include <sstream>
#include "Game.hpp"
Game::~Game()
{
clear_all();
}
void Game::fill_vector()
{
int nbr = -1;
_pos_block.push_back({160, 120});
_pos_block.push_back({160, 160});
_pos_block.push_back({160, 200});
_pos_block.push_back({160, 240});
_pos_block.push_back({160, 280});
_pos_block.push_back({160, 320});
_pos_block.push_back({120, 280});
_pos_block.push_back({200, 280});
_pos_block.push_back({240, 280});
_pos_block.push_back({280, 280});
_pos_block.push_back({280, 320});
_pos_block.push_back({320, 280});
_pos_block.push_back({280, 240});
_pos_block.push_back({280, 200});
_pos_block.push_back({280, 160});
_pos_block.push_back({280, 120});
while (++nbr != 16) {
_print_block.push_back(true);
}
}
void Game::clear_all()
{
_pos_block.clear();
_print_block.clear();
_middle = nullptr;
_wall = nullptr;
_space = nullptr;
_shot = nullptr;
_block = nullptr;
_eshot = nullptr;
_espace = nullptr;
_clock = nullptr;
_key = nullptr;
_art = nullptr;
_score = nullptr;
_lost = false;
}
void Game::init(SPIFactory factory, SPIWindow window)
{
this->_factory = factory;
this->_window = window;
if (factory == nullptr || window == nullptr) {
clear_all();
return;
}
_score_nbr = 0;
Vector2<int> pos = {0, 0};
std::string middle_string = "# #";
std::string wall_string = "# # # # # # # # # # # # # # # # # # # # # #";
this->_score = factory->createText("Score : 0", {0, 480}, "./games/assets_solarfox/font.ttf", *window);
this->_wall = factory->createSprite("./games/assets_solarfox/wall.png", pos, wall_string, *window);
this->_art = factory->createSprite("./games/assets_solarfox/solar_fox-art.jpg", {480, 0}, "//SOLAR FOX\\", *window);
this->_middle = factory->createSprite("./games/assets_solarfox/middle.png", pos, middle_string, *window);
this->_space = factory->createSprite("./games/assets_solarfox/space.png", {40, 40}, "[]", *window);
this->_space->setRect({0, 0, 40, 40});
this->_shot = factory->createSprite("./games/assets_solarfox/shot.png", {120, 120}, "**", *window);
this->_block = factory->createSprite("./games/assets_solarfox/block.png", pos, "/\\", *window);
fill_vector();
this->_espace = factory->createSprite("./games/assets_solarfox/espace.png", pos, "@", *window);
this->_espace->setRect({0, 0, 40, 40});
this->_eshot = factory->createSprite("./games/assets_solarfox/eshot.png", pos, "<>", *window);
this->_clock = factory->createClock();
this->_key = factory->createText("UP:Z DOWN:S LEFT:Q RIGHT:D A:Boost E:Shoot", {0, 600}, "./games/assets_solarfox/font.ttf", *window);
_lost = false;
_move = DOWN;
return;
}
void Game::show_block()
{
auto pos_it = _pos_block.begin();
auto print_it = _print_block.begin();
int nbr = 0;
while (pos_it != _pos_block.end()) {
if (*print_it == true) {
_block->setPosition(*pos_it);
nbr++;
_window->show(*_block);
}
pos_it++;
print_it++;
}
if (nbr == 0) {
_lost = true;
}
}
Vector2<int> Game::swap_vector2(Vector2<int> to_swap)
{
int copy = to_swap.x;
to_swap.x = to_swap.y;
to_swap.y = copy;
return to_swap;
}
void Game::move_enemy()
{
long int move;
if (_pos_left_enemy.x >= 400 && _pos_right_enemy.y <= 40 && _backward == false) {
_default_left = {400, 0};
_default_right = {440, 40};
less_time_move = _clock->getTime() * -1 / 1250;
_backward = true;
}
if (_pos_left_enemy.x <= 40 && _pos_right_enemy.y >= 400 && _backward == true) {
less_time_move = _clock->getTime() * -1 / 1250;
_default_left = {40, 0};
_default_right = {440, 400};
_backward = false;
}
move = ((_clock->getTime() / 1250) + less_time_move) * -1;
if (_backward == false) {
_pos_left_enemy.x = _default_left.x + move;
_pos_right_enemy.y = _default_right.y - move;
} else if (_backward == true) {
_pos_left_enemy.x = _default_left.x - move;
_pos_right_enemy.y = _default_right.y + move;
}
return;
}
void Game::show_enemy()
{
_espace->setRect({0, 0, 40, 40});
_espace->setPosition(_pos_left_enemy);
_pos_left_enemy = swap_vector2(_pos_left_enemy);
_window->show(*_espace);
_espace->setRect({80, 0, 40, 40});
_espace->setPosition(_pos_left_enemy);
_window->show(*_espace);
_pos_left_enemy = swap_vector2(_pos_left_enemy);
_espace->setRect({40, 0, 40, 40});
_espace->setPosition(_pos_right_enemy);
_pos_right_enemy = swap_vector2(_pos_right_enemy);
_window->show(*_espace);
_espace->setRect({120, 0, 40, 40});
_espace->setPosition(_pos_right_enemy);
_window->show(*_espace);
_pos_right_enemy = swap_vector2(_pos_right_enemy);
}
void Game::print_map()
{
int nbr = -1;
Vector2<int> pos = {0, 0};
_wall->setPosition(pos);
_window->show(*_wall);
while (++nbr != 10) {
pos.y += 40;
_middle->setPosition(pos);
_window->show(*_middle);
}
pos.y += 40;
_wall->setPosition(pos);
_window->show(*_wall);
return;
}
void Game::shot_space()
{
static long int last = _clock->getTime() / 1250 * -1;
long int advance = _clock->getTime() / 1250 * -1;
static Vector2<int> pos_shot;
static bool shot = false;
static int nbr = 0;
static Move direction;
if (_event == E_CASE && shot == false) {
shot = true;
pos_shot = _space->getPosition();
direction = _move;
}
if (shot == true) {
switch (direction)
{
case UP:
pos_shot.y -= advance - last + 8;
break;
case RIGHT:
pos_shot.x += advance - last + 8;
break;
case LEFT:
pos_shot.x -= advance - last + 8;
break;
default:
pos_shot.y += advance - last + 8;
break;
}
nbr += advance - last + 8;
_shot->setPosition(pos_shot);
_window->show(*_shot);
}
if (nbr >= 80) {
nbr = 0;
shot = false;
}
last = advance;
}
void Game::move_player()
{
long int advance = 0;
static long int last = _clock->getTime() / 1250 * -1;
switch (_event)
{
case Z_CASE:
if (_move != DOWN && _move != UP) {
_move = UP;
_space->setRect({80, 0, 40, 40});
}
break;
case Q_CASE:
if (_move != RIGHT && _move != LEFT) {
_move = LEFT;
_space->setRect({40, 0, 40, 40});
}
break;
case S_CASE:
if (_move != UP && _move != DOWN) {
_move = DOWN;
_space->setRect({0, 0, 40, 40});
}
break;
case D_CASE:
if (_move != LEFT && _move != RIGHT) {
_move = RIGHT;
_space->setRect({120, 0, 40, 40});
}
break;
case A_CASE:
if (_boost == 4) {
_boost = 1;
} else {
_boost = 4;
}
break;
default:
break;
}
advance = _clock->getTime() / 1250 * -1;
switch (_move)
{
case DOWN:
pos_player.y += (advance - last + _boost);
break;
case UP:
pos_player.y -= (advance - last + _boost);
break;
case RIGHT:
pos_player.x += (advance - last + _boost);
break;
case LEFT:
pos_player.x -= (advance - last + _boost);
break;
}
last = advance;
_space->setPosition(pos_player);
}
void Game::shot_next_enemy()
{
static long int last = _clock->getTime() / 1250 * -1;
long int advance = _clock->getTime() / 1250 * -1;
_shot_next_enemy += advance - last;
if (_shot_next_enemy > 100) {
_shot_bool.shot_3 = true;
_shot_bool.shot_4 = true;
_show_next_enemy = true;
_shot_next_enemy = 0;
pos_shot_next_enemy = _pos_right_enemy;
}
if (_show_next_enemy == true) {
pos_shot_next_enemy.x -= advance - last + 2;
if (_shot_bool.shot_3 == true) {
_eshot->setPosition(pos_shot_next_enemy);
_shot_bool.shot_3_pos = pos_shot_next_enemy;
_window->show(*_eshot);
} else {
_shot_bool.shot_3_pos = {440, 400};
}
if (_shot_bool.shot_4 == true) {
pos_shot_next_enemy = swap_vector2(pos_shot_next_enemy);
_eshot->setPosition(pos_shot_next_enemy);
_window->show(*_eshot);
_shot_bool.shot_4_pos = pos_shot_next_enemy;
pos_shot_next_enemy = swap_vector2(pos_shot_next_enemy);
} else {
_shot_bool.shot_4_pos = {400, 440};
}
}
if (pos_shot_next_enemy.x <= 200) {
_show_next_enemy = false;
_shot_bool.shot_3 = false;
_shot_bool.shot_4 = false;
_shot_bool.shot_3_pos = {440, 400};
_shot_bool.shot_4_pos = {400, 440};
}
last = advance;
}
void Game::shot_enemy()
{
static long int last = _clock->getTime() / 1250 * -1;
long int advance = _clock->getTime() / 1250 * -1;
_shot_enemy += advance - last;
if (_shot_enemy > 100) {
_shot_bool.shot_1 = true;
_shot_bool.shot_2 = true;
_show_enemy = true;
_shot_enemy = 0;
pos_shot_enemy = _pos_left_enemy;
}
if (_show_enemy == true) {
pos_shot_enemy.y += advance - last + 2;
if (_shot_bool.shot_1 == true) {
_eshot->setPosition(pos_shot_enemy);
_shot_bool.shot_1_pos = pos_shot_enemy;
_window->show(*_eshot);
} else {
_shot_bool.shot_1_pos = {40, 0};
}
if (_shot_bool.shot_2 == true) {
pos_shot_enemy = swap_vector2(pos_shot_enemy);
_eshot->setPosition(pos_shot_enemy);
_window->show(*_eshot);
_shot_bool.shot_2_pos = pos_shot_enemy;
pos_shot_enemy = swap_vector2(pos_shot_enemy);
} else {
_shot_bool.shot_2_pos = {0, 40};
}
}
if (pos_shot_enemy.y >= 250) {
_shot_bool.shot_1 = false;
_shot_bool.shot_2 = false;
_shot_bool.shot_1_pos = {40, 0};
_shot_bool.shot_2_pos = {0, 40};
_show_enemy = false;
}
last = advance;
shot_next_enemy();
}
void Game::check_block_colision()
{
auto pos_it = _pos_block.begin();
auto print_it = _print_block.begin();
Vector2<int> block;
Vector2<int> space = _space->getPosition();
Vector2<int> shot = _shot->getPosition();
while (pos_it != _pos_block.end()) {
block = *pos_it;
if (space.x + 10 < block.x + 40
&& space.x + 30 > block.x
&& space.y + 10 < block.y + 40
&& 30 + space.y > block.y) {
*print_it = false;
}
if (shot.x + 10 < block.x + 40
&& shot.x + 30 > block.x
&& shot.y + 10 < block.y + 40
&& 30 + shot.y > block.y) {
*print_it = false;
}
pos_it++;
print_it++;
}
}
void Game::show_score()
{
static long int last = _clock->getTime() / 1250 * -1;
long int advance = _clock->getTime() / 1250 * -1;
auto print_it = _print_block.begin();
int score = 0;
std::string score_string = "Score : ";
time_less += (advance - last) / 100;
while (print_it != _print_block.end()) {
if (*print_it == false) {
score += 500;
}
print_it++;
}
_score_nbr = score - time_less;
if (_score_nbr < 0) {
_score_nbr = 0;
}
score_string += std::to_string(_score_nbr);
_score->setText(score_string);
_window->show(*_score);
}
int Game::run(EventCase e)
{
_event = e;
print_map();
check_block_colision();
show_block();
move_enemy();
show_enemy();
shot_enemy();
move_player();
shot_space();
check_shot();
_window->show(*_space);
_window->show(*_art);
_window->show(*_key);
show_score();
return _score_nbr;
}
void Game::reset()
{
_space->setPosition({40, 40});
_space->setRect({0, 0, 40, 40});
_shot->setPosition({0, 0});
_eshot->setPosition({0, 0});
_espace->setPosition({0, 40});
_pos_block.clear();
_print_block.clear();
pos_player = {40, 40};
_show_next_enemy = false;
_show_enemy = false;
_boost = 1;
fill_vector();
less_time_move = _clock->getTime() * -1 / 1250;
_pos_left_enemy = {40, 0};
_pos_right_enemy = {440, 400};
pos_shot_enemy = {0, 0};
pos_shot_next_enemy = {0, 0};
_shot_bool.prep_shot();
_shot_bool.reset_pos();
_default_left = {40, 0};
_default_right = {440, 400};
_backward = false;
_move = DOWN;
_score->setText("Score : 0");
_lost = false;
_score_nbr = 0;
_shot_enemy = 0;
_shot_next_enemy = 0;
time_less = 0;
}
static bool check_shot_collision(Vector2<int> pos, Vector2<int> space_pos)
{
if (space_pos.x + 10 < pos.x + 40
&& space_pos.x + 30 > pos.x
&& space_pos.y + 10 < pos.y + 40
&& 30 + space_pos.y > pos.y) {
return true;
}
return false;
}
static bool check_shot_to_shot_collision(Vector2<int> pos, Vector2<int> space_pos)
{
if (space_pos.x + 10 < pos.x + 40
&& space_pos.x + 30 > pos.x
&& space_pos.y + 10 < pos.y + 40
&& 30 + space_pos.y > pos.y) {
return false;
}
return true;
}
void Game::check_shot()
{
Vector2<int> space_pos = _space->getPosition();
if (_shot_bool.shot_1 == true) {
_shot_bool.shot_1 = check_shot_to_shot_collision(_shot_bool.shot_1_pos, _shot->getPosition());
}
if (_shot_bool.shot_2 == true) {
_shot_bool.shot_2 = check_shot_to_shot_collision(_shot_bool.shot_2_pos, _shot->getPosition());
}
if (_shot_bool.shot_3 == true) {
_shot_bool.shot_3 = check_shot_to_shot_collision(_shot_bool.shot_3_pos, _shot->getPosition());
}
if (_shot_bool.shot_4 == true) {
_shot_bool.shot_4 = check_shot_to_shot_collision(_shot_bool.shot_4_pos, _shot->getPosition());
}
if (check_shot_collision(_shot_bool.shot_1_pos, space_pos)
|| check_shot_collision(_shot_bool.shot_2_pos, space_pos)
|| check_shot_collision(_shot_bool.shot_3_pos, space_pos)
|| check_shot_collision(_shot_bool.shot_4_pos, space_pos))
_lost = true;
}
bool Game::gameOver() const
{
Vector2<int> space_pos = _space->getPosition();
if (space_pos.x <= 30 || space_pos.x >= 405
|| space_pos.y <= 30 || space_pos.y >= 405) {
return true;
}
return _lost;
}
| true |
6e130b0e89d575635f69a0cef7102134118adde6 | C++ | DeadNight/robotics | /hw4/MapSearchable.h | UTF-8 | 1,696 | 2.90625 | 3 | [] | no_license | /*
* MapSearchable.h
*
* Created on: May 4, 2016
* Author: Nir Leibovitch 200315232
* Author: Ron Naor 021615356
* Author: Shay Kremer 201588126
*/
#ifndef MAPSEARCHABLE_H_
#define MAPSEARCHABLE_H_
#include <vector>
#include "Map.h"
#include "Position.h"
#include "Location.h"
#include "State.h"
#include "Color.h"
class MapSearchable {
std::vector<unsigned char> grid;
Map map;
Position start;
Location goal;
State startState;
State goalState;
public:
MapSearchable() { }
MapSearchable(Map map, Position start, Location goal);
Map getMap() const;
void setMap(Map map);
float getGridResolution() const;
float getMapResolution() const;
State& getStartState();
const State& getStartState() const;
State& getGoalState();
const State& getGoalState() const;
bool isGoal(const State& state) const;
// return the air distance
double airDistance(const Location& l1, const Location& l2) const;
// return states of all position moves from a position in the maze
std::vector<State*> getAllPossibleStates(const State& state);
unsigned getWidth() const;
unsigned getHeight() const;
std::vector<unsigned char> getGrid() const;
void smooth(Size robotSize);
void save(const char* mapFilePath) const;
Image toImage() const;
void colorPixel(std::vector<unsigned char>& image, double x, double y, unsigned pixelSize, Color color);
unsigned char operator[](std::size_t i);
const unsigned char operator[](std::size_t i) const;
double operator()(Location l) const;
double operator()(unsigned x, unsigned y) const;
friend std::ostream& operator<<(std::ostream& out, const MapSearchable& searchable);
};
#endif /* MAPSEARCHABLE_H_ */
| true |
9542c4ca165c9941e32676a8d4365bc118cb4027 | C++ | alexandraback/datacollection | /solutions_2749486_0/C++/syash/b1c.cpp | UTF-8 | 687 | 2.765625 | 3 | [] | no_license | #include <stdlib.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <string>
using namespace std;
void main() {
ifstream in;
ofstream out;
out.open("out.txt");
in.open("input.txt");
int T;
int x,y;
int j;
in >> T;
for (int i=0; i<T; i++)
{
in >> x >> y;
out << "Case #" << i+1 << ": ";
if (x>0)
{
for (j=0;j<x;j++)
out << "WE";
}
else
{
for (j=x;j<0;j++)
out << "EW";
}
if (y>0)
{
for (j=0;j<y;j++)
out << "SN";
}
else
{
for (j=y;j<0;j++)
out << "NS";
}
out << endl;
}
in.close();
out.close();
}
| true |
1c1d54939a7c3c7409f240a988ee31fa696e2490 | C++ | anflorea/mondlyQuiz | /src/actions/ActionCreator.cpp | UTF-8 | 4,161 | 2.71875 | 3 | [] | no_license | #include "ActionCreator.h"
#include <QQmlContext>
#include "ServiceProvider.h"
#include "Response.h"
#include "RequestService.h"
ActionCreator::ActionCreator(IDispatcher *dispatcher,
IServiceProvider *serviceProvider,
QObject *parent)
: QObject(parent)
{
m_dispatcher = dispatcher;
m_requestService = serviceProvider->getRequestService();
m_authService = serviceProvider->getAuthService();
m_generalService = serviceProvider->getGeneralService();
}
void ActionCreator::login(QString username, QString password)
{
qDebug() << Q_FUNC_INFO << username << " -- " << password;
m_dispatcher->dispatch(Action(ActionType::AuthStarted));
auto success = [&](QString token, QString username) {
m_requestService->setAccessToken(token);
m_dispatcher->dispatch(Action(ActionType::GotUsername, username));
m_dispatcher->dispatch(Action(ActionType::AuthSuccess, token));
connectToEventStream();
};
auto fail = [&](Response* response) {
m_dispatcher->dispatch(Action(ActionType::AuthError));
};
m_authService->signIn(username, password, success, fail);
}
void ActionCreator::logout()
{
qDebug() << Q_FUNC_INFO;
m_dispatcher->dispatch(Action(ActionType::LogoutSuccess));
m_requestService->setAccessToken("");
}
void ActionCreator::getLobbys()
{
qDebug() << Q_FUNC_INFO;
m_dispatcher->dispatch(Action(ActionType::GetLobbysStarted));
auto success = [&](Json::Value response) {
m_dispatcher->dispatch(Action(ActionType::GetLobbysSuccess, response));
};
auto fail = [&](Response* response) {
m_dispatcher->dispatch(Action(ActionType::GetLobbysError, response->bodyAsJson()));
};
m_generalService->getLobbys(success, fail);
}
void ActionCreator::connectToEventStream()
{
qDebug() << Q_FUNC_INFO;
auto success = [&]() {
};
auto fail = [&]() {
};
auto gotEvent = [&](Json::Value event) {
m_dispatcher->dispatch(Action(ActionType::GotEvent, event));
};
m_authService->connectToEventStream(success, gotEvent, fail);
}
void ActionCreator::createLobby()
{
qDebug() << Q_FUNC_INFO;
auto success = [&](Json::Value lobby) {
m_dispatcher->dispatch(Action(ActionType::CreateLobbySuccess, lobby));
};
auto fail = [&](Response* response) {
Q_UNUSED(response)
m_dispatcher->dispatch(Action(ActionType::CreateLobbyFail));
};
m_generalService->createLobby(success, fail);
}
void ActionCreator::joinLobby(QString lobbyId)
{
qDebug() << Q_FUNC_INFO;
auto success = [&](QString id) {
m_dispatcher->dispatch(Action(ActionType::JoinLobbySuccess, id));
};
auto fail = [&](Response* response) {
Q_UNUSED(response)
m_dispatcher->dispatch(Action(ActionType::JoinLobbyFail));
};
m_generalService->joinLobby(lobbyId, success, fail);
}
void ActionCreator::leaveLobby()
{
qDebug() << Q_FUNC_INFO;
auto success = [&]() {
m_dispatcher->dispatch(Action(ActionType::LeaveLobbySuccess));
};
auto fail = [&](Response* response) {
Q_UNUSED(response)
m_dispatcher->dispatch(Action(ActionType::LeaveLobbyFail));
};
m_generalService->leaveLobby(success, fail);
}
void ActionCreator::startGame()
{
auto success = [&](Json::Value) {
};
auto fail = [&](Response*) {
};
m_generalService->startGame(success, fail);
}
void ActionCreator::answerQuestion(QString questionId, QString answerId)
{
qDebug() << "Answer question: " << questionId << " " << answerId;
auto success = [&](Json::Value data) {
bool ok = data.get("ok", false).asBool();
if (ok) {
m_dispatcher->dispatch(Action(ActionType::AnswerQuestionSuccess));
} else {
m_dispatcher->dispatch(Action(ActionType::AnswerQuestionFail));
}
};
auto fail = [&](Response*) {
};
m_generalService->answerQuestion(questionId, answerId, success, fail);
}
void ActionCreator::returnToLobby()
{
m_dispatcher->dispatch(Action(ActionType::ReturnToLobby));
}
| true |
4660e0d48872519cf6e06ecca7e29f36c7ca8a1b | C++ | winkadd/Jottings_C-C- | /Project3.15/Project3.15/game.cpp | GB18030 | 2,417 | 3.421875 | 3 | [] | no_license | #define _CRT_SECURE_NO_WARNINGS
#include "game.h"
void InitBoard(char board[ROW][COL], int row, int col)
{
int i = 0;
int j = 0;
for ( i = 0; i < row; i++)
{
for (j = 0; j < row; j++)
{
board[i][j] = ' ';
}
}
}
void DisplayBoart(char board[ROW][COL], int row, int col)
{
int i = 0;
for ( i = 0; i < row; i++)
{
//1,ӡһе
/*printf(" %c | %C | %c \n",board[i][0],board[i][1],board[i][2]);*/
int j = 0;
for ( j = 0; j < col; j++)
{
printf(" %c ",board[i][j]);
if (j<col-1)
printf("|");
}
printf("\n");
//2.ӡָ
if (i < row - 1)
{
for ( j = 0; j <col; j++)
{
printf("---");
if (j<col-1)
printf("|");
}
printf("\n");
}
}
}
void playerMove(char board[ROW][COL], int row, int col)
{
int x, y = 0;
printf("ߣ>\n");
while (1)
{
printf("Ҫߵ:>");
scanf("%d%d", &x, &y);
//жĺϷ
if (x >= 1 && x <= row &&y >= 1 && y <= col)
{
if (board[x-1][y-1] == ' ')
{
board[x - 1][y - 1] = '*';
break;
}
else
{
printf("걻ռ\n");
}
}
else
{
printf("Ƿ룡\n");
}
}
}
void ComputerMove(char board[ROW][COL], int row, int col)
{
int x,y = 0;
printf("ߣ>\n");
x = rand() % row;
y = rand() % col;
while (1)
{
if (board[x][y] == ' ')
{
board[x][y] = '#';
break;
}
}
}
//1ʾ
//0ʾ
int IsFull(char board[ROW][COL], int row, int col)
{
int i, j = 0;
for ( i = 0; i < row; i++)
{
for (j = 0; j < row; j++)
{
if (board[i][j] == ' ')
{
return 0;//û
}
}
}
return 1;//
}
char IsWin(char board[ROW][COL], int row, int col)
{
int i = 0;
//
for ( i = 0; i <row ; i++)
{
if (board[i][0] == board[i][1] && board[i][1] == board[i][2] && board[i][1] != ' ')
{
return board[i][1];
}
}
//
for ( i = 0; i <col; i++)
{
if (board[0][i] == board[1][i] && board[1][i] == board[2][i] && board[1][i] != ' ')
{
return board[1][i];
}
}
//Խ
if (board[0][0] == board[1][1] && board[1][1]==board[2][2]&&board[1][1]!=' ')
return board[1][1];
if (board[2][0] == board[1][1] && board[1][1] == board[0][2] && board[1][1] != ' ')
return board[1][1];
//жǷƽ
if (1==IsFull(board,ROW,COL))
{
return'Q';
}
return'C';
} | true |
333a1f794687cf6eeec03b3f04f86068d7bbc33a | C++ | AdamPI314/Algorithm | /src/82_longest_common_prefix/solution.cpp | UTF-8 | 1,531 | 3 | 3 | [] | no_license | #include <iostream>
#include <utility>
#include <vector>
#include <list>
#include <set>
#include <unordered_set>
#include <unordered_map>
#include <map>
#include <queue>
#include <stack>
#include <forward_list>
#include <algorithm>
#include <climits>
#include <string>
#include <cstring>
#include <cstdlib>
#include <numeric>
#include <functional>
#include <iterator>
#include "../../include/fileIO/fileIO.h"
#include "../../include/dataStructure/dataStructure.h"
#include "../../include/misc/misc.h"
using namespace std;
class Solution
{
public:
/*
* @param strs: A list of strings
* @return: The longest common prefix
*/
string longestCommonPrefix(vector<string> &strs)
{
std::string result;
if (strs.size() == 0)
return result;
// write your code here
// n is the shortest string length
int n = INT_MAX;
for (auto x : strs)
{
if (x.size() < n)
n = x.size();
}
if (n == 0)
return result;
for (int i = 0; i < n; ++i)
{
for (int j = 1; j < strs.size(); ++j)
{
if (strs[j][i] != strs[j - 1][i])
if (i >= 1)
return strs[0].substr(0, i);
else
return std::string("");
}
}
return strs[0].substr(0, n);
}
};
int main(int argc, char **argv)
{
// initialization, data preparation
std::vector<std::string> strs = {"ABCD", "ABEF", "ACEF"};
// my solution
Solution sln;
// correct answer
auto x = sln.longestCommonPrefix(strs);
return EXIT_SUCCESS;
} | true |
5df301100f1859d2e18e0d51480015d9aa53fcba | C++ | BarryChenZ/Leetcode1 | /P197_RisingTemperature.cpp | UTF-8 | 174 | 2.625 | 3 | [] | no_license | # Write your MySQL query statement below
select w1.Id as Id
from Weather as w1,Weather as w2
where w1.RecordDate=AddDate(w2.RecordDate,1) and w1.Temperature>w2.Temperature
| true |
50bc99dd2d27ada2276331a911b698bce387ea8b | C++ | ajstacher/CST136SRS02 | /CST136SRS02/Waka/paddle.h | UTF-8 | 389 | 2.65625 | 3 | [] | no_license | #pragma once
#include "propulsion.h"
class Paddle final : public Propulsion
{
public:
Paddle();
//using Propulsion::getSpeed; <-- do I need this?
void setSpeed(const int current); //overload from base class
void setStrength(int n);
private:
int do_getSpeed() const override;
void do_setSpeed(int n) noexcept override;
//paddle strength, speed multiplier
int strength;
};
| true |
8722522d2c7a6b18afad2ffaf753ad90b5f8922a | C++ | splucs/Competitive-Programming | /Codeforces/Gym/101072 Brazilian Open Cup 2016, UFBA/G.cpp | UTF-8 | 760 | 2.65625 | 3 | [] | no_license | #include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
#define MAXN (1<<19)
double dp[MAXN];
int vet[20], N;
double DP(int mask){
if (dp[mask] >= 0.0) return dp[mask];
double ans = 0, aux;
int n = 0, nleft, nright;
for(int i=0; i<N; i++){
if ((mask & (1<<i)) > 0) continue;
n++;
nleft = 0;
nright = 0;
for(int j=0; j<N; j++){
if ((mask & (1<<j)) == 0) continue;
if (vet[i] > vet[j]) nleft++;
if (vet[i] < vet[j]) nright++;
}
aux = min(nleft, nright) + DP(mask | (1<<i));
ans += aux;
}
if (n > 0) ans /= n;
else ans = 0;
dp[mask] = ans;
return ans;
}
int main(){
scanf("%d", &N);
for(int i=0; i<N; i++){
scanf("%d", vet+i);
}
memset(dp, -1.0, sizeof dp);
printf("%.11f\n", DP(0));
return 0;
} | true |
6df35694337c0fad245f5ba0134a6680c588d8f5 | C++ | codgician/Competitive-Programming | /Codeforces-Gym/101908F/dp.cpp | UTF-8 | 2,919 | 2.53125 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <string>
#include <cstring>
#include <iomanip>
#include <climits>
#include <stack>
#include <queue>
#include <vector>
#include <set>
#include <map>
#include <functional>
#include <iterator>
using namespace std;
#define TIME_SIZE 2010
#define STAGE_SIZE 1024
#define SHOW_SIZE 1010
typedef struct _Show
{
int startPt, endPt;
int val, stage;
bool operator < (const struct _Show & snd) const
{
return startPt < snd.startPt;
}
} Show;
Show showArr[SHOW_SIZE];
int showPt;
int dp[TIME_SIZE][STAGE_SIZE], maxArr[STAGE_SIZE];
int dscArr[TIME_SIZE], dscPt;
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int stageNum;
while (cin >> stageNum)
{
dscPt = 0, showPt = 0;
for (int i = 0; i < stageNum; i++)
{
int cntNum;
cin >> cntNum;
for (int j = 0; j < cntNum; j++)
{
int startPt, endPt, val;
cin >> startPt >> endPt >> val;
showArr[showPt++] = {startPt, endPt, val, i};
dscArr[dscPt++] = startPt;
dscArr[dscPt++] = endPt;
}
}
sort(dscArr + 0, dscArr + dscPt);
dscPt = unique(dscArr + 0, dscArr + dscPt) - dscArr;
for (int i = 0; i < showPt; i++)
{
showArr[i].startPt = lower_bound(dscArr + 0, dscArr + dscPt, showArr[i].startPt) - dscArr + 1;
showArr[i].endPt = lower_bound(dscArr + 0, dscArr + dscPt, showArr[i].endPt) - dscArr + 1;
}
sort(showArr + 0, showArr + showPt);
for (int i = 0; i <= dscPt; i++)
for (int j = 0; j < (1 << stageNum); j++)
dp[i][j] = INT_MIN;
for (int i = 0; i < (1 << stageNum); i++)
maxArr[i] = INT_MIN;
dp[0][0] = 0;
maxArr[0] = 0;
for (int i = 0; i <= dscPt; i++)
{
for (int j = 0; j < (1 << stageNum); j++)
{
dp[i][j] = max(maxArr[j], dp[i][j]);
maxArr[j] = dp[i][j];
if (maxArr[j] == INT_MIN)
continue;
int pos = lower_bound(showArr + 0, showArr + showPt, Show{i}) - showArr;
// Update all values with the same startPt
for (int k = pos; k < showPt && showArr[k].startPt == showArr[pos].startPt; k++)
{
int nextPt = showArr[k].endPt;
int nextState = j | (1 << showArr[k].stage);
dp[nextPt][nextState] = max(dp[nextPt][nextState], dp[i][j] + showArr[k].val);
}
}
}
if (maxArr[(1 << stageNum) - 1] == INT_MIN)
cout << -1 << endl;
else
cout << maxArr[(1 << stageNum) - 1] << endl;
}
return 0;
} | true |
65f767620d4ad3fc75a174ad7ab13bf47bf77454 | C++ | carlschiller/highway | /highway/cppfiles/car.cpp | UTF-8 | 18,919 | 2.90625 | 3 | [
"MIT"
] | permissive | //
// Created by Carl Schiller on 2019-03-04.
//
#include "../headers/car.h"
#include <map>
#include <cmath>
#include <list>
#include <iostream>
#include "../headers/util.h"
////////////////////////////////////////////////////////////////////////////////
/// Constructor.
Car::Car() :
m_speed(0),
m_aggressiveness(0),
m_target_speed(0),
m_min_dist_to_car_in_front(0),
m_min_overtake_dist_trigger(0),
m_max_overtake_dist_trigger(0),
m_overtake_done_dist(0),
m_merge_min_dist(0),
m_search_radius_around(0),
m_search_radius_to_car_in_front(0),
current_segment(nullptr),
current_node(nullptr),
overtake_this_car(nullptr)
{
}
////////////////////////////////////////////////////////////////////////////////
/// Constructor for new car with specified lane numbering in spawn point.
/// Lane numbering @param lane must not exceed amount of lanes in
/// @param spawn_point, otherwise an exception will be thrown.
Car::Car(RoadSegment * spawn_point, int lane, float vel, float target_speed, float agressivness,
float m_min_dist_to_car_in_front, float m_min_overtake_dist_trigger, float m_max_overtake_dist_trigger,
float m_overtake_done_dist, float m_merge_min_dist, float m_search_radius_around,
float m_search_radius_to_car_in_front) :
m_speed(vel),
m_aggressiveness(agressivness),
m_target_speed(target_speed),
m_min_dist_to_car_in_front(m_min_dist_to_car_in_front),
m_min_overtake_dist_trigger(m_min_overtake_dist_trigger),
m_max_overtake_dist_trigger(m_max_overtake_dist_trigger),
m_overtake_done_dist(m_overtake_done_dist),
m_merge_min_dist(m_merge_min_dist),
m_search_radius_around(m_search_radius_around),
m_search_radius_to_car_in_front(m_search_radius_to_car_in_front),
current_segment(spawn_point),
current_node(current_segment->get_node_pointer(lane)),
overtake_this_car(nullptr)
{
current_segment->append_car(this);
if(!current_node->get_nodes_from_me().empty()){
heading_to_node = current_node->get_next_node(lane);
m_dist_to_next_node = Util::distance(current_node->get_x(),heading_to_node->get_x(),current_node->get_y(),heading_to_node->get_y());
m_theta = current_node->get_theta(heading_to_node);
}
else{
throw std::invalid_argument("Car spawns in node with empty connections, or with a nullptr segment");
}
}
////////////////////////////////////////////////////////////////////////////////
/// Constructor for new car with specified lane. Note that
/// @param lane must be in @param spawn_point, otherwise no guarantee on
/// functionality.
Car::Car(RoadSegment * spawn_point, RoadNode * lane, float vel, float target_speed, float agressivness,
float m_min_dist_to_car_in_front, float m_min_overtake_dist_trigger, float m_max_overtake_dist_trigger,
float m_overtake_done_dist, float m_merge_min_dist, float m_search_radius_around,
float m_search_radius_to_car_in_front):
m_speed(vel),
m_aggressiveness(agressivness),
m_target_speed(target_speed),
m_min_dist_to_car_in_front(m_min_dist_to_car_in_front),
m_min_overtake_dist_trigger(m_min_overtake_dist_trigger),
m_max_overtake_dist_trigger(m_max_overtake_dist_trigger),
m_overtake_done_dist(m_overtake_done_dist),
m_merge_min_dist(m_merge_min_dist),
m_search_radius_around(m_search_radius_around),
m_search_radius_to_car_in_front(m_search_radius_to_car_in_front),
current_segment(spawn_point),
current_node(lane),
overtake_this_car(nullptr)
{
current_segment->append_car(this);
if(!current_node->get_nodes_from_me().empty() || current_segment->next_segment() != nullptr){
heading_to_node = current_node->get_next_node(0);
m_dist_to_next_node = Util::distance(current_node->get_x(),heading_to_node->get_x(),current_node->get_y(),heading_to_node->get_y());
m_theta = current_node->get_theta(heading_to_node);
}
else{
throw std::invalid_argument("Car spawns in node with empty connections, or with a nullptr segment");
}
}
////////////////////////////////////////////////////////////////////////////////
/// Destructor for car.
Car::~Car(){
if(this->current_segment != nullptr){
this->current_segment->remove_car(this); // remove this pointer shit
}
overtake_this_car = nullptr;
current_segment = nullptr;
heading_to_node = nullptr;
current_node = nullptr;
}
////////////////////////////////////////////////////////////////////////////////
/// Updates position for car with time step @param delta_t.
void Car::update_pos(float delta_t) {
m_dist_to_next_node -= m_speed*delta_t;
// if we are at a new node.
if(m_dist_to_next_node < 0){
current_segment->remove_car(this); // remove car from this segment
current_segment = heading_to_node->get_parent_segment(); // set new segment
if(current_segment != nullptr){
current_segment->append_car(this); // add car to new segment
if(current_segment->meter){
current_segment->car_passed = true;
}
}
current_node = heading_to_node; // set new current node as previous one.
//TODO: place logic for choosing next node
std::vector<RoadNode*> connections = current_node->get_nodes_from_me();
if(!connections.empty()){
merge(connections);
m_dist_to_next_node += Util::distance(current_node->get_x(),heading_to_node->get_x(),current_node->get_y(),heading_to_node->get_y());
m_theta = current_node->get_theta(heading_to_node);
}
}
}
////////////////////////////////////////////////////////////////////////////////
/// Function to determine if we can merge into another lane depending on.
/// properties of @param connections.
void Car::merge(std::vector<RoadNode*> & connections) {
// check if we merge
int current_lane = current_segment->get_lane_number(current_node);
bool can_merge = true;
std::map<Car*,bool> cars_around_car = find_cars_around_car();
Car * closest_car = find_closest_car_ahead();
for(auto it : cars_around_car){
float delta_dist = Util::distance_to_car(it.first,this);
float delta_speed = abs(speed()-it.first->speed());
if(current_lane == 0 && it.first->heading_to_node->get_parent_segment()->get_lane_number(it.first->heading_to_node) == 1 ){
can_merge =
delta_dist > std::max(delta_speed*4.0f/m_aggressiveness,m_merge_min_dist);
}
else if(current_lane == 1 && it.first->heading_to_node->get_parent_segment()->get_lane_number(it.first->heading_to_node) == 0){
can_merge =
delta_dist > std::max(delta_speed*4.0f/m_aggressiveness,m_merge_min_dist);
}
if(!can_merge){
break;
}
}
if(current_segment->merge){
if(current_lane == 0 && connections[0]->get_parent_segment()->get_total_amount_of_lanes() != 2){
if(can_merge){
heading_to_node = connections[1];
}
else{
heading_to_node = connections[0];
}
}
else if(connections[0]->get_parent_segment()->get_total_amount_of_lanes() == 2){
current_lane = std::max(current_lane-1,0);
heading_to_node = connections[current_lane];
}
else{
heading_to_node = connections[current_lane];
}
}
// if we are in start section
else if(current_segment->get_total_amount_of_lanes() == 3){
if(connections.size() == 1){
heading_to_node = connections[0];
}
else{
heading_to_node = connections[current_lane];
}
}
// if we are in middle section
else if(current_segment->get_total_amount_of_lanes() == 2){
// normal way
if(connections[0]->get_parent_segment()->get_total_amount_of_lanes() == 2){
// check if we want to overtake car in front
do_we_want_to_overtake(closest_car,current_lane);
// commited to overtaking
if(overtake_this_car != nullptr){
if(current_lane != 1){
if(can_merge){
heading_to_node = connections[1];
}
else{
heading_to_node = connections[current_lane];
}
}
else{
heading_to_node = connections[current_lane];
}
}
// merge back if overtake this car is nullptr.
else{
if(can_merge){
heading_to_node = connections[0];
}
else{
heading_to_node = connections[current_lane];
}
}
}
else{
heading_to_node = connections[0];
}
}
else if(current_segment->get_total_amount_of_lanes() == 1){
heading_to_node = connections[0];
}
}
////////////////////////////////////////////////////////////////////////////////
/// Helper function to determine if this car wants to overtake
/// @param closest_car.
void Car::do_we_want_to_overtake(Car * & closest_car, int & current_lane) {
//see if we want to overtake car.
if(closest_car != nullptr){
//float delta_speed = closest_car->speed()-speed();
float delta_distance = Util::distance_to_car(this,closest_car);
if(overtake_this_car == nullptr){
if(delta_distance > m_min_overtake_dist_trigger && delta_distance < m_max_overtake_dist_trigger && (target_speed()/closest_car->target_speed() > m_aggressiveness*1.0f ) && current_lane == 0 && closest_car->current_node->get_parent_segment()->get_lane_number(closest_car->current_node) == 0){
overtake_this_car = closest_car;
}
}
}
if(overtake_this_car !=nullptr){
if(Util::is_car_behind(overtake_this_car,this) && (Util::distance_to_car(this,overtake_this_car) > m_overtake_done_dist)){
overtake_this_car = nullptr;
}
}
}
////////////////////////////////////////////////////////////////////////////////
/// Function to accelerate this car.
void Car::accelerate(float elapsed){
float target = m_target_speed;
float d_vel; // proportional control.
if(m_speed < target*0.75){
d_vel = m_aggressiveness*elapsed*2.0f;
}
else{
d_vel = m_aggressiveness*(target-m_speed)*4*elapsed*2.0f;
}
m_speed += d_vel;
}
////////////////////////////////////////////////////////////////////////////////
/// Helper function to avoid collision with another car.
void Car::avoid_collision(float delta_t) {
float min_distance = m_min_dist_to_car_in_front; // for car distance.
float ideal = min_distance+min_distance*(m_speed/20.f);
Car * closest_car = find_closest_car_ahead();
float detection_distance = m_speed*5.0f;
if(closest_car != nullptr) {
float radius_to_car = Util::distance_to_car(this, closest_car);
float delta_speed = closest_car->speed() - this->speed();
if (radius_to_car < ideal && delta_speed < 0 && radius_to_car > min_distance) {
m_speed -= std::max(std::max((radius_to_car-min_distance)*0.5f,0.0f),10.0f*delta_t);
}
else if(radius_to_car < min_distance){
m_speed -= std::max(std::max((min_distance-radius_to_car)*0.5f,0.0f),2.0f*delta_t);
}
else if(delta_speed < 0 && radius_to_car < detection_distance){
m_speed -= std::min(
abs(pow(delta_speed, 2.0f)) * pow(ideal * 0.25f / radius_to_car, 2.0f) * m_aggressiveness * 0.15f,
(double)10.0f * delta_t);
}
else {
accelerate(delta_t);
}
if(current_segment->merge){
std::map<Car*,bool> around = find_cars_around_car();
for(auto it : around){
float delta_dist = Util::distance_to_car(it.first,this);
delta_speed = abs(speed()-it.first->speed());
if(it.first->current_node->get_parent_segment()->get_lane_number(it.first->current_node) == 0 && delta_dist < ideal && this->current_segment->get_lane_number(current_node) == 1 && speed()/target_speed() > 0.5){
if(Util::is_car_behind(it.first,this)){
accelerate(delta_t);
}
else{
m_speed -= std::max(std::max((ideal-delta_dist)*0.5f,0.0f),10.0f*delta_t);
}
}
else if(it.first->current_node->get_parent_segment()->get_lane_number(it.first->current_node) == 1 && this->current_segment->get_lane_number(current_node) == 0 && speed()/target_speed() > 0.5 && delta_dist < ideal){
if(Util::is_car_behind(this,it.first)){
m_speed -= std::max(std::max((ideal-delta_dist)*0.5f,0.0f),10.0f*delta_t);
}
else{
accelerate(delta_t);
}
}
}
}
else{
}
}
if(heading_to_node->get_parent_segment()->meter){
if(heading_to_node->get_parent_segment()->car_passed || heading_to_node->get_parent_segment()->ramp_counter < heading_to_node->get_parent_segment()->period*0.5f){
if (m_dist_to_next_node < ideal) {
m_speed -= std::max(std::max((m_dist_to_next_node-min_distance)*0.5f,0.0f),10.0f*delta_t);
}
else if(m_dist_to_next_node < detection_distance){
m_speed -= std::min(
abs(pow(m_speed, 2.0f)) * pow(ideal * 0.25f / m_dist_to_next_node, 2.0f) * m_aggressiveness * 0.15f,
(double)10.0f * delta_t);
}
}
else{
accelerate(delta_t);
}
}
else{
accelerate(delta_t);
}
if(m_speed < 0){
m_speed = 0;
}
}
////////////////////////////////////////////////////////////////////////////////
/// Helper function to find closest car in the same lane ahead of this car.
/// Returns a car if found, otherwise nullptr.
Car* Car::find_closest_car_ahead() {
float search_radius = m_search_radius_to_car_in_front;
std::map<RoadNode*,bool> visited;
std::list<RoadNode*> queue;
for(RoadNode * node : (this->current_segment->get_nodes())){
queue.push_front(node);
}
Car* answer = nullptr;
float shortest_distance = 10000000;
while(!queue.empty()){
RoadNode * next_node = queue.back(); // get last element
queue.pop_back(); // remove element
if(next_node != nullptr){
if(!visited[next_node] && Util::distance(x_pos(),next_node->get_x(),y_pos(),next_node->get_y()) < search_radius){
visited[next_node] = true;
for(Car * car : next_node->get_parent_segment()->m_cars){
if(this != car){
float radius = Util::distance_to_car(this,car);
if(Util::is_car_behind(this,car) && Util::will_car_paths_cross(this,car) && radius < shortest_distance){
shortest_distance = radius;
answer = car;
}
}
}
// push in new nodes in front of list.
for(RoadNode * node : next_node->get_nodes_from_me()){
queue.push_front(node);
}
}
}
}
return answer;
}
////////////////////////////////////////////////////////////////////////////////
/// Searches for cars around this car in a specified radius. Note that
/// search radius is the radius to RoadNodes, and not surrounding cars.
/// Returns a map of cars the function has found.
std::map<Car *,bool> Car::find_cars_around_car() {
float search_radius = m_search_radius_around;
std::map<RoadNode*,bool> visited;
std::list<RoadNode*> queue;
for(RoadNode * node : (this->current_segment->get_nodes())){
queue.push_front(node);
}
std::map<Car *,bool> answer;
while(!queue.empty()){
RoadNode * next_node = queue.back(); // get last element
queue.pop_back(); // remove element
if(next_node != nullptr){
if(!visited[next_node] && Util::distance(x_pos(),next_node->get_x(),y_pos(),next_node->get_y()) < search_radius){
visited[next_node] = true;
for(Car * car : next_node->get_parent_segment()->m_cars){
if(this != car){
answer[car] = true;
}
}
// push in new nodes in front of list.
for(RoadNode * node : next_node->get_nodes_from_me()){
queue.push_front(node);
}
for(RoadNode * node: next_node->get_nodes_to_me()){
queue.push_front(node);
}
}
}
}
return answer;
}
////////////////////////////////////////////////////////////////////////////////
/// Returns x position of car.
float Car::x_pos() {
float x_position;
if(heading_to_node != nullptr){
x_position = heading_to_node->get_x()-m_dist_to_next_node*cos(m_theta);
}
else{
x_position = current_node->get_x();
}
return x_position;
}
////////////////////////////////////////////////////////////////////////////////
/// Returns y position of car.
float Car::y_pos() {
float y_position;
if(heading_to_node != nullptr){
y_position = heading_to_node->get_y()+m_dist_to_next_node*sin(m_theta);
}
else{
y_position = current_node->get_y();
}
return y_position;
}
////////////////////////////////////////////////////////////////////////////////
/// Returns speed of car, as reference.
float & Car::speed() {
return m_speed;
}
////////////////////////////////////////////////////////////////////////////////
/// Returns target speed of car as reference.
float & Car::target_speed() {
return m_target_speed;
}
////////////////////////////////////////////////////////////////////////////////
/// Returns theta of car, the direction of the car. Defined in radians as a
/// mathematitan would define angles.
float & Car::theta() {
return m_theta;
}
////////////////////////////////////////////////////////////////////////////////
/// Returns current segment car is in.
RoadSegment* Car::get_segment() {
return current_segment;
} | true |