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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
5097e3ee096da6626ef100fa4c9f4f9b90d591fc | C++ | utstikkar/sonar-beach-ball | /Accelerometer_piezo_player.ino | UTF-8 | 3,208 | 2.96875 | 3 | [] | no_license | #include <Wire.h>
#include <Adafruit_LSM303.h>
#include <SPI.h>
#include <SdFat.h>
#include <SdFatUtil.h>
#include <SFEMP3Shield.h>
#include <SFE_TPA2016D2.h>
const int knockSensor = A0; // the piezo is connected to analog pin 0
const int threshold = 3; // threshold value to decide when the detected vibration is a knock or not
const int EN_GPIO1 = A2; // Amp enable + MIDI/MP3 mode select
int sensorReading = 0; // variable to store the value read from the sensor pin
SdFat sd;
SFEMP3Shield MP3player;
Adafruit_LSM303 lsm; // accelerometer/compass
int previousX = 0; // variable to store the previous value of x dimension
int previousY = 0; // variable to store the previous value of y dimension
int previousZ = 0; // variable to store the previous value of z dimension
int currentX; // variable to store the most recent value of x dimension
int currentY; // variable to store the most recent value of y dimension
int currentZ; // variable to store the most recent value of z dimension
boolean moving = false; // boolean
int track; //number of the track currently playing
SFE_TPA2016D2 amp; // amplifier
void setup()
{
Serial.begin(9600);
// Try to initialise and warn if we couldn't detect the chip
if (!lsm.begin())
{
Serial.println("Oops ... unable to initialize the LSM303. Check your wiring!");
while (1);
}
// The board uses a single I/O pin to select the
// mode the MP3 chip will start up in (MP3 or MIDI),
// and to enable/disable the amplifier chip:
pinMode(EN_GPIO1,OUTPUT);
digitalWrite(EN_GPIO1,LOW); // MP3 mode / amp off
// Turn on the Wire (I2C) library (amplifier control)
Wire.begin();
//start the shield
sd.begin(SD_SEL, SPI_HALF_SPEED);
MP3player.begin();
//start playing a random track
track = random(1, 7);
digitalWrite(EN_GPIO1,HIGH); // amp on
MP3player.playTrack(track);
MP3player.setVolume(0,0); // set the volume on both channels to the highest value (0)
}
void loop()
{
// read the touch/knock sensor and store it in the variable sensorReading:
sensorReading = analogRead(knockSensor);
// if the sensor reading is greater than the threshold:
if (sensorReading >= threshold) {
// send the string "Knock!" back to the computer
Serial.println("Knock!");
// and play a random track
track = random(1, 7);
MP3player.stopTrack(); // stop the previous track first before playing a new one
digitalWrite(EN_GPIO1,HIGH);
MP3player.playTrack(track);
}
lsm.read();
currentX = (int)lsm.accelData.x;
currentY = (int)lsm.accelData.y;
currentZ = (int)lsm.accelData.z;
// if the difference between the previous and current value of the accelerometer on one of the dimensions at least is large enough
if (abs(currentX - previousX) > 250 || abs(currentY - previousY) > 250 || abs(currentZ - previousZ) > 250)
{
moving = true; // then the beach ball is moving
Serial.println("moving");
MP3player.resumeMusic(); // play the music
}else{
MP3player.pauseMusic(); // otherwise pause
}
delay(500); //re-evaluate the sensors data every 500ms
previousX = currentX;
previousY = currentY;
previousZ = currentZ;
moving = false;
}
| true |
643325024f67c8d1450969676ff1ca68ba66769f | C++ | cheuk-fung/Programming-Challenges | /USACO/6.1/rectbarn.cc | UTF-8 | 1,411 | 2.6875 | 3 | [] | no_license | /*
ID: os.idea1
LANG: C++
TASK: rectbarn
*/
#include <cstdio>
FILE *fin, *fout;
inline int fmin(short a, short b)
{
if (!a) return b;
return a < b ? a : b;
}
struct Point {
short u, l, r;
int area() const { return (int)u * (int)(r + l - 1); }
} p_buf[2][3010];
Point *prev = p_buf[0];
Point *curr = p_buf[1];
int r, c, p;
bool map[3010][3010];
int ans;
int main()
{
fin = fopen("rectbarn.in", "r");
fout = fopen("rectbarn.out", "w");
fscanf(fin, "%d%d%d", &r, &c, &p);
for (int i = 0; i < p; i++) {
int x, y;
fscanf(fin, "%d%d", &x, &y);
map[x][y] = 1;
}
for (int i = 1; i <= r; i++) {
for (int j = 1; j <= c; j++) {
if (map[i][j]) curr[j].u = 0;
else curr[j].u = prev[j].u + 1;
}
for (int j = 1, l_cnt = 0; j <= c; j++) {
if (map[i][j]) l_cnt = curr[j].l = 0;
else curr[j].l = fmin(prev[j].l, ++l_cnt);
}
for (int j = c, r_cnt = 0; j > 0; j--) {
if (map[i][j]) r_cnt = curr[j].r = 0;
else curr[j].r = fmin(prev[j].r, ++r_cnt);
}
for (int j = 1; j <= c; j++)
if (curr[j].area() > ans) ans = curr[j].area();
Point *temp = prev;
prev = curr;
curr = temp;
}
fprintf(fout, "%d\n", ans);
return 0;
}
| true |
2ee26f15a62908e7d741f2213ddf8e8f6b19b97d | C++ | GrahamDumpleton-abandoned/ose | /software/library/OTC/system/_stopwtch.cc | UTF-8 | 2,360 | 2.625 | 3 | [
"LicenseRef-scancode-generic-exception",
"BSD-3-Clause",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | /*
// ============================================================================
//
// = LIBRARY
// OTC
//
// = FILENAME
// _stopwtch.cc
//
// = AUTHOR(S)
// Graham Dumpleton
//
// = COPYRIGHT
// Copyright 1995-2003 DUMPLETON SOFTWARE CONSULTING PTY LIMITED
//
// ============================================================================
*/
#include <OTC/system/stopwtch.hh>
#include <OTC/debug/tracer.hh>
#include <stdlib.h>
#if defined(HAVE_UNISTD_H)
#include <unistd.h>
#endif
/* ------------------------------------------------------------------------- */
void test1()
{
OTC_Tracer tracer("void test1()");
OTC_StopWatch timer1("TIMER1");
OTC_StopWatch timer2("TIMER2");
OTC_StopWatch timer3;
int i = 0;
for (int j=1; j<5; j++)
{
OTC_StopWatch::report(tracer());
tracer() << "timer1 = " << timer1.total() << endl;
tracer() << "timer1.start()" << endl;
timer1.start();
tracer() << "loop" << endl;
for (i=1; i!=10000000; i++) ;
timer1.stop();
tracer() << "timer1.stop()" << endl;
OTC_StopWatch::report(tracer());
tracer() << "timer1 = " << timer1.total() << endl;
}
tracer() << "timer1.reset()" << endl;
tracer() << "timer1.start()" << endl;
timer1.reset();
timer1.start();
tracer() << "loop" << endl;
for (i=1; i!=10000000; i++) ;
timer1.stop();
tracer() << "timer1.stop()" << endl;
OTC_StopWatch::report(tracer());
tracer() << "timer1 = " << timer1.total() << endl;
OTC_StopWatch::report(tracer());
tracer() << "timer1.start()" << endl;
timer1.start();
tracer() << "loop" << endl;
for (i=1; i!=10000000; i++) ;
timer1.reset();
tracer() << "timer1.reset()" << endl;
OTC_StopWatch::report(tracer());
tracer() << "timer1 = " << timer1.total() << endl;
}
typedef void (*testFunc)();
testFunc tests[] =
{
test1
};
/* ------------------------------------------------------------------------- */
int main(int argc, char* argv[])
{
u_int const numTests = sizeof(tests)/sizeof(tests[0]);
if (argc != 2)
{
cout << numTests << endl;
return 1;
}
else
{
int testNum = atoi(argv[1]);
if (testNum > 0 && u_int(testNum) <= numTests)
{
tests[testNum-1]();
return 0;
}
else
return 1;
}
}
/* ------------------------------------------------------------------------- */
| true |
33d4e685b24dce72dd2f0922c244645785377f70 | C++ | EmilyEclipse/Breakout | /src/options.cpp | UTF-8 | 1,048 | 2.953125 | 3 | [
"MIT"
] | permissive | #include "Options.hpp"
#include <SDL2/SDL.h>
#include <iostream>
#include <fstream>
#include <sstream>
Options::Options()
{
readOptions();
}
void Options::readOptions()
{
std::fstream optionsFile("options.txt", std::ios::in);
Uint16 count = 1;
for(std::string inputLine; std::getline(optionsFile, inputLine); )
{
++count;
if(inputLine.empty())
continue;
std::istringstream lineStream(inputLine);
std::string rowHeading;
lineStream >> rowHeading;
if(rowHeading[0] == '#')
continue;
switch(optionsMap[rowHeading])
{
case window_width:
lineStream >> windowWidth;
case window_height:
lineStream >> windowHeight;
case fps:
lineStream >> framesPerSecond;
default:
std::cout << "Error reading option at line " << count;
}
}
xScale = windowWidth / 1920.0;
yScale = windowHeight / 1080.0;
} | true |
56eb56a799bb72c531596a87514423e1d34b6de7 | C++ | j-p-e-g/AdventOfCode2017 | /AdventOfCode/December04b.cpp | UTF-8 | 1,174 | 3.046875 | 3 | [] | no_license | #include "stdafx.h"
#include <iostream>
#include <set>
#include "CodeUtil.h"
#include "December04b.h"
using namespace AdventOfCode::December04;
AnagramPassPhraseCheck::AnagramPassPhraseCheck(const std::string& fileName)
: PassPhraseCheck(fileName)
{
}
void AnagramPassPhraseCheck::OutputResultToConsole() const
{
std::cout << "December04.b: result = " << CountValidPassPhrases(m_phraseList) << std::endl;
}
bool AnagramPassPhraseCheck::CheckPassPhrase(const std::string& input) const
{
const std::vector<std::string> elements = CodeUtils::CodeUtil::SplitStringBySpace(input);
std::set<std::string> uniqueElements;
for (const auto& elem : elements)
{
uniqueElements.emplace(SortLettersInString(elem));
}
return elements.size() == uniqueElements.size();
}
std::string AnagramPassPhraseCheck::SortLettersInString(const std::string & input)
{
std::vector<char> temp;
for (int k = 0; k < input.length(); k++)
{
temp.push_back(input[k]);
}
std::sort(temp.begin(), temp.end());
std::string sortedLetters;
for (auto c : temp)
{
sortedLetters += c;
}
return sortedLetters;
}
| true |
0e9f1960baff79733690de8a4e18a8462371a97e | C++ | Bhushan-joshi/CPP14 | /src/MultipleCatch.cpp | UTF-8 | 724 | 3.71875 | 4 | [] | no_license | #include <iostream>
using namespace std;
class MyException1
{
};
class MyException2 : public MyException1
{
};
int main()
{
try
{
throw 1;
throw 1.5f;
throw 'c';
}
catch (int i)
{
cout << "int catch" << endl;
}
catch (float f)
{
cout << "float catch" << endl;
}
catch (...)
{
//this catch block must be at last ; this can catch all type of exceptions
cout << "catch for all other throws\n";
}
cout<<"--------------------------------------------------\n";
try
{
throw MyException1();
}
catch (MyException2 e)
{
//if you have inheritace then child class should be first
cout << "My Exception2" << endl;
}
catch (MyException1 e)
{
cout << " My Exception1" << endl;
}
return 0;
}
| true |
9225eb153c26fe7fa3b14cfd4590e2d3c011d90c | C++ | VitBomm/hackerank | /Mini-Max-Sum.cpp | UTF-8 | 474 | 2.6875 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
vector<long long int> v;
int main()
{
long long int e;
for(int i = 0 ; i<5;i++)
{
cin>>e;
v.push_back(e);
}
sort(v.begin(),v.end());
long long int mMin = 0;
long long int mMax = 0;
for(int i= 0 ; i<4;i++)
{
mMin += v[i];
}
for(int i = 1 ; i <5;i++)
{
mMax += v[i];
}
cout<<mMin<<" "<<mMax;
return 0;
}
| true |
e26eac1c2b47273f5da5ea4a5faa531462487533 | C++ | vinamarora8/Monochromator-Automation | /StepperControl/StepperControl.cpp | UTF-8 | 2,434 | 3.40625 | 3 | [] | no_license | #include <StepperControl.h>
StepperControl::StepperControl(const int* stepper_pins) {
// Set initial values of private variables
stage = 0;
pins[0] = stepper_pins[0];
pins[1] = stepper_pins[1];
pins[2] = stepper_pins[2];
pins[3] = stepper_pins[3];
step_delay = 100;
// Set pin to output mode
pinMode(pins[0], OUTPUT);
pinMode(pins[1], OUTPUT);
pinMode(pins[2], OUTPUT);
pinMode(pins[3], OUTPUT);
// Set value of OUTPUTs to LOW
digitalWrite(pins[0], LOW);
digitalWrite(pins[1], LOW);
digitalWrite(pins[2], LOW);
digitalWrite(pins[3], LOW);
}
void StepperControl::set_step_delay(int delay) {
step_delay = delay;
return;
}
void StepperControl::step_up() {
// This will be a dispatch on the number "Stage"
switch(stage) {
case 0:
digitalWrite(pins[3], LOW);
digitalWrite(pins[0], HIGH);
delay(step_delay);
//digitalWrite(pins[0], LOW);
stage = 1;
break;
case 1:
digitalWrite(pins[0], LOW);
digitalWrite(pins[1], HIGH);
delay(step_delay);
//digitalWrite(pins[1], LOW);
stage = 2;
break;
case 2:
digitalWrite(pins[1], LOW);
digitalWrite(pins[2], HIGH);
delay(step_delay);
//digitalWrite(pins[2], LOW);
stage = 3;
break;
case 3:
digitalWrite(pins[2], LOW);
digitalWrite(pins[3], HIGH);
delay(step_delay);
//digitalWrite(pins[3], LOW);
stage = 0;
break;
}
}
void StepperControl::step_down() {
// This will also be a dispatch on the number "Stage"
switch(stage) {
case 0:
digitalWrite(pins[3], LOW);
digitalWrite(pins[2], HIGH);
delay(step_delay);
digitalWrite(pins[2], LOW);
stage = 3;
break;
case 1:
digitalWrite(pins[0], LOW);
digitalWrite(pins[3], HIGH);
delay(step_delay);
digitalWrite(pins[3], LOW);
stage = 0;
break;
case 2:
digitalWrite(pins[1], LOW);
digitalWrite(pins[0], HIGH);
delay(step_delay);
digitalWrite(pins[0], LOW);
stage = 1;
break;
case 3:
digitalWrite(pins[2], LOW);
digitalWrite(pins[1], HIGH);
delay(step_delay);
digitalWrite(pins[1], LOW);
stage = 2;
break;
}
}
void StepperControl::step(int steps) {
// Check if you have to use step_up or step_down
// Then run a while loop to step_up (down) that much
if (steps > 0) {
while (steps > 0) {
step_up();
steps--;
}
}
else if (steps < 0) {
while (steps < 0) {
step_down();
steps++;
}
}
for (int i=0; i<4; i++)
digitalWrite(pins[i], LOW);
}
| true |
77b8bf9688525f0cfb238accd4ede59556b3dd3f | C++ | kuangchen/ProtoMolAddon | /protomol/src/protomol/config/Configuration.cpp | UTF-8 | 7,206 | 2.75 | 3 | [] | no_license | #include <protomol/config/Configuration.h>
#include <protomol/base/Report.h>
#include <protomol/base/Exception.h>
using namespace std;
using namespace ProtoMol::Report;
using namespace ProtoMol;
//____ Configuration
void Configuration::registerKeyword(const string &keyword, Value value) {
if (end() != myValues.find(keyword) && myAliases.end() ==
myAliases.find(keyword)) {
if (!value.equalTypeAndConstraint(myValues[keyword]))
report << hint << "[Configuration::registerKeyword] overwriting "
<< "already registered keyword \'"
<< keyword << "\' with diffent type/constraint." << endr;
myValues[keyword] = value;
} else if (myAliases.end() == myAliases.find(keyword))
myValues[keyword] = value;
else
report << hint << "[Configuration::registerKeyword] keyword \'"
<< keyword << "\' already used for alias \'"
<< myAliases[keyword] << "\'." << endr;
}
void Configuration::registerAliases(const string &keyword,
const vector<string> &aliases) {
for (unsigned int i = 0; i < aliases.size(); ++i)
if (!aliases[i].empty() && !keyword.empty()) {
if (myAliases.end() == myAliases.find(aliases[i]))
myAliases[aliases[i]] = keyword;
else if (!equalNocase(myAliases[aliases[i]], keyword))
report << hint << "[Configuration::registerAliases] alias \'"
<< aliases[i] << "\' already used for \'" <<
myAliases[aliases[i]] << "\'." << endr;
}
}
void Configuration::unregisterKeyword(const string &keyword) {
iterator i = myValues.find(keyword);
if (i != end()) myValues.erase(i);
for (AliasMapType::iterator i = myAliases.begin(); i != myAliases.end();)
if (equalNocase(i->second, keyword)) myAliases.erase(i++);
else ++i;
TextMapType::iterator j = myTexts.find(keyword);
if (j != myTexts.end()) myTexts.erase(j);
}
bool Configuration::empty(const string &keyword) const {
if (keyword == "") return myValues.empty();
return find(keyword) == end();
}
bool Configuration::defined(const string &keyword) const {
const_iterator i = find(keyword);
if (i != end()) return i->second.isDefined();
return false;
}
bool Configuration::valid(const string &keyword) const {
const_iterator i = find(keyword);
if (i != end()) return i->second.valid();
return false;
}
bool Configuration::set(const string &keyword, Value v) {
iterator i = find(keyword);
if (i != end()) {
i->second.set(v);
return i->second.valid();
}
return false;
}
bool Configuration::set(const string &keyword, const string &v) {
iterator i = find(keyword);
if (i != end()) {
if (v == "") i->second.init();
else i->second.set(v);
return i->second.valid();
}
return false;
}
bool Configuration::set(const vector<vector<string> > &values) {
const unsigned int count = values.size();
bool ok = true;
for (unsigned int i = 0; i < count; ++i) {
if (values[i].empty()) continue;
iterator itr = find(values[i][0]);
if (itr == end()) {
report << recoverable << "Keyword \'" << values[i][0] <<
"\' not recognized." << endr;
continue;
}
string val("");
for (unsigned int j = 1; j < values[i].size(); ++j)
val += (j == 1 ? "" : " ") + values[i][j];
if (val == "") ok &= itr->second.init();
else if (itr->second.set(val)) ok = false;
if (!itr->second.valid())
report << hint << "Value \'" << val << "\' could not be assigned \'"
<< values[i][0] << "\' " << itr->second.
getDefinitionTypeString() << "." << endr;
}
return false;
}
bool Configuration::set(const string &keyword,
const vector<vector<string> > &values) {
const unsigned int count = values.size();
for (unsigned int i = 0; i < count; ++i) {
if (values[i].empty()) continue;
if (!equalNocase(values[i][0], keyword)) continue;
string val("");
for (unsigned int j = 1; j < values[i].size(); ++j)
val += (j == 1 ? "" : " ") + values[i][j];
return set(keyword, val);
}
return false;
}
const Value &Configuration::operator[](const string &keyword) const {
const_iterator i = find(keyword);
if (i == end())
THROW(string("Configuration index '") + keyword + "' out of range.");
return i->second;
}
Value &Configuration::operator[](const string &keyword) {
iterator i = find(keyword);
if (i == end())
THROW(string("Configuration index '") + keyword + "' out of range.");
return i->second;
}
Value Configuration::get(const string &keyword) const {
const_iterator i = find(keyword);
if (i != end()) return i->second;
return Value();
}
vector<Value> Configuration::get(const vector<Parameter> ¶meters) const {
vector<Value> values(parameters.size());
for (unsigned int i = 0; i < parameters.size(); ++i)
values[i] = get(parameters[i].keyword);
return values;
}
bool Configuration::hasUndefinedKeywords() const {
for (const_iterator i = begin(); i != end(); ++i)
if (!i->second.valid()) return true;
return false;
}
string Configuration::printUndefinedKeywords() const {
string result;
for (const_iterator i = begin(); i != end(); ++i)
if (!i->second.valid())
result += getRightFill(i->first, Constant:: PRINTMAXWIDTH) +
i->second.getDefinitionTypeString() + "\n";
return result;
}
ostream &Configuration::print(ostream &stream) const {
stream << "Keywords:\n\n";
for (const_iterator i = begin(); i != end(); ++i) {
stream << getRightFill(i->first, Constant::PRINTMAXWIDTH)
<< i->second.getDefinitionTypeString();
if (myTexts.find(i->first) != myTexts.end())
stream << " \t # " << myTexts.find(i->first)->second;
stream << "\n";
}
stream << "\nAliases:\n\n";
for (AliasMapType::const_iterator i = myAliases.begin();
i != myAliases.end(); ++i)
stream << getRightFill(i->first, Constant::PRINTMAXWIDTH)
<< i->second << "\n";
return stream;
}
Configuration::iterator Configuration::find(const string &keyword) {
iterator i = myValues.find(keyword);
if (i == end()) {
AliasMapType::iterator j = myAliases.find(keyword);
if (j != myAliases.end()) i = myValues.find(j->second);
}
return i;
}
Configuration::const_iterator Configuration::find(const string &keyword) const
{
const_iterator i = myValues.find(keyword);
if (i == end()) {
AliasMapType::const_iterator j = myAliases.find(keyword);
if (j != myAliases.end()) i = myValues.find(j->second);
}
return i;
}
bool Configuration::setText(const string &keyword, const string &text) {
if (!empty(keyword)) {
myTexts[keyword] = text;
return true;
}
return false;
}
string Configuration::getText(const string &keyword) const {
TextMapType::const_iterator i = myTexts.find(keyword);
if (i != myTexts.end()) return i->second;
else return string();
}
vector<string> Configuration::getAliases(const string &keyword) const {
vector<string> res;
for (AliasMapType::const_iterator i = myAliases.begin();
i != myAliases.end(); ++i)
if (equalNocase(i->second, keyword)) res.push_back(i->first);
return res;
}
| true |
d25755ab438bdaa8ed292d7083adb77759a850c0 | C++ | supersteph/randomstuff | /median.cpp | UTF-8 | 1,634 | 3.671875 | 4 | [] | no_license | #include<iostream>
using namespace std;
void swapay(int arr[], int a, int b)
{
int t = arr[a];
arr[a] = arr[b];
arr[b] = t;
}
int partition (int arr[], int low, int high)
{
int pivot = arr[high]; // pivot
int i = (low - 1); // Index of smaller element
for (int j = low; j <= high - 1; j++)
{
// If current element is smaller than the pivot
if (arr[j] < pivot)
{
i++; // increment index of smaller element
swapay(arr, i, j);
}
}
swapay(arr, i+1, high);
return (i + 1);
}
int findmax(int arr[], int end){
int max = INT_MIN;
for (int i = 0; i < end; i++){
if (arr[i] > max){
max = arr[i];
}
}
return max;
}
int findmin(int arr[], int start, int size){
int mins = INT_MAX;
for (int i = start; i < size; i++){
if (arr[i] < mins){
mins = arr[i];
}
}
return mins;
}
int quickSort(int arr[], int low, int high, int n)
{
if (low < high)
{
int pi = partition(arr, low, high);
if(abs(pi-(n-pi-1))<=1){
if (abs(pi-(n-pi-1))==0){
return arr[pi];
}
else if (pi > n-pi-1){
return (findmax(arr, pi)+arr[pi])/2;
}
else{
return (findmin(arr, pi+1, n))/2;
}
}
else if (pi > n-pi-1){
return quickSort(arr, low, pi - 1, n);
}
else {
return quickSort(arr, pi + 1, high, n);
}
}
}
int main()
{
int foo [5] = { 16, 2, 77, 40, 12071 };
cout << quickSort(foo, 0, 4, 5);
cout << "\n";
return 0;
} | true |
14e616c08f28d41b174401d15910854e44184931 | C++ | UnregisteredNameA/MiniDatabase | /MiniSQL/tableinfo.cpp | UTF-8 | 5,134 | 2.921875 | 3 | [] | no_license | #include "pch.h"
#include "tableinfo.h"
#include <iostream>
#include <algorithm>
#include <iomanip>
#include <algorithm>
#include <cstring>
using namespace std;
datablock::datablock()
{
len = 0;
}
void datablock::clear()
{
d.clear();
s.clear();
f.clear();
len = 0;
}
void table::clear()
{
name.clear();
keyname.clear();
keytype.clear();
keydata.clear();
prikeyname.clear();
}
void table::showinfo() const
{
cout << "Table name: " << name << endl;
for (int i = 0; i < keyname.size(); ++i)
{
cout << "Key #" << i << ": ";
cout << "name:[" << keyname[i] << "], " << "type:[" << keytype[i];
if (keytype[i] == "char") cout << "(" << keydata[i].len << ")";
cout << "]";
cout << (unique[i] ? ", unique;" : ";") << endl;
}
if (prikeyname.size())
{
cout << "Primary key: " << prikeyname[0] << endl;
}
}
bool table::equalType(const table &b) //*this is the standard. check if b can be saved into *this.
{
if (this->keytype.size() != b.keytype.size()) return 0;
for (int i = 0; i < this->keytype.size(); ++i)
{
if (this->keytype[i] != b.keytype[i] && !(this->keytype[i] == "float" && b.keytype[i] == "int")) return 0;
if (this->keydata[i].len < b.keydata[i].len) return 0;
}
return 1;
}
void table::copyTableHead(table & dst)
{
dst.clear();
dst.keyname = this->keyname;
dst.keytype = this->keytype;
datablock blank;
for (int i = 0; i < this->keyname.size(); ++i)
{
dst.keydata.push_back(blank);
if (this->keytype[i] == "char") dst.keydata[i].len = this->keydata[i].len;
}
dst.prikeyname = this->prikeyname;
}
void table::addTableHead(const table &head)
{
this->keyname = head.keyname;
for (int i = 0; i < head.keyname.size(); ++i) this->keydata[i].len = head.keydata[i].len;
this->prikeyname = head.prikeyname;
}
void table::copyIthRecord(int ith, table &dst) const
{
for (int i = 0; i < this->keyname.size(); ++i)
{
dst.keydata[i].clear();
if (this->keytype[i] == "int")
{
if (dst.keydata[i].d.size() == 0) dst.keydata[i].d.push_back(0);
dst.keydata[i].d[0] = this->keydata[i].d[ith];
}
if (this->keytype[i] == "float")
{
if (dst.keydata[i].f.size() == 0) dst.keydata[i].f.push_back(0);
dst.keydata[i].f[0] = this->keydata[i].f[ith];
}
if (this->keytype[i] == "char")
{
if (dst.keydata[i].s.size() == 0) dst.keydata[i].s.push_back(string());
dst.keydata[i].s[0] = this->keydata[i].s[ith];
dst.keydata[i].len = this->keydata[i].len;
}
}
}
void table::addOneRecord(const table &src)
{
for(int i = 0; i < this->keyname.size(); ++i)
{
if (this->keytype[i] == "int")
{
this->keydata[i].d.push_back(src.keydata[i].d[0]);
}
if (this->keytype[i] == "float")
{
this->keydata[i].f.push_back(src.keydata[i].f[0]);
}
if (this->keytype[i] == "char")
{
this->keydata[i].s.push_back(src.keydata[i].s[0]);
}
}
}
int table::columnOfName(const string & name) const
{
for (int i = 0; i < this->keyname.size(); ++i)
{
if (name == keyname[i]) return i;
}
return -1;
}
int table::recordNumber() const
{
if (keytype.size() == 0)
{
return 0;
}
if (keytype[0] == "int")
{
return keydata[0].d.size();
}
if (keytype[0] == "float")
{
return keydata[0].f.size();
}
if (keytype[0] == "char")
{
return keydata[0].s.size();
}
return 0;
}
void table::printTableContent() const
{
if (this->recordNumber() == 0)
{
cout << "Empty set." << endl;
return;
}
cout << this->recordNumber() << " tuples in total." << endl;
vector<int> space;
for (int i = 0; i < keyname.size(); ++i)
{
if (keytype[i] == "int" || keytype[i] == "float")
{
space.push_back(max(10U, keyname[i].size() + 1));
}
if (keytype[i] == "char")
{
int maxlen = strlen(keyname[i].c_str()) + 1;
for(int j = 0; j < keydata[i].s.size(); ++j)
{
int tt = strlen(keydata[i].s[j].c_str());
if (tt + 1 > maxlen) maxlen = tt + 1;
}
space.push_back(max(maxlen, 10));
}
}
cout << '+';
for (int i = 0; i < keyname.size(); ++i)
cout << string(space[i], '-') << '+';
cout << endl;
cout << '|';
for (int i = 0; i < keyname.size(); ++i)
{
cout << setw(space[i]) << right << keyname[i] << '|';
}
cout << endl;
cout << '+';
for (int i = 0; i < keyname.size(); ++i)
cout << string(space[i], '-') << '+';
cout << endl;
int recn = max(keydata[0].d.size(), keydata[0].f.size());
recn = max((unsigned)recn, keydata[0].s.size());
for (int i = 0; i < recn; ++i)
{
cout << "|";
for (int j = 0; j < keyname.size(); ++j)
{
if (keytype[j] == "int")
{
cout << setw(space[j]) << right << keydata[j].d[i];
}
if (keytype[j] == "float")
{
cout << setw(space[j]) << right << keydata[j].f[i];
}
if (keytype[j] == "char")
{
cout << setw(space[j]) << right << keydata[j].s[i].c_str();
}
cout << '|';
}
cout << endl;
cout << '+';
for (int i = 0; i < keyname.size(); ++i)
cout << string(space[i], '-') << '+';
cout << endl;
}
}
| true |
39e992984eff168d53aa8be87c23cbc86f815aa3 | C++ | LyamCournoyer/comp_422_lab_c | /task2/task2.ino | UTF-8 | 1,630 | 2.828125 | 3 | [] | no_license | #include<avr/io.h>
#define MYUBRR 103
#define CHUNK 5
#define MAXCHAR 40
#define TERMINATOR '\n'
void setup() {
UBRR0H = (MYUBRR>>8);
UBRR0L = MYUBRR;
UCSR0C = 0x06;
// UCSR0B = (1<<RXEN0);
UCSR0B = (1<<TXEN0)|(1<<RXEN0);
}
void loop() {
char * name_;
char * greeting = "hello ";
char * prompt = "Enter name. Terminate with newline \n";
writeString(prompt);
name_ = readName();
writeString(greeting);
writeString(name_);
writeChar(TERMINATOR);
free(name_);
}
void writeChar(char c){
while (!(UCSR0A & (1<<UDRE0)));
UDR0 = c;
}
char * readName(void){
char *name_ = NULL, *tmp = NULL;
size_t size = 0, idx = 0;
// char name[40];
while(1){
while ( !(UCSR0A & (1<<RXC0)) );
char input = UDR0;
if (idx >= MAXCHAR){
USART_Flush();
break;
}
if (input == TERMINATOR){
name_[idx] = '\0';
break;
}
if (size <= idx) {
size += CHUNK;
tmp = realloc(name_, size);
if (!tmp) {
free(name_);
name_ = NULL;
break;
}
name_ = tmp;
}
name_[idx++] = input;
}
return name_;
}
void writeString( char * string){
size_t i = 0;
while (string[i] != '\0') { /* Stop looping when we reach the null-character. */
writeChar(string[i]); /* Print each character of the string. */
i++;
}
}
void USART_Flush( void ){
unsigned char dummy = 'a';
while(dummy != TERMINATOR){
while ( UCSR0A & (1<<RXC0) ){
dummy = UDR0;
}
}
}
| true |
51cfbde5248f26261b6c0c6871bd18ccf683d00d | C++ | ImJsaw/ChineseChess | /ChineseChess/Screen.h | UTF-8 | 1,726 | 2.734375 | 3 | [] | no_license | #include<iostream>
#include<fstream>
#include<Windows.h>
//define out border size
#define screenX 81
#define screenY 23
//define UI height
#define UIY 21
//define UI width
#define logX 21
#define boardX 34
#define hintX 26
#define RED 1
#define BLACK 0
//define xy, easy to access array
#define X 0
#define Y 1
//define arrow face
#define UP 0
#define DOWN 1
#define LEFT 2
#define RIGHT 3
//define moveable table content
#define CANTMOVE 0
#define MOVEABLE 1
#define EATABLE 2
#define KINGZONE_X 5
#define KINGZONE_BLACK_Y 1
#define KINGZONE_RED_Y 9
using namespace std;
enum gameState
{
PICK = 0,
MOVE,
};
class Screen{
public:
Screen();
~Screen();
void update();
void init();
void callMenu();
void moveCursor(int face);
void checkCursor();
bool showMenu = false;
private:
//common
void drawBorder(int xStart,int yStart, int xEnd, int yEnd);
void writeString(int xStart, int y, string str, int color=15);
void changeBlockColor(int xStart, int yStart, int xEnd, int yEnd, int color);
void cleanBlock(int xStart, int yStart, int xEnd, int yEnd, int color);
bool markMove(int x, int y, int yStart, int yEnd, int xStart, int xEnd);
void changeTurn() { if (turn == RED) turn = BLACK; else turn = RED;};
//draw func
void readBoard();
void writeBoard();
void drawUI();
void drawCursor();
void drawMoveable();
void drawLog();
void drawMenu();
void drawBoard();
void drawChess(int x, int y);
void drawHint();
//other func
string num2chess(int num, int side);
bool calcAvaliableMove();
//variable
char screenBuffer[screenX][screenY];
int screenColor[screenX][screenY];
int board[9][10];
int moveAble[9][10];
int turn;
int cursor[2];
int choosedChess[2];
int gameState = PICK;
};
| true |
dd0637f2346e2ca7695c1de8a9501fd4440735a7 | C++ | codeheng/freshman_code | /dev-c++写的代码/郝斌老师的代码/函数的形参与实参.cpp | GB18030 | 337 | 3.3125 | 3 | [] | no_license | /* 19.8.11 1426
ʵξָmainµIJ
βαʾͨµ
DZ ͬ λһһӦͱݡ
*/
# include <stdio.h>
void f(int i,float x)
{
printf("%d %lf\n",i,x);
}
int main(void)
{
f(9.9,6.6);
return 0;
} //Ϊ 9 6.600000
| true |
85ad857db0754f0dd4c4593dfd9ce610c00e5220 | C++ | olegartys/CompilerCourseLabs | /lab2/ThompsonConstruction.cpp | UTF-8 | 17,604 | 2.546875 | 3 | [] | no_license | //
// Created by oleglevin on 17.02.17.
//
#include <iostream>
#include "ThompsonConstruction.h"
#include "InfixTransform.h"
using namespace std;
ThompsonConstruction::ThompsonConstruction(const std::string& regex) :
mRegex(regex), mCurId(0)
{ }
void ThompsonConstruction::pushOp(char c) {
State::StatePtr_t state0(new State(++mCurId));
State::StatePtr_t state1(new State(++mCurId));
state0->connect(state1, c);
NFAPtr_t nfa(new NFA_t());
nfa->push_back(state0);
nfa->push_back(state1);
mNFAList.push_back(nfa);
}
bool ThompsonConstruction::concatOp() {
NFAPtr_t nfa1, nfa2;
nfa2 = mNFAList.back();
if (!nfa2) {
return false;
}
mNFAList.pop_back();
nfa1 = mNFAList.back();
if (!nfa1) {
return false;
}
mNFAList.pop_back();
State::StatePtr_t qB0 = nfa2->front();
State::StatePtr_t qAn = nfa1->back();
// std::cout << "idB0=" << qB0->getId() << " qAnid=" << qAn->getId() << "\n";
qAn->connect(qB0, 'e');
for (auto i = 0; i < nfa2->size(); ++i) {
nfa1->push_back(nfa2->at(i));
}
mNFAList.push_back(nfa1);
return true;
}
bool ThompsonConstruction::orOp() {
NFAPtr_t nfa1, nfa2;
nfa1 = mNFAList.back();
if (!nfa1) {
return false;
}
mNFAList.pop_back();
nfa2 = mNFAList.back();
if (!nfa2) {
return false;
}
mNFAList.pop_back();
State::StatePtr_t q0(new State(++mCurId));
State::StatePtr_t q1(new State(++mCurId));
State::StatePtr_t qA0 = nfa1->front();
State::StatePtr_t qB0 = nfa2->front();
State::StatePtr_t qAn = nfa1->back();
State::StatePtr_t qBn = nfa2->back();
q0->connect(qA0, 'e');
q0->connect(qB0, 'e');
qAn->connect(q1, 'e');
qBn->connect(q1, 'e');
nfa1->push_front(q0);
nfa2->push_back(q1);
for (auto i = 0; i < nfa2->size(); ++i) {
nfa1->push_back(nfa2->at(i));
}
mNFAList.push_back(nfa1);
return true;
}
bool ThompsonConstruction::starOp() {
// NFAPtr_t nfa;
//
// nfa = mNFAList.back();
// if (!nfa) {
// return false;
// }
// mNFAList.pop_back();
//
// State::StatePtr_t qA0 = nfa->front();
// State::StatePtr_t qAn = nfa->back();
//
//// std::cout << "idA0=" << qA0->getId() << " qAnid=" << qAn->getId() << "\n";
//
// qA0->connect(qAn, 'e');
// qAn->connect(qA0, 'e');
//
// mNFAList.push_back(nfa);
NFAPtr_t nfaA, nfaB;
nfaA = mNFAList.back();
if (!nfaA) {
return false;
}
mNFAList.pop_back();
State::StatePtr_t qN0(new State(++mCurId));
State::StatePtr_t qNN(new State(++mCurId));
State::StatePtr_t qA0 = nfaA->front();
State::StatePtr_t qAn = nfaA->back();
qAn->connect(qA0, 'e');
qN0->connect(qA0, 'e');
qN0->connect(qNN, 'e');
qAn->connect(qNN, 'e');
nfaA->push_front(qN0);
nfaA->push_back(qNN);
mNFAList.push_back(nfaA);
return true;
}
bool ThompsonConstruction::plusOp() {
NFAPtr_t nfa;
nfa = mNFAList.back();
if (!nfa) {
return false;
}
mNFAList.pop_back();
State::StatePtr_t qN0(new State(++mCurId));
State::StatePtr_t qNN(new State(++mCurId));
State::StatePtr_t qA0 = nfa->front();
State::StatePtr_t qAn = nfa->back();
qN0->connect(qA0, 'e');
qAn->connect(qNN, 'e');
qAn->connect(qA0, 'e');
nfa->push_front(qN0);
nfa->push_back(qNN);
mNFAList.push_back(nfa);
return true;
}
ThompsonConstruction::NFAPtr_t ThompsonConstruction::apply() {
mRegex = *InfixTransform::toPostfix(mRegex);
std::cout << "Postfix regex: " << mRegex << std::endl;
for (auto& c: mRegex) {
switch (c) {
case 'a':
case 'b':
case 'e':
pushOp(c);
break;
case '|':
if (!orOp()) {
return nullptr;
}
break;
case '*':
if (!starOp()) {
return nullptr;
}
break;
case '+':
if (!plusOp()) {
return nullptr;
}
break;
case '.':
if (!concatOp()) {
return nullptr;
}
break;
default:
return nullptr;
}
}
NFAPtr_t nfa = mNFAList.back();
if (!nfa) {
return nullptr;
}
mNFAList.pop_back();
nfa->back()->setFinal();
return nfa;
}
ThompsonConstruction::NFAPtr_t ThompsonConstruction::optimize(const ThompsonConstruction::NFAPtr_t& nfa) {
ThompsonConstruction::NFAPtr_t optimizedNfa(new ThompsonConstruction::NFA_t);
*optimizedNfa = *nfa;
// Need to make 2 iterations because of dependency between e-transition states (e.x. ba*)
for (int i = 0; i < 2; ++i) {
// Delete e
for (const auto& state: *optimizedNfa) {
// Check whether there are E-transitions from this state
for (const auto& conn: state->getConnections()) {
if (conn->mChar == 'e') {
// If it is e-transition to the final state - make this state final
if (conn->mState->isFinal()) {
state->setFinal();
}
// Delete e-transition
if (i == 1) state->deleteConnection(conn);
// Go to this state and copy all the transitions from it to the current state
// FIXME: need copy e-transitions or not?
auto eTransitionState = conn->mState;
for (const auto& eTransStateConn: eTransitionState->getConnections()) {
if (eTransStateConn->mChar != 'e') {
state->connect(eTransStateConn->mState, eTransStateConn->mChar);
}
}
}
}
}
}
// Delete unreachable states (algorithm 3 lecture, 22 slide)
std::set<State::StatePtr_t> stateSet;
stateSet.insert(optimizedNfa->front());
bool f = true;
while(f) {
auto size0 = stateSet.size();
for (auto s: stateSet) {
for (auto& conn: s->getConnections()) {
stateSet.insert(conn->mState);
}
}
auto size1 = stateSet.size();
if (size1 == size0) f = false;
}
optimizedNfa->clear();
for (auto& s: stateSet) {
optimizedNfa->push_back(s);
}
return optimizedNfa;
}
//void ThompsonConstruction::epsilon_steps(const std::set<State::StatePtr_t>& in, std::set<State::StatePtr_t>& out) {
// // std::shared_ptr<std::deque<State::ConnectionWrapper>> connections;
// std::stack<State::StatePtr_t> toProcess;
//
// out.clear();
// out = in;
//
// for (const auto& state: in) {
// toProcess.push(state);
// }
//
// while (!toProcess.empty()) {
// auto state = toProcess.top();
// toProcess.pop();
//
// auto connections = state->getConnections();
//
// std::cout << "stack_size=" << toProcess.size() << "\nid=" << state->getId() << "\n";
//
// for (const auto& conn: connections) {
// std::cout << conn->mChar << " ";
// if (conn->mChar != 'e') continue;
//
// if (out.find(conn->mState) == out.end()) {
// out.insert(conn->mState);
// toProcess.push(conn->mState);
// }
// }
// }
//
// for (const auto& state: in) {
// // Get connections for the current state
// auto connections = state->getConnections();
//
//
// }
//}
//
//void ThompsonConstruction::step(char c, const std::set<State::StatePtr_t>& in, std::set<State::StatePtr_t>& out) {
// out.clear();
//
// for (const auto& state: in) {
// auto connections = state->getConnections();
//
// for (const auto& conn: connections) {
// if (conn->mChar == c) {
// out.insert(conn->mState);
// }
// }
// }
//}
//ThompsonConstruction::DFAPtr_t ThompsonConstruction::powerset(const NFAPtr_t &nfa) {
// DFAPtr_t dfa(new DFA_t);
//
// *dfa = *nfa;
//
// // Need to make 2 iterations because of dependency between e-transition states (e.x. ba*)
// for (int i = 0; i < 2; ++i) {
// // Delete e
// for (const auto& state: *dfa) {
// // Check whether there are E-transitions from this state
// for (const auto& conn: state->getConnections()) {
// if (conn->mChar == 'e') {
// // If it is e-transition to the final state - make this state final
// if (conn->mState->isFinal()) {
// state->setFinal();
// }
//
// // Delete e-transition
// if (i == 1) state->deleteConnection(conn);
//
// // Go to this state and copy all the transitions from it to the current state
// // FIXME: need copy e-transitions or not?
// auto eTransitionState = conn->mState;
// for (const auto& eTransStateConn: eTransitionState->getConnections()) {
// if (eTransStateConn->mChar != 'e') {
// state->connect(eTransStateConn->mState, eTransStateConn->mChar);
// }
// }
// }
// }
// }
// }
//
// // Delete unreachable states (algorithm 3 lecture, 22 slide)
// std::set<State::StatePtr_t> stateSet;
// stateSet.insert(dfa->front());
//
// bool f = true;
// while(f) {
// auto size0 = stateSet.size();
// for (auto s: stateSet) {
// for (auto& conn: s->getConnections()) {
// stateSet.insert(conn->mState);
// }
// }
// auto size1 = stateSet.size();
//
// if (size1 == size0) f = false;
// }
//
// NFAPtr_t optimizedNFA(new NFA_t());
// for (auto& s: stateSet) {
// optimizedNFA->push_back(s);
// }
//
// std::cout << "\nOptimized NFA: \n";
// for (auto state: *optimizedNFA) {
// cout << state->getId() << "(" << state->isFinal() << ") ";
// cout << *state;
// cout << endl;
// }
//
// // Filling the DFA
// dfa->clear();
// mCurId = 0;
// std::stack<State::StatePtr_t> processStack;
// std::set<int> processedStates;
//
// std::set<State::StatePtr_t> subsetStateA;
// std::set<State::StatePtr_t> subsetStateB;
//
// // For initial state of NFA create subsets of transitions for all alphabet symbols.
// auto initNFAstate = optimizedNFA->at(0);
// for (const auto& conn: initNFAstate->getConnections()) {
// subsetStateA.insert(conn->mState);
// }
//
// State::StatePtr_t initDFAstate(new State(++mCurId, subsetStateA));
// dfa->push_back(initDFAstate);
// processStack.push(initDFAstate);
//
// while (!processStack.empty()) {
// auto curState = processStack.top();
// processStack.pop();
//
// subsetStateA.clear();
//
// for (int i = 0; i < 2; ++i) {
// char c = i == 0 ? 'a' : 'b';
//
// // Fill the subsetConstruction with transitions
// for (const auto& subsState: curState->getSubset()) {
// for (const auto& connSubs: subsState->getConnections()) {
// if (connSubs->mChar == c) {
// subsetStateA.insert(connSubs->mState);
// }
// }
// }
//
// // Check whether it exists in dfa
// bool isExist = false;
// auto dfaState = *dfa->begin();
// for (auto j = 0; j < dfa->size(); ++j) {
// dfaState = dfa->at(j);
//
// if (subsetStateA == dfaState->getSubset()) {
// isExist = true;
// break;
// }
// }
//
// if (isExist) {
// curState->connect(dfaState, c);
// } else {
// std::cout << "here\n";
// State::StatePtr_t newState(new State(++mCurId, subsetStateA));
//
// processStack.push(newState);
// dfa->push_back(newState);
//
// curState->connect(newState, c);
// }
// }
// }
// State::StatePtr_t stateA(new State(++mCurId, subsetStateA));
// State::StatePtr_t stateB(new State(++mCurId, subsetStateB));
//
// if (/* stateA->isFinal() || */!stateA->getSubset().empty()) { initDFAstate->connect(stateA, 'a'); processStack.push(stateA); }
// if (/*stateB->isFinal() || */!stateB->getSubset().empty()) { initDFAstate->connect(stateB, 'b'); processStack.push(stateB); }
//
// if (stateA->getSubset().empty() && stateB->getSubset().empty()) {
// if (stateA->isFinal() || stateB->isFinal()) {
// dfa->push_back(initDFAstate);
// // processedStates.insert(nfa->at(1)->getId());
// }
// } else {
// dfa->push_back(initDFAstate);
// // processedStates.insert(nfa->at(1)->getId());
// }
//
// while (!processStack.empty()) {
// auto curState = processStack.top();
// processStack.pop();
//
// std::cout << curState->getId() << " " << *curState << "\n";
// sleep(1);
// std::cout.flush();
//
// subsetStateA.clear();
// subsetStateB.clear();
//
// for (const auto& subState: curState->getSubset()) {
// for (const auto& connSubState: subState->getConnections()) {
// // std::cout << "subId=" << subState->getId() << " ";
// if (connSubState->mChar == 'a') {
// // if (processedStates.find(subState->getId()) != processedStates.end())
// subsetStateA.insert(connSubState->mState);
// } else if (connSubState->mChar == 'b') {
// // if (processedStates.find(subState->getId()) != processedStates.end())
// subsetStateB.insert(connSubState->mState);
// } else {
// std::cerr << "Undefined symbol\n";
// }
// }
// }
//
// State::StatePtr_t stateA(new State(++mCurId, subsetStateA));
// State::StatePtr_t stateB(new State(++mCurId, subsetStateB));
//
// if (!stateA->getSubset().empty()) { curState->connect(stateA, 'a'); processStack.push(stateA); }
// if (!stateB->getSubset().empty()) { curState->connect(stateB, 'b'); processStack.push(stateB); }
//
// bool isExist = false;
// if (stateA->getSubset().empty() && stateB->getSubset().empty()) {
// if (stateA->isFinal() || stateB->isFinal()) {
//// for (const auto& s: *dfa) {
//// if (s->getId() == curState->getId()) {
//// isExist = true;
//// break;
//// }
//// }
//// if (isExist) break;
// dfa->push_back(curState);
// }
// } else {
//// for (const auto& s: *dfa) {
//// if (s->getId() == curState->getId()) {
//// isExist = true;
//// break;
//// }
//// }
//// if (isExist) break;
// dfa->push_back(curState);
// }
//
// }
// return dfa;
//}
//ThompsonConstruction::DFAPtr_t ThompsonConstruction::powerset(const NFAPtr_t& nfa) {
// DFAPtr_t dfa(new DFA_t);
// std::stack<State::StatePtr_t> toProcess;
// std::set<State::StatePtr_t> dfaStartSet;
// std::set<State::StatePtr_t> nfaStartSet;
//
// mCurId = 0;
//
// nfaStartSet.insert(nfa->at(0));
//
// epsilon_steps(nfaStartSet, dfaStartSet);
// for (auto state: *nfa) {
// cout << state->getId() << " ";
// cout << *state;
// cout << endl;
// }
// cout << "DFA=" << endl;
// for (auto state: dfaStartSet) {
// cout << state->getId() << " ";
// cout << *state;
// cout << endl;
// }
//
// State::StatePtr_t dfaStart(new State(mCurId, dfaStartSet));
// dfa->push_back(dfaStart);
// toProcess.push(dfaStart);
//
// while (!toProcess.empty()) {
// State::StatePtr_t state = toProcess.top();
// toProcess.pop();
//
// // For the terminal alphabet
// for (int i = 0; i < 2; ++i) {
// char c = i == 0 ? 'a' : 'b';
//
// set<State::StatePtr_t> stepSet, epsStepSet;
// step(c, state->getSubset(), stepSet);
// epsilon_steps(stepSet, epsStepSet);
//
// bool enclosed = false;
// State::StatePtr_t enclosure;
//
// for (auto j = 0; j < dfa->size(); ++j) {
// enclosure = dfa->at(j);
//
// if (enclosure->getSubset() == epsStepSet) {
// enclosed = true;
// break;
// }
// }
//
// if (!epsStepSet.empty()) {
// if (enclosed) {
// state->connect(enclosure, c);
// } else {
// State::StatePtr_t join(new State(++mCurId, epsStepSet));
// toProcess.push(join);
// dfa->push_back(join);
//
// state->connect(join, c);
// }
// }
// }
// }
//
// return dfa;
//} | true |
b63f392c703493f173cd3ea50605673345f7b197 | C++ | mjun1208/ShootingGame3D | /cBoundingSphere.h | UTF-8 | 1,099 | 2.59375 | 3 | [] | no_license | #pragma once
enum ObjTag
{NONE, PLAYER, ENEMY, PLAYERBULLET, DARKBALL ,BAT, ENEMYATTACKBOUND, MAP , COIN, HEAL};
struct CollInfo
{
ObjTag Tag;
Vec3 Pos;
float Size;
};
class cBoundingSphere
{
public:
private:
struct SPHERE {
Vec3 vCenter;
float fRadius;
SPHERE(Vec3 Center, float Radius)
:vCenter(Center), fRadius(Radius) {};
};
LPD3DXMESH SphereMesh;
Vec3 m_vPos;
ObjTag m_Tag;
bool b_Del;
float f_Size;
bool b_SetActive;
bool b_IsColl;
CollInfo * MyInfo;
vector<CollInfo *> m_Collinfo;
public:
cBoundingSphere();
~cBoundingSphere();
void ComputeBoundingSphere(ObjTag tag, float radius);
void Update();
void Render();
void Release();
void SetPos(Vec3 vPos) { m_vPos = vPos; }
Vec3 GetPos() { return m_vPos; }
bool GetDel() { return b_Del; }
void SetDel(bool del) { b_Del = del; }
ObjTag GetTag() { return m_Tag; }
float GetSize() { return f_Size; }
vector<CollInfo *>& GetCollinfo() { return m_Collinfo; }
bool GetActive() { return b_SetActive; }
void SetActive(bool Coll) { b_SetActive = Coll; }
CollInfo * GetInfo() { return MyInfo; }
};
| true |
28de157bbb9215975247affb5451411b3b54de69 | C++ | KaranKaira/Questions-Algorithms | /Tree/MaximumPathSumLeafNodes.cpp | UTF-8 | 646 | 2.875 | 3 | [
"MIT"
] | permissive | #include<bits/stdc++.h>
using namespace std;
int ans = INT_MIN ;
int solve(Node * root)
{
if(root == NULL) return 0;
if(!root->right && !root->left) return root->data;
int l = solve(root->left);
int r = solve(root->right);
if(root->left && root->right) {
ans = max(ans,root->data + l +r );
return max(l,r) + root->data;
}
else if(root->right)
{
return (root->data + r );
}
else return (root->data + l);
}
int maxPathSum(Node* root)
{
// code here
if(root==NULL) return 0;
ans = INT_MIN;
solve(root);
return ans;
}
int main()
{
//formality
}
| true |
8afbb60c44a67c2ace255953bc900c26ba7ba751 | C++ | jas-bar/quark | /quarkgamecontainer.cpp | UTF-8 | 1,882 | 2.59375 | 3 | [
"Zlib"
] | permissive | #include "quarkgamecontainer.h"
QuarkGameContainer::QuarkGameContainer()
{
running = true;
maxFPS = 60;
}
void QuarkGameContainer::setGame(QuarkGame *g)
{
this->game = g;
}
void QuarkGameContainer::init(EngineSettings* settings)
{
maxFPS = settings->maxFPS;
input.reset(new Input());
input->registerListener(SDL_QUIT, &quitListener);
idealFrameDuration = (Uint32)(1000 / maxFPS);
window = SDL_CreateWindow(settings->windowTitle, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, settings->width, settings->height, settings->flags);
glContext = SDL_GL_CreateContext(window);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
game->init(window, input.get());
}
void QuarkGameContainer::render()
{
game->render();
SDL_GL_SwapWindow(window);
}
void QuarkGameContainer::update()
{
input->update();
if(quitListener.isQuitRequested()){
running = false;
}
game->update(input.get());
}
bool QuarkGameContainer::isRunning()
{
return running;
}
void QuarkGameContainer::tickStart()
{
tickStartTime = SDL_GetTicks();
}
void QuarkGameContainer::tickEnd()
{
Uint32 tickEndTime = SDL_GetTicks();
Uint32 realFrameDuration = tickEndTime - tickStartTime;
if(realFrameDuration < idealFrameDuration){
SDL_Delay(idealFrameDuration - realFrameDuration);
}
}
QuarkGameContainer::~QuarkGameContainer()
{
SDL_GL_DeleteContext(glContext);
SDL_DestroyWindow(window);
}
QuarkGCQuitListener::QuarkGCQuitListener()
{
quitRequested = false;
}
void QuarkGCQuitListener::onEvent(SDL_Event* event)
{
if(event->type == SDL_QUIT)
quitRequested = true;
}
bool QuarkGCQuitListener::isQuitRequested()
{
return quitRequested;
}
| true |
39b4bcbd9a226198298e3fa5a6df9221bc96a8b0 | C++ | omkarlenka/leetcode | /buy_and_sell_stock II.cpp | UTF-8 | 863 | 3.078125 | 3 | [] | no_license | //
// buy_and_sell_stock II.cpp
//
// Created by omlenka on 21/06/20.
// Copyright © 2020 omkar lenka. All rights reserved.
//
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int maxProfit(vector<int>& prices)
{
int profit = 0;
int buy = -1;
for(int i = 0;i<prices.size();i++)
{
if(buy == -1)
{
buy = prices[i];
}
else
{
if(prices[i] <= buy)
buy = prices[i];
else
{
if(i == prices.size()-1 || prices[i+1] < prices[i])
{
profit += prices[i] - buy;
buy = -1;
}
}
}
}
return profit;
}
};
| true |
e22c85d53bd2ec849609b2864d3055ff7056ceec | C++ | dnfwlq8054/coding_test | /baekjoon/Silver/Gcd_14490.cpp | UTF-8 | 547 | 2.640625 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <string>|
#include <random>
#pragma warning(disable: 4996)
using namespace std;
int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
int main() {
int N, a, b, M;
int MAX = 1;
string s;
cin >> s;
int n1 = 0, n2 = 0;
for (int i = 0; i < s.size(); i++) {
if (s[i] == ':') {
n1 = stoi(s.substr(0, i));
n2 = stoi(s.substr(i + 1, s.size()));
break;
}
}
int re = gcd(n1, n2);
cout << n1 / re << ":" << n2 / re << endl;
return 0;
} | true |
b35b0bfee1b007cd57b7a840aa14f935e9b4f9ad | C++ | Dmitrivm/msu_cpp_autumn_2018 | /Yerzhanov/hw7/vector.h | UTF-8 | 4,238 | 3.578125 | 4 | [
"MIT"
] | permissive | #pragma once
#include <exception>
#include <iterator>
#include <new>
#include <limits>
template<class T>
class Allocator {
public:
T* address(T& x) const noexcept {
return &x;
}
const T* adress(const T& x) const noexcept {
return &x;
}
T* allocate(size_t n) {
return static_cast<T*>(::operator new(n * sizeof(T)));
}
void deallocate(T* p) {
::operator delete(static_cast<void*>(p));
}
size_t max_size() const noexcept {
return std::numeric_limits<size_t>::max() / sizeof(T);
}
template<typename... Args>
void construct(T* p, Args&&... args) {
::new ((void*) p) T(std::forward<Args>(args)...);
}
void destroy(T* p) {
p->~T();
}
};
template <class T>
class Iterator: public std::iterator<std::random_access_iterator_tag, T>
{
T* p_;
public:
Iterator(){}
Iterator(T* position) {
p_ = position;
}
~Iterator() {}
bool operator==(const Iterator<T>& data) const {
return p_ == data.p_;
}
bool operator!=(const Iterator<T>& data) const {
return !(p_ == data.p_);
}
T& operator*() {
return *p_;
}
T operator*() const {
return *p_;
}
Iterator<T>& operator++() {
++p_;
return *this;
}
Iterator<T> operator++(int) {
return p_++;
}
Iterator<T>& operator--() {
--p_;
return *this;
}
Iterator<T> operator--(int) {
return p_--;
}
};
template <class T, class Alloc = Allocator<T>>
class Vector
{
size_t size_;
size_t capacity_;
T* data_;
Alloc alloc_;
public:
using iterator = Iterator<T>;
Vector()
: size_(0)
, capacity_(1)
, data_(alloc_.allocate(capacity_))
{}
~Vector() {
for (size_t i = 0; i < size_; ++i) {
alloc_.destroy(data_ + i);
}
alloc_.deallocate(data_);
}
bool empty() const noexcept {
return size_ == 0;
}
size_t size() const noexcept {
return size_;
}
size_t capacity() const noexcept {
return capacity_;
}
auto begin() const noexcept {
return iterator(data_);
}
auto end() const noexcept {
return iterator(data_ + size_);
}
auto rbegin() const noexcept {
return std::reverse_iterator<iterator>(data_ + size_);
}
auto rend() const noexcept {
return std::reverse_iterator<iterator>(data_);
}
void push_back(T&& item) {
if (size_ == capacity_) {
reserve(capacity_ * 2);
}
alloc_.construct(data_ + size_++, std::move(item));
}
void push_back(const T& item) {
if (size_ == capacity_) {
reserve(capacity_ * 2);
}
alloc_.construct(data_ + size_++, item);
}
void pop_back() {
if (size_ == 0) {
throw std::out_of_range("");
}
alloc_.destroy(data_ + --size_);
}
void reserve(size_t n) {
if (capacity_ < n) {
T* tmp = alloc_.allocate(n);
for (size_t i = 0; i < size_; ++i) {
alloc_.construct(tmp + i, std::move(*(data_ + i)));
alloc_.destroy(data_ + i);
}
alloc_.deallocate(data_);
data_ = tmp;
capacity_ = n;
}
}
void resize(size_t n) {
if (size_ > n) {
for (size_t i = n; i < size_; ++i) {
alloc_.destroy(data_ + i);
}
} else {
if (n > capacity_) {
reserve(n);
}
for (size_t i = size_; i < n; ++i) {
alloc_.construct(data_ + i);
}
}
size_ = n;
}
void clear() {
for (size_t i = 0; i < size_; ++i) {
alloc_.destroy(data_ + i);
}
size_ = capacity_ = 0;
}
const T& operator[](size_t n) const {
if (n >= size_) {
throw std::out_of_range("");
}
return data_[n];
}
T& operator[](size_t n) {
if (n >= size_) {
throw std::out_of_range("");
}
return data_[n];
}
};
| true |
2cf2558fdb5375bca8665be96b9dae834c6affc6 | C++ | PROUSDER/Uni-work | /program/practice/divide_and_multiply.cpp | UTF-8 | 155 | 2.921875 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main () {
double x;
cout << "enter a value.";
cin >> x;
cout << x/3 << ' ' << x * 2;
return 0;
}
| true |
9a1723b5b2932b1e489a02b027a2a53e9c66ca1d | C++ | bbernardoni/pillow | /pillow/animation.cpp | UTF-8 | 2,197 | 2.8125 | 3 | [
"MIT"
] | permissive | #include "animation.h"
AnimFrame::AnimFrame(IntRect textureRect, Time frameLength) :
texRect(textureRect),
frameLen(frameLength)
{
changeTex = true;
transform = false;
}
AnimFrame::AnimFrame(Vector2f trans, float rot, Vector2f scl, Time frameLength) :
translate(trans),
rotate(rot),
scale(scl),
frameLen(frameLength)
{
changeTex = false;
transform = true;
}
AnimFrame::AnimFrame(IntRect textureRect, Vector2f trans, float rot, Vector2f scl, Time frameLength) :
texRect(textureRect),
translate(trans),
rotate(rot),
scale(scl),
frameLen(frameLength)
{
changeTex = true;
transform = true;
}
Animation::Animation(Time frameLength):
frameLen(frameLength)
{
reset();
}
void Animation::addFrame(AnimFrame animFrame){
frames.push_back(animFrame);
animLen += getFrameLen(animFrame);
}
bool Animation::update(Sprite& sprite, Time deltaTime){
for (AnimFrame curFrame = frames[frame]; frameTime + deltaTime > getFrameLen(curFrame); curFrame = frames[frame]){
Time totalLen = getFrameLen(curFrame);
Time animLen = totalLen - frameTime;
if (curFrame.transform){
float ratio = animLen / totalLen;
sprite.rotate(curFrame.rotate * ratio);
Vector2f scaleBy(pow(curFrame.scale.x, ratio), pow(curFrame.scale.y, ratio));
sprite.scale(scaleBy);
sprite.move(curFrame.translate * ratio);
}
deltaTime -= animLen;
frameTime = Time::Zero;
frame++;
if (frame >= frames.size()){
reset();
if (curFrame.changeTex){
sprite.setTextureRect(curFrame.texRect);
}
return true;
}
}
AnimFrame curFrame = frames[frame];
Time totalLen = getFrameLen(curFrame);
if (curFrame.transform){
float ratio = deltaTime / totalLen;
sprite.rotate(curFrame.rotate * ratio);
Vector2f scaleBy(pow(curFrame.scale.x, ratio), pow(curFrame.scale.y, ratio));
sprite.scale(scaleBy);
sprite.move(curFrame.translate * ratio);
}
if (curFrame.changeTex){
sprite.setTextureRect(curFrame.texRect);
}
frameTime += deltaTime;
return false;
}
void Animation::reset(){
frame = 0;
frameTime = Time::Zero;
}
Time Animation::getFrameLen(AnimFrame af){
Time curFrameLen = af.frameLen;
if (curFrameLen == Time::Zero)
return frameLen;
return curFrameLen;
} | true |
e75fbb2e2aaf8e29526db3ddaacc62fa6fb0335f | C++ | viditg2896/GFGRepo | /Arrays/wavearray.cpp | UTF-8 | 813 | 3.265625 | 3 | [] | no_license | #include<algorithm>
#include<vector>
using namespace std;
int main()
{
//need to sort the array first to get lexicographically least ans
int i,t,n,temp;
cin>>t;
while(t){
cin>>n;
int arr[n];
for(i=0;i<n;i++){
cin>>arr[i];
}
sort(arr,arr+n);
//Swapping outliers alternatively
for(i=0;i<n-1;i++){
if(i%2==0){
if(arr[i+1]>arr[i]){
temp = arr[i+1];
arr[i+1] = arr[i];
arr[i] = temp;
}
}
else{
if(arr[i]>arr[i+1]){
temp = arr[i+1];
arr[i+1] = arr[i];
arr[i] = temp;
}
}
}
for(i=0;i<n;i++){
cout<<arr[i]<<" ";
}
cout<<endl;
t--;
}
return 0;
} | true |
3bcd84fcd6fe1bf8ee33bde36707af6f0807fc1b | C++ | king7282/algorithm | /codeforces/681Div2D.cpp | UTF-8 | 783 | 2.53125 | 3 | [] | no_license | #include <stdio.h>
#include <algorithm>
#include <climits>
int input[30010];
int main(void) {
int test;
scanf("%d", &test);
for (int t = 0; t < test; t++) {
int n;
scanf("%d", &n);
for (int i = 1; i <= n; i++)
scanf("%d", input + i);
int start = n;
input[n + 1] = INT_MAX / 2;
while (start >= 1) {
if (input[start] <= input[start + 1])
start--;
else
break;
}
if (start == 0) {
printf("YES\n");
continue;
}
bool flag = true;
int minus = 0;
for (int i = start; i >= 1 && flag; i--) {
int need = std::max(0, input[i] - input[i + 1]);
input[i] -= std::max(need, minus);
minus = std::max(minus, need);
if (input[i] < 0)
flag = false;
}
if (flag)
printf("YES\n");
else
printf("NO\n");
}
} | true |
7080daea5ba5810e3416f1bb90222ad4d2dd21ed | C++ | sravya273/BasicProgramming | /String Manipulation/ReverseString.cpp | UTF-8 | 338 | 3.328125 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
void reverseString(string &str)
{
int length = str.length();
for(int i=0;i<length/2;i++)
{
swap(str[i], str[length-i-1]);
}
}
int main() {
string str;
cin>> str;
cout<<"Reversal of "<<str<<" is ";
reverseString(str);
cout<<str<<endl;
return 0;
}
| true |
058f8a255dcaff6f6bb4adf762e5f1b5de172428 | C++ | AlexFirfarov/olympic-programming | /Осень/Siberia 1 ноября/11.cpp | UTF-8 | 556 | 2.84375 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <unordered_map>
#include <vector>
int main() {
int n;
std::cin >> n;
std::string f;
std::vector<std::string> types;
std::unordered_map<std::string, int> m;
while (n--) {
std::cin >> f;
int idx = f.find('.');
std::string type = f.substr(idx + 1);
if (!m.count(type))
types.push_back(type);
++m[type];
}
for (const std::string& type: types) {
std::cout << type << ": " << m[type] << "\n";
}
} | true |
1bc43edecbef9267be80c29f2b4ead041b2c0487 | C++ | Jorgitou98/Acepta-el-Reto | /Soluciones/AceptaElReto285VacasPensantes.cpp | UTF-8 | 1,949 | 3.390625 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
#ifndef MATRIZ_H
#define MATRIZ_H
#include <vector>
template <typename Object>
class Matriz {
public:
// crea una matriz con fils filas y cols columnas,
// con todas sus celdas inicializadas al valor e
Matriz(int fils, int cols, Object e = Object()) : datos(fils, std::vector<Object>(cols, e)) {}
// operadores para poder utilizar notación M[i][j]
std::vector<Object> const& operator[](int f) const {
return datos[f];
}
std::vector<Object> & operator[](int f) {
return datos[f];
}
// métodos que lanzan una excepción si la posición no existe
Object const& at(int f, int c) const {
return datos.at(f).at(c);
}
Object & at(int f, int c) { // este método da problemas cuando Object == bool
return datos.at(f).at(c);
}
int numfils() const { return datos.size(); }
int numcols() const { return numfils() > 0 ? datos[0].size() : 0; }
bool posCorrecta(int f, int c) const {
return 0 <= f && f < numfils() && 0 <= c && c < numcols();
}
private:
std::vector<std::vector<Object>> datos;
};
#endif
#include <vector>
using namespace std;
bool resuelveCaso() {
int N;
cin >> N;
if (N == 0)
return false;
vector <int> cubos;
int valor;
for (int i = 0; i < N; ++i) {
cin >> valor;
cubos.push_back(valor);
}
Matriz<int> M(N, N);
for (int i = 0; i < N; ++i) M[i][i] = cubos[i];
for (int d = 1; d < N; ++d)
for (int i = 0; i < N - d; ++i) {
int j = i + d;
int suma1, suma2;
if (i + 1 == j) suma1 = cubos[i];
else if (cubos[i + 1] >= cubos[j]) suma1 = cubos[i] + M[i + 2][j];
else suma1 = cubos[i] + M[i + 1][j-1];
if (j - 1 == i) suma2 = cubos[j];
else if (cubos[j-1] >= cubos[i]) suma2 = cubos[j] + M[i][j-2];
else suma2 = cubos[j] + M[i + 1][j - 1];
M[i][j] = max(suma1, suma2);
}
cout << M[0][N - 1] << '\n';
return true;
}
int main() {
cin.sync_with_stdio(false);
cin.tie(nullptr);
while (resuelveCaso());
return 0;
}
| true |
6b000f01e13266e40a879bcc3da51e0f9d2162b0 | C++ | kmilo9999/Mico | /Mico/Math.cpp | UTF-8 | 5,894 | 3.171875 | 3 | [] | no_license | #include "Math.h"
#include <glm/gtx/transform.hpp>
#include <glm/gtx/quaternion.hpp>
#include <glm/gtx/norm.hpp>
#include <glm/gtx/euler_angles.hpp>
Math::Math()
{
}
Math::~Math()
{
}
mat4 Math::CreateTransformationMatrix(vec3& translation, quat& orientation, vec3& scaleSize)
{
mat4 translate = glm::translate(mat4(), translation);
mat4 rotate = toMat4(orientation);
mat4 scale = glm::scale(mat4(), scaleSize);
return translate * rotate * scale;
}
quat Math::RotationBetweenVectors(vec3& start, vec3& dest)
{
start = normalize(start);
dest = normalize(dest);
float cosTheta = dot(start, dest);
vec3 rotationAxis;
if (cosTheta < -1 + 0.001f) {
rotationAxis = cross(vec3(0.0f, 0.0f, 1.0f), start);
if (length2(rotationAxis) < 0.01)
rotationAxis = cross(vec3(1.0f, 0.0f, 0.0f), start);
rotationAxis = normalize(rotationAxis);
return angleAxis(180.0f, rotationAxis);
}
rotationAxis = cross(start, dest);
float s = sqrt((1 + cosTheta) * 2);
float invs = 1 / s;
return quat(
s * 0.5f,
rotationAxis.x * invs,
rotationAxis.y * invs,
rotationAxis.z * invs
);
}
vec3 Math::Cross(vec3& v, vec3& w)
{
vec3 result = glm::cross(v, w);
return result;
}
float Math::Dot(vec3& v, vec3& w)
{
float result = glm::dot(v, w);
return result;
}
vec3 Math::EulerAngles(quat q)
{
return glm::eulerAngles(q);
}
quat Math::fromEulerAngles(vec3 eulerAngles)
{
return glm::toQuat(glm::orientate3(eulerAngles));
}
quat Math::GetRotation(vec3& orig, vec3& dest, vec3& up)
{
quat q;
vec3 v0 = orig;
vec3 v1 = dest;
v0 = normalize(v0);
v1 = normalize(v1);
float d = Math::Dot(v0, v1);
if (d >= 1.0f)
{
return q;
}
if (d < (1e-6f - 1.0f))
{
if (up != vec3(0, 0, 0))
{
q = angleAxis(180.0f, up);
}
else
{
// Generate an axis
vec3 axis = cross(vec3(1, 0, 0), v0);
if (length(axis) == 0)
{
axis = cross(vec3(0, 1, 0), v0);
}
axis = normalize(axis);
q = angleAxis(180.0f, axis);
}
}
else
{
float s = sqrt((1 + d) * 2);
float invs = 1 / s;
vec3 c = cross(v0, v1);
q.x = c.x * invs;
q.y = c.y * invs;
q.z = c.z * invs;
q.w = s * 0.5f;
q = normalize(q);
}
return q;
}
quat Math::Slerp(quat& q1, quat& q2, float t)
{
quat out = q2;
float alpha, beta;
float cosom = q1.x*q2.x + q1.y*q2.y + q1.z*q2.z + q1.w*q2.w;
float slerp_epsilon = 0.00001f;
bool flip;
if (flip = (cosom < 0))
{
cosom = -cosom;
}
if ((1.0 - cosom) > slerp_epsilon)
{
float omega = acos(cosom);
float sinom = sin(omega);
alpha = (float)(sin((1.0 - t) * omega) / sinom);
beta = (float)(sin(t * omega) / sinom);
}
else
{
alpha = (float)(1.0 - t);
beta = (float)t;
}
if (flip)
{
beta = -beta;
}
out.x = (float)(alpha*q1.x + beta*q2.x);
out.y = (float)(alpha*q1.y + beta*q2.y);
out.z = (float)(alpha*q1.z + beta*q2.z);
out.w = (float)(alpha*q1.w + beta*q2.w);
return out;
}
float Math::Distance(vec3& v, vec3& w)
{
return length(w - v);
}
mat4 & Math::InverseTranspose(const mat4 & m)
{
float SubFactor00 = m[2][2] * m[3][3] - m[3][2] * m[2][3];
float SubFactor01 = m[2][1] * m[3][3] - m[3][1] * m[2][3];
float SubFactor02 = m[2][1] * m[3][2] - m[3][1] * m[2][2];
float SubFactor03 = m[2][0] * m[3][3] - m[3][0] * m[2][3];
float SubFactor04 = m[2][0] * m[3][2] - m[3][0] * m[2][2];
float SubFactor05 = m[2][0] * m[3][1] - m[3][0] * m[2][1];
float SubFactor06 = m[1][2] * m[3][3] - m[3][2] * m[1][3];
float SubFactor07 = m[1][1] * m[3][3] - m[3][1] * m[1][3];
float SubFactor08 = m[1][1] * m[3][2] - m[3][1] * m[1][2];
float SubFactor09 = m[1][0] * m[3][3] - m[3][0] * m[1][3];
float SubFactor10 = m[1][0] * m[3][2] - m[3][0] * m[1][2];
float SubFactor11 = m[1][1] * m[3][3] - m[3][1] * m[1][3];
float SubFactor12 = m[1][0] * m[3][1] - m[3][0] * m[1][1];
float SubFactor13 = m[1][2] * m[2][3] - m[2][2] * m[1][3];
float SubFactor14 = m[1][1] * m[2][3] - m[2][1] * m[1][3];
float SubFactor15 = m[1][1] * m[2][2] - m[2][1] * m[1][2];
float SubFactor16 = m[1][0] * m[2][3] - m[2][0] * m[1][3];
float SubFactor17 = m[1][0] * m[2][2] - m[2][0] * m[1][2];
float SubFactor18 = m[1][0] * m[2][1] - m[2][0] * m[1][1];
mat4 Inverse;
Inverse[0][0] = +(m[1][1] * SubFactor00 - m[1][2] * SubFactor01 + m[1][3] * SubFactor02);
Inverse[0][1] = -(m[1][0] * SubFactor00 - m[1][2] * SubFactor03 + m[1][3] * SubFactor04);
Inverse[0][2] = +(m[1][0] * SubFactor01 - m[1][1] * SubFactor03 + m[1][3] * SubFactor05);
Inverse[0][3] = -(m[1][0] * SubFactor02 - m[1][1] * SubFactor04 + m[1][2] * SubFactor05);
Inverse[1][0] = -(m[0][1] * SubFactor00 - m[0][2] * SubFactor01 + m[0][3] * SubFactor02);
Inverse[1][1] = +(m[0][0] * SubFactor00 - m[0][2] * SubFactor03 + m[0][3] * SubFactor04);
Inverse[1][2] = -(m[0][0] * SubFactor01 - m[0][1] * SubFactor03 + m[0][3] * SubFactor05);
Inverse[1][3] = +(m[0][0] * SubFactor02 - m[0][1] * SubFactor04 + m[0][2] * SubFactor05);
Inverse[2][0] = +(m[0][1] * SubFactor06 - m[0][2] * SubFactor07 + m[0][3] * SubFactor08);
Inverse[2][1] = -(m[0][0] * SubFactor06 - m[0][2] * SubFactor09 + m[0][3] * SubFactor10);
Inverse[2][2] = +(m[0][0] * SubFactor11 - m[0][1] * SubFactor09 + m[0][3] * SubFactor12);
Inverse[2][3] = -(m[0][0] * SubFactor08 - m[0][1] * SubFactor10 + m[0][2] * SubFactor12);
Inverse[3][0] = -(m[0][1] * SubFactor13 - m[0][2] * SubFactor14 + m[0][3] * SubFactor15);
Inverse[3][1] = +(m[0][0] * SubFactor13 - m[0][2] * SubFactor16 + m[0][3] * SubFactor17);
Inverse[3][2] = -(m[0][0] * SubFactor14 - m[0][1] * SubFactor16 + m[0][3] * SubFactor18);
Inverse[3][3] = +(m[0][0] * SubFactor15 - m[0][1] * SubFactor17 + m[0][2] * SubFactor18);
float Determinant =
+m[0][0] * Inverse[0][0]
+ m[0][1] * Inverse[0][1]
+ m[0][2] * Inverse[0][2]
+ m[0][3] * Inverse[0][3];
Inverse /= Determinant;
return Inverse;
}
quat Math::angleAxis(float angle, vec3& axis)
{
return glm::angleAxis(angle, axis);
}
| true |
fdb0f3f967b51baf1a45aecb533977b64b2ad945 | C++ | ydszza/chatroom | /CLIENT/client/sign_in.cpp | UTF-8 | 2,501 | 2.59375 | 3 | [] | no_license | #include "sign_in.h"
#include "ui_sign_in.h"
#include <QDebug>
#include <QtNetwork>
#include <QMessageBox>
#include <cstring>
/*构造函数,布局页面*/
sign_in::sign_in(QWidget *parent) :
QWidget(parent),
ui(new Ui::sign_in)
{
this->setFixedSize(400, 300);
ui->setupUi(this);
connect(ui->pushButton_sign_in, SIGNAL(clicked()), this, SLOT(slot_sign_in()));
}
/*析构函数*/
sign_in::~sign_in()
{
delete ui;
}
/*登录槽函数,进行账号密码有效判断并连接服务器*/
void sign_in::slot_sign_in()
{
//获取账号密码
account = ui->lineEdit_account->text();
password = ui->lineEdit_password->text();
//判断是否为空,为空直接返回
if(!account.isEmpty() && !password.isEmpty())
{
//创建连接发送并验证
//qDebug()<<sock_fd;
qDebug()<<"点击登陆显示:"<<account+" "<<password;
}
else
{
QMessageBox::information(this,tr("错误"),tr("账号或密码不能为空"));
return;
}
this->ui->pushButton_sign_in->setEnabled(false);
thread = new msg_manage;
//thread->run();
connect(this, SIGNAL(signal_sign_in(QString,QString)), thread, SLOT(slot_sign_in(QString, QString)));
connect(thread, SIGNAL(signal_sign_in_verify(msg_t *)),this, SLOT(slot_sign_in_verify(msg_t *)));
emit signal_sign_in(account, password);
}
/*验证登录状态槽函数*/
void sign_in::slot_sign_in_verify(msg_t *msg)
{
qDebug()<<"get verify msg!";
if(msg->verify == 0)
{
this->ui->pushButton_sign_in->setEnabled(false);
//登录成功
Home = new home;
connect(thread, SIGNAL(signal_add_or_out_newclient(msg_t *)),Home, SLOT(slot_add_or_out_newclient(msg_t *)));
connect(thread, SIGNAL(signal_get_new_msg(msg_t*)),Home, SLOT(slot_get_new_msg(msg_t*)));
connect(Home, SIGNAL(signal_home_send_msg(QString*)),thread, SLOT(slot_send_data(QString*)));
qDebug()<<"验证账号成功";
this->hide();
Home->show();
}
else if(msg->verify == 1)
{
//该账号已登录
this->ui->pushButton_sign_in->setEnabled(true);
QMessageBox::information(this,tr("错误"),tr("账号已登录"));
}
else
{
//账号或密码错误
QMessageBox::information(this,tr("错误"),tr("账号或密码错误"));
this->ui->pushButton_sign_in->setEnabled(true);
}
//验证完成,释放消息s
delete msg;
msg = NULL;
}
| true |
e95bbf189550dc5f77aff8c3ba6630f3d1e7f386 | C++ | jsen07/CS2010_Groop3 | /TakeoverGame/TakeoverGame/src/engine/core/Mouse.h | UTF-8 | 1,056 | 2.515625 | 3 | [] | no_license | #pragma once
#include "ValkyrieEngine.h"
#include "../utils/Vector.h"
namespace vlk
{
typedef Int MouseButton;
namespace MouseButtons
{
extern const MouseButton BUTTON_1;
extern const MouseButton BUTTON_2;
extern const MouseButton BUTTON_3;
extern const MouseButton BUTTON_4;
extern const MouseButton BUTTON_5;
extern const MouseButton BUTTON_6;
extern const MouseButton BUTTON_7;
extern const MouseButton BUTTON_8;
extern const MouseButton BUTTON_LEFT;
extern const MouseButton BUTTON_RIGHT;
extern const MouseButton BUTTON_MIDDLE;
extern const MouseButton BUTTON_LAST;
}
namespace Mouse
{
void Init();
void Destroy();
//Is this button pressed?
Boolean IsButtonDown(MouseButton button);
//Was this button pressed this frame?
Boolean IsButtonPressed(MouseButton button);
//Was this button released this frame?
Boolean IsButtonReleased(MouseButton button);
Vector2 GetPosition();
Vector2 GetCenteredPosition();
Vector2 GetPositionDelta();
Vector2 GetScroll();
Vector2 GetScrollDelta();
}
} | true |
774fc76e03e6cf461400f29f2ed7a366df5d5b1f | C++ | Diusrex/UVA-Solutions | /10160 Servicing Stations.cpp | UTF-8 | 3,416 | 3.046875 | 3 | [
"Apache-2.0"
] | permissive | #include <iostream>
#include <vector>
#include <bitset>
using namespace std;
typedef bitset<35> bset;
// Is quite fast (top 3) with the least obvious speedup being only search in connected components
// (which shaved the last 0.02 seconds off)
// Also ensures that, if trying to skip node, that it can be completed
// Nothing really fancy other than those two
// A further improvement could be, for nodes that are only connected to a single other node who is not connected to a service station, know will just include the other guy
// This could be advanced quite far along the graph
int N;
bset allIncluded;
// Who is connected to
bset connections[35];
// Who may be connected after this node. Based on following checks
bset connectedAfter[35];
// To find connected components
void dfs(int node, bset &included)
{
included[node] = true;
for (int i = 0; i < N; ++i)
if (connections[node][i] && !included[i])
dfs(i, included);
}
void FindLowestCost(bset connected, int currentNode, int currentCount, int & bestCount)
{
// All are connected
if (connected == allIncluded)
{
bestCount = min(bestCount, currentCount);
return;
}
// No point in continuing
// If is equal to bestCount - 1, will need to add at least one more node
if (currentCount >= bestCount - 1)
return;
// Cannot continue. Don't think this should be reached
if (currentNode == N)
{
return;
}
// Try including this guy, but only if he will add any usefulness
bset whenAdded = connected | connections[currentNode];
if (connected != whenAdded)
{
FindLowestCost(whenAdded, currentNode + 1, currentCount + 1, bestCount);
}
// Try not including this guy. But only if there is still a valid solution after
if ((connected | connectedAfter[currentNode]) == allIncluded)
{
FindLowestCost(connected, currentNode + 1, currentCount, bestCount);
}
}
int main()
{
int M;
while (cin >> N >> M, N)
{
for (int i = 0; i < N; ++i)
{
connections[i].reset();
connections[i].set(i);
}
allIncluded.reset();
for (int i = 0; i < N; ++i)
allIncluded.set(i);
while (M--)
{
int i, j;
cin >> i >> j;
--i; --j;
connections[i].set(j);
connections[j].set(i);
}
// Since nothing can be reached after it
connectedAfter[N - 1].reset();
for (int i = N - 2; i >= 0; --i)
connectedAfter[i] = connectedAfter[i + 1] | connections[i + 1];
// Will match for the overallIncluded
bset overallIncluded;
int bestOverall = 0;
for (int i = 0; i < N; ++i)
{
if (!overallIncluded[i])
{
// Will need to include i, or part of its component
bset component;
dfs(i, component);
bset outsideComponent = allIncluded ^ component;
int componentBest = N;
FindLowestCost(outsideComponent, 0, 0, componentBest);
overallIncluded |= component;
bestOverall += componentBest;
}
}
cout << bestOverall << '\n';
}
} | true |
252c6ae4945a89dff0f39dc531277376be8d4eff | C++ | hansewetz/gitrep2 | /src/cpp/experiments/tests/test-atomic/test1.cc | UTF-8 | 600 | 2.6875 | 3 | [] | no_license | // (C) Copyright Hans Ewetz 2010,2011,2012,2013,2014,2015,2016. All rights reserved.
#include <atomic>
#include <thread>
#include <assert.h>
std::atomic<bool> x,y;
std::atomic<int> z;
void write_x_then_y(){
x.store(true,std::memory_order_relaxed);
y.store(true,std::memory_order_release);
}
void read_y_then_x(){
while(!y.load(std::memory_order_acquire));
if(x.load(std::memory_order_relaxed))
++z;
}
int main(){
for(auto i=0;i<(2<<15);++i){
x=false;
y=false;
z=0;
std::thread a(write_x_then_y);
std::thread b(read_y_then_x);
a.join();
b.join();
assert(z.load()!=0);
}
}
| true |
b748f27e5c4b2782b6370796e65401f4a897bfe5 | C++ | fcccode/interview-1 | /cpp/opengl_game/0.3.5/oorion/src/iichan/iichan_player.h | UTF-8 | 367 | 2.640625 | 3 | [] | no_license | #ifndef __PLAYER_H_
#define __PLAYER_H_
#include "iichan_character.h"
class PLAYER : public CHARACTER
{
private:
int score;
public:
int GetScore() const { return score; }
void SetScore(int new_value) { score = new_value; }
void CollectPowerup(enum POWERUP_TYPE power_type, int count);
PLAYER(int health, int ammo, int score);
virtual void Move();
};
#endif | true |
e22aa6112704cddb592ec365e58df56aa8c4a098 | C++ | yuexing/problems | /container_util.h | UTF-8 | 3,059 | 3.390625 | 3 | [] | no_license | #ifndef _CONTAINER_UTIL_HPP
#define _CONTAINER_UTIL_HPP
#include <map>
#include <iostream>
/// avoid long type declaration
#define LET(a, b) \
__typeof__(b) a(b)
#define LETREF(a, b) \
__typeof__(b)& a(b)
#define LETCREF(a, b) \
const __typeof__(b)& a(b)
/// const_iterator type
template<typename C>
class const_iterator_wrapper {
public:
typedef typename C::const_iterator type;
};
template<typename C>
inline typename const_iterator_wrapper<C>::type get_const_iterator(const C& c)
{
return const_iterator_wrapper<C>::type();
}
/// const_reverse_iterator
template<typename C>
class const_reverse_iterator_wrapper {
public:
typedef typename C::const_reverse_iterator type;
};
template<typename C>
inline typename const_reverse_iterator_wrapper<C>::type get_const_reverse_iterator(const C& c)
{
return const_reverse_iterator_wrapper<C>::type();
}
/// foreach util
#define foreach(it, c) \
for(LET(it, (c).begin()); it != (c).end(); ++it)
#define cforeach(it, c) \
for(__typeof__(get_const_iterator((c))) it = (c).begin(); it != (c).end(); ++it)
#define reverse_foreach(it, c) \
for(LET(it, (c).rbegin()); it != (c).rend(); ++it)
#define creverse_foreach(it, c) \
for(__typeof__(get_const_reverse_iterator((c))) it = (c).rbegin(); it != (c).rend(); ++it)
// erase all the elements that satisfy the \p predict.
// \p iter_ahead: used in condition to specify the current element
// \p seq: the sequential container
#define SEQ_ERASE(iter_ahead, seq, predicate) \
{ \
LET(iter_ahead, (seq).begin()); \
LET(iter_valid, (seq).begin()); \
for(; iter_ahead != (seq).end(); ++iter_ahead) { \
if (!(predicate)) { \
*(iter_valid++) = *iter_ahead; \
} \
} \
(seq).erase(iter_valid, (seq).end()); \
}
/// general
template<typename C, typename K>
inline bool contains(C c, K k)
{
return c.find(k) != c.end();
}
template<typename K, typename V>
inline std::ostream& operator<<(std::ostream &os, const std::pair<K,V> &p)
{
os << "("<< p.first << "," << p.second << ")";
return os;
}
/// print containers
/// usage: ostream << printable_container(c);
template<typename C>
struct printable_container_t
{
const C& c;
char seperator;
printable_container_t(const C& c, char seperator)
: c(c), seperator(seperator)
{}
virtual void print(std::ostream &os) const {
bool first = true;
foreach(it, c) {
if(first){
first = false;
os << *it;
} else {
os << seperator << *it;
}
}
}
};
template<typename C>
inline std::ostream& operator<<(std::ostream &os, const printable_container_t<C> &pc)
{
pc.print(os);
return os;
}
template<typename C>
inline printable_container_t<C> printable_container(const C& c, char seperator = ',')
{
return printable_container_t<C>(c, seperator);
}
#endif
| true |
8641a696783f0184af120f1b556552d0fbee00c3 | C++ | Atsu30/ProgramingContest | /ABC/131D.cpp | UTF-8 | 706 | 2.984375 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
struct Work{
long long A;
long long B;
};
bool cmp(const Work &a, const Work &another) {
return a.B < another.B;
};
int main(){
int N;
cin >> N;
vector<long long> A(N), B(N);
vector<Work> works(N);
for(int i = 0; i < N; i++){
cin >> A[i] >> B[i];
Work w = {A[i], B[i]};
works[i] = w;
}
sort(works.begin(), works.end(), cmp);
long long t = 0;
for(int i = 0; i < N; i++){
t += works[i].A;
if(t > works[i].B){
cout << "No" << endl;
return 0;
}
// cout << works[i].B << endl;
}
cout << "Yes" << endl;
return 0;
} | true |
5a8a9e35190607af14ea49198c8c22e4572a48bc | C++ | LKolya97/my-work | /6.cpp | UTF-8 | 1,509 | 3.359375 | 3 | [] | no_license | // ConsoleApplication5.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
double n, s;
int a, b;
cout << "Choose which type of temperature you want to convert\n 1-Fahrenheit\n 2-Celsius\n 3-Kelvin\n";
cin >> (a);
switch (a)
{
case 1:{
cout << "Choose to which type of temperature you want to convert to\n 1-Celsius\n 2-Kelvin ";
cin >> (b);
switch (b) {
case 1: {
cout << "Enter the temperature \n";
cin >> (n);
s = (n - 32) / 1.8;
};
case 2: {
cout << "Enter the temperature \n";
cin >> (n);
s = (n - 32) / 1.8 +273;
}
}
break;
};
case 2:{
cout << "Choose which type of temperature you want to convert\n 1-Fahrenheit\n 2-Kelvin\n";
cin >> (b);
switch (b) {
case 1: {
cout << "Enter the temperature \n";
cin >> (n);
s = (n-32)/1.8 ;
};
case 2: {
cout << "Enter the temperature \n";
cin >> (n);
s = n + 273;
}
}
break;
};
case 3:{
cout << "Choose which type of temperature you want to convert\n 1-Fahrenheit\n 2-Celsius\n";
cin >> (b);
switch (b) {
case 1: {
cout << "Enter the temperature \n";
cin >> (n);
s = 1.8*(n - 273) + 32;
};
case 2: {
cout << "Enter the temperature \n";
cin >> (n);
s = n-273;
}
}
break;
};
default:
break;
}
cout << s;
cin >> a;
return 0;
}
| true |
953fa2495c2b3d102e8a8434be242ba6666cfd3e | C++ | anhvvcs/corana | /libs/z3/src/util/s_integer.cpp | UTF-8 | 1,297 | 2.953125 | 3 | [
"MIT"
] | permissive | /*++
Copyright (c) 2006 Microsoft Corporation
Module Name:
s_integer.cpp
Abstract:
<abstract>
Author:
Leonardo de Moura (leonardo) 2007-06-10.
Revision History:
--*/
#include "util/s_integer.h"
s_integer s_integer::m_zero(0);
s_integer s_integer::m_one(1);
s_integer s_integer::m_minus_one(-1);
s_integer::s_integer(const char * str) {
m_val = static_cast<int>(strtol(str, nullptr, 10));
}
s_integer power(const s_integer & r, unsigned p) {
unsigned mask = 1;
s_integer result = s_integer(1);
s_integer power = r;
while (mask <= p) {
if (mask & p) {
result *= power;
}
power *= power;
mask = mask << 1;
}
return result;
}
s_integer gcd(const s_integer & r1, const s_integer & r2) {
SASSERT(r1.is_int() && r2.is_int());
s_integer tmp1(r1);
s_integer tmp2(r2);
if (tmp1.is_neg()) {
tmp1.neg();
}
if (tmp2.is_neg()) {
tmp2.neg();
}
if (tmp1 < tmp2) {
tmp1.swap(tmp2);
}
for(;;) {
s_integer aux = tmp1 % tmp2;
if (aux.is_zero()) {
return tmp2;
}
tmp1 = tmp2;
tmp2 = aux;
}
}
s_integer lcm(const s_integer & r1, const s_integer & r2) {
s_integer g = gcd(r1, r2);
return (r1 / g) * r2;
}
| true |
6f8326c719b2a7579062d72e504f38246c5b1a40 | C++ | wangning0/learn_cpp | /StrBlob.cpp | UTF-8 | 1,007 | 3.453125 | 3 | [] | no_license | #include <iostream>
#include <memory>
#include <list>
#include <vector>
using namespace std;
class StrBlob {
public:
typedef vector<string>::size_type size_type;
StrBlob();
StrBlob(initializer_list<string> li);
size_type size() const { return data -> size(); };
bool empty() const { return data -> empty(); };
void push_back(const string &t) { data -> push_back(t); };
void pop_back();
string& front();
string& back();
private:
shared_ptr<vector<string>> data;
void check(size_type i,const string &msg) const;
};
void StrBlob::check(size_type i,const string &msg) const {
if( i >= data->size() ) {
throw out_of_range(msg);
}
}
string& StrBlob::front() {
check(0,"front on empty StrBlob");
return data -> front();
}
string& StrBlob::back() {
check(0, "back on empty StrBlob");
return data -> back();
}
void StrBlob::pop_back() {
check(0, "pop_back on empty StrBlob");
data->pop_back();
}
int main() {
return 0;
}
| true |
72422bcd53e4b40f96ea2843cccccce567e75a50 | C++ | GPUOpen-LibrariesAndSDKs/TAN | /tan/tests/src/common/anyoption.h | UTF-8 | 9,282 | 2.59375 | 3 | [
"MIT"
] | permissive | /*
The MIT License(MIT)
Copyright(c) 2016 Kishan Thomas www.hackorama.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files(the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions :
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#pragma once
#include <iostream>
#include <stdlib.h>
#include <string>
//#include <fstream>
#include <wchar.h>
using namespace std;
#define COMMON_OPT 1
#define COMMAND_OPT 2
#define FILE_OPT 3
#define COMMON_FLAG 4
#define COMMAND_FLAG 5
#define FILE_FLAG 6
#define COMMAND_OPTION_TYPE 1
#define COMMAND_FLAG_TYPE 2
#define FILE_OPTION_TYPE 3
#define FILE_FLAG_TYPE 4
#define UNKNOWN_TYPE 5
#define DEFAULT_MAXOPTS 10
#define MAX_LONG_PREFIX_LENGTH 2
#define DEFAULT_MAXUSAGE 3
#define DEFAULT_MAXHELP 10
#define TRUE_FLAG L"true"
using namespace std;
class AnyOption
{
public: /* the public interface */
AnyOption();
AnyOption(int maxoptions);
AnyOption(int maxoptions, int maxcharoptions);
~AnyOption();
/*
* following set methods specifies the
* special characters and delimiters
* if not set traditional defaults will be used
*/
void setCommandPrefixChar(wchar_t _prefix); /* '-' in "-w" */
void setCommandLongPrefix(wchar_t *_prefix); /* '--' in "--width" */
void setFileCommentChar(wchar_t _comment); /* '#' in shellscripts */
void setFileDelimiterChar(wchar_t _delimiter);/* ':' in "width : 100" */
/*
* provide the input for the options
* like argv[] for commndline and the
* option file name to use;
*/
void useCommandArgs(int _argc, wchar_t **_argv);
void useFiileName(const wchar_t *_filename);
/*
* turn off the POSIX style options
* this means anything starting with a '-' or "--"
* will be considered a valid option
* which alo means you cannot add a bunch of
* POIX options chars together like "-lr" for "-l -r"
*
*/
void noPOSIX();
/*
* prints warning verbose if you set anything wrong
*/
void setVerbose();
/*
* there are two types of options
*
* Option - has an associated value ( -w 100 )
* Flag - no value, just a boolean flag ( -nogui )
*
* the options can be either a string ( GNU style )
* or a character ( traditional POSIX style )
* or both ( --width, -w )
*
* the options can be common to the commandline and
* the optionfile, or can belong only to either of
* commandline and optionfile
*
* following set methods, handle all the aboove
* cases of options.
*/
/* options comman to command line and option file */
void setOption(const wchar_t *opt_string);
void setOption(wchar_t opt_char);
void setOption(const wchar_t *opt_string, wchar_t opt_char);
void setFlag(const wchar_t *opt_string);
void setFlag(wchar_t opt_char);
void setFlag(const wchar_t *opt_string, wchar_t opt_char);
/* options read from commandline only */
void setCommandOption(const wchar_t *opt_string);
void setCommandOption(wchar_t opt_char);
void setCommandOption(const wchar_t *opt_string, wchar_t opt_char);
void setCommandFlag(const wchar_t *opt_string);
void setCommandFlag(wchar_t opt_char);
void setCommandFlag(const wchar_t *opt_string, wchar_t opt_char);
/* options read from an option file only */
void setFileOption(const wchar_t *opt_string);
void setFileOption(wchar_t opt_char);
void setFileOption(const wchar_t *opt_string, wchar_t opt_char);
void setFileFlag(const wchar_t *opt_string);
void setFileFlag(wchar_t opt_char);
void setFileFlag(const wchar_t *opt_string, wchar_t opt_char);
/*
* process the options, registerd using
* useCommandArgs() and useFileName();
*/
void processOptions();
void processCommandArgs();
void processCommandArgs(int max_args);
bool processFile();
/*
* process the specified options
*/
void processCommandArgs(int _argc, wchar_t **_argv);
void processCommandArgs(int _argc, wchar_t **_argv, int max_args);
//bool processFile( const wchar_t *_filename );
/*
* get the value of the options
* will return NULL if no value is set
*/
wchar_t *getValue(const wchar_t *_option);
bool getFlag(const wchar_t *_option);
wchar_t *getValue(wchar_t _optchar);
bool getFlag(wchar_t _optchar);
/*
* Print Usage
*/
void printUsage();
void printAutoUsage();
void addUsage(const wchar_t *line);
void printHelp();
/* print auto usage printing for unknown options or flag */
void autoUsagePrint(bool flag);
/*
* get the argument count and arguments sans the options
*/
int getArgc();
wchar_t* getArgv(int index);
bool hasOptions();
private: /* the hidden data structure */
int argc; /* commandline arg count */
wchar_t **argv; /* commndline args */
const wchar_t* filename; /* the option file */
wchar_t* appname; /* the application name from argv[0] */
int *new_argv; /* arguments sans options (index to argv) */
int new_argc; /* argument count sans the options */
int max_legal_args; /* ignore extra arguments */
/* option strings storage + indexing */
int max_options; /* maximum number of options */
const wchar_t **options; /* storage */
int *optiontype; /* type - common, command, file */
int *optionindex; /* index into value storage */
int option_counter; /* counter for added options */
/* option chars storage + indexing */
int max_char_options; /* maximum number options */
wchar_t *optionchars; /* storage */
int *optchartype; /* type - common, command, file */
int *optcharindex; /* index into value storage */
int optchar_counter; /* counter for added options */
/* values */
wchar_t **values; /* common value storage */
int g_value_counter; /* globally updated value index LAME! */
/* help and usage */
const wchar_t **usage; /* usage */
int max_usage_lines; /* max usage lines reseverd */
int usage_lines; /* number of usage lines */
bool command_set; /* if argc/argv were provided */
bool file_set; /* if a filename was provided */
bool mem_allocated; /* if memory allocated in init() */
bool posix_style; /* enables to turn off POSIX style options */
bool verbose; /* silent|verbose */
bool print_usage; /* usage verbose */
bool print_help; /* help verbose */
wchar_t opt_prefix_char; /* '-' in "-w" */
wchar_t long_opt_prefix[MAX_LONG_PREFIX_LENGTH]; /* '--' in "--width" */
wchar_t file_delimiter_char; /* ':' in width : 100 */
wchar_t file_comment_char; /* '#' in "#this is a comment" */
wchar_t equalsign;
wchar_t comment;
wchar_t delimiter;
wchar_t endofline;
wchar_t whitespace;
wchar_t nullterminate;
bool set; //was static member
bool once; //was static member
bool hasoptions;
bool autousage;
private: /* the hidden utils */
void init();
void init(int maxopt, int maxcharopt);
bool alloc();
void cleanup();
bool valueStoreOK();
/* grow storage arrays as required */
bool doubleOptStorage();
bool doubleCharStorage();
bool doubleUsageStorage();
bool setValue(const wchar_t *option, wchar_t *value);
bool setFlagOn(const wchar_t *option);
bool setValue(wchar_t optchar, wchar_t *value);
bool setFlagOn(wchar_t optchar);
void addOption(const wchar_t* option, int type);
void addOption(wchar_t optchar, int type);
void addOptionError(const wchar_t *opt);
void addOptionError(wchar_t opt);
bool findFlag(wchar_t* value);
void addUsageError(const wchar_t *line);
bool CommandSet();
bool FileSet();
bool POSIX();
wchar_t parsePOSIX(wchar_t* arg);
int parseGNU(wchar_t *arg);
bool matchChar(wchar_t c);
int matchOpt(wchar_t *opt);
/* dot file methods */
wchar_t *readFile();
wchar_t *readFile(const wchar_t* fname);
bool consumeFile(char *buffer);
void processLine(wchar_t *theline, int length);
wchar_t *chomp(wchar_t *str);
void valuePairs(wchar_t *type, wchar_t *value);
void justValue(wchar_t *value);
void printVerbose(const wchar_t *msg);
void printVerbose(wchar_t *msg);
void printVerbose(wchar_t ch);
void printVerbose();
};
| true |
c37356b14271be992bda6b45b08fc97625351380 | C++ | nabilme/xplduino.software | /beta/test_switch_lighting_shutter_xpl_i2c/switch_core.h | UTF-8 | 3,381 | 2.59375 | 3 | [] | no_license | #ifndef switch_core_h
#define switch_core_h
#include "Arduino.h"
#include <stdio.h>
//~ #define MAX_SWITCH 16
#define T_CMND 1
#define T_STAT 2
#define T_TRIG 3
#define ADDR_TEMP 0 // 1=nouveau niveau de l'entree
#define ADDR_PULSE 1 // 1=appui pulse
#define ADDR_DPULSE 2 // 1=appui double pulse
#define ADDR_ON 3 // 1=appui maintenu
#define ADDR_ON_OSR 4 // 1=appui maintenu, sur un cycle
#define ADDR_ON_OSF 5 // 1=switch relaché, sur un cycle
#define ADDR_LEVEL 6 // 1=niveau precedent de l'entree
#define ADDR_HIGH 0 // 1=LOW, inverse le sens de l’entrée
#define ADDR_PRE0 4 // fonction de pré-traitement associé
#define ADDR_PRE1 5 // fonction de pré-traitement associé
#define R_LEVEL bitRead(status, ADDR_LEVEL)
#define R_PULSE bitRead(status, ADDR_PULSE)
#define R_DPULSE bitRead(status, ADDR_DPULSE)
#define R_ON bitRead(status, ADDR_ON)
#define R_ON_OSR bitRead(status, ADDR_ON_OSR)
#define R_ON_OSF bitRead(status, ADDR_ON_OSF)
#define R_TEMP bitRead(status, ADDR_TEMP)
#define R_HIGH bitRead(parameter, ADDR_HIGH)
#define R_PRE0 bitRead(parameter, ADDR_PRE0)
#define R_PRE1 bitRead(parameter, ADDR_PRE1)
#define W_LEVEL(value) bitWrite(status, ADDR_LEVEL, value)
#define W_PULSE(value) bitWrite(status, ADDR_PULSE, value)
#define W_DPULSE(value) bitWrite(status, ADDR_DPULSE, value)
#define W_ON(value) bitWrite(status, ADDR_ON, value)
#define W_ON_OSR(value) bitWrite(status, ADDR_ON_OSR, value)
#define W_ON_OSF(value) bitWrite(status, ADDR_ON_OSF, value)
#define W_TEMP(value) bitWrite(status, ADDR_TEMP, value)
#define W_HIGH(value) bitWrite(parameter, ADDR_HIGH, value)
#define W_PRE0(value) bitWrite(parameter, ADDR_PRE0, value)
#define W_PRE1(value) bitWrite(parameter, ADDR_PRE1, value)
class Switch
{
public:
//méthodes
Switch();
int init(char *_name, byte _parameter, byte _DI_address, byte _maintained_delay); // initialise les paramètres du switch
int update(byte _new_level); // mis à jour de l'état de l'entrée
int isPulse(); // renvoi l'état pulse
int isDoublePulse(); // renvoi l'état double pulse
int isOn(); // renvoi l'état On
int isOnOSR(); // renvoi l'état du trigger Off -> On
int isOff(); // renvoi l'état Off
int isOnOSF(); // renvoi l'état du trigger On -> Off
int config(); //provisoire, juste pour relire les valeurs et vérifier qu'elles sont correctement memorisees. TODO: a supprimer
private:
byte maintained_delay; // délai en ms button pour considérer comme maintenu
byte timer_maintained; // compteur de temps incrémenté tant que l’entrée est à 1 (x100ms)
byte timer_doublepulse; // compteur de temps décrémenté dès qu'une impulsion est détecté
public:
char name[16+1]; // nom du switch
byte DI_address; // entrée numérique de la fonction de pré-traitement
byte status; // octet contenant les états calculés (cf détails)
byte parameter; // octet contenant un ensemble de paramètres (cf détails)
};
#endif
| true |
f34e79a7fc9bad6b8a4d83b04fe9612f3e6d8bd8 | C++ | teym/captchacker | /C++ sources/Centrage caractères/main.cpp | UTF-8 | 3,186 | 2.71875 | 3 | [] | no_license | #include <iostream>
#include <string>
#include "boost/filesystem.hpp"
#include "cv.h"
#include "cxcore.h"
#include "highgui.h"
#if defined (WIN32)
#pragma comment(lib,"cv")
#pragma comment(lib,"cvaux")
#pragma comment(lib,"cxcore")
#pragma comment(lib,"highgui")
#pragma comment(lib,"cvcam")
#endif
using namespace std;
using namespace boost::filesystem;
void process_file(string filenameIN, int WIDTH, int HEIGHT)
{
//cout << "processing file: " << filenameIN << endl;
IplImage *srcImg=0, *res=0;
srcImg = cvLoadImage(filenameIN.c_str(),0);
if (srcImg) {
res = cvCreateImage( cvSize(WIDTH, HEIGHT), IPL_DEPTH_8U, 1 );
cvFillImage(res, 255);
int xmin=WIDTH, xmax=0, ymin=HEIGHT, ymax=0;
for (int i=0; i<srcImg->width; ++i)
{
for (int j=0; j<srcImg->height; ++j)
{
if (cvGet2D(srcImg, j, i).val[0] == 0)
{
if (i<xmin)
xmin = i;
if (i>xmax)
xmax = i;
if (j<ymin)
ymin=j;
if (j>ymax)
ymax=j;
}
}
}
int offsetx = (WIDTH - (xmax-xmin))/2;
int offsety = (HEIGHT - (ymax-ymin))/2;
for (int i=0; i<=xmax-xmin; ++i)
{
for (int j=0; j<=ymax-ymin; ++j)
{
if ((offsety+j>0) && (offsety+j<res->height) && (offsetx+i>0) && (offsetx+i<res->width))
cvSet2D(res, offsety+j, offsetx+i, cvGet2D(srcImg, ymin+j, xmin+i));
}
}
cvSaveImage(filenameIN.c_str(), res);
}
else {
cout << "WARNING: File not found!!" << endl;
}
}
void process_folder(path folder, int WIDTH, int HEIGHT) {
cout << "Processing "<<folder.native_directory_string() << " folder... ";
if ( !exists(folder ) ) {
cout << "Folder not found. Aborting.";
exit(1);
}
directory_iterator itr(folder), end_itr;
for ( ; itr != end_itr; ++itr ){
if (is_directory(itr->status())){
process_folder(itr->path(), WIDTH, HEIGHT);
}
else if (is_regular(itr->status())) {
string filename = itr->leaf();
if (filename.substr(filename.length()-3,3) == "bmp") {
//cout<<itr->leaf()<< " => bmp found!!"<< endl;
process_file(folder.native_directory_string()+"/"+itr->leaf(), WIDTH, HEIGHT);
}
}
}
cout << "Done." << endl;
}
int main(int argc, char *argv[])
{
path folder;
int WIDTH;
int HEIGHT;
if (argc < 2)
{
/*folder = "./DBTraining-Simulation_based";
WIDTH = 20;
HEIGHT = 20;*/
cout << "Usage:"<<endl<<" Linux: Centrage path/to/folder WIDTH HEIGHT"<<endl<<" Windows: Centrage.exe path/to/folder WIDTH HEIGHT"<<endl;
exit(1);
}
else
{
folder = argv[1];
//cout << "folder IN " << folder << endl;
WIDTH = atoi(argv[2]);
//cout << "WIDTH " << WIDTH << endl;
HEIGHT = atoi(argv[3]);
//cout << "HEIGHT " << HEIGHT << endl;
}
process_folder(folder, WIDTH, HEIGHT);
return 0;
}
| true |
7551b709bcdda8a85f1c4ec49211a1d2bb14d0e4 | C++ | eariunerdene/C-course | /Day#1/#1 Homework.cpp | UTF-8 | 190 | 3.171875 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main ()
{
int x=1,y=2,z=3;
cout<<"1. "<<x+y-z<<endl;
cout<<"2. "<<x/z*y<<endl;
cout<<"3. "<<20*x*(z+y)<<endl;
return 0;
}
| true |
bd2f437482c640f69f7fe306bdb72d66cbce15c3 | C++ | goaldae/Algorithm | /src/programmers/stringCompression.cpp | UTF-8 | 1,065 | 2.90625 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
#include <map>
#include <string>
using namespace std;
string ans = "";
using namespace std;
int shortest(int cutNum, string s) {
int n = s.size() / cutNum; //잘린 개수
vector<string> temp;
for (int i = 0; i < n; i++) {
temp.push_back(s.substr(i*cutNum, cutNum));
}
if (s.size() % cutNum != 0) {
temp.push_back(s.substr(n*cutNum, s.size() % cutNum));
}
string cur = temp[0];
int cnt = 1;
string answer = "";
for (int i = 1; i < temp.size(); i++) {
if (cur != temp[i]) {
if (cnt != 1) {
answer += to_string(cnt);
}
answer += cur;
cnt = 1;
cur = temp[i];
}
else {
cnt++;
}
}
if (cnt != 1) {
answer += to_string(cnt);
}
answer += cur;
return answer.size();
}
int solution(string s) {
int answer = 10000;
if (s.size() == 1) return 1;
for (int i = 1; i <= s.size() / 2; i++) {
answer = min(answer, shortest(i, s));
}
return answer;
}
int main(void) {
cout << solution("abcabcabcabcdededededede");
} | true |
ef8cdfea953e5545f5d930a094d0567f8e01193b | C++ | likeleon/Geometry | /Geometry/Public/Rtree.h | UTF-8 | 1,797 | 2.640625 | 3 | [] | no_license | #pragma once
#include <cassert>
#include <memory>
#include <utility>
#include "Geometry/Public/Box.h"
#include "Geometry/Public/InsertVisitor.h"
#include "Geometry/Public/Node.h"
#include "Math/Vec3.h"
namespace Geometry {
namespace Index {
namespace Detail {
template <size_t MaxElements>
struct DefaultMinElements {
static const size_t raw_value = (MaxElements * 3) / 10;
static const size_t value = 1 <= raw_value ? raw_value : 1;
};
template <size_t MaxElements>
struct DefaultRstarReinsertedElements {
static const size_t value = (MaxElements * 3) / 10;
};
} // namespace Detail
struct NoProperty {
};
template <
size_t MaxElements,
size_t MinElements = Detail::DefaultMinElements<MaxElements>::value,
typename Property = NoProperty
>
class Rtree {
static_assert(0 < MinElements && 2 * MinElements <= MaxElements + 1, "Invalid min max parameters");
using Value = std::pair<Math::Vec3, Property>;
using Leaf = Detail::Leaf<Property>;
public:
void Insert (const Math::Vec3& point, const Property& property = NoProperty()) {
if (root_ == nullptr) {
RawCreate();
}
RawInsert(std::make_pair(point, property));
}
size_t size () const {
return values_count_;
}
bool empty () const {
return values_count_ == 0;
}
size_t depth () const {
return depth_;
}
private:
void RawCreate () {
root_ = std::make_unique<Leaf>();
values_count_ = 0;
depth_ = 0;
}
void RawInsert (const Value& value) {
assert(root_ != nullptr && "The root must exist");
InsertVisitor<Value, Value, MinElements, MaxElements> insert_visitor(*root_, value, depth_, 0 /* relative_level */);
insert_visitor(*root_);
++values_count_;
}
std::unique_ptr<Leaf> root_;
size_t values_count_ = 0;
size_t depth_ = 0;
};
} // namespace Index
} // namespace Geometry
| true |
8be644156516a3df88ddbb61763969cec8aaefcb | C++ | akudrinsky/sorts | /src/statsInt.cpp | UTF-8 | 1,728 | 3.03125 | 3 | [] | no_license | #include "../include/statsInt.hpp"
#include "../include/usefulDefines.hpp"
#include <cstdio>
#define GENERATE_COMPARE_OPERATOR_STATSINT(op)\
bool StatsInt::operator op (const StatsInt& other) {\
++compareNum;\
return number op other.number;\
}
Stats::Stats(const char* filename) {
FILE* file = fopen(filename, "r");
int nSize = 0, nSwaps = 0, nCompares = 0;
while (EOF != fscanf(file, "%d: %d %d\n", &nSize, &nSwaps, &nCompares)) {
sizes.push_back(nSize);
swaps.push_back(nSwaps);
compares.push_back(nCompares);
LOGS("read %d: %d %d\n", nSize, nSwaps, nCompares)
}
fclose(file);
}
unsigned long StatsInt::compareNum = 0;
unsigned long StatsInt::swapNum = 0;
StatsInt::StatsInt(): number(0) {}
StatsInt::StatsInt(int number): number(number) {}
StatsInt::StatsInt(const StatsInt& other): number(other.number) {}
StatsInt& StatsInt::operator = (const StatsInt& other) {
number = other.number;
return *this;
}
StatsInt::operator int() {
return number;
}
unsigned long StatsInt::showCompares() {
return StatsInt::compareNum;
}
unsigned long StatsInt::showSwaps() {
return StatsInt::swapNum;
}
void StatsInt::restart() {
StatsInt::compareNum = 0;
StatsInt::swapNum = 0;
}
GENERATE_COMPARE_OPERATOR_STATSINT(<)
GENERATE_COMPARE_OPERATOR_STATSINT(==)
GENERATE_COMPARE_OPERATOR_STATSINT(!=)
GENERATE_COMPARE_OPERATOR_STATSINT(>)
GENERATE_COMPARE_OPERATOR_STATSINT(<=)
GENERATE_COMPARE_OPERATOR_STATSINT(>=)
void std::swap(StatsInt& first, StatsInt& second) {
//printf("SWAP: %d and %d\n", first.number, second.number);
++StatsInt::swapNum;
int tmp = first.number;
first.number = second.number;
second.number = tmp;
} | true |
0cc4d27d2e256cc8bfa3432e3063c41e1b09e548 | C++ | segoranov/exam_preparation_programming | /introduction_to_programming_problems/10_09_2018_SOFTUERNO_problem1/reveal_password_v2.cpp | UTF-8 | 1,569 | 3.8125 | 4 | [] | no_license | #include <string.h>
#include <iostream>
#include <string>
bool isSorted(const char* books[], int booksCnt) {
for (int i = 0; i < booksCnt - 1; ++i) {
if (strcmp(books[i], books[i + 1]) > 0) return false;
}
return true;
}
std::string processTitle(const char* title) {
std::string result;
int cnt = 0;
while (*title != '\0') {
if (*title != ' ') {
++cnt;
} else {
result += std::to_string(cnt);
result += " ";
cnt = 0;
}
++title;
}
result += std::to_string(cnt);
return result;
}
void revealPassword(const char** books[], int rows, int booksInRow) {
std::string password;
const int middle =
(booksInRow % 2 == 0) ? (booksInRow - 1) / 2 : booksInRow / 2;
for (int row = 0; row < rows; row++) {
if (isSorted(books[row], booksInRow)) {
password += processTitle(books[row][middle]);
password += " ";
}
}
std::cout << password << std::endl;
}
int main() {
// clang-format off
const char* row1[] = {"Algebra", "Analytical Geometry", "Mathematical analysis"};
const char* row2[] = {"Data structures", "Introduction to programming", "Object oriented programming"};
const char* row3[] = {"Data bases", "Artifical intelligence", "Functional programming"};
const char** books[] = {row1, row2, row3};
// clang-format on
// We should print "Analytical Geometry" and "Introduction to programming" as
// password, which gives us '10 8 12 2 11'. The 3rd row should be skipped,
// since it is not sorted alphabetically
revealPassword(books, 3, 3);
}
| true |
4eb6841aed2928f8ed1451cbb3a9fa16d4d9b743 | C++ | blayzekohime/GSP420_MAIN | /GSP420_Main/AI.cpp | UTF-8 | 3,432 | 2.828125 | 3 | [] | no_license | #include "AI.h"
//#include "Game.h"
AI::AI(void)
{
}
AI::~AI(void)
{
}
void AI::update(const float dt, std::list<Enemy> enemies, std::list<GSP420::ABC> projectiles, GSP420::ABC player)
{
// Iterate through the list of enemies and updtae their AI based on their type
std::list<Enemy>::iterator enemyIt = enemies.begin();
while (enemyIt != enemies.end())
{
switch(enemyIt->getObjectType())
{
case OT_ENEMY1:
{
enemy1Update(*enemyIt, player);
} break;
case OT_ENEMY2:
{
enemy2Update(*enemyIt);
} break;
case OT_ENEMY3:
{
enemy3Update(*enemyIt);
} break;
case OT_ENEMYBOSS:
{
enemyBossUpdate(*enemyIt);
} break;
}
enemyIt++;
}
// Iterate through the list of projectiles and updtae their AI based on their type
std::list<GSP420::ABC>::iterator projectileIt = projectiles.begin();
while (projectileIt != projectiles.end())
{
switch(projectileIt->getObjectType())
{
case OT_PLAYER_MISSILE:
{
playerMissUpdate(*projectileIt);
} break;
case OT_ENEMY_MISSILE:
{
enemyMissUpdate(*projectileIt, player);
} break;
}
projectileIt++;
}
}
/////// This enemy behavior seeks out the player ////////
/////// until they reach a set Y value at which ////////
/////// point they simply fly straight. ////////
void AI::enemy1Update(Enemy enemy, GSP420::ABC player)
{
// Check if enemy Y position is higher than half the game height
if (enemy.getPosition().y > 0.0f) // TODO: Modify for exact game height constant
{
D3DXVECTOR3 tempVel;
tempVel = player.getPosition() - enemy.getPosition();
D3DXVec3Normalize(&tempVel, &tempVel);
// TODO: Multiply tempVel by enemy speed constant
enemy.setVelocity(tempVel);
}
if (enemy.getBulletFireRate() == 0.0f)
enemy.fireBullet(D3DXVECTOR3(0.0f, 5.0f, 0.0f)); // TODO: Modify for a fixed bullet speed constant
}
void AI::enemy2Update(Enemy enemy)
{
}
void AI::enemy3Update(Enemy enemy)
{
}
void AI::enemyBossUpdate(Enemy enemy)
{
}
void AI::playerMissUpdate(GSP420::ABC proj)
{
}
//////// Missile tracks player and follows them ////////
//////// Has a limited turning radius. ////////
//////// Has a limited lifetime until it ////////
//////// explodes ////////
void AI::enemyMissUpdate(GSP420::ABC proj, GSP420::ABC player)
{
D3DXVECTOR3 currDir, newDir;
// Get the missiles current direction from its velocity
currDir = proj.getVelocity();
D3DXVec3Normalize(&currDir, &currDir);
// Get the missiles new direction according to player position
newDir = player.getPosition() - proj.getPosition();
D3DXVec3Normalize(&newDir, &newDir);
// Find the angle between the two vectors
float angle = D3DXVec3Dot(&currDir, &newDir);
angle = acos(angle);
// Re-use newDir vector for updating projectile velocity
newDir = proj.getVelocity();
// Check if angle is larger than our missile's turning radius
// Then update the missiles velocity
if (abs(angle) > 5.0f) // TODO: modify for a constant max turning radius value
{
if (angle > 0.0f)
{
newDir.x += 5.0f;
proj.setVelocity(newDir);
}
else
{
newDir.x -= 5.0f;
proj.setVelocity(newDir);
}
}
else
{
if (angle > 0.0f)
{
newDir.x += angle;
proj.setVelocity(newDir);
}
else
{
newDir.x -= angle;
proj.setVelocity(newDir);
}
}
// TODO: Modify orientation of projectile
// TODO: Add check for missile lifetime to see if it has run out of time
} | true |
9729283d2f6f3e494c01e4fb52b2a63f389afe2b | C++ | visanalexandru/TerrainGeneration | /Engine/Texture/Texture2d.cpp | UTF-8 | 1,330 | 2.953125 | 3 | [] | no_license | #include "Texture2d.h"
Texture2d::Texture2d():Texture()
{
//ctor
}
void Texture2d::load_texture(std::string path)
{
unsigned int texture;
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
// set the texture wrapping/filtering options (on the currently bound texture object)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
// load and generate the texture
int width, height, nrChannels;
GLuint type=GL_RGB;
stbi_set_flip_vertically_on_load(true);
unsigned char *data = stbi_load(path.c_str(), &width, &height, &nrChannels, 0);
if(nrChannels==4)
type=GL_RGBA;
if (data)
{
glTexImage2D(GL_TEXTURE_2D, 0, type, width, height, 0, type, GL_UNSIGNED_BYTE, data);
glGenerateMipmap(GL_TEXTURE_2D);
std::cout<<"Texture loaded: "<<path<<std::endl;
}
else
{
std::cout << "Failed to load texture: " <<path<<std::endl;
}
stbi_image_free(data);
texture_index=texture;
}
void Texture2d::bind_texture()
{
glBindTexture(GL_TEXTURE_2D, texture_index);
}
Texture2d::~Texture2d()
{
//dtor
}
| true |
4673e115ad715c0bf559482c1b9a2a0b5caba0f8 | C++ | charleswang007/c-plus-plus | /C++4ed-SourceCode/Visual Studio/forloop.cpp | UTF-8 | 506 | 3.21875 | 3 | [] | no_license | //=============================================
// C++ Programming in easy steps 4ed. [3:48]
//=============================================
#include <iostream>
using namespace std ;
int main()
{
int i , j ;
for ( i = 1 ; i < 4 ; i++ )
{
cout << "Loop iteration: " << i << endl ;
// Uncomment the lines below to add the nested loop.
// for ( j = 1 ; j < 4 ; j++ )
// {
// cout << " Inner loop iteration: " << j << endl ;
// }
}
system("PAUSE");
return 0 ;
}
| true |
36cbd3f266b62682e804932934017ade713487e9 | C++ | chris118/threadPool | /main.cpp | UTF-8 | 1,604 | 2.53125 | 3 | [] | no_license | //
// main.cpp
// Demo
//
// Created by admin on 2017/3/21.
// Copyright © 2017年 admin. All rights reserved.
//
#include <iostream>
#include <stdio.h>
#include <unistd.h>
#include <signal.h>
#include <string.h>
#include <sys/time.h>
#include <errno.h>
#include <vector>
#include <pthread.h>
#include <thread>
#include <sys/syscall.h>
#define gettid() syscall(__NR_gettid)
#include "ThreadPool.h"
using namespace std;
using namespace hh;
class DetectionTask;
ThreadPool threadPool(2);
int task_id = 0;
class DetectionTask: public Task
{
public:
DetectionTask(){
}
virtual int run()
{
// cout<<"thread name:"<<std::this_thread::get_id()<< " task args: " << (char*)this->arg_ << endl;
cout << taskName_ << " Running !!!" << endl;
sleep(4);
cout << taskName_ << " finished !!!" << endl;
return 0;
}
~DetectionTask(){
cout << taskName_ <<" destroy ~~~" << endl;
}
};
void sigalrm_fn(int sig)
{
alarm(1);
// cout << "threadPool count: " << threadPool.size() << endl;
if(task_id >= 1000){
task_id = 0;
}
else{
task_id++;
}
if(threadPool.size() >= 5)
{
threadPool.clearTask();
}
DetectionTask *task = new DetectionTask();
task->setName(std::to_string(task_id));
task->setArg((void*)std::to_string(task_id).c_str());
threadPool.addTask(task);
return;
}
int main(int argc, const char * argv[]) {
signal(SIGALRM, sigalrm_fn);
alarm(1);
getchar();
return 0;
}
| true |
324be6001582926a25a1dd6bfe601995064b4dc5 | C++ | himanshuromeo/competitive_programming | /multimoo.cpp | UTF-8 | 2,065 | 2.703125 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int N;
bool vis1[260][260];
bool vis2[260][260];
int A[260][260];
int dfs1(int i,int j){
vis1[i][j]=1;
int ans=0;
if(i+1<=N && A[i+1][j]==A[i][j] && !vis1[i+1][j])
ans+=dfs1(i+1,j);
if(i-1>=1 && A[i-1][j]==A[i][j] && !vis1[i-1][j])
ans+=dfs1(i-1,j);
if(j+1<=N && A[i][j+1]==A[i][j] && !vis1[i][j+1])
ans+=dfs1(i,j+1);
if(j-1>=1 && A[i][j-1]==A[i][j] && !vis1[i][j-1])
ans+=dfs1(i,j-1);
return ans+1;
}
int dfs2(int i,int j,int val1,int val2){
vis2[i][j]=1;
int ans=0;
//cout<<i<<" "<<j<<" "<<val1<<" "<<val2<<" "<<A[i][j]<<" "<<A[i+1][j]<<"\n";
if(i+1<=N && (A[i+1][j]==val1 || A[i+1][j]==val2) && !vis2[i+1][j])
ans+=dfs2(i+1,j,val1,val2);
if(i-1>=1 && (A[i-1][j]==val1 || A[i-1][j]==val2) && !vis2[i-1][j])
ans+=dfs2(i-1,j,val1,val2);
if(j+1<=N && (A[i][j+1]==val1 || A[i][j+1]==val2) && !vis2[i][j+1])
ans+=dfs2(i,j+1,val1,val2);
if(j-1>=1 && (A[i][j-1]==val1 || A[i][j-1]==val2) && !vis2[i][j-1])
ans+=dfs2(i,j-1,val1,val2);
return ans+1;
}
int main(){
freopen("multimoo.in","r",stdin);
freopen("multimoo.out","w",stdout);
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int i,j;
cin>>N;
for(i=1;i<=N;i++){
for(j=1;j<=N;j++){
cin>>A[i][j];
}
}
//calculating answer for first part
int ans1=0;
memset(vis1,0,sizeof vis1);
for(i=1;i<=N;i++){
for(j=1;j<=N;j++){
if(!vis1[i][j])
ans1=max(ans1,dfs1(i,j));
}
}
cout<<ans1<<"\n";
//calculating answer for second part
memset(vis2,0,sizeof vis2);
int ans2=0;
for(i=1;i<=N;i++){
for(j=1;j<=N;j++){
if(i>1 && !vis2[i][j]){
ans2=max(ans2,dfs2(i,j,A[i][j],A[i-1][j]));
}
memset(vis2,0,sizeof vis2);
if(i<N && !vis2[i][j]){
ans2=max(ans2,dfs2(i,j,A[i][j],A[i+1][j]));
}
memset(vis2,0,sizeof vis2);
if(j>1 && !vis2[i][j]){
ans2=max(ans2,dfs2(i,j,A[i][j],A[i][j-1]));
}
memset(vis2,0,sizeof vis2);
if(j<N && !vis2[i][j]){
ans2=max(ans2,dfs2(i,j,A[i][j],A[i][j+1]));
}
memset(vis2,0,sizeof vis2);
}
}
cout<<ans2<<"\n";
return 0;
} | true |
36c7e7d08a3893403f8da7c85d1319201512060a | C++ | ashu4306/CSES-Solution | /CSES_1094_Increasing_Array.cpp | UTF-8 | 1,139 | 3.484375 | 3 | [] | no_license | /**
* @author Ashutosh Sharma
* Problem https://cses.fi/problemset/task/1094
*
* Solution 1:
* Time complexity : O(n)
* space complexity : O(1)
*
* if current number >= last number no moves is required
* if current number < last number, for min moves we need to increment current number by value equal to last number
*
* we actually dont need to store all numbers
* we only want last number
**/
#include<bits/stdc++.h>
using namespace std;
int main() {
int n;
cin>>n;
long long min_moves = 0;
/* Storing input */
// vector<int> arr(n);
// for(int i=0;i<n;i++)
// cin>>arr[i];
//
// for(int i=1;i<n;i++) {
// if(arr[i]<arr[i-1]) {
// min_moves += arr[i-1] - arr[i];
// arr[i] = arr[i-1];
// }
// }
//
/* Not Storing input numbers */
int prev_number = 0;
int current_number;
for(int i=0;i<n;i++) {
cin>>current_number;
if(current_number<prev_number) {
min_moves += prev_number - current_number;
current_number = prev_number;
}
prev_number = current_number;
}
cout<<min_moves;
}
| true |
577774533c02cb2fd19609e97ac552357e6ec575 | C++ | yshgpta/Competitive-Coding | /Spoj/SHPATH.cpp | UTF-8 | 1,388 | 2.640625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
#define mxn 100005
#define INF 1000000000
int dist[mxn];
bool vis[mxn];
void initialise(){
for(int i=0;i<mxn;i++){
dist[i]=INF;
vis[i]=false;
}
}
int dijkstra(vector<vector<pair<int,int> > > &adj,int s,int e){
dist[s]=0;
priority_queue <pair<int,int>> pq;
pq.push(make_pair(0,s));
while(!pq.empty()){
pair<int,int> p = pq.top();
pq.pop();
int u = p.second;
if(vis[u]) continue;
int sz = adj[u].size();
for(int i=0;i<sz;i++){
int v = adj[u][i].first;
int cost = adj[u][i].second;
if(vis[v]) continue;
if(dist[v]>dist[u]+cost){
dist[v]=dist[u]+cost;
pq.push(make_pair(-dist[v],v));
}
}
vis[u]=true;
if(e==u)
return dist[e];
}
}
int main(){
int t;
cin>>t;
initialise();
while(t--){
int num;
cin>>num;
map <string,int> mep;
vector < vector< pair < int, int > > > adj(num+1);
for(int i=1;i<=num;i++){
string name;
cin>>name;
mep.insert(make_pair(name,i));
int p;
cin>>p;
for(int j=1;j<=p;j++){
int v,c;
cin>>v>>c;
adj[i].push_back(make_pair(v,c));
}
}
int q;
cin>>q;
string beg,end;
for(int i=0;i<q;i++){
cin>>beg>>end;
cout<<dijkstra(adj,mep[beg],mep[end])<<endl;
initialise();
}
}
return 0;
}
| true |
2bba5a6f9c88fa52fc4af75273a60cb42e5d0388 | C++ | syinari0123/GQN-pytorch | /three/core/renderer/opengl/vao.cpp | UTF-8 | 5,395 | 2.546875 | 3 | [] | no_license | #include "vao.h"
namespace three {
namespace renderer {
namespace opengl {
VertexArrayObject::~VertexArrayObject()
{
delete_buffers();
}
void VertexArrayObject::delete_buffers()
{
if (_prev_num_objects == -1) {
return;
}
glDeleteVertexArrays(_prev_num_objects, _vao.get());
glDeleteBuffers(_prev_num_objects, _vbo_faces.get());
glDeleteBuffers(_prev_num_objects, _vbo_vertices.get());
glDeleteBuffers(_prev_num_objects, _vbo_normal_vectors.get());
glDeleteBuffers(_prev_num_objects, _vbo_vertex_normal_vectors.get());
glDeleteBuffers(_prev_num_objects, _vbo_vertex_colors.get());
}
void VertexArrayObject::build(scene::Scene* scene)
{
delete_buffers();
int num_objects = scene->_objects.size();
_prev_num_objects = num_objects;
_vao = std::make_unique<GLuint[]>(num_objects);
glCreateVertexArrays(num_objects, _vao.get());
_vbo_faces = std::make_unique<GLuint[]>(num_objects);
glCreateBuffers(num_objects, _vbo_faces.get());
_vbo_vertices = std::make_unique<GLuint[]>(num_objects);
glCreateBuffers(num_objects, _vbo_vertices.get());
_vbo_normal_vectors = std::make_unique<GLuint[]>(num_objects);
glCreateBuffers(num_objects, _vbo_normal_vectors.get());
_vbo_vertex_normal_vectors = std::make_unique<GLuint[]>(num_objects);
glCreateBuffers(num_objects, _vbo_vertex_normal_vectors.get());
_vbo_vertex_colors = std::make_unique<GLuint[]>(num_objects);
glCreateBuffers(num_objects, _vbo_vertex_colors.get());
for (int object_index = 0; object_index < num_objects; object_index++) {
GLuint vao = _vao[object_index];
auto& object = scene->_objects[object_index];
int num_faces = object->_num_faces;
int num_vertices = object->_num_vertices;
glNamedBufferData(_vbo_vertices[object_index], 3 * num_faces * sizeof(glm::vec3f), object->_face_vertices.get(), GL_STATIC_DRAW);
glEnableVertexArrayAttrib(vao, _attribute_position);
glVertexArrayAttribFormat(vao, _attribute_position, 3, GL_FLOAT, GL_FALSE, 0);
glVertexArrayAttribBinding(vao, _attribute_position, 0);
glVertexArrayVertexBuffer(vao, 0, _vbo_vertices[object_index], 0, sizeof(glm::vec3f));
glNamedBufferData(_vbo_normal_vectors[object_index], 3 * num_faces * sizeof(glm::vec3f), object->_face_normal_vectors.get(), GL_STATIC_DRAW);
glEnableVertexArrayAttrib(vao, _attribute_face_normal_vector);
glVertexArrayAttribFormat(vao, _attribute_face_normal_vector, 3, GL_FLOAT, GL_FALSE, 0);
glVertexArrayAttribBinding(vao, _attribute_face_normal_vector, 1);
glVertexArrayVertexBuffer(vao, 1, _vbo_normal_vectors[object_index], 0, sizeof(glm::vec3f));
glNamedBufferData(_vbo_vertex_normal_vectors[object_index], 3 * num_faces * sizeof(glm::vec3f), object->_face_vertex_normal_vectors.get(), GL_STATIC_DRAW);
glEnableVertexArrayAttrib(vao, _attribute_vertex_normal_vector);
glVertexArrayAttribFormat(vao, _attribute_vertex_normal_vector, 3, GL_FLOAT, GL_FALSE, 0);
glVertexArrayAttribBinding(vao, _attribute_vertex_normal_vector, 2);
glVertexArrayVertexBuffer(vao, 2, _vbo_vertex_normal_vectors[object_index], 0, sizeof(glm::vec3f));
glNamedBufferData(_vbo_vertex_colors[object_index], 3 * num_faces * sizeof(glm::vec4f), object->_face_vertex_colors.get(), GL_STATIC_DRAW);
glEnableVertexArrayAttrib(vao, _attribute_vertex_color);
glVertexArrayAttribFormat(vao, _attribute_vertex_color, 3, GL_FLOAT, GL_FALSE, 0);
glVertexArrayAttribBinding(vao, _attribute_vertex_color, 3);
glVertexArrayVertexBuffer(vao, 3, _vbo_vertex_colors[object_index], 0, sizeof(glm::vec4f));
}
}
void VertexArrayObject::bind_object(int object_index)
{
if (object_index >= _prev_num_objects) {
throw std::runtime_error("(object_index >= _prev_num_objects) -> false");
}
glBindVertexArray(_vao[object_index]);
// glBindBuffer(GL_ARRAY_BUFFER, _vbo_vertices[object_index]);
// glVertexAttribPointer(_attribute_position, 3, GL_FLOAT, GL_FALSE, 0, 0);
// glEnableVertexAttribArray(_attribute_position);
// glVertexAttribPointer(_attribute_position, 3, GL_FLOAT, GL_FALSE, 0, 0);
// glEnableVertexAttribArray(_attribute_position);
// glVertexAttribPointer(_attribute_face_normal_vector, 3, GL_FLOAT, GL_FALSE, 0, 0);
// glEnableVertexAttribArray(_attribute_face_normal_vector);
// glVertexAttribPointer(_attribute_vertex_normal_vector, 3, GL_FLOAT, GL_FALSE, 0, 0);
// glEnableVertexAttribArray(_attribute_vertex_normal_vector);
// glVertexAttribPointer(_attribute_vertex_color, 4, GL_FLOAT, GL_FALSE, 0, 0);
// glEnableVertexAttribArray(_attribute_vertex_color);
}
}
}
} | true |
326550e727bbd892ba2a1a16b33b5d069466a0f6 | C++ | methsaan/cpp | /usefulprograms/functionOutput.cpp | UTF-8 | 921 | 2.96875 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
using namespace std;
int main(int argc, char *argv[]) {
string function;
cout << "Enter function using f(x): ";
getline(cin, function);
ofstream fo;
fo.open("functionRun.cpp");
fo << "#include <iostream>" << endl;
fo << "#include <cmath>" << endl << endl;
fo << "#include <cstdlib>" << endl << endl;
fo << "using namespace std;" << endl << endl;
fo << "double f(double x) {" << endl;
fo << "\treturn " << function.substr(function.find("=")+1, function.size()-(function.find("=")+1)) << ";" << endl;
fo << "}" << endl;
fo << "int main(int argc, char *argv[]) {" << endl;
for (int x = atoi(argv[1]); x <= atoi(argv[2]); x++) {
fo << "\tcout << " << x << " << \" | \" << f(" << x << ") << endl;" << endl;
}
fo << "}" << endl;
fo.close();
system("g++ functionRun.cpp");
system("./a.out");
system("g++ functionOutput.cpp");
}
| true |
631380d61e0c3e70fc0423bfb8c56ceed95dae0a | C++ | sitenight/StackAttack | /StackAttack/StackAttack/Game.h | WINDOWS-1251 | 438 | 2.9375 | 3 | [] | no_license | #pragma once
#include <ctime>
struct Point
{
public:
int x;
int y;
};
/*
0-
1-
2-
*/
class Game
{
private:
static const int cols = 30;
static const int rows = 39;
Point body;
unsigned char mas[rows][cols];
Point block;
public:
Game() : mas{0}
{
for (int i = 0; i < 30; ++i)
mas[38][i] = 1;
body.x = 14;
body.y = 12;
}
void Move(char);
void Drop();
int Random();
void Show();
};
| true |
03b87d86375056e6ebc809074f3ea7dfbdfb45e5 | C++ | itohdak/AtCoder | /AGC/032/B.cpp | UTF-8 | 619 | 2.578125 | 3 | [] | no_license | #include <iostream>
#include <cstdlib>
#include <algorithm>
#include <cmath>
#include <vector>
#include <numeric> // accumulate(v.begin(), v.end(), 0)
using namespace std;
#define ll long long
int main(){
int N;
cin >> N;
if(N % 2 == 0) {
cout << N * (N-2) / 2 << endl;
for(int i=1; i<=N; i++) {
for(int j=i+1; j<=N; j++) {
if(i + j != N + 1)
cout << i << ' ' << j << endl;
}
}
} else {
cout << (N-1) * (N-3) / 2 + (N-1) << endl;
for(int i=1; i<=N; i++) {
for(int j=i+1; j<=N; j++) {
if(i + j != N)
cout << i << ' ' << j << endl;
}
}
}
return 0;
}
| true |
17663df12b57972b6a17d9d4c76d95d9b9f1ecea | C++ | smallhand/codePractice | /gpe_20190320/10295_Hey_Points_q1.cpp | UTF-8 | 975 | 3.390625 | 3 | [] | no_license | /*
uva 10295: Hay Points
用Map紀錄每個單字得數值,然後再切字串
*/
#include <iostream>
#include <map>
#include <sstream>
using namespace std;
int main(){
int number, article;
while(cin >> number >> article) {
map<string, int> dict;
string word;
int value;
while(number--) {
cin >> word >> value;
dict[word] = value;
}
string lines, tmp;
stringstream ss;
int total;
while(article--) {
total = 0;
while(getline(cin, lines)){
if (lines==".")
break;
ss << lines;
while(ss >> tmp){
if (dict.count(tmp)>0) { // 有在map裡面
total += dict[tmp];
}
}
ss.str("");
ss.clear();
}
cout << total << endl;
}
}
return 0;
} | true |
bd16796f62693fd27ccb142f94d4032c5a0ac750 | C++ | DMCDavi/Arduino | /trem-da-alegria.ino | UTF-8 | 1,138 | 2.71875 | 3 | [] | no_license | void setup(){
pinMode(A0, INPUT);
pinMode(A1, OUTPUT);
pinMode(A2, OUTPUT);
pinMode(A3, OUTPUT);
pinMode(A4, OUTPUT);
pinMode(A5, OUTPUT);
}
void loop(){
int sensor, LED[5], valor = 1023/5;
sensor = analogRead(A0);
LED[0] = map(sensor, 0, valor, 0, 1023);
LED[1] = map(sensor, valor, valor * 2, 0, 1023);
LED[2] = map(sensor, valor * 2, valor * 3, 0, 1023);
LED[3] = map(sensor, valor * 3, valor * 4, 0, 1023);
LED[4] = map(sensor, valor * 4, valor * 5, 0, 1023);
if(sensor <= valor){
analogWrite(A1, LED[0]);
} else{
analogWrite(A1, 0);
} if(sensor > valor && sensor <= valor * 2){
analogWrite(A2, LED[1]);
} else{
analogWrite(A2,0);
} if(sensor > valor * 2 && sensor <= valor * 3){
analogWrite(A3, LED[2]);
} else{
analogWrite(A3, 0);
} if(sensor > valor * 3 && sensor <= valor * 4){
analogWrite(A4, LED[3]);
} else{
analogWrite(A4, 0);
} if(sensor > valor * 4 && sensor <= valor * 5){
analogWrite(A5, LED[4]);
} else{
analogWrite(A5, 0);
}
}
| true |
7e98f04e25eedad48329f3439ad8407923199275 | C++ | grimquarry/SfmlCtrl | /SfmlCtrlDriver.cpp | UTF-8 | 635 | 2.765625 | 3 | [] | no_license | #include "SfmlCtrl.h"
#include <iostream>
int main()
{
SfmlCtrl sfmlCtrl1;
sfmlCtrl1.index = 7;
sfmlCtrl1.name = "The ultra delux controller pad";
sfmlCtrl1.productId = 3827;
sfmlCtrl1.vendorId = 1234;
sfmlCtrl1. vendorName = "Jack Cowdry";
std::cout << "Controller Index: " << sfmlCtrl1.index << std::endl;
std::cout << "Controller Name: " << sfmlCtrl1.name << std::endl;
std::cout << "Controller Product ID: " << sfmlCtrl1.productId << std::endl;
std::cout << "Controller Vendor ID: " << sfmlCtrl1.vendorId << std::endl;
std::cout << "Controller Vendor Name: " << sfmlCtrl1.vendorName << std::endl;
return 0;
}
| true |
bbb0412453b3ed35560bcae7adc834c38cc0e91d | C++ | electrodude/esc | /parser.hpp | UTF-8 | 4,798 | 3.015625 | 3 | [] | no_license | #include <stack>
#include <string>
#include <iostream>
#include <sstream>
class Parser;
class Token
{
public:
Token(std::string::iterator start, std::string::iterator end, Parser* parser);
virtual ~Token() {}
virtual bool isIdent() const { return false; }
virtual bool isNum() const { return false; }
//virtual String(const Token& token);
std::string tok;
};
class TokenFactory
{
public:
virtual Token* factory_new(std::string::iterator start, std::string::iterator end, Parser* parser);
};
// The basic abstract parser state
class ParserState
{
public:
virtual ParserState* next(Parser* parser) = 0;
virtual bool hasToken() const { return false; }
std::string name; // for debug
//virtual std::ostream& print(std::ostream& out) const;
};
// Superclass for states that have exactly one non-error next state
class ParserStateTransition : public ParserState
{
public:
ParserStateTransition();
ParserStateTransition(ParserState* _nextstate) : nextstate(_nextstate) {}
virtual ~ParserStateTransition() {}
virtual ParserState* next(Parser* parser);
ParserState* nextstate;
};
// debug
class ParserStateDebug : public ParserStateTransition
{
public:
ParserStateDebug();
ParserStateDebug(ParserState* _nextstate, std::string _msg) : ParserStateTransition(_nextstate), msg(_msg) {}
virtual ~ParserStateDebug() {}
virtual ParserState* next(Parser* parser);
std::string msg;
};
class ParserStateBackUp : public ParserStateTransition
{
public:
ParserStateBackUp(ParserState* _nextstate) : ParserStateTransition(_nextstate), distance(1) {}
ParserStateBackUp(ParserState* _nextstate, int _distance) : ParserStateTransition(_nextstate), distance(_distance) {}
virtual ~ParserStateBackUp() {}
virtual ParserState* next(Parser* parser);
int distance;
};
// accept char
class ParserStateChar : public ParserState
{
public:
ParserStateChar();
ParserStateChar(const ParserStateChar& original);
ParserStateChar(ParserState* _defaultstate, ParserStateChar* _templatestate);
virtual ~ParserStateChar() {}
void add(unsigned char c, ParserState* nextstate);
void add(std::string word, ParserState* nextstate);
void add(std::string::iterator start, std::string::iterator end, ParserState* nextstate);
void add(const ParserStateChar& additional);
void add(unsigned char first, unsigned char last, ParserState* nextstate);
void replace(ParserState* target, ParserState* replacement);
virtual ParserState* next(Parser* parser);
ParserStateChar* templatestate;
ParserState* transitions[256];
};
// state stack call
class ParserStateCall : public ParserStateTransition
{
public:
ParserStateCall();
ParserStateCall(ParserState* _nextstate, ParserState* _retstate, std::stack<ParserState*>* _stack) :
ParserStateTransition(_nextstate),
retstate(_retstate),
stack(_stack) {}
virtual ~ParserStateCall() {}
virtual ParserState* next(Parser* parser);
ParserState* retstate;
std::stack<ParserState*>* stack;
};
// state stack return
class ParserStateRet : public ParserState
{
public:
ParserStateRet();
ParserStateRet(ParserState* _failstate, std::stack<ParserState*>* _stack) :
failstate(_failstate),
stack(_stack) {}
virtual ~ParserStateRet() {}
virtual ParserState* next(Parser* parser);
ParserState* failstate;
std::stack<ParserState*>* stack;
};
// token start
class ParserStateMark : public ParserStateTransition
{
public:
ParserStateMark();
ParserStateMark(ParserState* _nextstate, std::string::iterator* _mark) :
ParserStateTransition(_nextstate),
mark(_mark) {}
virtual ~ParserStateMark() {}
virtual ParserState* next(Parser* parser);
std::string::iterator* mark;
};
// token end
class ParserStateEmit : public ParserStateTransition
{
public:
ParserStateEmit();
ParserStateEmit(ParserState* _nextstate, std::string::iterator* _startmark, std::string::iterator* _endmark, TokenFactory* _tokenfactory, std::stack<Token*>* _stack) :
ParserStateTransition(_nextstate),
startmark(_startmark),
endmark(_endmark),
tokenfactory(_tokenfactory),
stack(_stack) {}
virtual ~ParserStateEmit() {}
virtual bool hasToken() const { return true; }
virtual ParserState* next(Parser* parser);
std::string::iterator* startmark;
std::string::iterator* endmark;
TokenFactory* tokenfactory;
std::stack<Token*>* stack;
};
// parser class
class Parser
{
public:
Parser(ParserState* initial, std::string& code);
void parse();
std::string::iterator curr;
std::string::iterator end;
ParserState* currState;
};
inline std::string c2s(char c)
{
std::stringstream ss;
ss << "'";
switch (c)
{
case '\n': ss << "\\n"; break;
case '\r': ss << "\\r"; break;
case '\t': ss << "\\t"; break;
default : ss << c; break;
}
ss << "'(" << ((unsigned int)(c) & 255) << ")";
return ss.str();
}
| true |
47cbe04581ce36650f0204a5d6fd85aa35898eff | C++ | alfinur1011/alfi-nur-20063 | /Menghitung segitiga siku-siku.3.cpp | UTF-8 | 1,288 | 3.4375 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
int menu;
float a,b,c;
while(1) {
printf("------- Menu Pitagoras -------\n");
printf("1. Mencari sisi miring (c) \n");
printf("2. Mencari sisi alas (a) \n");
printf("3. Mencari sisi tegak (b) \n");
printf("4. Keluar program \n");
printf("------------------------------\n");
printf("Pilih nomor menu: ");
scanf("%d",&menu);
fflush(stdin);
if(menu == 1){
printf("Masukkan nilai a: ");
scanf("%f", &a);
printf("Masukkan nilai b: ");
scanf("%f", &b);
c=sqrt((a*a)+(b*b));
printf("Nilai sisi miring adalah %.2f\n", c);
} else if (menu == 2){
printf("Masukkan nilai b: ");
scanf("%f",&b);
printf("Masukkan nila c: ");
scanf("%f",&c);
a=sqrt((c*c)-(b*b));
printf("Nilai sisi alas adalah %.2f\n",a);
} else if (menu == 3){
printf("Masukkan nilai a: ");
scanf("%f", &a);
printf("Masukkan nilai c: ");
scanf("%f", &c);
b=sqrt((c*c)-(a*a));
printf("Nilai sisi tegak adalah %.2f\n",b);
} else if(menu == 4){
exit(0);
} else {
printf("Menu yang anda input salah");
}
}
return 0;
}
| true |
e5ebe18c46c426a4ea8bc139247d6f7137a167a1 | C++ | Abramov-solutions/solutioms | /8.cpp | UTF-8 | 160 | 2.578125 | 3 | [] | no_license | #include <iostream>
#include <cmath>
using namespace std;
int main() {
double r, n, p;
cin >> r >> n;
p=2 * r * n * tan(M_PI/n);
cout << p;
}
| true |
dc4d71af4d44dbf1eda070c74a50d3beb6c268a1 | C++ | tkchanat/LobsterGameEngine | /LobsterGameEngine/src/components/Component.cpp | UTF-8 | 1,344 | 2.75 | 3 | [] | no_license | #pragma once
#include "pch.h"
#include "objects/GameObject.h"
#include "scripts/Script.h"
namespace Lobster
{
// Maps a component enum to a string.
std::string Component::componentName[] = {
"Unknown",
"Mesh Component",
"Camera Component",
"Light Component",
"Physics Component",
"Script Component",
"Audio Source Component",
"Audio Listener Component",
"Particle Component",
"Script Component"
};
void Component::RemoveComponent(Component* comp)
{
gameObject->RemoveComponent(comp);
}
Component* CreateComponentFromType(const ComponentType& type)
{
switch (type)
{
case ComponentType::MESH_COMPONENT:
return new MeshComponent();
case ComponentType::PHYSICS_COMPONENT:
return new Rigidbody();
case ComponentType::CAMERA_COMPONENT:
return new CameraComponent();
case ComponentType::LIGHT_COMPONENT:
return new LightComponent(LightType::DIRECTIONAL_LIGHT);
case ComponentType::AUDIO_SOURCE_COMPONENT:
return new AudioSource();
case ComponentType::AUDIO_LISTENER_COMPONENT:
return new AudioListener();
case ComponentType::PARTICLE_COMPONENT:
return new ParticleComponent();
case ComponentType::SCRIPT_COMPONENT:
return new Script();
default:
assert(false && "Please register your own typeName-to-component conversion here!");
break;
}
return nullptr;
}
}
| true |
1e9c4ce28d2a6107ad031aba209a366617b6b4a6 | C++ | deepwaterooo/MyAlgorithms | /myalgorithms/ctci_WinterBreak2013/ch8two.cpp | UTF-8 | 1,756 | 3.125 | 3 | [] | no_license | #include <iostream>
#include <stack>
#include <cstdio>
using namespace std;
typedef long long ll;
struct point {
int x;
int y;
};
stack<point> sp;
const int MAXN = 20;
int g[MAXN][MAXN];
point vp[MAXN+MAXN];
ll path(ll m, ll n) {
if (m == 1 || n == 1) return 1;
else return path(m-1, n) + path(m, n-1);
}
ll fact(ll n) {
if (n == 0) return 1;
else return n*fact(n-1);
}
ll path1(ll m, ll n) {
return fact(m-1+n-1)/(fact(m-1)*fact(n-1));
}
bool get_path(int m, int n) {
point p; p.x = m; p.y = n;
sp.push(p);
if (m == 1 && n == 1) return true;
bool suc = false;
if (m > 1 && g[m-1][n])
suc = get_path(m-1, n);
if (!suc && n>1 && g[m][n-1])
suc = get_path(m, n-1);
if (!suc) sp.pop();
return suc;
}
void print_paths(int m, int n, int M, int N, int len) {
if (g[m][n] == 0) return;
point p; p.x = m; p.y = n;
vp[len++] = p;
if (m == M && n == N) {
for (int i = 0; i < len; ++i)
cout << "(" << vp[i].x << ", " << vp[i].y << ")" << " ";
cout << endl;
} else {
print_paths(m+1, n, M, N, len);
print_paths(m, n+1, M, N, len);
}
}
int main() {
freopen("ch88.2.in", "r", stdin);
for (int i = 1; i < 10; ++i)
cout << path(i, i) << endl;
cout << endl;
for (int i = 1; i < 10; ++i)
cout << path1(i, i) << endl;
cout << endl;
int M, N;
cin >> M >> N;
for (int i = 1; i <= M; ++i)
for (int j = 1; j <= N; ++j)
cin >> g[i][j];
cout << "one of the paths: " << endl;
get_path(M, N);
while( !sp.empty() ) {
point p = sp.top();
cout << "(" << p.x << ", " << p.y << ")" << " ";
sp.pop();
}
cout << endl << "all paths: " << endl;
print_paths(1, 1, M, N, 0);
fclose(stdin);
return 0;
}
| true |
ceab9223d3741211fd68d37619830d4f553e1637 | C++ | Zahidsqldba07/codesignal-solutions-4 | /Trees Basic/kthSmallestInBST.cpp | UTF-8 | 543 | 3.0625 | 3 | [] | no_license | // https://app.codesignal.com/interview-practice/task/jAKLMWLu8ynBhYsv6
// Definition for binary tree:
// template<typename T>
// struct Tree {
// Tree(const T &v) : value(v), left(nullptr), right(nullptr) {}
// T value;
// Tree *left;
// Tree *right;
// };
//
void solve(Tree <int> *t, int &k, int &ret) {
if (!t || !k) return;
solve(t->left, k, ret);
--k;
if (!k) ret = t->value;
solve(t->right, k, ret);
}
int kthSmallestInBST(Tree<int> * t, int k) {
int ret = 0;
solve(t, k, ret);
return ret;
}
| true |
caacd8f04b263d2754956eedad2af332865c3a78 | C++ | farshadsafavi/Cpp | /Dynamic/inheritance/src/Derived.cpp | UTF-8 | 317 | 3.046875 | 3 | [] | no_license | #include "Derived.h"
#include<iostream>
using namespace std;
Derived::Derived()
{
this->y = 0;
}
Derived::Derived(int x, int y)
{
this->setX(x);
this->y = y;
}
Derived::~Derived()
{
//dtor
}
void Derived::show(){
this->display();
cout << "Display of Derived member:" << this->y << endl;
}
| true |
868eece942ccd2125fa584f0c431e0954d949cd1 | C++ | joeaoregan/LIT-Yr3-Project-Antibody | /AntibodyV4-CodeBlocks/EnterName.h | UTF-8 | 1,730 | 3.1875 | 3 | [] | no_license | /* ---------------------------------------------------------------------------------------------------------------------
- Name: EnterName.h
- Description: Header file for the name entering system
- Information: The enter name state is where the player will enter their name before beginning level 1,
This name will be used to store the name along with the score of the player in the High Scores
table, if the player achieves a high enough score. A separate state is needed as entering text
from the keyboard will interfere with the keyboard controls for the player playing the game.
----------------------------------------------------------------------------------------------------------------------*/
#ifndef ENTER_NAME_H
#define ENTER_NAME_H
#include "Button.h"
#include "Texture.h"
class EnterName {
public:
TTF_Font *gFont = NULL; // Set the font for the states text
// Menu Text
Texture gNameMenuTextTexture1; // Enter Name title text
Texture gNameMenuTextTexture2; // Return to Menu text
Texture gNameMenuTextTexture3; // Reset the text entered
Texture gNameMenuTextTexture4; // Enter Name prompt text
//Buttons objects
Button gNameButtons[TOTAL_ENTER_NAME_BUTTONS]; // Array of buttons
SDL_Rect gSpriteClipsName[TOTAL_ENTER_NAME_BUTTONS]; // Sprite for button animation
Texture gButtonSpriteSheetTexture4; // Sprite animation texture
bool loadNameMedia(); // Load the media for Enter Name state
void closeNameMedia(); // Free the media for Enter Name state from memory
void handleNameEvents(SDL_Event& e); // Handle events for Enter Name state
void draw(); // Render the enter name state
};
#endif | true |
760010f58f5ee5d220b8496e2329b94e8584f991 | C++ | oumkale/Geeks-For-Geeks-Work | /LinkList/matrixtoLL.cpp | UTF-8 | 1,090 | 3.375 | 3 | [] | no_license | // n is the size of the matrix
// function must return the pointer to the first element
// of the in linked list i.e. that should be the element at arr[0][0]
Node* constructLinkedMatrix(int mat[MAX][MAX], int n)
{
// code here
int i=0,j=0,k=0;
Node *head=NULL,*tail=NULL,*hh=NULL,*hhh=NULL;
Node* node=NULL;
for(i=0;i<n;i++)
{
head=NULL;
for(j=0;j<n;j++)
{
node = new Node(mat[i][j]);
if(head == NULL)
{
if(hh==NULL)
{ hh=node;
hhh=hh;
}
head=node;
tail=node;
}
else
{
tail->right=node;
tail=tail->right;
}
}
Node *temp=hhh;
if(i>0)
{
for(j=0;j<n;j++)
{
hhh->down=head;
hhh=hhh->right;
head=head->right;
}
hhh=temp;
hhh=hhh->down;
}
}
return hh;
}
| true |
2d4a258c372dcf95b185afcc21c4a034ceba456d | C++ | heon24500/PS | /BOJ/2606.cpp | UTF-8 | 574 | 2.640625 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <queue>
using namespace std;
#define N 105
vector<int> adj[N];
queue<int> q;
bool visited[N];
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int n, e, ret = -1;
cin >> n >> e;
for (int i = 0; i < e; i++) {
int u, v;
cin >> u >> v;
adj[u].push_back(v);
adj[v].push_back(u);
}
q.push(1);
visited[1] = true;
while (!q.empty()) {
int now = q.front();
q.pop();
ret++;
for (auto u : adj[now]) {
if (visited[u]) continue;
visited[u] = true;
q.push(u);
}
}
cout << ret;
return 0;
} | true |
37392034c39dbbc28f3bd9648411d107fcb393d7 | C++ | josokw/ExamGenerator | /app/examGen/GenImage.h | UTF-8 | 495 | 2.625 | 3 | [
"MIT"
] | permissive | #ifndef GENIMAGE_H
#define GENIMAGE_H
#include "ILeafGenerator.h"
#include <string>
class GenImage : public ILeafGenerator
{
public:
GenImage(std::string_view id, std::string_view fileName);
~GenImage() override = default;
[[nodiscard]] IGenPtr_t copy() const override;
void generate(std::ostream &os) override;
std::ostream &write(std::ostream &os, int level = 0) const override;
private:
std::string fileName_;
std::string caption_;
};
#endif
| true |
f681f26d496eae91392adad38ed3ecd5f6898e6a | C++ | talkami/OOP | /Project2/AllFiles/Boat.cpp | UTF-8 | 2,273 | 3.421875 | 3 | [] | no_license | #include "Boat.h"
#include "Point.h"
#include <iostream>
//constructor
Boat::Boat(int size, int player, IBattleshipGameAlgo* PlayerPointer, IBattleshipGameAlgo* RivalPointer, Point* firstPoint) :
boatSize(size),
direction(0),
acctualSize(1),
hits(0),
player(player),
owner(PlayerPointer),
rival(RivalPointer),
validity(true)
{
this->pointsArray.push_back(firstPoint);
this->value = setValue(size);
}
Boat::~Boat() {
for (size_t i = 0; i < pointsArray.size(); i++) {
this->pointsArray[i]->setBoat(nullptr);
}
}
//getters
int Boat::getNumOftHits() {
return this->hits;
}
int Boat::getDirection() {
return this->direction;
}
int Boat::getPlayer() {
return this->player;
}
int Boat::getBoatSize() {
return this->boatSize;
}
int Boat::getAcctualSize() {
return this->acctualSize;
}
IBattleshipGameAlgo* Boat::getOwner() {
return this->owner;
}
IBattleshipGameAlgo* Boat::getRival() {
return this->rival;
}
bool Boat::isSunk() {
if (hits == boatSize) {
return true;
}
else {
return false;
}
}
int Boat :: getValue (){
return this->value;
}
bool Boat::isValid() {
return this->validity;
}
//setters
void Boat::addHit() {
this->hits++;
}
void Boat::addPoint(Point* point) {
this->pointsArray.push_back(point);
this->acctualSize++;
}
void Boat::setDirection(int direction) {
this->direction = direction;
}
void Boat::setValidity(bool validity) {
this->validity = validity;
}
void Boat::mergeBoats(Boat* boat) {
std::vector<Point*> otherPoints = boat->pointsArray;
this->acctualSize += boat->acctualSize;
delete boat;
for (size_t i = 0; i < otherPoints.size(); i++) {
otherPoints[i]->setBoat(this);
this->pointsArray.push_back(otherPoints[i]);
}
}
//private
int Boat::setValue(int size) {
if (size == 1) {
return 2;
}
if (size == 2) {
return 3;
}
if (size == 3) {
return 7;
}
if (size == 4) {
return 8;
}
else {
std::cout << "Error! illegal boat!" << std::endl;
return -1;
}
}
std::vector<std::pair<int, int>> Boat::getPoints() {
int size = this->acctualSize;
std::vector<std::pair<int, int>> arr;
for (int i = size; i > 0; i--) {
std::pair<int, int> point(this->pointsArray[i - 1]->getRow(), this->pointsArray[i - 1]->getCol());
arr.push_back(point);
}
std::cout << std::endl;
return arr;
} | true |
f088cab372aee6c1e173e17c4dcac643b94ecc32 | C++ | tlegorju/Escape_prototype | /src/ParticleSystem.cpp | ISO-8859-1 | 1,390 | 2.796875 | 3 | [] | no_license | #include "../include/ParticleSystem.h"
using namespace std;
using namespace sf;
ParticleSystem::ParticleSystem(unsigned int count) :
m_particles(count), m_vertices(sf::Points, count), m_lifetime(seconds(1)), m_emitter(0,0)
{
//ctor
_color=Color::White;
_speed=50;
_angle.x=0;
_angle.y=360;
}
ParticleSystem::ParticleSystem()
{
}
ParticleSystem::~ParticleSystem()
{
//dtor
}
void ParticleSystem::setColor(sf::Color color)
{
/*for(int i=0; i<m_particles.size(); ++i)
{
m_vertices[i].color=color;
}*/
_color=color;
}
void ParticleSystem::update(sf::Time elapsed)
{
for(size_t i = 0; i<m_particles.size(); ++i)
{
/// on met jour la dure de vie de la particule
Particle& p = m_particles[i];
p._lifetime -= elapsed;
/// si la particule est arrive en fin de vie, on la rinitialise
if(p._lifetime <= sf::Time::Zero)
resetParticle(i);
/// on met jour la position du vertex correspondant
m_vertices[i].position += p._velocity * elapsed.asSeconds();
/// on met jour l'alpha (transparence) de la particule en fonction de sa dure de vie
float ratio = p._lifetime.asSeconds() / m_lifetime.asSeconds();
m_vertices[i].color.a = static_cast<sf::Uint8>(ratio * 255);
}
}
| true |
859ddc0c3c621722220d6b21c2711b34e3300606 | C++ | xacid/UvaOnlineJudge | /638/main.cpp | UTF-8 | 4,695 | 3.21875 | 3 | [] | no_license | #include <iostream>
#include <map>
#include <vector>
#include <algorithm>
#include <string>
#include <cstring>
#include <cstdio>
#include <cassert>
using namespace std;
struct Point
{
char c;
int x;
int y;
};
struct Rect
{
string sAbcd;
Rect(const Point* a, const Point* b, const Point* c, const Point* d) :
sAbcd(5, '\0')
{
sAbcd[0] = a->c;
sAbcd[1] = b->c;
sAbcd[2] = c->c;
sAbcd[3] = d->c;
}
struct CompareStr
{
bool operator()(const Rect& l, const Rect& r)
{
return l.sAbcd < r.sAbcd;
}
};
};
class Line
{
public:
typedef typename vector<Point*>::iterator iterator;
explicit Line(int iSize) :
m_vPoint(iSize, NULL)
{
}
Point*& operator[](int n)
{
assert(n < m_vPoint.size());
return m_vPoint[n];
}
iterator begin()
{
iterator begin = m_vPoint.begin();
if(*begin == NULL)
{
begin = getNext(begin);
}
return begin;
}
iterator end()
{
return m_vPoint.end();
}
iterator getNext(iterator itr)
{
while(itr != m_vPoint.end())
{
++itr;
if((itr != m_vPoint.end()) && (*itr != NULL))
{
break;
}
}
return itr;
}
iterator getNext(const Point* p)
{
int i = 0;
for(i = 0; i < m_vPoint.size(); ++i)
{
if(p == m_vPoint[i])
{
break;
}
}
return getNext(m_vPoint.begin() + i);
}
bool empty() const
{
for(int i = 0; i < m_vPoint.size(); ++i)
{
if(m_vPoint[i] != NULL)
{
return false;
}
}
return true;
}
private:
vector<Point*> m_vPoint;
};
class PointMap
{
public:
typedef typename vector<Line>::iterator iterator;
PointMap(int iSizeA, int iSizeB) :
m_vLine(iSizeA, Line(iSizeB))
{
}
Line& operator[](int n)
{
assert(n < m_vLine.size());
return m_vLine[n];
}
iterator begin()
{
iterator begin = m_vLine.begin();
if(begin->empty())
{
begin = getNext(begin);
}
return begin;
}
iterator end()
{
return m_vLine.end();
}
iterator getNext(iterator itr)
{
while(itr != m_vLine.end())
{
++itr;
if((itr != m_vLine.end()) && (itr->empty() == false))
{
break;
}
}
return itr;
}
private:
vector<Line> m_vLine;
};
void _calcRects(vector<Point>& p)
{
// Sort input in row and col.
PointMap row(51, 51);
PointMap col(51, 51);
for(int i = 0; i < p.size(); ++i)
{
row[p[i].y][p[i].x] = &p[i];
col[p[i].x][p[i].y] = &p[i];
}
// Find rect for each point
vector<Rect> ans;
for(PointMap::iterator itr = row.begin(); itr < row.end(); itr = row.getNext(itr))
{
Line& lineY = *itr;
for(Line::iterator itrP = lineY.begin(); itrP < lineY.end(); itrP = lineY.getNext(itrP))
{
Point* p4 = *itrP;
Line& lineX = col[p4->x];
for(Line::iterator pp3 = lineY.getNext(p4); pp3 < lineY.end(); pp3 = lineY.getNext(pp3))
{
for(Line::iterator pp1 = lineX.getNext(p4); pp1 < lineX.end(); pp1 = lineY.getNext(pp1))
{
if(row[(*pp1)->y][(*pp3)->x] != NULL)
{
//Found rect.
Point* p2 = row[(*pp1)->y][(*pp3)->x];
ans.push_back(Rect(*pp1, p2, *pp3, p4));
}
}
}
}
}
//Sort ans
sort(ans.begin(), ans.end(), Rect::CompareStr());
// Print, no ans
if(ans.size() == 0)
{
printf(" No rectangles\n");
return;
}
// Print ans
for(int i = 0; i < ans.size(); ++i)
{
if((i % 10) == 0)
{
puts("");
}
printf(" %s", ans[i].sAbcd.c_str());
}
puts("");
}
int main()
{
int iNumPoint = 0;
int iSetCount = 1;
cin >> iNumPoint;
while(0 < iNumPoint)
{
// Get points
vector<Point> vP(iNumPoint);
for(int i = 0; i < iNumPoint; ++i)
{
cin >> vP[i].c >> vP[i].x >> vP[i].y;
}
// Print
printf("Point set %ld:", iSetCount);
_calcRects(vP);
// Next set
++iSetCount;
cin >> iNumPoint;
}
return 0;
}
| true |
dc6a03cfde8ccf98f8254f32fa6140cae86f8cbd | C++ | moustafa-mk/Fibonacci-nim--C--CLI-version- | /Source code/main.cpp | UTF-8 | 3,834 | 3.125 | 3 | [] | no_license | #include <iostream>
#include <stdlib.h>
#include <windows.h>
using namespace std;
int main();
int tryAgain(int lastuse, int current, bool start){
int ret;
if(start == true){
cout << "Number is more than twice last used number or the number of coins!! please enter a valid number: " << endl;
cin >> ret;
}
else cout << "You can't take all the coins directly. \n Please enter a valid number: " << endl;
while(ret > 2*lastuse || ret > current){
if(start == true) cout << "Number is more than twice last used number or the number of coins!! please enter a valid number: " << endl;
else cout << "You can't take all the coins directly. \n Please enter a valid number: " << endl;
}
return ret;
}
void player1(string name, int &lastuse, int ¤t, bool &start){
int p1;
cout << name << "'s turn: ";
cin >> p1;
if(p1 > 2*lastuse || p1 > current) p1 = tryAgain(lastuse, current, start);
lastuse = p1;
current -= lastuse;
start = true;
cout << "There are " << current << " coins on the table." << endl;
}
void player2(string name, int &lastuse, int ¤t, bool &start){
int p2;
cout << name << "'s turn: ";
cin >> p2;
if(p2 > 2*lastuse || p2 > current) p2 = tryAgain(lastuse, current, start);
lastuse = p2;
current -= lastuse;
cout << "There are " << current << " coins on the table." << endl;
}
void comp(int &lastuse, int ¤t, bool &start){
int cplay;
if(current <= 2*lastuse) cplay = current;
else{
cplay = current / 4;
if(cplay > 2*lastuse) cplay = 2*lastuse;
if(cplay == 0) cplay == 1;
}
cout << "Computer:Hmm..." << endl;
Sleep(1500);
cout << "Computer chose the number " << cplay << endl;
lastuse = cplay;
current -= lastuse;
cout << "There are " << current << " coins on the table: " << endl;
}
int playAgain(int &lastuse, int ¤t, bool &start){
char x;
cout << "Do you wanna play again? (y/n) ";
cin >> x;
if(x == 'y'){
current = rand() % 1000 + 1;
lastuse = (current - 1) / 2;
start = false;
main();
}
else return 0;
}
void multiplayer(string &name1, string &name2, int &lastuse, int ¤t, bool &start){
cout << "There are " << current << " on the table." << endl;
while(current != 0){
player1(name1, lastuse, current, start);
if(current == 0){
cout << name1 << " wins!!" << endl;
playAgain(lastuse, current, start);
}
player2(name2, lastuse, current, start);
}
cout << name2 << " wins!!" << endl;
playAgain(lastuse, current, start);
}
void oneplayer(string &name1, int &lastuse, int ¤t, bool &start ){
cout << "There are " << current << " coins on the table." << endl;
while(current != 0){
player1(name1, lastuse, current, start);
if(current == 0){
cout << name1 << " wins!!" << endl;
playAgain(lastuse, current, start);
}
comp(lastuse, current, start);
}
cout << "Computer wins!!" << endl;
playAgain(lastuse, current, start);
}
int main()
{
int orig = rand() % 1000 + 1;
int last = (orig-1)/2;
bool beg = false;
string p1Name = "", p2Name = "", playmood;
cout << "Enter 1 for one player or 2 for two players: ";
cin >> playmood;
if(playmood == "1"){
cout << "Player 1 name: ";
cin >> p1Name;
oneplayer(p1Name, last, orig, beg);
}
else{
cout << "Player 1 name: ";
cin >> p1Name;
cout << "Player 2 name: ";
cin >> p2Name;
multiplayer(p1Name, p2Name, last, orig, beg);
}
}
| true |
354b4f50cc86581ddc0a94204ac5414e081385b5 | C++ | LittleTemple/PATExam | /PATExam/p1075.cpp | UTF-8 | 4,932 | 2.515625 | 3 | [] | no_license | //////开始时间15:23
////#include<iostream>
////#include<vector>
////#include<algorithm>
////#include <map>
////using namespace std;
////struct user{
//// int id;
//// string name;
//// int total = 0;
//// int num = 0;//完美解决的个数
//// int rank;
//// bool flag = false;//解决过问题
//// vector<int> p;
////};
////int N,pnum,M,ind = 0;//M提交者,pnum问题的个数
////vector<user> list;
////vector<int> plist;//满分列表
////map<string,int> nameToId;
////map<int,string> idToName;
////
////int change(string str){
//// if(nameToId.find(str)!=nameToId.end()){
//// return nameToId[str];
//// }else{
//// nameToId[str] = ind;
//// idToName[ind] = str;
//// ind++;
//// return nameToId[str];
//// }
////}
////
////bool cmp(user a,user b){
//// if(a.total == b.total){
//// if(a.num == b.num) return a.name < b.name;
//// else return a.num > b.num;
//// }else{
//// return a.total > b.total;
//// }
////}
////
////int main(){
//// cin>>N>>pnum>>M;
//// plist.resize(pnum+1);
//// list.resize(N);
//// for(int i = 1;i<=pnum;i++){
//// cin>>plist[i];
//// }
//// getchar();
////
////
//// //初始化
//// for(int i = 0;i<N;i++){
//// list[i].p.resize(pnum+1);
//// for(int j = 0;j<=pnum;j++){
//// list[i].p[j] = -2;
//// }
//// }
////
//// //输入
//// for(int i = 0;i<M;i++){
//// string str;
//// int id,pid,score;
//// cin>>str>>pid>>score;
//// getchar();
//// id = change(str);
//// list[id].id = id;
//// list[id].name = str;
//// if(score > list[id].p[pid]){//判断当前的成绩是否需要修改
//// list[id].p[pid] = score;
//// }
//// if(score != -1) list[id].flag = true;//设定解决过问题
//// if(score == plist[pid]) list[id].num++;//得到完美答案
//// }
////
//// //先计算总成绩
//// for(int i = 0;i<N;i++){
//// for(int j = 1;j<=pnum;j++){
//// if(list[i].p[j] > 0) list[i].total+=list[i].p[j];
//// }
//// }
////
//// sort(list.begin(),list.end(),cmp);
//// list[0].rank = 1;
//// for(int i = 1;i<N;i++){
//// list[i].rank = i+1;
//// if(list[i].total == list[i-1].total) list[i].rank = list[i-1].rank;
//// }
////
//// //最后的输出
//// for(int i = 0;i<N;i++){
//// if(!list[i].flag) continue;
////
//// printf("%d %s %d",list[i].rank,idToName[list[i].id].c_str(),list[i].total);
//// for(int j = 1;j<=pnum;j++){
//// if(list[i].p[j] == -2) printf(" -");
//// else if(list[i].p[j] == -1) printf(" 0");
//// else printf(" %s",to_string(list[i].p[j]).c_str());
//// }
//// printf("\n");
//// }
//// return 0;
////}
//
//#include <iostream>
//#include <vector>
//#include <algorithm>
//using namespace std;
//struct node {
// int rank, id, total = 0;
// vector<int> score;
// int passnum = 0;
// bool isshown = false;
//};
//bool cmp1(node a, node b) {
// if(a.total != b.total)
// return a.total > b.total;
// else if(a.passnum != b.passnum)
// return a.passnum > b.passnum;
// else
// return a.id < b.id;
//}
//
//int main() {
// int n, k, m, id, num, score;
// scanf("%d %d %d", &n, &k, &m);
// vector<node> v(n + 1);
// for(int i = 1; i <= n; i++)
// v[i].score.resize(k + 1, -1);
// vector<int> full(k + 1);
// for(int i = 1; i <= k; i++)
// scanf("%d", &full[i]);
// for(int i = 0; i < m; i++) {
// scanf("%d %d %d", &id, &num, &score);
// v[id].id = id;
// v[id].score[num] = max(v[id].score[num], score);
// if(score != -1)
// v[id].isshown = true;
// else if(v[id].score[num] == -1)
// v[id].score[num] = -2;
// }
// for(int i = 1; i <= n; i++) {
// for(int j = 1; j <= k; j++) {
// if(v[i].score[j] != -1 && v[i].score[j] != -2)
// v[i].total += v[i].score[j];
// if(v[i].score[j] == full[j])
// v[i].passnum++;
// }
// }
// sort(v.begin() + 1, v.end(), cmp1);
// for(int i = 1; i <= n; i++) {
// v[i].rank = i;
// if(i != 1 && v[i].total == v[i - 1].total)
// v[i].rank = v[i - 1].rank;
// }
// for(int i = 1; i <= n; i++) {
// if(v[i].isshown == true) {
// printf("%d %05d %d", v[i].rank, v[i].id, v[i].total);
// for(int j = 1; j <= k; j++) {
// if(v[i].score[j] != -1 && v[i].score[j] != -2)
// printf(" %d", v[i].score[j]);
// else if(v[i].score[j] == -1)
// printf(" -");
// else
// printf(" 0");
// }
// printf("\n");
// }
// }
// return 0;
//} | true |
8e57ca1425c639f53f2e709d106a86105ea1d87e | C++ | abhishekchavannn/DSA | /placment_practice_problem/delete_nth_node_back_of_list.cpp | UTF-8 | 493 | 3.09375 | 3 | [] | no_license | node* solve(node* head, int n) {
node* start = new node(0);
start->next = head;
node* fast = start;
node* slow = start;
for (int i = 0; i < n; i++) {
if (fast->next == nullptr) {
// n is larger than the length of the list
return nullptr;
}
fast = fast->next;
}
while (fast->next != nullptr) {
slow = slow->next;
fast = fast->next;
}
slow->next = slow->next->next;
return start->next;
} | true |
22ec6af67cc15058b26be5f37a93b677d797be2e | C++ | YinXinLION/Cpp | /practice/73.cpp | UTF-8 | 651 | 2.796875 | 3 | [] | no_license | /*************************************************************************
> File Name: 73.cpp
> Author:YinXin
> Mail:yinxin19950816@gmail.com
> Created Time: 2016年03月26日 星期六 20时02分52秒
************************************************************************/
#include<iostream>
#include<string>
#include<vector>
using namespace std;
template<class T>
class myclass;
template<class T>
void print(myclass<T> my);
template <class T>
class myclass
{
public:
friend void print<T>(myclass<T> my);
private:
int x = 0;
};
template<class T>
void print(myclass<T> my)
{
my.x;
}
int main(void)
{
myclass<int> my;
print(my);
}
| true |
8812545a978d7a3ac290132d76e0c4cf852c3c5b | C++ | Catlinz/catcore-cpp | /tests/core/unit/threading/taskrunnersinglethread_tests.cpp | UTF-8 | 36,217 | 2.765625 | 3 | [] | no_license | #include "core/testcore.h"
#include "core/threading/taskrunner.h"
#include "core/threading/spinlock.h"
namespace cc {
I32 destroyed_count = 0;
I32 failure_count = 0;
I32 success_count = 0;
I32 terminated_count = 0;
Spinlock locky;
void reset_counts() {
locky.lock();
destroyed_count = 0;
failure_count = 0;
success_count = 0;
terminated_count = 0;
locky.unlock();
}
inline void test_counts(I32 success, I32 failed, I32 terminated, I32 destroyed) {
locky.lock();
ass_eq(success_count, success);
ass_eq(failure_count, failed);
ass_eq(terminated_count, terminated);
ass_eq(destroyed_count, destroyed);
locky.unlock();
}
class TestTask : public Task {
public:
ConditionVariable lock;
TestTask()
: Task(),m_val(0), m_timeToRun(0) {}
TestTask(OID pid, I32 val, U32 timeToRun = 1, Task::TaskState finishState = Task::kTSSucceeded)
: Task(pid), m_val(val), m_timeToRun(timeToRun), m_finishState(finishState) {}
TestTask(const Char* name, I32 val, U32 timeToRun = 1, Task::TaskState finishState = Task::kTSSucceeded)
: Task(name), m_val(val), m_timeToRun(timeToRun), m_finishState(finishState) {}
~TestTask() {
locky.lock();
DMSG("Test Task " << m_val << " destroyed.");
destroyed_count++;
locky.unlock();
}
void onFailure() {
locky.lock();
DMSG("Test task (" << m_val << ") failed!");
failure_count++;
locky.unlock();
lock.lock();
lock.broadcast();
lock.unlock();
}
void onInitialize() {
locky.lock();
DMSG("Test task (" << m_val << ") initialized!");
locky.unlock();
}
void onSuccess() {
locky.lock();
DMSG("Test task (" << m_val << ") succeeded!");
success_count++;
locky.unlock();
lock.lock();
lock.broadcast();
lock.unlock();
}
void onTermination() {
locky.lock();
DMSG("Test task (" << m_val << ") terminated!");
terminated_count++;
locky.unlock();
lock.lock();
lock.broadcast();
lock.unlock();
}
void run() {
DMSG("Task " << m_val << " ran for " << m_timeToRun << " time.");
usleep(100000*m_timeToRun);
switch(m_finishState) {
case Task::kTSSucceeded:
succeeded();
break;
case Task::kTSTerminated:
terminate();
break;
case Task::kTSFailed:
failed();
break;
default:
break;
}
}
void waitForFinished() {
lock.lock();
while (state() == Task::kTSNotStarted || isAlive()) {
lock.wait();
}
lock.unlock();
}
inline I32 val() const { return m_val; }
inline U32 timeToRun() const { return m_timeToRun; }
inline static TaskPtr create(const Char* name, I32 val, U32 timeToRun = 1, Task::TaskState finishState = Task::kTSSucceeded) {
return TaskPtr(new TestTask(name, val, timeToRun, finishState));
}
private:
I32 m_val;
U32 m_timeToRun;
Task::TaskState m_finishState;
};
void testCreateAndDestroyTaskRunner() {
BEGIN_TEST;
TaskRunner* pm1 = new TaskRunner();
ass_false(pm1->isRunning());
ass_true(pm1->isStopped());
ass_eq(pm1->name(), NIL);
ass_eq(pm1->oID(), 0);
ass_eq(pm1->state(), TaskRunner::kTRSNotStarted);
ass_eq(pm1->inputQueue()->capacity(), 0);
ass_eq(pm1->messageQueue()->capacity(), 0);
ass_eq(pm1->numFree(), 0);
ass_eq(pm1->numUsed(), 0);
TaskRunner* pm2 = new TaskRunner("PM2");
ass_false(pm2->isRunning());
ass_true(pm2->isStopped());
ass_eq(strcmp(pm2->name(), "PM2"), 0);
ass_eq(pm2->oID(), crc32("PM2"));
ass_eq(pm2->state(), TaskRunner::kTRSNotStarted);
ass_eq(pm2->inputQueue()->capacity(), 32);
ass_true(pm2->inputQueue()->isEmpty());
ass_eq(pm2->messageQueue()->capacity(), 32);
ass_true(pm2->messageQueue()->isEmpty());
ass_false(pm2->hasQueued());
ass_false(pm2->hasFullQueue());
ass_false(pm2->hasRunningTask());
ass_eq(pm2->numFree(), 32);
ass_eq(pm2->numUsed(), 0);
TaskRunner* pm3 = new TaskRunner("PM3", 8);
ass_false(pm3->isRunning());
ass_true(pm3->isStopped());
ass_eq(strcmp(pm3->name(), "PM3"), 0);
ass_eq(pm3->oID(), crc32("PM3"));
ass_eq(pm3->state(), TaskRunner::kTRSNotStarted);
ass_eq(pm3->inputQueue()->capacity(), 8);
ass_true(pm3->inputQueue()->isEmpty());
ass_eq(pm3->messageQueue()->capacity(), 8);
ass_true(pm3->messageQueue()->isEmpty());
ass_false(pm3->hasQueued());
ass_false(pm3->hasFullQueue());
ass_false(pm3->hasRunningTask());
ass_eq(pm3->numFree(), 8);
ass_eq(pm3->numUsed(), 0);
delete pm1;
delete pm2;
delete pm3;
FINISH_TEST;
}
void testTaskRunnerQueueTask() {
BEGIN_TEST;
destroyed_count = 0;
TaskRunner* m = new TaskRunner("PM", 4);
ass_false(m->isRunning());
ass_true(m->isStopped());
ass_eq(strcmp(m->name(), "PM"), 0);
ass_eq(m->oID(), crc32("PM"));
ass_eq(m->state(), TaskRunner::kTRSNotStarted);
ass_eq(m->inputQueue()->capacity(), 4);
ass_true(m->inputQueue()->isEmpty());
ass_eq(m->messageQueue()->capacity(), 4);
ass_true(m->messageQueue()->isEmpty());
ass_false(m->hasFullQueue());
ass_eq(m->numFree(), 4);
ass_eq(m->numUsed(), 0);
TaskPtr retVal;
retVal = m->queueTask(TestTask::create("Task 1", 1));
ass_true(retVal.notNull());
ass_eq(m->inputQueue()->capacity(), 4);
ass_false(m->inputQueue()->isEmpty());
ass_false(m->hasFullQueue());
ass_eq(m->messageQueue()->capacity(), 4);
ass_true(m->messageQueue()->isEmpty());
retVal = m->queueTask(TestTask::create("Task 2", 2));
ass_true(retVal.notNull());
ass_eq(m->inputQueue()->capacity(), 4);
ass_false(m->inputQueue()->isEmpty());
ass_false(m->hasFullQueue());
ass_eq(m->messageQueue()->capacity(), 4);
ass_true(m->messageQueue()->isEmpty());
retVal = m->queueTask(TestTask::create("Task 3", 3));
ass_true(retVal.notNull());
ass_eq(m->inputQueue()->capacity(), 4);
ass_false(m->inputQueue()->isEmpty());
ass_false(m->hasFullQueue());
ass_eq(m->messageQueue()->capacity(), 4);
ass_true(m->messageQueue()->isEmpty());
retVal = m->queueTask(TestTask::create("Task 4", 4));
ass_true(retVal.notNull());
ass_eq(m->inputQueue()->capacity(), 4);
ass_false(m->inputQueue()->isEmpty());
ass_true(m->hasFullQueue());
ass_eq(m->messageQueue()->capacity(), 4);
ass_true(m->messageQueue()->isEmpty());
ass_eq(destroyed_count, 0);
retVal = m->queueTask(TestTask::create("Task 5", 5));
ass_false(retVal.notNull());
ass_eq(destroyed_count, 1);
delete m;
ass_eq(destroyed_count, 5);
FINISH_TEST;
}
void testTaskRunnerPostMessages() {
BEGIN_TEST;
TaskRunner* m = new TaskRunner("PM", 4);
ass_false(m->isRunning());
ass_true(m->isStopped());
ass_eq(strcmp(m->name(), "PM"), 0);
ass_eq(m->oID(), crc32("PM"));
ass_eq(m->state(), TaskRunner::kTRSNotStarted);
ass_eq(m->inputQueue()->capacity(), 4);
ass_true(m->inputQueue()->isEmpty());
ass_eq(m->messageQueue()->capacity(), 4);
ass_true(m->messageQueue()->isEmpty());
ass_false(m->hasFullQueue());
ass_eq(m->numFree(), 4);
ass_eq(m->numUsed(), 0);
Boolean retVal = false;
retVal = m->clearAllWaitingTasks();
ass_true(retVal);
ass_eq(m->messageQueue()->capacity(), 4);
ass_false(m->messageQueue()->isEmpty());
ass_false(m->messageQueue()->isFull());
retVal = m->terminateTaskRunner();
ass_true(retVal);
ass_eq(m->messageQueue()->capacity(), 4);
ass_false(m->messageQueue()->isEmpty());
ass_false(m->messageQueue()->isFull());
SimpleQueue<TaskRunner::TRMessage>::Iterator itr = m->messageQueue()->begin();
ass_true(itr.isValid());
ass_true(itr.hasNext());
ass_eq(itr.val().type, TaskRunner::kTRMClearAllWaitingTasks);
itr.next();
ass_true(itr.isValid());
ass_false(itr.hasNext());
ass_eq(itr.val().type, TaskRunner::kTRMTerminateTaskRunner);
itr.next();
ass_false(itr.isValid());
ass_false(itr.hasNext());
retVal = m->terminateTaskRunner();
ass_true(retVal);
ass_eq(m->messageQueue()->capacity(), 4);
ass_false(m->messageQueue()->isEmpty());
ass_false(m->messageQueue()->isFull());
retVal = m->clearAllWaitingTasks();
ass_true(retVal);
ass_eq(m->messageQueue()->capacity(), 4);
ass_false(m->messageQueue()->isEmpty());
ass_true(m->messageQueue()->isFull());
retVal = m->terminateTaskRunner();
ass_false(retVal);
itr = m->messageQueue()->begin();
ass_true(itr.isValid());
ass_true(itr.hasNext());
ass_eq(itr.val().type, TaskRunner::kTRMClearAllWaitingTasks);
itr.next();
ass_true(itr.isValid());
ass_true(itr.hasNext());
ass_eq(itr.val().type, TaskRunner::kTRMTerminateTaskRunner);
itr.next();
ass_true(itr.isValid());
ass_true(itr.hasNext());
ass_eq(itr.val().type, TaskRunner::kTRMTerminateTaskRunner);
itr.next();
ass_true(itr.isValid());
ass_false(itr.hasNext());
ass_eq(itr.val().type, TaskRunner::kTRMClearAllWaitingTasks);
itr.next();
ass_false(itr.isValid());
ass_false(itr.hasNext());
ass_eq(itr.val().type, TaskRunner::kTRMClearAllWaitingTasks);
delete m;
FINISH_TEST;
}
void testTaskRunnerRunTasksSimple() {
BEGIN_TEST;
destroyed_count = 0;
TaskRunner* m = new TaskRunner("PM", 4);
m->queueTask(TestTask::create("Task 1", 1, 1, Task::kTSSucceeded));
m->queueTask(TestTask::create("Task 2", 2, 2, Task::kTSFailed));
m->queueTask(TestTask::create("Task 4", 4, 5, Task::kTSTerminated));
m->queueTask(TestTask::create("Task 3", 3, 3, Task::kTSSucceeded));
ass_eq(m->inputQueue()->capacity(), 4);
ass_false(m->inputQueue()->isEmpty());
ass_true(m->hasFullQueue());
ass_true(m->inputQueue()->isFull());
ass_eq(m->messageQueue()->capacity(), 4);
ass_true(m->messageQueue()->isEmpty());
ass_eq(destroyed_count, 0);
m->runNextTask(); /* Task 1 succeeds */
ass_eq(m->inputQueue()->capacity(), 4);
ass_true(m->inputQueue()->isEmpty());
ass_false(m->hasFullQueue());
ass_false(m->inputQueue()->isFull());
ass_eq(m->messageQueue()->capacity(), 4);
ass_true(m->messageQueue()->isEmpty());
ass_eq(m->numFree(), 1);
ass_eq(m->numUsed(), 3);
ass_eq(destroyed_count, 1);
m->runNextTask(); /* Task 2 fails */
ass_eq(m->inputQueue()->capacity(), 4);
ass_true(m->inputQueue()->isEmpty());
ass_false(m->hasFullQueue());
ass_false(m->inputQueue()->isFull());
ass_eq(m->messageQueue()->capacity(), 4);
ass_true(m->messageQueue()->isEmpty());
ass_eq(m->numFree(), 2);
ass_eq(m->numUsed(), 2);
ass_eq(destroyed_count, 2);
m->runNextTask(); /* Task 4 Terminated */
ass_eq(m->inputQueue()->capacity(), 4);
ass_true(m->inputQueue()->isEmpty());
ass_false(m->hasFullQueue());
ass_false(m->inputQueue()->isFull());
ass_eq(m->messageQueue()->capacity(), 4);
ass_true(m->messageQueue()->isEmpty());
ass_eq(m->numFree(), 3);
ass_eq(m->numUsed(), 1);
ass_eq(destroyed_count, 3);
m->runNextTask(); /* Task 3 succeeded */
ass_eq(m->inputQueue()->capacity(), 4);
ass_true(m->inputQueue()->isEmpty());
ass_false(m->hasFullQueue());
ass_false(m->inputQueue()->isFull());
ass_eq(m->messageQueue()->capacity(), 4);
ass_true(m->messageQueue()->isEmpty());
ass_eq(m->numFree(), 4);
ass_eq(m->numUsed(), 0);
ass_eq(destroyed_count, 4);
delete m;
ass_eq(destroyed_count, 4);
FINISH_TEST;
}
void testTaskRunnerRunTasksComplex() {
BEGIN_TEST;
reset_counts();
TaskRunner* m = new TaskRunner("PM", 4);
m->queueTask(TestTask::create("Task 1", 1, 1, Task::kTSSucceeded));
m->queueTask(TestTask::create("Task 2", 2, 2, Task::kTSFailed));
m->queueTask(TestTask::create("Task 4", 4, 5, Task::kTSTerminated));
m->queueTask(TestTask::create("Task 3", 3, 3, Task::kTSSucceeded));
ass_eq(m->inputQueue()->capacity(), 4);
ass_false(m->inputQueue()->isEmpty());
ass_eq(m->messageQueue()->capacity(), 4);
ass_true(m->messageQueue()->isEmpty());
ass_true(m->hasFullQueue());
ass_true(m->inputQueue()->isFull());
test_counts(0, 0, 0, 0);
DMSG(" ---- Run #1");
m->runNextTask(); /* Task 1 succeeded */
/* iqueue: 2f, 4t, 3s
* destroyed: 1s
* queued:
*/
ass_eq(m->inputQueue()->capacity(), 4);
ass_true(m->inputQueue()->isEmpty());
ass_false(m->hasFullQueue());
ass_false(m->inputQueue()->isFull());
ass_eq(m->messageQueue()->capacity(), 4);
ass_true(m->messageQueue()->isEmpty());
ass_eq(m->numFree(), 1);
ass_eq(m->numUsed(), 3);
test_counts(1, 0, 0, 1);
m->queueTask(TestTask::create("Task 5", 5, 2));
m->queueTask(TestTask::create("Task 6", 6, 1));
DMSG(" ---- Run #2");
m->runNextTask(); /* Task 2 failed */
/* iqueue: 4t, 3s, 5s
* destroyed: 1s, 2f
* queued: 6s
*/
ass_eq(m->inputQueue()->capacity(), 4);
ass_false(m->inputQueue()->isEmpty());
ass_eq(m->messageQueue()->capacity(), 4);
ass_true(m->messageQueue()->isEmpty());
ass_eq(m->numFree(), 1);
ass_eq(m->numUsed(), 3);
test_counts(1, 1, 0, 2);
DMSG(" ---- Run #3");
m->runNextTask(); /* Task 4 terminated */
/* iqueue: 3s, 5s, 6s
* destroyed: 1s, 2f, 4t
* queued:
*/
ass_eq(m->inputQueue()->capacity(), 4);
ass_true(m->inputQueue()->isEmpty());
ass_eq(m->messageQueue()->capacity(), 4);
ass_true(m->messageQueue()->isEmpty());
ass_eq(m->numFree(), 1);
ass_eq(m->numUsed(), 3);
test_counts(1, 1, 1, 3);
DMSG(" ---- Run #4");
m->runNextTask(); /* Task 3 suceeded */
/* iqueue: 5s, 6s
* destroyed: 1s, 2f, 4t, 3s
* queued:
*/
ass_eq(m->inputQueue()->capacity(), 4);
ass_true(m->inputQueue()->isEmpty());
ass_eq(m->messageQueue()->capacity(), 4);
ass_true(m->messageQueue()->isEmpty());
ass_eq(m->numFree(), 2);
ass_eq(m->numUsed(), 2);
test_counts(2, 1, 1, 4);
DMSG(" ---- Run #5");
m->runNextTask(); /* Task 5 suceeded */
/* iqueue: 6s
* destroyed: 1s, 2f, 4t, 3s, 5s
* queued:
*/
ass_eq(m->inputQueue()->capacity(), 4);
ass_true(m->inputQueue()->isEmpty());
ass_eq(m->messageQueue()->capacity(), 4);
ass_true(m->messageQueue()->isEmpty());
ass_eq(m->numFree(), 3);
ass_eq(m->numUsed(), 1);
test_counts(3, 1, 1, 5);
DMSG(" ---- Run #6");
m->runNextTask(); /* Task 6 suceeded */
/* iqueue:
* destroyed: 1s, 2f, 4t, 3s, 5s, 6s
* queued:
*/
ass_eq(m->inputQueue()->capacity(), 4);
ass_true(m->inputQueue()->isEmpty());
ass_eq(m->messageQueue()->capacity(), 4);
ass_true(m->messageQueue()->isEmpty());
ass_eq(m->numFree(), 4);
ass_eq(m->numUsed(), 0);
test_counts(4, 1, 1, 6);
m->queueTask(TestTask::create("Task 7", 7, 2, Task::kTSTerminated));
m->queueTask(TestTask::create("Task 8", 8, 2, Task::kTSFailed));
m->queueTask(TestTask::create("Task 9", 9, 2, Task::kTSFailed));
DMSG(" ---- Run #7"); /* Task 7 terminated */
m->runNextTask();
/* iqueue: 8f, 9f
* destroyed: 1s, 2f, 4t, 3s, 5s, 6s, 7t
* queued:
*/
ass_eq(m->inputQueue()->capacity(), 4);
ass_true(m->inputQueue()->isEmpty());
ass_eq(m->messageQueue()->capacity(), 4);
ass_true(m->messageQueue()->isEmpty());
ass_eq(m->numFree(), 2);
ass_eq(m->numUsed(), 2);
test_counts(4, 1, 2, 7);
DMSG(" ---- Run #8");
m->runNextTask(); /* Task 8 failed */
/* iqueue: 9f
* destroyed: 1s, 2f, 4t, 3s, 5s, 6s, 7t, 8f
* queued:
*/
ass_eq(m->inputQueue()->capacity(), 4);
ass_true(m->inputQueue()->isEmpty());
ass_eq(m->messageQueue()->capacity(), 4);
ass_true(m->messageQueue()->isEmpty());
ass_eq(m->numFree(), 3);
ass_eq(m->numUsed(), 1);
test_counts(4, 2, 2, 8);
m->queueTask(TestTask::create("Task 10", 10, 1, Task::kTSSucceeded));
DMSG(" ---- Run #9");
m->runNextTask(); /* Task 9 failed */
/* iqueue: 10s
* destroyed: 1s, 2f, 4t, 3s, 5s, 6s, 7t, 8f, 9f
* queued:
*/
ass_eq(m->inputQueue()->capacity(), 4);
ass_true(m->inputQueue()->isEmpty());
ass_eq(m->messageQueue()->capacity(), 4);
ass_true(m->messageQueue()->isEmpty());
ass_eq(m->numFree(), 3);
ass_eq(m->numUsed(), 1);
test_counts(4, 3, 2, 9);
m->queueTask(TestTask::create("Task 11", 11, 1, Task::kTSTerminated));
m->queueTask(TestTask::create("Task 12", 12, 1, Task::kTSSucceeded));
m->queueTask(TestTask::create("Task 13", 13, 1, Task::kTSFailed));
m->queueTask(TestTask::create("Task 14", 14, 1, Task::kTSSucceeded));
DMSG(" ---- Run #10");
m->runNextTask(); /* Task 10 suceeded */
/* iqueue: 11t, 12s, 13f
* destroyed: 1s, 2f, 4t, 3s, 5s, 6s, 7t, 8f, 9f, 10s
* queued: 14s
*/
ass_eq(m->inputQueue()->capacity(), 4);
ass_false(m->inputQueue()->isEmpty());
ass_eq(m->messageQueue()->capacity(), 4);
ass_true(m->messageQueue()->isEmpty());
ass_eq(m->numFree(), 1);
ass_eq(m->numUsed(), 3);
test_counts(5, 3, 2, 10);
DMSG(" ---- Run #11");
m->runNextTask(); /* Task 11 terminated */
/* iqueue: 12s, 13f, 14s
* destroyed: 1s, 2f, 4t, 3s, 5s, 6s, 7t, 8f, 9f, 10s, 11t
* queued:
*/
ass_eq(m->inputQueue()->capacity(), 4);
ass_true(m->inputQueue()->isEmpty());
ass_eq(m->messageQueue()->capacity(), 4);
ass_true(m->messageQueue()->isEmpty());
ass_eq(m->numFree(), 1);
ass_eq(m->numUsed(), 3);
test_counts(5, 3, 3, 11);
DMSG(" ---- Run #12");
m->runNextTask(); /* Task 12 succeeded */
/* iqueue: 13f, 14s
* destroyed: 1s, 2f, 4t, 3s, 5s, 6s, 7t, 8f, 9f, 10s, 11t, 12s
* queued:
*/
ass_eq(m->inputQueue()->capacity(), 4);
ass_true(m->inputQueue()->isEmpty());
ass_eq(m->messageQueue()->capacity(), 4);
ass_true(m->messageQueue()->isEmpty());
ass_eq(m->numFree(), 2);
ass_eq(m->numUsed(), 2);
test_counts(6, 3, 3, 12);
m->queueTask(TestTask::create("Task 15", 15, 1, Task::kTSSucceeded));
m->queueTask(TestTask::create("Task 16", 16, 2, Task::kTSTerminated));
m->queueTask(TestTask::create("Task 17", 17, 1, Task::kTSFailed));
m->queueTask(TestTask::create("Task 18", 18, 1, Task::kTSFailed));
DMSG(" ---- Run #13");
m->runNextTask(); /* Task 13 failed */
/* iqueue: 14s, 15s, 16t
* destroyed: 1s, 2f, 4t, 3s, 5s, 6s, 7t, 8f, 9f, 10s, 11t, 12s, 13f
* queued: 17f, 18f
*/
ass_eq(m->inputQueue()->capacity(), 4);
ass_false(m->inputQueue()->isEmpty());
ass_eq(m->messageQueue()->capacity(), 4);
ass_true(m->messageQueue()->isEmpty());
ass_eq(m->numFree(), 1);
ass_eq(m->numUsed(), 3);
test_counts(6, 4, 3, 13);
m->queueTask(TestTask::create("Task 19", 19, 2));
m->queueTask(TestTask::create("Task 20", 20, 3));
ass_true(m->hasFullQueue());
DMSG(" ---- Run #14");
m->runNextTask(); /* Task 14 succeeded*/
/* iqueue: 15s, 16t, 17f
* destroyed: 1s, 2f, 4t, 3s, 5s, 6s, 7t, 8f, 9f, 10s, 11t, 12s, 13f, 14s
* queued: 18f, 19s, 20s
*/
ass_eq(m->inputQueue()->capacity(), 4);
ass_false(m->inputQueue()->isEmpty());
ass_eq(m->messageQueue()->capacity(), 4);
ass_true(m->messageQueue()->isEmpty());
ass_false(m->hasFullQueue());
ass_eq(m->numFree(), 1);
ass_eq(m->numUsed(), 3);
test_counts(7, 4, 3, 14);
m->queueTask(TestTask::create("Task 21", 21, 1, Task::kTSFailed));
ass_true(m->hasFullQueue());
DMSG(" ---- Run #15");
m->runNextTask(); /* Task 15 succeeded*/
/* iqueue: 16t, 17f, 18f
* destroyed: 1s, 2f, 4t, 3s, 5s, 6s, 7t, 8f, 9f, 10s, 11t, 12s, 13f, 14s, 15s
* queued: 19s, 20s, 21f
*/
ass_eq(m->inputQueue()->capacity(), 4);
ass_false(m->inputQueue()->isEmpty());
ass_eq(m->messageQueue()->capacity(), 4);
ass_true(m->messageQueue()->isEmpty());
ass_false(m->hasFullQueue());
ass_eq(m->numFree(), 1);
ass_eq(m->numUsed(), 3);
test_counts(8, 4, 3, 15);
m->queueTask(TestTask::create("Task 22", 22, 1, Task::kTSTerminated));
ass_true(m->hasFullQueue());
DMSG(" ---- Run #16");
m->runNextTask(); /* Task 16 terminated */
/* iqueue: 17f, 18f, 19s
* destroyed: 1s, 2f, 4t, 3s, 5s, 6s, 7t, 8f, 9f, 10s, 11t, 12s, 13f, 14s, 15s, 16t,
* queued: 20s, 21f, 22t
*/
ass_eq(m->inputQueue()->capacity(), 4);
ass_false(m->inputQueue()->isEmpty());
ass_eq(m->messageQueue()->capacity(), 4);
ass_true(m->messageQueue()->isEmpty());
ass_false(m->hasFullQueue());
ass_eq(m->numFree(), 1);
ass_eq(m->numUsed(), 3);
test_counts(8, 4, 4, 16);
DMSG(" ---- Run #17");
m->runNextTask(); /* Task 17 failed */
/* iqueue: 18f, 19s, 20s
* destroyed: 1s, 2f, 4t, 3s, 5s, 6s, 7t, 8f, 9f, 10s, 11t, 12s, 13f, 14s, 15s, 16t, 17f
* queued: 21f, 22t
*/
ass_eq(m->inputQueue()->capacity(), 4);
ass_false(m->inputQueue()->isEmpty());
ass_eq(m->messageQueue()->capacity(), 4);
ass_true(m->messageQueue()->isEmpty());
ass_false(m->hasFullQueue());
ass_eq(m->numFree(), 1);
ass_eq(m->numUsed(), 3);
test_counts(8, 5, 4, 17);
DMSG(" ---- Run #18");
m->runNextTask(); /* Task 18 failed */
/* iqueue: 19s, 20s, 21f
* destroyed: 1s, 2f, 4t, 3s, 5s, 6s, 7t, 8f, 9f, 10s, 11t, 12s, 13f, 14s, 15s, 16t, 17f, 18f
* queued: 22t
*/
ass_eq(m->inputQueue()->capacity(), 4);
ass_false(m->inputQueue()->isEmpty());
ass_eq(m->messageQueue()->capacity(), 4);
ass_true(m->messageQueue()->isEmpty());
ass_false(m->hasFullQueue());
ass_eq(m->numFree(), 1);
ass_eq(m->numUsed(), 3);
test_counts(8, 6, 4, 18);
DMSG(" ---- Run #19");
m->runNextTask(); /* Task 19 succeeded */
/* iqueue: 20s, 21f, 22t
* destroyed: 1s, 2f, 4t, 3s, 5s, 6s, 7t, 8f, 9f, 10s, 11t, 12s, 13f, 14s, 15s, 16t, 17f, 18f, 19s
* queued:
*/
ass_eq(m->inputQueue()->capacity(), 4);
ass_true(m->inputQueue()->isEmpty());
ass_eq(m->messageQueue()->capacity(), 4);
ass_true(m->messageQueue()->isEmpty());
ass_eq(m->numFree(), 1);
ass_eq(m->numUsed(), 3);
test_counts(9, 6, 4, 19);
DMSG(" ---- Run #20");
m->runNextTask(); /* Task 20 succeeded */
/* iqueue: 21f, 22t
* destroyed: 1s,2f,4t,3s,5s,6s,7t,8f,9f,10s,11t,12s,13f,14s,15s,16t,17f,18f,19s,20s
* queued:
*/
ass_eq(m->inputQueue()->capacity(), 4);
ass_true(m->inputQueue()->isEmpty());
ass_eq(m->messageQueue()->capacity(), 4);
ass_true(m->messageQueue()->isEmpty());
ass_eq(m->numFree(), 2);
ass_eq(m->numUsed(), 2);
test_counts(10, 6, 4, 20);
DMSG(" ---- Run #21");
m->runNextTask(); /* Task 21 failed */
/* iqueue: 22t
* destroyed: 1s,2f,4t,3s,5s,6s,7t,8f,9f,10s,11t,12s,13f,14s,15s,16t,17f,18f,19s,20s,21f
* queued:
*/
ass_eq(m->inputQueue()->capacity(), 4);
ass_true(m->inputQueue()->isEmpty());
ass_eq(m->messageQueue()->capacity(), 4);
ass_true(m->messageQueue()->isEmpty());
ass_eq(m->numFree(), 3);
ass_eq(m->numUsed(), 1);
test_counts(10, 7, 4, 21);
DMSG(" ---- Run #22");
m->runNextTask(); /* Task 22 terminated */
/* iqueue:
* destroyed: 1s,2f,4t,3s,5s,6s,7t,8f,9f,10s,11t,12s,13f,14s,15s,16t,17f,18f,19s,20s,21f,22t
* queued:
*/
ass_eq(m->inputQueue()->capacity(), 4);
ass_true(m->inputQueue()->isEmpty());
ass_eq(m->messageQueue()->capacity(), 4);
ass_true(m->messageQueue()->isEmpty());
ass_eq(m->numFree(), 4);
ass_eq(m->numUsed(), 0);
test_counts(10, 7, 5, 22);
delete m;
test_counts(10, 7, 5, 22);
FINISH_TEST;
}
void testTaskRunnerAddChildTaskOnSuccess() {
BEGIN_TEST;
reset_counts();
test_counts(0, 0, 0, 0);
TaskRunner* m = new TaskRunner("PM", 4);
TaskPtr p = TestTask::create("Task 1", 1, 1, Task::kTSSucceeded);
p->attachChild(TestTask::create("Task 1c", 11, 2, Task::kTSSucceeded));
m->queueTask(p);
m->queueTask(TestTask::create("Task 2", 2, 1, Task::kTSSucceeded));
p = TestTask::create("Task 4", 4, 3, Task::kTSTerminated);
p->attachChild(TestTask::create("Task 4c", 44, 1, Task::kTSSucceeded));
m->queueTask(p);
p = TestTask::create("Task 3", 3, 1, Task::kTSFailed);
p->attachChild(TestTask::create("Task 3c", 33, 2, Task::kTSSucceeded));
m->queueTask(p);
p.setNull();
ass_eq(m->inputQueue()->capacity(), 4);
ass_false(m->inputQueue()->isEmpty());
ass_eq(m->messageQueue()->capacity(), 4);
ass_true(m->messageQueue()->isEmpty());
test_counts(0, 0, 0, 0);
DMSG(" ---- Run #1");
m->runNextTask(); /* Task 1 succeeds and adds 1c */
/* finished: 1
* destroyed:
* iqueue: 2, 4, 3, 1c
* queued:
*/
ass_eq(m->inputQueue()->capacity(), 4);
ass_true(m->inputQueue()->isEmpty());
ass_eq(m->messageQueue()->capacity(), 4);
ass_true(m->messageQueue()->isEmpty());
test_counts(1, 0, 0, 0);
DMSG(" ---- Run #2");
m->runNextTask(); /* Task 2 succeeded */
/* finished: 1
* destroyed: 2
* iqueue: 4, 3, 1c
* queued:
*/
ass_eq(m->inputQueue()->capacity(), 4);
ass_true(m->inputQueue()->isEmpty());
ass_eq(m->messageQueue()->capacity(), 4);
ass_true(m->messageQueue()->isEmpty());
test_counts(2, 0, 0, 1);
DMSG(" ---- Run #3");
m->runNextTask(); /* Task 4 terminate, terminate child */
/* finished: 1
* destroyed: 2, 4, 4c
* iqueue: 3, 1c
* queued:
*/
ass_eq(m->inputQueue()->capacity(), 4);
ass_true(m->inputQueue()->isEmpty());
ass_eq(m->messageQueue()->capacity(), 4);
ass_true(m->messageQueue()->isEmpty());
test_counts(2, 0, 2, 3);
m->queueTask(TestTask::create("Task 5", 5, 1));
DMSG(" ---- Run #4");
m->runNextTask(); /* 3 fails */
/* finished: 1
* destroyed: 2, 4, 4c, 3, 3c
* iqueue: 1c, 5
* queued:
*/
ass_eq(m->inputQueue()->capacity(), 4);
ass_true(m->inputQueue()->isEmpty());
ass_eq(m->messageQueue()->capacity(), 4);
ass_true(m->messageQueue()->isEmpty());
test_counts(2, 1, 3, 5);
DMSG(" ---- Run #5");
m->runNextTask(); /* Task 1c succeeds */
/* finished:
* destroyed: 2, 4, 4c, 3, 3c, 1, 1c
* iqueue: 5
* queued:
*/
ass_eq(m->inputQueue()->capacity(), 4);
ass_true(m->inputQueue()->isEmpty());
ass_eq(m->messageQueue()->capacity(), 4);
ass_true(m->messageQueue()->isEmpty());
test_counts(3, 1, 3, 7);
DMSG(" ---- Run #6");
m->runNextTask(); /* Task 5 succeeds */
/* finished:
* destroyed: 2, 4, 4c, 3, 3c, 1, 1c, 5
* iqueue:
* queued:
*/
ass_eq(m->inputQueue()->capacity(), 4);
ass_true(m->inputQueue()->isEmpty());
ass_eq(m->messageQueue()->capacity(), 4);
ass_true(m->messageQueue()->isEmpty());
test_counts(4, 1, 3, 8);
delete m;
test_counts(4, 1, 3, 8);
FINISH_TEST;
}
void testTaskRunnerClearAllWaitingTasks() {
BEGIN_TEST;
reset_counts();
TaskRunner* m = new TaskRunner("PM", 4);
ass_eq(m->inputQueue()->capacity(), 4);
ass_true(m->inputQueue()->isEmpty());
ass_eq(m->messageQueue()->capacity(), 4);
ass_true(m->messageQueue()->isEmpty());
ass_false(m->hasFullQueue());
ass_eq(m->state(), TaskRunner::kTRSNotStarted);
ass_false(m->hasQueued());
ass_eq(m->numFree(), 4);
ass_eq(m->numUsed(), 0);
test_counts(0, 0, 0, 0);
m->clearAllWaitingTasks();
ass_eq(m->inputQueue()->capacity(), 4);
ass_true(m->inputQueue()->isEmpty());
ass_eq(m->messageQueue()->capacity(), 4);
ass_false(m->messageQueue()->isEmpty());
ass_false(m->hasFullQueue());
ass_false(m->hasQueued());
ass_eq(m->state(), TaskRunner::kTRSNotStarted);
ass_eq(m->numFree(), 4);
ass_eq(m->numUsed(), 0);
test_counts(0, 0, 0, 0);
DMSG(" ---- Run #1"); /* Nothing should happen */
m->runNextTask();
ass_eq(m->inputQueue()->capacity(), 4);
ass_true(m->inputQueue()->isEmpty());
ass_eq(m->messageQueue()->capacity(), 4);
ass_true(m->messageQueue()->isEmpty());
ass_false(m->hasFullQueue());
ass_false(m->hasQueued());
ass_eq(m->state(), TaskRunner::kTRSNotStarted);
ass_eq(m->numFree(), 4);
ass_eq(m->numUsed(), 0);
test_counts(0, 0, 0, 0);
m->queueTask(TestTask::create("Task 1", 1, 1));
m->queueTask(TestTask::create("Task 2", 2, 2));
m->queueTask(TestTask::create("Task 4", 4, 1));
m->queueTask(TestTask::create("Task 3", 3, 3));
ass_eq(m->inputQueue()->capacity(), 4);
ass_false(m->inputQueue()->isEmpty());
ass_eq(m->messageQueue()->capacity(), 4);
ass_true(m->messageQueue()->isEmpty());
ass_true(m->hasFullQueue());
ass_true(m->hasQueued());
ass_eq(m->state(), TaskRunner::kTRSNotStarted);
ass_eq(m->numFree(), 4);
ass_eq(m->numUsed(), 0);
test_counts(0, 0, 0, 0);
m->clearAllWaitingTasks();
ass_eq(m->inputQueue()->capacity(), 4);
ass_false(m->inputQueue()->isEmpty());
ass_eq(m->messageQueue()->capacity(), 4);
ass_false(m->messageQueue()->isEmpty());
ass_true(m->hasFullQueue());
ass_true(m->hasQueued());
ass_eq(m->state(), TaskRunner::kTRSNotStarted);
ass_eq(m->numFree(), 4);
ass_eq(m->numUsed(), 0);
test_counts(0, 0, 0, 0);
DMSG(" ---- Run #2");
m->runNextTask(); /* Should destroy all tasks in the queue(s) */
/* destroyed: 1, 2, 3, 4
* iqueue:
* queued:
*/
ass_eq(m->inputQueue()->capacity(), 4);
ass_true(m->inputQueue()->isEmpty());
ass_eq(m->messageQueue()->capacity(), 4);
ass_true(m->messageQueue()->isEmpty());
ass_eq(m->state(), TaskRunner::kTRSNotStarted);
ass_false(m->hasFullQueue());
ass_false(m->hasQueued());
ass_eq(m->numFree(), 4);
ass_eq(m->numUsed(), 0);
test_counts(0, 0, 4, 4);
/* Add tasks, run once, then add more so tasks in both queues */
m->queueTask(TestTask::create("Task 1", 1, 1));
TaskPtr task = m->queueTask(TestTask::create("Task 2", 2, 1));
task->attachChild(TestTask::create("Task 2c", 22, 1));
m->queueTask(TestTask::create("Task 4", 4, 1));
task = m->queueTask(TestTask::create("Task 3", 3, 3));
task->attachChild(TestTask::create("Task 3c", 33, 2));
task.setNull();
test_counts(0, 0, 4, 4);
DMSG(" ---- Run #3");
m->runNextTask(); /* Task 1 suceeds */
/* destroyed: 1, 2, 3, 4, 1
* iqueue: 2, 3, 4
* queued:
*/
ass_eq(m->inputQueue()->capacity(), 4);
ass_true(m->inputQueue()->isEmpty());
ass_eq(m->messageQueue()->capacity(), 4);
ass_true(m->messageQueue()->isEmpty());
ass_eq(m->state(), TaskRunner::kTRSNotStarted);
ass_false(m->hasFullQueue());
ass_true(m->hasQueued());
ass_eq(m->numFree(), 1);
ass_eq(m->numUsed(), 3);
test_counts(1, 0, 4, 5);
m->queueTask(TestTask::create("Task 1", 1, 1));
m->queueTask(TestTask::create("Task 2", 2, 1));
m->queueTask(TestTask::create("Task 4", 4, 1));
m->queueTask(TestTask::create("Task 3", 3, 3));
DMSG(" ---- Run #4");
m->runNextTask(); /* Task 2 suceeded */
/* destroyed: 1, 2, 3, 4, 1
* finished: 2
* iqueue: 3, 4, 1, 2c
* queued: 2, 3, 4
*/
ass_eq(m->inputQueue()->capacity(), 4);
ass_false(m->inputQueue()->isEmpty());
ass_eq(m->messageQueue()->capacity(), 4);
ass_true(m->messageQueue()->isEmpty());
ass_eq(m->state(), TaskRunner::kTRSNotStarted);
ass_true(m->hasQueued());
ass_eq(m->numFree(), 0);
ass_eq(m->numUsed(), 4);
test_counts(2, 0, 4, 5);
m->clearAllWaitingTasks();
DMSG(" ---- Run #5");
m->runNextTask(); /* 2, 3, 3c, 4, 3, 4, 1, 2, 2c terminated */
/* destroyed: 1, 2, 3, 4, 1, 2, 3, 3c, 4, 3, 4, 1, 2c, 2
* finished:
* iqueue:
* queued:
*/
ass_eq(m->inputQueue()->capacity(), 4);
ass_true(m->inputQueue()->isEmpty());
ass_eq(m->messageQueue()->capacity(), 4);
ass_true(m->messageQueue()->isEmpty());
ass_eq(m->state(), TaskRunner::kTRSNotStarted);
ass_false(m->hasFullQueue());
ass_false(m->hasQueued());
ass_eq(m->numFree(), 4);
ass_eq(m->numUsed(), 0);
test_counts(2, 0, 12, 14);
delete m;
test_counts(2, 0, 12, 14);
FINISH_TEST;
}
void testTaskRunnerTerminateTaskRunner() {
BEGIN_TEST;
reset_counts();
TaskRunner* m = new TaskRunner("PM", 4);
m->queueTask(TestTask::create("Task 1", 1, 1));
m->queueTask(TestTask::create("Task 2", 2, 2));
m->queueTask(TestTask::create("Task 4", 4, 1));
m->queueTask(TestTask::create("Task 3", 3, 3));
ass_eq(m->inputQueue()->capacity(), 4);
ass_false(m->inputQueue()->isEmpty());
ass_eq(m->messageQueue()->capacity(), 4);
ass_true(m->messageQueue()->isEmpty());
ass_true(m->hasFullQueue());
ass_eq(m->numFree(), 4);
ass_eq(m->numUsed(), 0);
test_counts(0, 0, 0, 0);
m->terminateTaskRunner();
ass_eq(m->state(), TaskRunner::kTRSNotStarted);
DMSG(" ---- Run #1");
m->runNextTask(); /* Task 1, 2, 3, 4 should terminate, status = will terminate */
/* destroyed: 1, 2, 3, 4
* running:
* queued: NONE
*/
ass_eq(m->inputQueue()->capacity(), 4);
ass_true(m->inputQueue()->isEmpty());
ass_eq(m->messageQueue()->capacity(), 4);
ass_true(m->messageQueue()->isEmpty());
ass_eq(m->state(), TaskRunner::kTRSTerminated);
ass_false(m->hasFullQueue());
ass_eq(m->numFree(), 4);
ass_eq(m->numUsed(), 0);
test_counts(0, 0, 4, 4);
/** No taskes should be added */
m->queueTask(TestTask::create("Task 1", 1, 1));
m->queueTask(TestTask::create("Task 2", 2, 1));
m->queueTask(TestTask::create("Task 4", 4, 1));
m->queueTask(TestTask::create("Task 3", 3, 3));
DMSG(" ---- Run #2");
m->runNextTask(); /* */
/* destroyed: 1, 2, 3, 4
* running:
* queued:
*/
ass_eq(m->inputQueue()->capacity(), 4);
ass_true(m->inputQueue()->isEmpty());
ass_eq(m->messageQueue()->capacity(), 4);
ass_true(m->messageQueue()->isEmpty());
ass_eq(m->state(), TaskRunner::kTRSTerminated);
ass_false(m->hasFullQueue());
ass_eq(m->numFree(), 4);
ass_eq(m->numUsed(), 0);
test_counts(0, 0, 4, 8);
DMSG(" ---- Run #3");
m->runNextTask(); /* */
/* finished:
* destroyed: 1, 2, 3, 4
* running:
* queued:
*/
ass_eq(m->inputQueue()->capacity(), 4);
ass_true(m->inputQueue()->isEmpty());
ass_eq(m->messageQueue()->capacity(), 4);
ass_true(m->messageQueue()->isEmpty());
ass_eq(m->state(), TaskRunner::kTRSTerminated);
ass_false(m->hasFullQueue());
ass_eq(m->numFree(), 4);
ass_eq(m->numUsed(), 0);
test_counts(0, 0, 4, 8);
/** No taskes should be added */
m->queueTask(TestTask::create("Task 1", 1, 1));
m->queueTask(TestTask::create("Task 2", 2, 3));
m->queueTask(TestTask::create("Task 4", 4, 1));
m->queueTask(TestTask::create("Task 3", 3, 1));
ass_eq(m->inputQueue()->capacity(), 4);
ass_true(m->inputQueue()->isEmpty());
ass_eq(m->messageQueue()->capacity(), 4);
ass_true(m->messageQueue()->isEmpty());
ass_eq(m->state(), TaskRunner::kTRSTerminated);
ass_false(m->hasFullQueue());
ass_eq(m->numFree(), 4);
ass_eq(m->numUsed(), 0);
test_counts(0, 0, 4, 12);
DMSG(" ---- Run #4");
m->runNextTask(); /* */
/* finished:
* destroyed: 1, 2, 3, 4
* running:
* queued:
*/
ass_eq(m->inputQueue()->capacity(), 4);
ass_true(m->inputQueue()->isEmpty());
ass_eq(m->messageQueue()->capacity(), 4);
ass_true(m->messageQueue()->isEmpty());
ass_eq(m->state(), TaskRunner::kTRSTerminated);
ass_false(m->hasFullQueue());
ass_eq(m->numFree(), 4);
ass_eq(m->numUsed(), 0);
test_counts(0, 0, 4, 12);
delete m;
test_counts(0, 0, 4, 12);
m = new TaskRunner("PM2", 4);
m->terminateTaskRunner();
ass_eq(m->state(), TaskRunner::kTRSNotStarted);
DMSG(" ---- Run #5");
m->runNextTask(); /* */
/* finished:
* destroyed:
* running:
* queued:
*/
ass_eq(m->inputQueue()->capacity(), 4);
ass_true(m->inputQueue()->isEmpty());
ass_eq(m->messageQueue()->capacity(), 4);
ass_true(m->messageQueue()->isEmpty());
ass_eq(destroyed_count, 12);
ass_eq(m->state(), TaskRunner::kTRSTerminated);
/** No taskes should be added */
m->queueTask(TestTask::create("Task 1", 1, 1));
m->queueTask(TestTask::create("Task 2", 2, 1));
m->queueTask(TestTask::create("Task 4", 4, 1));
m->queueTask(TestTask::create("Task 3", 3, 1));
ass_eq(destroyed_count, 16);
ass_eq(m->state(), TaskRunner::kTRSTerminated);
DMSG(" ---- Run #6");
m->runNextTask(); /* */
/* finished:
* destroyed:
* running:
* queued:
*/
ass_eq(m->inputQueue()->capacity(), 4);
ass_true(m->inputQueue()->isEmpty());
ass_eq(m->messageQueue()->capacity(), 4);
ass_true(m->messageQueue()->isEmpty());
ass_eq(destroyed_count, 16);
ass_eq(m->state(), TaskRunner::kTRSTerminated);
delete m;
ass_eq(destroyed_count, 16);
FINISH_TEST;
}
} // namespace cc
int main(int argc, char** argv) {
cc::testCreateAndDestroyTaskRunner();
cc::testTaskRunnerQueueTask();
cc::testTaskRunnerPostMessages();
cc::testTaskRunnerRunTasksSimple();
cc::testTaskRunnerRunTasksComplex();
cc::testTaskRunnerAddChildTaskOnSuccess();
cc::testTaskRunnerClearAllWaitingTasks();
cc::testTaskRunnerTerminateTaskRunner();
return 0;
}
| true |
bdaa0b2f762da6b54d62a2a8aff6c3f629ace2d1 | C++ | scortier/Leetcode-Submissions | /problems/count_good_nodes_in_binary_tree/solution.cpp | UTF-8 | 962 | 2.921875 | 3 | [] | no_license | class Solution {
public:
// new integer and chars
int good(TreeNode * root, int mm)
{
// new integer and chars
int ans=0;
// if else looping condition
if(!root)
// return value
return 0;
// new chars
mm=max(mm,root->val);
// logicl execution
ans+=good(root->left,mm);
ans+=good(root->right,mm);
// if else logical input
if(mm<=root->val)
{
// answering loop
ans++;
}
return ans;
}
// new integers
int goodNodes(TreeNode* root) {
// if looping
if(!root) return 0;
// new integer
int mm=root->val;
// retrning value
return good(root,mm);
}
}; | true |
afb33a4363924970d67bb922b23f348ae2ce1480 | C++ | cloneforyou/fundamentals-computer-animation | /Assignment 1/include/math/mat4f.h | UTF-8 | 1,562 | 3.203125 | 3 | [
"MIT"
] | permissive | #pragma once
#include <array>
#include <initializer_list>
#include <iosfwd>
#include <memory>
namespace math {
class Mat4f {
public:
enum Size { DIM = 4, NUMBER_ELEMENTS = 16 };
using array16f = std::array<float, NUMBER_ELEMENTS>;
using handle = std::unique_ptr<array16f>;
explicit Mat4f();
explicit Mat4f(float fillValue);
Mat4f(std::initializer_list<float> list);
Mat4f(Mat4f &&);
Mat4f(Mat4f const &);
~Mat4f();
void fill(float t);
Mat4f &operator=(Mat4f const &other);
Mat4f &operator=(Mat4f &&other);
float &operator()(int row, int column);
float &operator[](int element);
float operator()(int row, int column) const;
float operator[](int element) const;
float &at(int row, int column);
float &at(int element);
float at(int row, int column) const;
float at(int element) const;
bool isValidDim(int idx) const;
bool isValidElement(int idx) const;
float *data();
float const *data() const;
int rowMajorIndex(int row, int column) const;
array16f::iterator begin();
array16f::iterator end();
array16f::const_iterator begin() const;
array16f::const_iterator end() const;
private:
handle m_ptr = nullptr;
};
Mat4f identity();
Mat4f transposed(Mat4f mat);
Mat4f operator+(Mat4f const &lhs, Mat4f const &rhs);
Mat4f operator-(Mat4f const &lhs, Mat4f const &rhs);
Mat4f operator*(Mat4f const &lhs, Mat4f const &rhs);
Mat4f operator*(float s, Mat4f const &rhs);
Mat4f operator*(Mat4f const &lhs, float s);
std::ostream &operator<<(std::ostream &out, Mat4f const &mat);
} // namespace math
| true |
e4643b39e3e59d6b0bf73d4663c0d3b23ec63d2e | C++ | mholzel/pid | /src/mimo_pid.h | UTF-8 | 2,478 | 3.109375 | 3 | [] | no_license | #ifndef MIMO_PID_HEADER
#define MIMO_PID_HEADER
#include <sstream>
#include <string>
#include "Eigen/Dense"
template <typename T = double, int n_controls = 1, int n_measurements = 1>
class MimoPID
{
private:
/* Errors */
using Error = Eigen::Matrix<T, n_measurements, 1>;
Error last_error;
Error integral_of_errors;
/* Coefficients */
using Gain = Eigen::Matrix<T, n_controls, n_measurements>;
Gain k_p;
Gain k_i;
Gain k_d;
using Control = Eigen::Matrix<T, n_controls, 1>;
static const int n_parameters_per_gain = n_controls * n_measurements;
static const int n_parameters = 3 * n_parameters_per_gain;
public:
bool was_reset = false;
/** Constructors */
MimoPID(const Gain &k_p,
const Gain &k_i,
const Gain &k_d)
: k_p(k_p),
k_i(k_i),
k_d(k_d)
{
last_error = Error::Zero();
integral_of_errors = Error::Zero();
}
/** Destructor */
virtual ~MimoPID() {}
/** Compute the PID output and update the PID state */
Control update(Error &error, double dt = 1)
{
Error derivative_of_error = (error - last_error) / dt;
integral_of_errors += dt * (last_error + (error - last_error) / 2);
last_error = error;
return -k_p * error - k_d * derivative_of_error - k_i * integral_of_errors;
}
/** Convert the parameters to a comman-separated list string in the form k_p,k_i,k_d */
std::string toString()
{
std::stringstream cout;
cout << k_p << "," << k_i << "," << k_d << std::endl;
return cout.str();
}
/** Overload the () operator so that the coefficients can be accessed via linear indexing.
* This is used primarily by the optimization algorithms */
T &operator()(int index)
{
if (index < n_parameters_per_gain)
{
return k_p(index);
}
else if (index < 2 * n_parameters_per_gain)
{
return k_i(index - n_parameters_per_gain);
}
else if (index < 3 * n_parameters_per_gain)
{
return k_d(index - 2 * n_parameters_per_gain);
}
else
{
assert(false);
}
}
int size() const
{
return n_parameters;
}
void reset()
{
last_error = Error::Zero();
integral_of_errors = Error::Zero();
was_reset = true;
}
};
#endif /* MIMO_PID_HEADER */
| true |
c18b2e94906b2e91b060a4109e706556ed83ca55 | C++ | TomasKimer/RetroSpace | /src/Controls.h | UTF-8 | 2,988 | 2.796875 | 3 | [] | no_license | // +------------------------------------------------------------+
// | RetroSpace v1.0 |
// | Retrospektivni hra pro dva hrace s vesmirnou tematikou |
// | Bakalarska prace, FIT VUT v Brne, 2011 |
// +------------------------------------------------------------+
/** @author Tomas Kimer (xkimer00@stud.fit.vutbr.cz)
* @date 18.5.2011
* @file Controls.h
* @brief Sprava ovladani pro dva hrace.
*/
#pragma once
#include "Keyboard.h"
#include "Mouse.h"
#include <utility>
using namespace GameFramework;
namespace RetroSpace
{
/**
* Sprava ovladani.
*/
class Controls
{
public:
/**
* Mozne ovladane akce.
*/
enum Action
{
ACT_ACCELERATE,
ACT_TURN_LEFT,
ACT_TURN_RIGHT,
ACT_SHOOT,
ACT_TRANSFER,
ACT_NONE
};
/**
* Ovladac.
*/
enum Controller
{
CTRL_KEYBOARD,
CTRL_MOUSE,
CTRL_NONE
};
/**
* Nastaveni tlacitek mysi.
*/
struct MouseControls
{
BtnCode accel, shoot, transfer;
};
/**
* Nastaveni klaves.
*/
struct KeyboardControls
{
KeyCode accel, shoot, turnLeft, turnRight, transfer;
};
/**
* Celkove nastaveni jednoho hrace.
*/
struct PlayerControls
{
Controller ctrl;
KeyboardControls keyb;
MouseControls mouse;
};
public:
Controls(void);
~Controls(void);
int GetMousePlayer();
// unbuffered
int MouseAction(const Mouse & m, Action action);
void KeyboardAction(const Keyboard & k, Action action, bool & pl1, bool & pl2);
// buffered
std::pair<Action, int> MouseAction(BtnCode btn);
std::pair<Action, int> KeyboardAction(KeyCode key);
std::string GetKeyAsString(KeyCode kc) { return m_refKeyb->GetAsString(kc); }
std::string GetBtnAsString(BtnCode bc) { return m_refMouse->GetAsString(bc); }
bool SwitchPlayerController(int pNum, bool force = true);
void SetDefaultKeyboardControls(int playerNum);
void SetDefaultMouseControls(int playerNum);
void EditActionButton(Action action, int playerNum, BtnCode newButton);
void EditActionKey(Action action, int playerNum, KeyCode newKey);
void SetPlayerControls(PlayerControls & pl1, PlayerControls & pl2, PlayerControls & defaultPl1, PlayerControls & defaultPl2);
void SetInputDevices(Keyboard & keyb, Mouse & mouse);
PlayerControls & GetPlayerControls(int num) { return *m_playerCtrl[num % 2]; }
private:
PlayerControls *m_playerCtrl[2];
PlayerControls *m_defaultPlayerCtrl[2];
Keyboard *m_refKeyb;
Mouse *m_refMouse;
};
}
| true |
e37e0f82d6b3ac82ab2359b7f641756504db2f8b | C++ | mayank1751997/c-exp | /binary number.cpp | UTF-8 | 267 | 2.59375 | 3 | [] | no_license | #include<stdio.h>
int main()
{
int n,nsave,rem,d,j=1,dec=0;
printf("enter the binary number");
scanf("%d",&n);
nsave = n;
while(n>0)
{
d=rem*j;
rem=n%10;
dec+=d;
j*=2;
n/=10;
}
printf("enter number =%d,dec =%d\n",nsave,dec);
return 0;
}
| true |
c7fe7031926b10be32a7ccc470fdd8322454385a | C++ | Kraghan/Dead-Pixel-Society | /include/GraphicEngine/AnimationState.hpp | UTF-8 | 1,139 | 2.828125 | 3 | [] | no_license | /*!
* \brief File that contains the header of the class
* animation state
* \file AnimationState.hpp
* \author Aredhele
* \version 0.1
* \date 22/11/2016
*/
#ifndef __ANIMATION_STATE_HPP
#define __ANIMATION_STATE_HPP
#include "GraphicEngine/Sprite.hpp"
#include "GameEngine/Updatable.hpp"
class AnimationState : public Updatable
{
public:
/*!
* \brief TODO
*/
explicit AnimationState();
/*!
* \brief Initialize the state
*/
void init(Sprite * pSrite, bool repeat,
sf::Vector2i pos, sf::Vector2i size,
int offset, char step, double delay);
/*!
* \brief Implements abstract method
* \param dt The elapsed time
*/
virtual void update(double dt);
/*!
* \brief TODO
*/
void setRepeat(bool repeat);
/*!
* \brief TODO
*/
void onEnter();
private:
Sprite * m_sprite;
bool m_repeat;
sf::Vector2i m_size;
sf::Vector2i m_position;
char m_step;
char m_currentStep;
int m_offset;
double m_delay;
double m_elapsed;
};
#endif // __ANIMATION_STATE_HPP
| true |
081fb2e7cb42be0f4d002802fbd803c4ad708f1f | C++ | kravtsovguy/BaseEngine | /GameEngine/GameObject.cpp | UTF-8 | 555 | 2.515625 | 3 | [] | no_license | //
// GameObject.cpp
// GameEngine
//
// Created by Matvey Kravtsov on 18/01/2017.
// Copyright © 2017 Matvey Kravtsov. All rights reserved.
//
#include "GameObject.hpp"
GameObject::GameObject()
{
addComponent(new Transform());
}
Transform* GameObject::getTransform()
{
return (Transform*)findComponent<Transform>();
}
void GameObject::addComponent(Component* c)
{
c->setGO(this);
components.push_back(c);
}
void GameObject::removeComponent(Component* c)
{
components.erase(remove(components.begin(), components.end(), c), components.end());
}
| true |
158ea8475b78fe8468b1a55161f4482da8deaef3 | C++ | atlas25git/DSA_Mastery | /Sorting/MinPlatformReq.cpp | UTF-8 | 2,518 | 3.5625 | 4 | [] | no_license | // { Driver Code Starts
// Program to find minimum number of platforms
// required on a railway station
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
class Solution{
public:
//Function to sort vector elements first according to time and if time is
//same for two events, then arrival comes first followed by departure.
static bool customsort(const pair<int,char> &a,const pair<int,char> &b)
{
if(a.first == b.first) return a.second < b.second;
return a.first < b.first;
}
//Function to find the minimum number of platforms required at the
//railway station such that no train waits.
int findPlatform(int arr[], int dep[], int n)
{
vector< pair<int,char> > order;
//inserting all the values of time(arrival and departure)
//in the vector of pairs.
for (int i = 0; i < n; i++) {
//if the time is of arrival then we keep second value
//of pair as 'a' else 'd'.
order.push_back(make_pair(arr[i], 'a'));
order.push_back(make_pair(dep[i], 'd'));
}
//using custom sort vector, first according to time and if time is
//same for two events, then arrival comes first followed by departure.
sort(order.begin(),order.end(),customsort);
int result = 1;
int plat_needed = 0;
//using an iterator on vector of pairs.
vector< pair<int,char> >::iterator it = order.begin();
for (; it != order.end(); it++) {
//if the second value of vector element is 'a' which stands
//for arrival then we add 1 to platform needed else we
//subtract 1 from platform needed.
if ((*it).second == 'a')
plat_needed++;
else
plat_needed--;
//we keep updating the value of result.
if (plat_needed>result)
result = plat_needed;
}
//returning the minimum number of platforms required.
return result;
}
};
// { Driver Code Starts.
// Driver code
int main()
{
int t;
cin>>t;
while(t--)
{
int n;
cin>>n;
int arr[n];
int dep[n];
for(int i=0;i<n;i++)
cin>>arr[i];
for(int j=0;j<n;j++){
cin>>dep[j];
}
Solution ob;
cout <<ob.findPlatform(arr, dep, n)<<endl;
}
return 0;
} // } Driver Code Ends | true |
d976ecc6765b5909b6a3568b1c980e5c95f9de5b | C++ | williamthio/competitive-programming-3 | /Programming Exercises/2.2 Linear DS with Built-in Libraries/2. 2D Array Manipulation/UVa_10855.cpp | UTF-8 | 1,708 | 2.8125 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <functional>
using namespace std;
void uva_10855() {
int bn, sn;
while (cin >> bn, bn) {
cin >> sn;
vector<vector<char>> big, small;
big.resize(bn);
small.resize(sn);
for (int i = 0; i < bn; i++) {
big[i].resize(bn);
for (int j = 0; j < bn; j++)
cin >> big[i][j];
}
for (int i = 0; i < sn; i++) {
small[i].resize(sn);
for (int j = 0; j < sn; j++)
cin >> small[i][j];
}
auto isSame = [&](int row, int col) -> bool {
for (int i = 0; i < sn; i++) {
for (int j = 0; j < sn; j++) {
if (big[row + i][col + j] != small[i][j]) {
return false;
}
}
}
return true;
};
auto rotate = [&]() {
vector<vector<char>> rotated = small;
for (int i = 0; i < sn; i++) {
for (int j = 0; j < sn; j++) {
rotated[i][j] = small[sn - 1 - j][i];
}
}
small = rotated;
};
for (int rotation = 0; rotation < 4; rotation++) {
if (rotation > 0) {
cout << " ";
rotate();
}
int count = 0;
for (int row = 0; row <= bn - sn; row++) {
for (int col = 0; col <= bn - sn; col++) {
if (isSame(row, col)) {
count++;
}
}
}
cout << count;
}
cout << "\n";
}
}
| true |
efb590154437d5f4fb6ae8e495fbfd7c33ee05ed | C++ | Wingman639/cpp_learning | /class/init_instence.cpp | UTF-8 | 760 | 3.890625 | 4 | [] | no_license | #include <iostream>
#include <string>
using namespace std;
class stuff {
string name;
int age;
public:
stuff() { //这是写法一
cout << name << "---" << age << endl; //赋值前可能会为未初始化值
name = "赋值前可能会为空";
age = 0;
cout << name << "---" << age << endl;
}
stuff(string n, int a):name(n),age(a) //这是写法二, 在成员变量分配空间的同时将参数的值赋给成员变量。
{
cout << name << "---" << age << endl;
}
string getName() {
return name;
}
int getAge() {
return age;
}
};
int main ( )
{
stuff st2;
stuff st1("构造的同时初始化,避免半初始化状态", 3);
return 0;
} | true |
4dbebc35f0016a9cc97a89378af66ca6815dd21f | C++ | bibhuticoder/IES-snake | /snake.ino | UTF-8 | 5,562 | 2.921875 | 3 | [
"MIT"
] | permissive | #include <SPI.h>
#include <U8g2lib.h>
#include <math.h>
#include <string>
#include <MPU9250.h>
using namespace std;
struct Point{ int x; int y;};
#define SPI_CLK 14
U8G2_SSD1306_128X64_NONAME_F_4W_HW_SPI oled(U8G2_R2, 10, 15, 16);
MPU9250 imu;
//function prototypes
bool collission(int x1, int y1, int x2, int y2, int size1, int size2);
class Food{
public:
Point location;
int size;
Food(){
location = {random(10, 120), random(10, 50)};
size = 4;
}
void reset(){
location = {random(10, 120), random(10, 50)};
}
void draw(){
oled.drawCircle((int)location.x + size/2, (int)location.y+size/2, size/2, U8G2_DRAW_ALL);
}
};
class Snake{
public:
String name;
Point body[100];
int direction;
int length;
int speedX;
int speedY;
int speed;
int size;
int type;
int score;
Snake(int t, String n){
type = t;
name = n;
direction = random(0,4); // up:0, left:1, down:2, right:3
speed = 3;
size = 3;
score = 0;
length = 3;
//random initial position
body[0] = {random(10, 120), random(10, 50)};
//populate body
for(int i=1; i<length; i++){
body[i] = {body[i-1].x - size, body[i-1].y};
Serial.println(body[i].x);
}
}
void draw(Food *food){
//move body
for(int i=length-1; i>=1; i--){
body[i].x = body[i-1].x;
body[i].y = body[i-1].y;
if(type == 1) oled.drawFrame(body[i].x, body[i].y, size+1, size+1);
else oled.drawFrame(body[i].x, body[i].y, size, size);
}
//move head according to direction
if(direction == 0){
speedY = - speed;
speedX = 0;
}
else if(direction == 1){
speedX = - speed;
speedY = 0;
}
else if(direction == 2){
speedY = speed;
speedX = 0;
}
else if(direction == 3){
speedX = speed;
speedY = 0;
}
body[0].x += speedX;
body[0].y += speedY;
if(type == 1) oled.drawFrame(body[0].x, body[0].y, size+1, size+1);
else oled.drawFrame(body[0].x, body[0].y, size, size);
//check boundary collission
if(body[0].x + size > 128) body[0].x = 0; //right
else if(body[0].x < 0)body[0].x = 128; //left
else if(body[0].y < 0) body[0].y = 64; //up
else if(body[0].y+size > 64) body[0].y = 0; //down
//check food collission
if(collission(food->location.x, food->location.y, body[0].x, body[0].y, size, size+1)){
score++;
body[length] = {130, 130};
length++;
food->reset();
}
}
void changeDir(int d){
//snake can't bend in opposite direction
bool allow = true;
if(direction == 0 && d == 2) allow = false;
else if(direction == 1 && d == 3) allow = false;
else if(direction == 2 && d == 0) allow = false;
else if(direction == 3 && d == 1) allow = false;
if(allow) direction = d;
}
};
class Game{
public:
Snake* snakes[10]; // first one is you
int numSnakes;
Food *food;
elapsedMillis gameTimer;
elapsedMillis dirTimer;
elapsedMillis inputTimer;
Game(){
//initialize game components
snakes[0] = new Snake(1, "Me");
numSnakes = 3;
for(int i=1; i<numSnakes; i++) snakes[i] = new Snake(0, "other"+String(i));
food = new Food();
}
void draw(){
//snake and food
for(int i=0; i<numSnakes; i++) snakes[i]->draw(food);
food->draw();
//score
oled.setFont(u8g2_font_u8glib_4_tr);
int offsetX = 1;
int offsetY = 5;
int gapY = 10;
for(int i=0; i<numSnakes; i++){
oled.setCursor(offsetX, offsetY + i*gapY);
oled.print(snakes[i]->name + ": " + String(snakes[i]->score));
}
}
bool collission(int x1, int y1, int x2, int y2, int size1, int size2) {
int w1 = size1;
int h1 = size1;
int w2 = size2;
int h2 = size2;
return ((abs(x1 - x2) * 2 < (w1 + w2)) && (abs(y1 - y2) * 2 < (h1 + h2)));
}
int getAccDir(){
int dir = 0;
if(abs(imu.ay) > abs(imu.ax)){
if(imu.ay < 0){
return 1;
}
else if(imu.ay > 0){
return 3;
}
}
else{
if(imu.ax < 0){
return 0;
}
else if(imu.ax > 0){
return 2;
}
}
}
};
Game *game;
void setup() {
SPI.setSCK(SPI_CLK); // move the SPI SCK pin from default of 13
oled.begin(); // initialize the OLED
Serial.begin(115200);
randomSeed(analogRead(0));
game = new Game();
//calibrate IMU
byte c = imu.readByte(MPU9250_ADDRESS, WHO_AM_I_MPU9250);
imu.initMPU9250();
imu.MPU9250SelfTest(imu.selfTest);
imu.calibrateMPU9250(imu.gyroBias, imu.accelBias);
imu.initAK8963(imu.factoryMagCalibration);
imu.getAres();
}
void loop() {
if(game->gameTimer > 80){
oled.clearBuffer();//clear
game->draw();
oled.sendBuffer();
game->gameTimer = 0;
}
if(game->dirTimer > 1000){
for(int i=1; i<game->numSnakes; i++) game->snakes[i]->direction = random(0, 4);
Serial.println(game->dirTimer);
game->dirTimer = 0;
}
if(game->inputTimer > 100){
//snake control
imu.readAccelData(imu.accelCount);
imu.ax = (float)imu.accelCount[0]*imu.aRes;
imu.ay = (float)imu.accelCount[1]*imu.aRes;
imu.az = (float)imu.accelCount[2]*imu.aRes;
game->snakes[0]->changeDir(game->getAccDir());
game->inputTimer = 0;
}
}
| true |
8164bc820b943349b03dde2538a66895dab9e727 | C++ | hennesseyr14/EECS-183 | /Project 2/Project 2/test.cpp | UTF-8 | 5,065 | 3.46875 | 3 | [] | no_license | /**
* test.cpp
*
* Ryan Hennessey
* rjhenn
*
* EECS 183: Project 2
*
* Testing functions for your birthdays.cpp implementation.
* Holds the definitions of required testing functions.
* We have stubbed all required functions for you.
*/
#include <cassert>
#include <cctype>
#include <iostream>
#include <limits>
#include <string>
using namespace std;
//************************************************************************
// You should have implemented the following functions in birthdays.cpp
//************************************************************************
bool isLeapYear (int year);
bool isGregorianDate(int m, int d, int y);
bool isValidDate(int month, int day, int year);
int determineDay (int month, int day, int year);
//************************************************************************
// Put all your test function implementations below here.
// We have stubbed all required functions for you
// to recieve full points when submitting test.cpp
//************************************************************************
static void test_isLeapYear() {
cout << "Begin testing isLeapYear() " << endl;
cout << isLeapYear(2000) << " correct value is: 1" << endl;
cout << isLeapYear(1900) << " correct value is: 0" << endl;
cout << isLeapYear(1996) << " correct value is: 1" << endl;
cout << isLeapYear(1995) << " correct value is: 0" << endl;
cout << "End testing isLeapYear() " << endl << endl;
}
void test_isGregorianDate() {
cout << "Begin testing isGregorianDate() " << endl;
cout << isGregorianDate(8, 19, 2016) << " correct value is: 1" << endl;
cout << isGregorianDate(3, 12, 1234) << " correct value is: 0" << endl;
cout << isGregorianDate(9, 13, 1752) << " correct value is: 0" << endl;
cout << isGregorianDate(9, 14, 1752) << " correct value is: 1" << endl;
cout << isGregorianDate(10, 13, 1752) << " correct value is: 1" << endl;
cout << isGregorianDate(10, 14, 1752) << " correct value is: 1" << endl;
cout << isGregorianDate(9, 13, 1753) << " correct value is: 1" << endl;
cout << isGregorianDate(9, 14, 1753) << " correct value is: 1" << endl;
cout << isGregorianDate(9, 13, 1750) << " correct value is: 0" << endl;
cout << isGregorianDate(9, 14, 1750) << " correct value is: 0" << endl;
cout << isGregorianDate(10, 13, 1750) << " correct value is: 0" << endl;
cout << isGregorianDate(10, 14, 1750) << " correct value is: 0" << endl;
cout << isGregorianDate(10, 13, 1753) << " correct value is: 1" << endl;
cout << isGregorianDate(10, 14, 1753) << " correct value is: 1" << endl;
cout << isGregorianDate(8, 13, 1752) << " correct value is: 0" << endl;
cout << isGregorianDate(8, 14, 1752) << " correct value is: 0" << endl;
cout << isGregorianDate(8, 13, 1754) << " correct value is: 1" << endl;
cout << isGregorianDate(8, 14, 1754) << " correct value is: 1" << endl;
cout << isGregorianDate(11, 1, 1995) << " correct value is: 1" << endl;
cout << "End testing isGregorianDate() " << endl << endl;
}
static void test_isValidDate() {
cout << "Begin testing isValidDate() " << endl;
cout << isValidDate(8, 19, 2016) << " correct value is: 1" << endl;
cout << isValidDate(13, 12, 1994) << " correct value is: 0" << endl;
cout << isValidDate(9, 13, 1750) << " correct value is: 0" << endl;
cout << isValidDate(9, 14, 1752) << " correct value is: 1" << endl;
cout << isValidDate(0, 13, 1776) << " correct value is: 0" << endl;
cout << isValidDate(9, 31, 2004) << " correct value is: 0" << endl;
cout << isValidDate(4, 31, 2004) << " correct value is: 0" << endl;
cout << isValidDate(11, 31, 2004) << " correct value is: 0" << endl;
cout << isValidDate(6, 31, 2004) << " correct value is: 0" << endl;
cout << isValidDate(8, 32, 2004) << " correct value is: 0" << endl;
cout << isValidDate(2, 29, 2004) << " correct value is: 1" << endl;
cout << isValidDate(2, 29, 2003) << " correct value is: 0" << endl;
cout << isValidDate(1, 31, 2005) << " correct value is: 1" << endl;
cout << isValidDate(1, 0, 2005) << " correct value is: 0" << endl;
cout << isValidDate(0, 1, 2015) << " correct value is: 0" << endl;
cout << isValidDate(1, 1, 1005) << " correct value is: 0" << endl;
cout << "End testing isValidDate() " << endl << endl;
}
static void test_determineDay() {
cout << "Begin testing determineDay() " << endl;
cout << determineDay(10, 6, 2017) << " correct value is: 6" << endl;
cout << determineDay(11, 1, 1995) << " correct value is: 4" << endl;
cout << determineDay(1, 29, 2064) << " correct value is: 3" << endl;
cout << determineDay(2, 5, 2017) << " correct value is: 1" << endl;
cout << "End testing determineDay() " << endl << endl;
}
int main(int argc, char *argv[]) {
test_isLeapYear();
test_isGregorianDate();
test_isValidDate();
test_determineDay();
}
| true |
179046fed5cf9459c97e9cef29500c1f42cdd8dc | C++ | codingsf/netlib | /ds/binary_search_tree.cc | UTF-8 | 5,130 | 3.671875 | 4 | [
"MIT"
] | permissive | #include "binary_node.h"
template<typename T>
class BinarySearchTree
{
public:
BinarySearchTree(): root_(nullptr) {}
~BinarySearchTree();
void Create();
// Return nullptr if fails, otherwise return the new node's pointer.
BinaryNode<T> *Insert(const T &data);
// Return nullptr if fails, otherwise return the match node's pointer.
BinaryNode<T> *Search(const T &data, BinaryNode<T>* &parent_node);
// Return nullptr if fails, otherwise return the node that replaces deleted node.
BinaryNode<T> *Delete(const T &data);
void LevelOrder() const;
void Height() const;
void NodeCount() const;
private:
BinaryNode<T> *root_;
};
template<typename T>
BinarySearchTree<T>::~BinarySearchTree()
{
::Delete(root_);
}
template<typename T>
void BinarySearchTree<T>::Create()
{
int data_number;
scanf("%d", &data_number);
while(data_number-- > 0)
{
int data;
scanf("%d", &data);
Insert(data);
}
}
template<typename T>
BinaryNode<T>* BinarySearchTree<T>::Insert(const T &data)
{
BinaryNode<T> *parent_node = nullptr;
if(Search(data, parent_node) != nullptr)
{
return nullptr;
}
BinaryNode<T> *new_node = new BinaryNode<T>(data);
if(parent_node == nullptr) // BST is empty.
{
root_ = new_node;
}
else
{
if(data < parent_node->data_)
{
parent_node->left_ = new_node;
}
else
{
parent_node->right_ = new_node;
}
}
return new_node;
}
template<typename T>
BinaryNode<T>* BinarySearchTree<T>::Search(const T &data, BinaryNode<T>* &parent_node)
{
BinaryNode<T> *search_node = root_;
while(search_node != nullptr)
{
if(data == search_node->data_)
{
return search_node;
}
parent_node = search_node; // Must after `if(==)` condition.
if(data < search_node->data_)
{
search_node = search_node->left_;
}
else
{
search_node = search_node->right_;
}
}
return nullptr;
}
template<typename T>
BinaryNode<T>* BinarySearchTree<T>::Delete(const T &data)
{
BinaryNode<T> *parent_node = nullptr;
BinaryNode<T> *delete_node = Search(data, parent_node);
if(delete_node == nullptr) // Must FIRST check data isn't in tree.
{
return nullptr;
}
// Assume delete_node has 2 subnodes, change it to left_max_node,
// then it has 1 or 0 subnodes.
if(delete_node->left_ != nullptr && delete_node->right_ != nullptr)
{
BinaryNode<T> *left_max_parent = delete_node, *left_max = delete_node->left_;
while(left_max->right_ != nullptr)
{
left_max_parent = left_max;
left_max = left_max->right_;
}
delete_node->data_ = left_max->data_;
parent_node = left_max_parent;
delete_node = left_max;
}
BinaryNode<T> *child_node =
(delete_node->left_ ? delete_node->left_ : delete_node->right_);
if(parent_node == nullptr)
{
root_ = child_node;
}
else
{
if(delete_node == parent_node->left_)
{
parent_node->left_ = child_node;
}
else
{
parent_node->right_ = child_node;
}
}
delete delete_node;
return child_node;
}
template<typename T>
void BinarySearchTree<T>::LevelOrder() const
{
printf("LevelOrder: ");
::LevelOrder(root_);
printf("\n");
}
template<typename T>
void BinarySearchTree<T>::Height() const
{
printf("Height: %d\n", ::Height(root_));
}
template<typename T>
void BinarySearchTree<T>::NodeCount() const
{
printf("NodeCount: %d\n", ::NodeCount(root_));
}
int main()
{
BinarySearchTree<int> tree;
printf("0: Exit\n1: Create\n2: Insert\n3: Search\n4: Delete\n");
int operation, data;
BinaryNode<int> *temp = nullptr;
while(scanf("%d", &operation) == 1)
{
switch(operation)
{
case 0:
return 0;
case 1:
tree.Create();
break;
case 2:
scanf("%d", &data);
tree.Insert(data);
break;
case 3:
scanf("%d", &data);
if(tree.Search(data, temp) != nullptr)
{
printf("Found\n");
}
else
{
printf("Not Found\n");
}
break;
case 4:
scanf("%d", &data);
if(tree.Delete(data) != nullptr)
{
printf("Deleted\n");
}
else
{
printf("Not Deleted\n");
}
break;
}
tree.LevelOrder();
tree.Height();
tree.NodeCount();
}
}
/*
1 11 6 10 9 0 1 5 7 2 8 3 4
2 6
2 2
2 100
3 -1
3 0
3 100
3 101
4 -1
4 101
4 4
4 2
4 10
4 6
0
LevelOrder: 6 0 10 1 9 5 7 2 8 3 4
Height: 7
NodeCount: 11
LevelOrder: 6 0 10 1 9 5 7 2 8 3 4
Height: 7
NodeCount: 11
LevelOrder: 6 0 10 1 9 5 7 2 8 3 4
Height: 7
NodeCount: 11
LevelOrder: 6 0 10 1 9 100 5 7 2 8 3 4
Height: 7
NodeCount: 12
Not Found
LevelOrder: 6 0 10 1 9 100 5 7 2 8 3 4
Height: 7
NodeCount: 12
Found
LevelOrder: 6 0 10 1 9 100 5 7 2 8 3 4
Height: 7
NodeCount: 12
Found
LevelOrder: 6 0 10 1 9 100 5 7 2 8 3 4
Height: 7
NodeCount: 12
Not Found
LevelOrder: 6 0 10 1 9 100 5 7 2 8 3 4
Height: 7
NodeCount: 12
Not Deleted
LevelOrder: 6 0 10 1 9 100 5 7 2 8 3 4
Height: 7
NodeCount: 12
Not Deleted
LevelOrder: 6 0 10 1 9 100 5 7 2 8 3 4
Height: 7
NodeCount: 12
Not Deleted
LevelOrder: 6 0 10 1 9 100 5 7 2 8 3
Height: 6
NodeCount: 11
Deleted
LevelOrder: 6 0 10 1 9 100 5 7 3 8
Height: 5
NodeCount: 10
Deleted
LevelOrder: 6 0 9 1 7 100 5 8 3
Height: 5
NodeCount: 9
Deleted
LevelOrder: 5 0 9 1 7 100 3 8
Height: 4
NodeCount: 8
*/
| true |
2bee3f7f700d3726ea943d6f1c59b39fce6e266c | C++ | hacker-taso/algorithm_judges | /algospot_judge/book1_sample/MORSE/main.cpp | UTF-8 | 1,216 | 2.78125 | 3 | [] | no_license | #include<iostream>
#include<vector>
#include<cstring>
#define MAX_KTH (1000000000+100)
using namespace std;
int numFirst, numSecond, k;
int bino[201][201];
int getNumComb(int numFirst, int numSecond) {
return bino[numFirst+numSecond][numSecond];
}
string construct(int numFirst, int numSecond, int skip) {
if (numFirst == 0) {
if (numSecond == 0) return "";
else return "o" + construct(numFirst, numSecond-1, skip-getNumComb(numFirst, numSecond-1));
}
if (skip == 0) return "-" + construct(numFirst-1, numSecond, skip);
int numWithFirst = getNumComb(numFirst-1, numSecond);
if (numWithFirst <= skip) {
return "o" + construct(numFirst, numSecond-1, skip-numWithFirst);
} else {
return "-" + construct(numFirst-1, numSecond, skip);
}
}
string solve() {
return construct(numFirst, numSecond, k-1);
}
void calcBino() {
for (int i=0; i<201; i++) {
bino[i][i] = bino[i][0] = 1;
for (int j=1; j<i; j++) {
bino[i][j] = min(bino[i-1][j-1] + bino[i-1][j], MAX_KTH);
}
}
}
int main() {
int C;
vector<string> sols;
cin >> C;
calcBino();
for (int i=0; i<C; i++) {
cin >> numFirst >> numSecond >> k;
sols.push_back(solve());
}
for (int i=0; i<C; i++) {
cout << sols[i] << endl;
}
}
| true |
9dbebae6c31a6f086d9fbea457f63f9377db4313 | C++ | fdanesse/Giroscopios | /ADXL335/ADXL335.ino | UTF-8 | 2,021 | 3.171875 | 3 | [] | no_license | // https://lastminuteengineers.com/adxl335-accelerometer-arduino-tutorial/
/*
Los tres ángulos son la dirección (heading o yaw), elevación (pitch) y ángulo de alabeo (roll).
Estos tres ángulos son equivalentes a tres maniobras consecutivas. Dado un sistema de tres ejes fijos en el aeroplano,
llamados eje de guiñada (yaw en inglés), de cabeceo (pitch) y de alabeo (roll), existen tres rotaciones principales,
normalmente llamadas igual que el eje sobre el que se producen,
que permiten alcanzar el sistema del aeroplano desde el sistema de referencia.
Cabeceo (pitch): es una inclinación del morro del avión, o rotación respecto al eje ala-ala. (Derecha - Izquierda)
Alabeo (roll): rotación respecto de un eje morro-cola del avión. (Arriba - Abajo)
Guiñada (yaw): rotación intrínseca alrededor del eje vertical perpendicular al avión.
*/
#define xInput A0
#define yInput A1
#define zInput A2
double x_g_value, y_g_value, z_g_value;
double roll, pitch, yaw;
const int sampleSize = 10;
void setup(){
Serial.begin(9600);
}
void loop(){
giroscopio();
delay(200);
}
void giroscopio(){
int xRaw = ReadAxis(xInput);
int yRaw = ReadAxis(yInput);
int zRaw = ReadAxis(zInput);
x_g_value = ((((double)(xRaw * 5)/1024) - 1.65) / 0.330);
y_g_value = ((((double)(yRaw * 5)/1024) - 1.65) / 0.330);
z_g_value = ((((double)(zRaw * 5)/1024) - 1.80) / 0.330);
roll = (((atan2(y_g_value, z_g_value) * 180) / 3.14) + 180);
pitch = (((atan2(z_g_value, x_g_value) * 180) / 3.14) + 180);
// yaw = (((atan2 (x_g_value, y_g_value) * 180) / 3.14) + 180);
// No es posible medir la guiñada con un acelerómetro. Se debe usar un giroscopio.
Serial.print(" roll: "); Serial.print(roll);
Serial.print(" pitch: "); Serial.println(pitch);
}
int ReadAxis(int axisPin){
long reading = 0;
analogRead(axisPin);
delay(1);
for (int i = 0; i < sampleSize; i++){
reading += analogRead(axisPin);
}
return reading/sampleSize;
}
| true |
ab2684b82c0a2db6bc84596e8bca7648135a0f63 | C++ | tonyxwz/leetcode | /9.Graph/133. Clone Graph.cc | UTF-8 | 988 | 3.203125 | 3 | [] | no_license | /*
// Definition for a Node.
class Node {
public:
int val;
vector<Node*> neighbors;
Node() {
val = 0;
neighbors = vector<Node*>();
}
Node(int _val) {
val = _val;
neighbors = vector<Node*>();
}
Node(int _val, vector<Node*> _neighbors) {
val = _val;
neighbors = _neighbors;
}
};
*/
class Solution
{
public:
Node* cloneGraph(Node* node)
{
if (!node)
return nullptr;
unordered_map<Node*, Node*> m;
unordered_set<Node*> done;
queue<Node*> q;
q.push(node);
while (!q.empty()) {
Node* n = q.front();
q.pop();
if (done.count(n))
continue;
done.insert(n);
if (!m.count(n))
m[n] = new Node(n->val);
for (Node* nn : n->neighbors) {
if (!m.count(nn))
m[nn] = new Node(nn->val);
m[n]->neighbors.push_back(m[nn]);
if (!done.count(nn))
q.push(nn);
}
}
return m[node];
}
};
| true |
9ff8a3afa528403b6bc6c915d92d5030e85dc6f9 | C++ | Sunyandong-CS/Algorithm | /LeetCode/DynamicProgramming/CombinationSumIV/CombinationSumIV/main.cpp | UTF-8 | 1,426 | 3.4375 | 3 | [] | no_license | //
// main.cpp
// CombinationSumIV
//
// Created by 孙艳东 on 2018/3/5.
// Copyright © 2018年 com.xidian.edu.cn. All rights reserved.
//
/**
Given an integer array with all positive numbers and no duplicates, find the number of possible combinations that add up to a positive integer target.
Example:
nums = [1, 2, 3]
target = 4
The possible combination ways are:
(1, 1, 1, 1)
(1, 1, 2)
(1, 2, 1)
(1, 3)
(2, 1, 1)
(2, 2)
(3, 1)
Note that different sequences are counted as different combinations.
Therefore the output is 7.
题目大意:给定一个无重复的正整数数组,和一个目标值,求所有能组成目标整数的组合,(每个数字可以无限使用)(类似于组成钱数)
解法:超时解法====递归和迭代
动态规划解决比较合适 dp[i]表示组成值为i的组合有多少种,dp[i] = dp[i] + dp[i - j];
*/
#include <iostream>
#include <vector>
using namespace std;
int combinationSum4(vector<int> &nums, int target) {
int len = nums.size();
vector<int> dp(target + 1,0); //dp[i]表示组成值为i的组合有多少种
dp[0] = 1;
for (int i = 0; i < target ; i ++) {
for(int j = 0; j < len ; j ++) {
if(nums[j] <= i){
dp[i] += dp[i - nums[j]];
}
}
}
return dp[target];
}
int main(int argc, const char * argv[]) {
return 0;
}
| true |
6b72854d2d784b197d2f58eadf2ab20dff5c39cd | C++ | tejasMadrewar/CPP_notes | /3_functions/ex_inline.cpp | UTF-8 | 894 | 3.71875 | 4 | [] | no_license | #include <iostream>
using namespace std;
// if function is small then overhead in calling increases
// alternative is macro but error checking is not done
//
// inline function is a function that expanded in line when it is invoked.
// must defined before called
// they are made inline when they are small enough to be defined in one or two lines
//
//
// inline function may not work
// if returning value, if loop switch exists
// if not returning value, if return statement exists
// recursive
//
inline double cube(double a){ return (a*a*a);}
inline float mul(float x, float y){return (x*y);}
inline double div(double x, double y){return (x/y);}
int main()
{
std::cout << cube(3.0) << std::endl;
std::cout << cube(2.5 + 1.5) << std::endl; // macro fails
float a = 12.345;
float b = 9.35;
std::cout << mul(a,b) << std::endl;
std::cout << div(a,b) << std::endl;
return 0;
}
| true |
5de80e0eed70050dc36079e1b4211289a5855e27 | C++ | rubensim/rubluskaskazka | /Chess/ChessWithUi/FigureKing.cpp | UTF-8 | 827 | 2.765625 | 3 | [] | no_license | #include "stdafx.h"
#include "FigureKing.h"
#include "Constants.h"
King::King(PieceColor color, string image) :Piece(color, image){}
King::~King(){}
bool King::CheckMove(Coordinate currentPosition, Coordinate movePosition, bool allowDoCornerStep){
if (abs(currentPosition.GetX() - movePosition.GetX()) <= SQUARESIZE &&
abs(currentPosition.GetY() - movePosition.GetY()) <= SQUARESIZE)
return true;
/*if (current == movePosition + 1 || current == movePosition - 1
|| current == movePosition + pair<int, int>(0, 1) || current == movePosition + pair<int, int>(0, -1)
|| current == movePosition + pair<int, int>(1, 0) || current == movePosition + pair<int, int>(-1, 0)
|| current == movePosition + pair<int, int>(1, -1) || current == movePosition + pair<int, int>(-1, 1))
return true;
*/
return false;
}
| true |
827eba6f1ebbd379057b30b5fde35afd0d8d9060 | C++ | LingyanWu2016/Simple-computer-system-with-CPU-and-memory | /SourceFile/cpu.cpp | UTF-8 | 7,555 | 2.8125 | 3 | [] | no_license | /*
* cpu.cpp
*
* Created on: Feb 18, 2016
* Author: angie
*/
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <math.h>
#include <unistd.h>
#include <string>
#include "cpu.h"
#include"memory.h"
#include"message.h"
using namespace std;
void cpu::setPipeCPU(int psd1,int psd2){ //set pipe for cpu
p3=psd1;
p4=psd2;
}
void cpu::setTimerCount(int c){
COUNT=c;
}
void cpu::cpuWrite(int addr,char c){
m.arrIndex=addr;
m.msg=c;
write(p3, &m, sizeof(m)); //write the message to p3
if(m.msg=='E'){ //close pipe
close(p3);
close(p4);
exit(0);
}
}
int cpu::cpuRead(){ //read message from p4
read(p4, &m, sizeof(m));
if(m.msg=='V'){ //memory violation,close pipe
close(p3);
close(p4);
exit(0);
return 0;
}
else{
return m.data;
}
}
void cpu::cpuExecute(){ //execute instruction
char r='R';
char w='W';
char e='E';
int tmp;
int tmp1;
int pc;
SP=1000; //SP register initialize
int count=0; //counter initialize
system_mode = false;
while(PC<2000){
cpuWrite(PC,r); // call function cpuWrite
IR = cpuRead(); //get the value from memory and assign it to register IR
PC++;
switch(IR){
case 1: //Load the value into the AC
cpuWrite(PC,r);
tmp = cpuRead();
load(tmp);
PC++;
break;
case 2: //Load the value at the address into the AC
pc=PC;
cpuWrite(PC,r);
PC=cpuRead();
cpuWrite(PC,r);
AC=cpuRead();
PC=pc;
PC+= 1;
break;
case 3: //Load the value from the address found in the given address into the AC
cpuWrite(PC,r);
PC=cpuRead();
cpuWrite(PC,r);
PC=cpuRead();
break;
case 4: //Load the value at (address+X) into the AC
pc=PC;
cpuWrite(PC,r);
tmp=cpuRead();
PC=X+tmp;
cpuWrite(PC,r);
tmp1=cpuRead();
load(tmp1);
PC=pc;
PC++;
break;
case 5: //Load the value at (address+Y) into the AC
pc=PC;
cpuWrite(PC,r);
tmp=cpuRead();
PC=Y+tmp;
cpuWrite(PC,r);
tmp1=cpuRead();
load(tmp1);
PC=pc;
PC++;
break;
case 6: //Load from (Sp+X) into the AC
cpuWrite(SP+X,r);
AC=cpuRead();
break;
case 7: //Store the value in the AC into the address
cpuWrite(PC,r);
tmp=cpuRead();
m.data = AC;
cpuWrite(tmp,w);
cpuRead();
PC++;
break;
case 8: //Gets a random int from 1 to 100 into the AC
get_AC();
break;
case 9: //if port=1, writes AC as an int,If port=2, writes AC as a char
cpuWrite(PC,r);
tmp = cpuRead();
put_port(tmp);
PC++;
break;
case 10: //Add the value in X to the AC
AC+=X;
break;
case 11: //Add the value in Y to the AC
AC+=Y;
break;
case 12: //12.Subtract the value in X from the AC
AC=AC-X;
break;
case 13: //13.Subtract the value in Y from the AC
AC=AC-Y;
break;
case 14: //Copy the value in the AC to X
X=AC;
break;
case 15: //Copy the value in X to the AC
AC=X;
break;
case 16: //Copy the value in the AC to Y
Y=AC;
break;
case 17: //Copy the value in Y to the AC
AC=Y;
break;
case 18: //Copy the value in AC to the SP
SP=AC;
break;
case 19: //Copy the value in SP to the AC
AC=SP;
break;
case 20: //Jump to the address
cpuWrite(PC,r);
tmp = cpuRead();
PC=jmp_addr(tmp);
break;
case 21: //jump to the address only if the value in the AC is zero
cpuWrite(PC,r);
tmp = cpuRead();
PC=jmpif(tmp);
break;
case 22: //Jump to the address only if the value in the AC is not zero
cpuWrite(PC,r);
tmp = cpuRead();
PC=jmpifnot(tmp);
break;
case 23: //Push return address onto stack, jump to the address
cpuWrite(PC,r);
tmp1=cpuRead(); // tmp1 is jump address
tmp=PC+1;
SP--;
m.data=tmp; // return address
cpuWrite(SP,w);
cpuRead();
PC=tmp1;
break;
case 24: //Pop return address from the stack, jump to the address
cpuWrite(SP,r);
PC=cpuRead();
SP++;
break;
case 25: //Increment the value in X
X++;
break;
case 26: //Decrement the value in X
X--;
break;
case 27: //Push AC onto stack
SP=SP-1;
m.data=AC;
cpuWrite(SP,w);
cpuRead(); // must pair discard result
break;
case 28: //Pop from stack into AC
cpuWrite(SP,r);
AC=cpuRead();
SP=SP+1;
break;
case 29: //Perform system call
Int(1);
break;
case 30: // IRet
system_mode = false;
cpuWrite(SP,r);
tmp=cpuRead();
SP++;
cpuWrite(SP,r);
PC=cpuRead();
SP++;
SP=tmp;
m.user_mode = true;
break;
case 50: //end
cpuWrite(PC,e);
close(p3);
close(p4);
exit(0);
break;
default:
cout<<"Error! "<<IR<<" is an invalid instruction!"<<endl;
return;
}
if(count==COUNT){ //every COUNT instructions,execute timer()
count=0;
if (system_mode==false) { //timer will delay the execution if cpu is performing system call
Int(0);
}
}
else{
count++;
}
}
}
//Interrupt
void cpu::Int(bool flag){
system_mode = true;
char w='W';
int tmp=SP; //store SP(user stack) into a local variable tmp
SP=2000;
SP--;
m.user_mode = false;
m.data=PC;
cpuWrite(SP,w); //save PC on the system stack
cpuRead();
SP--;
m.data=tmp; // SP on user stack
cpuWrite(SP,w); //save SP on the system stack
cpuRead();
if(flag==0){
PC=1000; // timer
}
else{
PC=1500; // int instruction
}
}
//1.Load the value into the AC
void cpu::load (int val)
{
AC = val;
}
//8.Gets a random int from 1 to 100 into the AC
void cpu::get_AC(){
AC=rand()%100+1;
}
//9.If port=1, writes AC as an int to the screen;If port=2, writes AC as a char to the screen
void cpu::put_port(int port){
if (port==1){
cout<<(int)AC;
}
else if (port==2){
cout<<(char)AC;
}
}
//20.jump to the address
int cpu::jmp_addr(int address){
return address;
}
//21.Jump to the address only if the value in the AC is zero
int cpu::jmpif(int address){
if (AC==0){
return address;
}
else
return ++PC;
}
//22.Jump to the address only if the value in the AC is not zero
int cpu::jmpifnot(int address){
if(AC!=0){
return address ;
}
else
return ++PC;
}
| true |