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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
ce208e33e066beb14bd8c2f3e2c221bb2fb23b96 | C++ | pillowpilot/problem_solving | /UVa/10003 - Cutting Sticks/code.cpp | UTF-8 | 1,385 | 2.921875 | 3 | [] | no_license | #include <cstdio>
#include <vector>
#include <limits>
using namespace std;
typedef vector<int> vi;
typedef vector<vi> vvi;
vvi memo;
vi s;
void printMemo(){
for( int i = 0; i < memo.size(); i++ ){
for( int j = 0; j < memo[i].size(); j++ ){
printf("%4d", memo[i][j]);
}
printf("\n");
}
}
int f(int a, int b){
if( b - a == 1 ){
if( memo[a][b] == -1 ) memo[a][b] = 0;
return memo[a][b];
}else{
int cost, lower, higher, minimum, sum;
cost = s[b] - s[a];
minimum = numeric_limits<int>::max();
for( int i = 1; i < b - a; i++ ){
if( memo[a][a + i] == -1 ){
memo[a][a + i] = f(a, a + i);
}
lower = memo[a][a + i];
if( memo[a + i][b] == -1 ){
memo[a + i][b] = f(a + i, b);
}
higher = memo[a + i][b];
sum = lower + higher + cost;
if( sum < minimum ){
minimum = sum;
}
}
memo[a][b] = minimum;
return memo[a][b];
}
}
void init(int s_size){
s.clear();
s.push_back( 0 );
memo.clear();
memo = vvi( s_size + 5, vi( s_size + 5, -1 ) );
}
int main(){
int l, c;
s.reserve( 50 + 5 );
scanf("%d", &l);
while( l != 0 ){
scanf("%d", &c);
init(c);
while( c-- > 0 ){
int a;
scanf("%d", &a);
s.push_back( a );
}
s.push_back(l);
printf("The minimum cutting is %d.\n", f(0, s.size() - 1));
scanf("%d", &l);
}
}
| true |
2c5cbc649c313c6151c43082b351b52d6536d0d0 | C++ | JimNilsson/FSJimNilsson | /FilsystemJimNilsson/src/MetaData.h | UTF-8 | 714 | 3.015625 | 3 | [] | no_license | #ifndef METADATA_H
#define METADATA_H
#include <iostream>
enum chmod_t : int { CH_READ = 2, CH_WRITE = 4, CH_ALL = 6, CH_NONE = 0 };
enum filetype_t : int { TYPE_DIRECTORY = 1, TYPE_FILE = 2, TYPE_ERROR = -1 };
struct MetaData
{
MetaData()
{
//empty
}
MetaData(filetype_t type, std::string name, int location, int size, chmod_t rights)
{
mType = type;
memset(pName, 0, 16);
strcpy_s(pName, name.c_str());
//name.copy(pName, sizeof(pName));
mLocation = location;
mSize = size;
mRights = rights;
}
filetype_t mType;
char pName[16];
int mLocation;
/* If type is directory, mSize (number of files and directories) * sizeof(MetaData) it contains */
int mSize;
chmod_t mRights;
};
#endif
| true |
00927dcc0a735c47be17ced345c76abee3227a2b | C++ | Zapominacz/PEA_TSP_Approx | /Solution.h | UTF-8 | 282 | 2.9375 | 3 | [] | no_license | #pragma once
#include <iostream>
class Solution
{
public:
float cost;
unsigned* order;
unsigned size;
Solution(unsigned size): cost(0), size(size)
{
order = new unsigned[size];
}
~Solution()
{
if (order != nullptr)
{
delete order;
order = nullptr;
}
}
};
| true |
adb7a435626ecd0f13b67c955e981b908eab1724 | C++ | NeuralEnsemble/pype9 | /pype9/simulate/neuron/code_gen/templates/ninemlnrn.cpp | UTF-8 | 1,861 | 2.984375 | 3 | [
"MIT"
] | permissive | /*
A library that wraps GSL random routines for use in mod-files:
gsl_rng* get_gsl_rng()
void release_gsl_rng()
double nineml_gsl_normal(double m, double s);
double nineml_gsl_uniform(double a, double b);
double nineml_gsl_binomial(double p, int n);
double nineml_gsl_exponential(double mu);
double nineml_gsl_poisson(double mu);
*/
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
gsl_rng* nineml_gsl_rng = NULL;
unsigned int _seed = 0;
/* FUNCTIONS FOR ALLOCATING & DEALLOCATING RNG */
extern "C"
gsl_rng* get_gsl_rng()
{
if(nineml_gsl_rng == NULL)
{
nineml_gsl_rng = gsl_rng_alloc (gsl_rng_mt19937);
}
return nineml_gsl_rng;
}
extern "C"
void release_gsl_rng()
{
if(nineml_gsl_rng)
{
gsl_rng_free (nineml_gsl_rng);
nineml_gsl_rng = NULL;
}
}
extern "C"
void nineml_seed_gsl_rng(unsigned int seed) {
gsl_rng* rng = get_gsl_rng();
gsl_rng_set(rng, seed);
_seed = seed;
}
extern "C"
unsigned int nineml_get_gsl_rng_seed() {
printf("%d\n", _seed);
return _seed;
}
// Wrapper Functions:
//
extern "C"
double nineml_gsl_normal(double m, double s)
{
gsl_rng* r = get_gsl_rng();
return m + gsl_ran_gaussian(r, s);
}
extern "C"
double nineml_gsl_uniform(double a, double b)
{
gsl_rng* r = get_gsl_rng();
return gsl_ran_flat(r, a, b);
}
extern "C"
double nineml_gsl_binomial(double p, int n)
{
gsl_rng* r = get_gsl_rng();
return gsl_ran_binomial(r, p, n);
}
extern "C"
double nineml_gsl_exponential(double lambda)
{
gsl_rng* r = get_gsl_rng();
return gsl_ran_exponential(r,1.0/lambda);
}
extern "C"
double nineml_gsl_poisson(double mu)
{
gsl_rng* r = get_gsl_rng();
return gsl_ran_poisson(r,mu);
}
| true |
9ee69864cf83ec7f22a4fa33d305892ce60f4b7c | C++ | arms22/BigFont | /src/BigFont.cpp | UTF-8 | 804 | 2.796875 | 3 | [] | no_license | /*
BigFont.cpp - A library that displays large characters on the LCD.
Copyright 2011,2016(c) arms22. All right reserved.
License: Refer to the phi_big_font.h/cpp file.
*/
#include "BigFont.h"
BigFont::BigFont()
{
_cur_col = _cur_row = 0;
_invert = false;
}
BigFont::~BigFont()
{
}
void BigFont::attach(LiquidCrystal *lcd)
{
_lcd = lcd;
_invert = false;
init_big_font();
}
void BigFont::clear()
{
lcd_clear();
home();
}
void BigFont::home()
{
_cur_col = _cur_row = 0;
}
void BigFont::setInvert(bool yes)
{
_invert = yes;
}
void BigFont::setCursor(uint8_t col, uint8_t row)
{
_cur_col = col;
_cur_row = row;
}
size_t BigFont::write(uint8_t ch)
{
render_big_char(ch, _cur_col, _cur_row);
_cur_col += 4;
return 1;
}
| true |
adb220997c8839a9b1a4685451d9bd167af80f7b | C++ | joann8/CPP | /C05/ex01/Bureaucrat.cpp | UTF-8 | 1,768 | 3.3125 | 3 | [] | no_license | #include "Bureaucrat.hpp"
const char* Bureaucrat::GradeTooHighException::what() const throw()
{
return "Grade too high.";
}
const char* Bureaucrat::GradeTooLowException::what() const throw()
{
return "Grade too low.";
}
Bureaucrat::Bureaucrat(void) : _name("default"), _grade(LOW_GRADE)
{
return;
}
Bureaucrat::Bureaucrat(std::string const & name, unsigned int grade)
: _name(name)
{
if (grade > LOW_GRADE)
throw Bureaucrat::GradeTooLowException();
else if (grade < HIGH_GRADE)
throw Bureaucrat::GradeTooHighException();
else
this->_grade = grade;
return;
}
Bureaucrat::Bureaucrat(Bureaucrat const & src) : _name(src.getName()), _grade(src.getGrade())
{
return;
}
Bureaucrat & Bureaucrat::operator=(Bureaucrat const & src)
{
this->_grade = src.getGrade();
return *this;
}
Bureaucrat::~Bureaucrat(void)
{
return;
}
std::string const & Bureaucrat::getName(void) const
{
return this->_name;
}
unsigned int Bureaucrat::getGrade(void) const
{
return this->_grade;
}
void Bureaucrat::upgrade(void)
{
if (this->_grade - 1 < HIGH_GRADE)
throw Bureaucrat::GradeTooHighException();
else
this->_grade -= 1;
}
void Bureaucrat::downgrade(void)
{
if (this->_grade + 1 > LOW_GRADE)
throw Bureaucrat::GradeTooLowException();
else
this->_grade += 1;
}
void Bureaucrat::signForm(Form & form)
{
try
{
form.beSigned(*this);
std::cout << this->_name << " sign " << form.getName() << std::endl;
}
catch (std::exception & e)
{
std::cout << this->_name << " cannot sign " << form.getName() << " because ";
std::cout << e.what() << std::endl;
}
return;
}
std::ostream & operator<<(std::ostream & out, Bureaucrat const & src)
{
out << src.getName() << ", bureaucrat grade " << src.getGrade() << "." << std::endl;
return out;
}
| true |
fae8fd81f4a9ebf530d3fc7a05437ed7f0094511 | C++ | ykingdsjj/StudentCourseChooseSystem | /Course.cpp | GB18030 | 1,297 | 3.625 | 4 | [] | no_license | /*
**@ ȡ
**@ Courseʵ
**@ 2013/12/20
*/
#include "Course.h"
//>>
ifstream & operator>> (ifstream &in,Course &c){
string num,name,teacher;
double credit;
int times;
in>>num>>name>>teacher>>credit>>times;
c.setNum(num);
c.setName(name);
c.setTeacher(teacher);
c.setCredit(credit);
c.setTimes(times);
return in;
}
//<<
ofstream & operator<< (ofstream &out,Course &c){
out<<c.getNum()<<" "<<c.getName()<<" "<<c.getTeacher()<<" "<<c.getCredit()<<" "<<c.getTimes();
return out;
}
//ȡγ̱
string Course::getNum(){
return classNum;
}
//ȡγ
string Course::getName(){
return className;
}//ȡڿʦ
string Course::getTeacher(){
return teacher;
}
//ȡѧ
double Course::getCredit(){
return credit;
}
//ȡѧʱ
int Course::getTimes(){
return times;
}
//ÿγ̱
void Course::setNum(string classNum){
this->classNum=classNum;
}
//ÿγ
void Course::setName(string className){
this->className=className;
}
//ÿγѧ
void Course::setCredit(double credit){
this->credit=credit;
}
//ÿγѧʱ
void Course::setTimes(int times){
this->times=times;
}
//ڿʦ
void Course::setTeacher(string teacher){
this->teacher=teacher;
} | true |
6c11f77bc1939e87d57ce0519f6a5ec1d2f6090d | C++ | thePetrMarek/ArduinoLedArray | /sendPixel.ino | UTF-8 | 1,332 | 3.203125 | 3 | [
"Apache-2.0"
] | permissive | //Sending pixel from top to bottom and back
bool sendPixelArray[8][8] = {
{0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0},
};
void sendPixelRun() {
if (isEmptySendPixel()) {
initialize();
}
show(sendPixelArray, 100);
movePixel();
}
bool isEmptySendPixel() {
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
if (sendPixelArray[i][j] == 1) {
return false;
}
}
}
return true;
}
void initialize() {
for (int i = 0; i < 8; i++) {
int randNumber = random(0, 2);
if (randNumber == 0) {
sendPixelArray[0][i] = 1;
} else {
sendPixelArray[7][i] = 1;
}
}
}
void movePixel() {
int randNumber = random(0, 8);
if (sendPixelArray[0][randNumber] == 1) {
movePixelDown(randNumber);
} else {
movePixelUp(randNumber);
}
}
void movePixelDown(int index) {
for (int i = 0; i < 7; i++) {
sendPixelArray[i][index] = 0;
sendPixelArray[i + 1][index] = 1;
show(sendPixelArray, 50);
}
}
void movePixelUp(int index) {
for (int i = 8; i > 0; i--) {
sendPixelArray[i][index] = 0;
sendPixelArray[i - 1][index] = 1;
show(sendPixelArray, 50);
}
}
| true |
0608817a2f8b9ca81f30d49e34aabb1f137297a5 | C++ | shashank0107/CompetitiveProgramming | /LIVEARCHIVE/5133.cpp | UTF-8 | 3,338 | 2.546875 | 3 | [] | no_license | /*
Author : manu_sy
Idea : Using dynamic hull (to insert lines and query of max) :
- Sort machines with start dates
- Now each machines earning can be represented using line : k * x + m
- mi = -pi + ri + gi * di + max(mj + gj * (di - 1))
- ki = gi
- Keep inserting lines in hull and querying for maximum
*/
#include "bits/stdc++.h"
using namespace std;
/** Template Begins **/
#define int ll
typedef long long ll;
typedef pair<int,int> PII;
#define IOS ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
#define endl '\n'
#define pb push_back
#define F first
#define S second
#define mp make_pair
#define all(a) (a).begin(), (a).end()
#define FOR(i,a,b) for(int i=a;i<=b;i++)
#define LP(i,n) for(int i=0;i< n;i++)
/* Debug */
template<class L, class R> ostream &operator<<(ostream &os, pair<L,R> P) {
return os << "(" << P.F << "," << P.S << ")";
}
template<class T> ostream &operator<<(ostream& os, vector<T> V) {
os << "["; for (auto vv : V) os << vv << ","; return os << "]";
}
template<class TH> void _dbg(const char *sdbg, TH h){ cerr << sdbg << '=' << h << endl; }
template<class TH, class... TA> void _dbg(const char *sdbg, TH h, TA... a) {
while(*sdbg!=',') cerr << *sdbg++;
cerr<<'='<<h<<','; _dbg(sdbg+1, a...);
}
#ifdef LOCAL
#define debug(...) _dbg(#__VA_ARGS__, __VA_ARGS__)
#else
#define debug(...) (__VA_ARGS__)
#define cerr if(0)cout
#endif
/* Debug Ends */
const int N = 5e6+7;
/** Template Ends **/
bool Q;
struct Line {
mutable ll k, m, p;
bool operator<(const Line& o) const {
return Q ? p < o.p : k < o.k;
}
};
struct LineContainer : multiset<Line> {
// (for doubles, use inf = 1/.0, div(a,b) = a/b)
const ll inf = LLONG_MAX;
ll div(ll a, ll b) { // floored division
return a / b - ((a ^ b) < 0 && a % b); }
bool isect(iterator x, iterator y) {
if (y == end()) { x->p = inf; return false; }
if (x->k == y->k) x->p = x->m > y->m ? inf : -inf;
else x->p = div(y->m - x->m, x->k - y->k);
return x->p >= y->p;
}
void add(ll k, ll m) {
auto z = insert({k, m, 0}), y = z++, x = y;
while (isect(y, z)) z = erase(z);
if (x != begin() && isect(--x, y)) isect(x, y = erase(y));
while ((y = x) != begin() && (--x)->p >= y->p)
isect(x, erase(y));
}
ll query(ll x) {
assert(!empty());
Q = 1; auto l = *lower_bound({0,0,x}); Q = 0;
return l.k * x + l.m;
}
};
ll n, c, d;
struct machine {
ll d, p, r, g;
bool operator<(const machine& o) const {
return d < o.d;
}
};
signed main() {
IOS;
int tc = 1;
while (cin >> n >> c >> d) {
if (n == 0) break;
LineContainer lc;
lc.add(0, c);
vector<machine> v(n);
for (int i = 0; i < n; i++) {
cin >> v[i].d >> v[i].p >> v[i].r >> v[i].g;
}
sort(all(v));
for (auto mac: v) {
ll tot = lc.query(mac.d - 1);
if (tot < mac.p) continue;
ll m = -mac.p + mac.r + tot - mac.g * mac.d;
lc.add(mac.g, m);
}
cout << "Case " << tc++ << ": " << lc.query(d) << endl;
}
return 0;
}
| true |
36288559cf78e5244a4ebf7d550dd94316db2629 | C++ | pbraga88/study | /Legacy/CPA_cpp/5_ObjectProgrammingEssentials/5.4_StaticComponents/src/main.cpp | UTF-8 | 1,931 | 3.765625 | 4 | [] | no_license | #include <iostream>
using namespace std;
/*Variáveis estáticas*/
// void func(){
// // int var = 0;
// static int var = 0;
// cout<<var++<<endl;
// }
//
// int main(){
// for(int i = 0; i<5;i++)
// func();
//
// return 0;
// }
/********************/
/*Componentes estáticos da classe*/
// class Classe{
// public:
// static int var_1;
// int var_2;
// void print_var(){
// cout<<"Static: "<<++var_1<<" Auto: "<<++var_2<<endl;
// }
// };
// int Classe::var_1 = 0;
// int main(){
// Classe instance1, instance2;
//
// instance1.var_2 = 0;
// instance2.var_2 = 0;
//
// // As três declarações à seguir têm o mesmo efeito e irão alterar a variável
// // estática var_1 para todas as instâncias da classe
// instance1.var_1 += 1;
// instance1.var_1 += 1;
// Classe::var_1 += 1;
//
// instance1.print_var();
// instance2.print_var();
//
// return 0;
// }
/******************************/
/*Variáveis e métodos estáticos de uma classe */
// class Classe{
// private:
// static int counter;
// public:
// Classe(){
// counter++;
// }
// ~Classe(){
// if(!(--counter))
// cout<<"bye bye!"<<endl;
// }
// static void how_many(){
// cout<<counter<<" instances"<<endl;
// }
// };
// int Classe::counter = 0;
//
// int main(){
// Classe::how_many();
// Classe a;
// Classe b;
// b.how_many(); // Também pode ser chamada com Classe::how_many() ou a.how_many()
// Classe c;
// Classe d;
// d.how_many(); // Também pode ser chamada com Classe::how_many() ou c.how_many()
// return 0;
// }
/****************************/
/* Interação entre componentes estáticos e não estáticos */
// class Test{
// public:
// // void funN1(){cout<<"non-static"<<endl;}
// // static void funS1{funN1();}
//
// static void funN1(){cout<<"static"<<endl;}
// void funS1(){funN1();}
// };
| true |
69be89fde99793e48a0913895de1ba32ddfbf7ce | C++ | Liousvious/LeetCode | /Dynamic_Problems/Game_dynamic_problem/1140. Stone Game II.cpp | UTF-8 | 1,329 | 2.890625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
class Solution {
public:
vector<vector<int>> memo;
vector<int> postSum;
int stoneGameII(vector<int>& piles) {
memo = vector<vector<int>>(piles.size(), vector<int>(piles.size(), -1));
postSum = vector<int> (piles.size());
postSum[piles.size() - 1] = piles[piles.size() - 1];
for (int i = piles.size() - 2; i >= 0; i--) {
postSum[i] = postSum[i + 1] + piles[i];
}
return memorableDfs(piles, 0, 1);
}
int memorableDfs(vector<int>& piles, int start, int M) {
if (piles.size() - start <= 2 * M) {
memo[start][M] = postSum[start];
return postSum[start];
}
if (memo[start][M] != -1) return memo[start][M];
int res = 0;
for (int i = 1; i <= 2 * M && start + i <= piles.size(); i++) {
res = max(res, postSum[start] - memorableDfs(piles, start + i, max(M, i))); // 石子游戏假定第一个玩家和
//第二个玩家一样聪明
//因此都会在各自的回合进行最优的选取
}
memo[start][M] = res;
return res;
}
}; | true |
d975b70b928ddfd9bf79248b9f59346dc402051d | C++ | mosmeh/islands | /islands/include/Health.h | UTF-8 | 694 | 3.015625 | 3 | [
"MIT",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"BSD-3-Clause",
"Zlib",
"Unlicense"
] | permissive | #pragma once
#include "Component.h"
namespace islands {
class Health : public Component {
public:
using HealthType = unsigned int;
Health(HealthType maxHealth, double invincibleDuration = 0.0);
virtual ~Health() = default;
void update() override;
bool isDead() const;
bool takeDamage(HealthType damage);
HealthType get() const;
float getNormalized() const;
HealthType getMaxHealth() const;
void setMaxHealth(HealthType maxHealth);
void set(HealthType health);
bool isInvincible() const;
private:
using SignedHealthType = std::make_signed<HealthType>::type;
const double invincibleDuration_;
HealthType maxHealth_;
SignedHealthType health_;
double lastDamageTakenAt_;
};
}
| true |
8f5217938f6734db400b6342770a59d76a25f897 | C++ | greenwookez/ex_05_cpp | /intarray.hpp | UTF-8 | 629 | 3.09375 | 3 | [] | no_license | #include "intlist.hpp"
class IntArray : public IntList {
int low_index;
int high_index;
protected:
int * AddLeft(int elem);
int * AddRight(int elem);
public:
IntArray();
IntArray(int lb);
IntArray(IntArray &_array);
IntArray(int lb, int cnt, int val);
int Low() { return low_index; };
int High() { return high_index; };
int Size() { return high_index - low_index + 1; }; // returns amount of elements
int & operator[] (int index); // overloads a[i] = ...
int * operator --();
int * operator --(int nothing);
IntArray & operator =(IntArray & _array);
}; | true |
3552d28c684d89461db45e6c286f0f831667c0ba | C++ | eliwoods/arduino | /proj/revo_mirror/Animation.ino | UTF-8 | 5,171 | 2.875 | 3 | [
"MIT"
] | permissive | // Some utility shit
uint8_t triwave(uint8_t in) {
if ( in < 64) {
return in;
}
else if (in >= 64 && in < 128) {
return (127 - in);
}
else if (in >= 128 && in < 192) {
return (in - 128);
}
else if (in >= 192) {
return (255 - in);
}
}
// Reset everything aka set everything to black
void reset_all() {
fill_solid(leds, numLED, CRGB::Black);
}
void fill_all() {
fill_solid(leds, numLED, CHSV(gHue, 255, gBrightness));
FastLED.show();
FastLED.delay(20);
}
void fill_all_grad() {
// Grab the colors
CRGB col_start = CHSV(gHue, 255, gBrightness);
CRGB col_end = CHSV((gHue + 128) % 255, 255, gBrightness);
fill_gradient_RGB(leds, numLED, col_start, col_end);
FastLED.show();
FastLED.delay(20);
}
void fill_all_grad_2() {
CRGB col0 = CHSV(gHue, 255, gBrightness);
CRGB col1 = CHSV((gHue + 64) % 255, 255, gBrightness);
CRGB col2 = CHSV((gHue + 128) % 255, 255, gBrightness);
CRGB col3 = CHSV((gHue + 192) % 255, 255, gBrightness);
fill_gradient_RGB(leds, 72, col0, col1);
fill_gradient_RGB(leds + 72, 71, col1, col0);
FastLED.show();
FastLED.delay(20);
}
///////////////////////////////////////////////////////////////////////////////////////////
// All of the following animations are some kind of theater marquee style. This means //
// at the core, its packets of light chasing eachother across the strip, although we'll //
// change up how they chase in different animations. //
///////////////////////////////////////////////////////////////////////////////////////////
// Simple theater chase where packets move continuously
void theater_chase() {
fill_palette(leds, numLED, gIndex, 6, gPalette, gBrightness, gBlending);
FastLED.show();
}
void theater_chase_mir() {
fill_palette(leds(0, 71), 72, gIndex, 6, gPalette, gBrightness, gBlending);
leds(72, 142) = leds(71, 0);
FastLED.show();
}
void theater_chase_mir2() {
fill_palette(leds(0, 35), 36, gIndex, 6, gPalette, gBrightness, gBlending);
leds(36, 71) = leds(35, 0);
leds(72, 107) = leds(0, 35);
leds(108, 142) = leds(34, 0);
FastLED.show();
}
// Bouncing with wider bounces
void theater_tri8() {
fill_palette(leds, numLED, triwave8(gIndex), 6, gPalette, gBrightness, gBlending);
FastLED.show();
}
void theater_tri8_mir() {
fill_palette(leds(0, 71), 72, triwave8(gIndex), 6, gPalette, gBrightness, gBlending);
leds(72, 142) = leds(71, 0);
FastLED.show();
}
void theater_tri8_mir2() {
fill_palette(leds(0, 35), 36, triwave8(gIndex), 6, gPalette, gBrightness, gBlending);
leds(36, 71) = leds(35, 0);
leds(72, 107) = leds(0, 35);
leds(108, 142) = leds(34, 0);
FastLED.show();
}
// A theater chase where packets switch direction every once in a while. Lets see how
// this looks with a saw wave
void theater_tri() {
fill_palette(leds, numLED, triwave(gIndex), 6, gPalette, gBrightness, gBlending);
FastLED.show();
}
void theater_tri_mir() {
fill_palette(leds(0, 71), 72, triwave(gIndex), 6, gPalette, gBrightness, gBlending);
leds(72, 142) = leds(71, 0);
FastLED.show();
}
void theater_tri_mir2() {
fill_palette(leds(0, 35), 36, triwave(gIndex), 6, gPalette, gBrightness, gBlending);
leds(36, 71) = leds(35, 0);
leds(72, 107) = leds(0, 35);
leds(108, 142) = leds(34, 0);
FastLED.show();
}
// A glitchy style "chase". It not even really a chase, I just keep the palette static and
// change the width of the packets. Looks kind of funky, but kind of cool too.
void theater_mod() {
fill_palette(leds, numLED, 0, gIndex, gPalette, gBrightness, gBlending);
FastLED.show();
}
void theater_mod_mir() {
fill_palette(leds(0, 71), 72, 0, gIndex, gPalette, gBrightness, gBlending);
leds(72, 142) = leds(71, 0);
FastLED.show();
}
void theater_mod_mir2() {
fill_palette(leds(0, 35), 36, 0, gIndex, gPalette, gBrightness, gBlending);
leds(36, 71) = leds(35, 0);
leds(72, 107) = leds(0, 35);
leds(108, 142) = leds(34, 0);
FastLED.show();
}
// Ramp the brightness up, then cut off quickly like a saw wave
void ramp_up() {
static uint8_t brightness = 0;
static uint8_t cIndex = 0;
// Ramp the brightness up at a input controlled rate
EVERY_N_MILLISECONDS_I(thisTimer, 100) {
thisTimer.setPeriod(map(analogRead(RATE_POT), 0, 1253, 1, 50));
brightness += 16;
}
// Jump to next color in the gradient if we are at the bottom of the ramp
if (brightness == 0) {
cIndex += 16;
}
fill_solid(leds, numLED, ColorFromPalette(gPalette, cIndex, brightness, gBlending));
FastLED.show();
}
// Jump to a fully illuminated strand, then ramp down. Also like a saw wave, but
// the opposite direction.
void ramp_down() {
static uint8_t brightness = 0;
static uint8_t cIndex = 0;
// Ramp the brightness up at a input controlled rate
EVERY_N_MILLISECONDS_I(thisTimer, 100) {
thisTimer.setPeriod(map(analogRead(RATE_POT), 0, 1253, 10, 200));
brightness -= 16;
}
// Jump to next color in the gradient if we are at the bottom of the ramp
if (brightness == 0) {
cIndex -= 16;
}
fill_solid(leds, numLED, ColorFromPalette(gPalette, cIndex, brightness, gBlending));
FastLED.show();
}
| true |
caba264d9c2a721ddffe988b3724ff1dc5e491b5 | C++ | dibery/UVa | /vol113/11384.cpp | UTF-8 | 246 | 2.859375 | 3 | [] | no_license | #include<cstdio>
#include<algorithm>
int main()
{
int pow2[ 31 ] = { 1 };
for( int i = 1; i < 31; ++i )
pow2[ i ] = pow2[ i-1 ] << 1;
for( int n; scanf( "%d", &n ) == 1; )
printf( "%d\n", std::upper_bound( pow2, pow2+31, n ) - pow2 );
}
| true |
d546fd016386652207c9b3ba75bc90cc72f5cb67 | C++ | hermanzdosilovic/computer-aided-analysis-and-design | /include/caas/optimization/axis.hpp | UTF-8 | 1,465 | 2.53125 | 3 | [] | no_license | #pragma once
#include <caas/optimization/golden.hpp>
#include <caas/optimization/types.hpp>
#include <caas/utils/log.hpp>
#include <cstddef>
#include <iterator>
#include <vector>
namespace caas::optimization
{
template< typename Function, typename T >
T axis( Function f, T const & x0, T const & precision )
{
//#define ITERATION_LOG() LOG_INFO( "Iteration %u: f(%s) = %f\n", iteration, std::to_string( x ).c_str(), f( x ) )
auto const N{ std::size( x0 ) };
std::vector< T > e( N );
for ( std::size_t i{ 0 }; i < N; ++i )
{
e[ i ][ i ] = 1;
}
std::uint16_t iteration{ 0 };
std::uint16_t functionCalls{ 0 };
auto x{ x0 };
T y;
do
{
//ITERATION_LOG();
y = x;
for ( std::size_t i{ 0 }; i < N; ++i )
{
auto lambda = golden
(
[ & f, & x, & ei = e[ i ], & functionCalls ]( double const lambda )
{
++functionCalls;
return f( x + lambda * ei );
},
x[ i ],
precision[ i ]
);
x += lambda * e[ i ];
//LOG_INFO( "Iteration %u: lambda[%d] = %f\n", iteration, i, lambda );
}
++iteration;
} while ( !( std::abs( x - y ) <= precision ) );
//ITERATION_LOG();
//LOG_INFO( "Total number of function calls: %u\n", functionCalls );
//#undef ITERATION_LOG
return x;
}
}
| true |
440f78418d9b766b2c1761815e52ab3cad4b99e2 | C++ | MK2020/Software-Engineering-2 | /SE2L4 - Intvector/notes_main1.cpp | UTF-8 | 1,523 | 3.078125 | 3 | [] | no_license | /*
* notes_main1.cpp
*
* Created on: 13 Nov 2016
* Author: mwanahusssein
*/
//#include <cstdlib>
//#include <vector>
//#include "point4.h"
//using namespace std;
//
///*
// *
// */
//int main(int argc, char** argv) {
// cout<<"main1"<<endl;
// ifstream infile (argv[1]);
// vector<;Point>vp;
// vector<Point*>vpt; //i am creating a vector of pointers of type Point
//
// double x, y;
//
// int i =0;
//
// while(infile >> x >> y ) {//while in file is open extract x and y
// i++;
// cout<<"i: "<<i<<endl;
// //Point tmp(x,y); Creatting a temp point and pushing it into the vector
// //vp.push_back(tmp);
//
// vp.push_back(Point(x,y));// once the point is pushed in the vector after that it is outside its scope.
// cout<<"vp.capacity(); "<<vp.capacity()<<endl;
// vpt.push_back(new Point(x,y));//here we are creating a point dynamically and pushing back.
// //Here we don't lose our point when it comes out of the push_back scope.
// cout<<"vpt.capacity(): "<<vpt.capacity()<<endl;
//
// //the capacity increase by 2^n each time starting with n = 0
// //When the capacity is less than the # of items then they are all deallocated(including the new element that is being added)and a new vector is created
// //with twice the capacity. When the capacity is equal to or greater than the # of items then only the latest element is deallocated
//
// }
//
// infile.close();
//
// return 0;
//}
//
| true |
80875f7e8fa5a5ba5d4f7b105c57e3a02b2aa5b2 | C++ | sarahHe/LeetCode-solution | /Find the Duplicate Number.cpp | UTF-8 | 1,354 | 3.59375 | 4 | [] | no_license | //Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive),
//prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one.
//The main idea is the same with problem Linked List Cycle II,
//https://leetcode.com/problems/linked-list-cycle-ii/. Use two pointers the fast and the slow.
//The fast one goes forward two steps each time, while the slow one goes only step each time.
//They must meet the same item when slow==fast. In fact, they meet in a circle,
//the duplicate number must be the entry point of the circle when visiting the array from nums[0].
//Next we just need to find the entry point.
//We use a point(we can use the fast one before) to visit form begining with one step each time,
//do the same job to slow. When fast==slow, they meet at the entry point of the circle. The easy understood code is as follows.
class Solution {
public:
int findDuplicate(vector<int>& nums) {
if (nums.empty()) return -1;
int slow = nums[0], fast = nums[nums[0]];
while (slow != fast) {
slow = nums[slow];
fast = nums[nums[fast]];
}
fast = 0;
while (slow != fast) {
slow = nums[slow];
fast = nums[fast];
}
return slow;
}
};
| true |
bbd023631a2299791ff8b6a94f573b063dbd67f2 | C++ | wuzhipeng2014/CPP-Primer | /CH13.35/Message.h | GB18030 | 793 | 2.984375 | 3 | [] | no_license | #pragma once
#include <string>
#include <set>
#include "Folder.h"
using std::string;
using std::set;
class CMessage
{
public:
friend void swap(CMessage& lhs, CMessage& rhs);
//ƳԱ
CMessage(const string & m); //ĬϹ캯
CMessage(const CMessage & rhs); //캯
CMessage& operator = (const CMessage& rhs); //ֵ
~CMessage(); //
void save(CFolder &f); //ϢӵĿ¼
void remove(CFolder &f); //Ŀ¼ƳϢ
private:
string contents; //¼Ϣ
set<CFolder *> folders; //¼ϢĿ¼
void add_to_folders(const CMessage &);
void remove_from_folders();
};
| true |
751db4c94b1086e0ed6a64e426beeac8fc9dd98f | C++ | steven2795/JamesJohnson-CSCI20-Fall2016 | /lab2/lab2.cpp | UTF-8 | 259 | 2.734375 | 3 | [] | no_license | // computer chooses a number between 1 and 20
//user guesses 5
//computer says wrong its higher
//user guesses 15
//computer says wrong its lower
//user guesses 10
//computer says wrong its higher
//user guesses 13
//computer says correct, you earned 7 points | true |
5b28771a664f35deafcf18aa8a0aed74771ec5dc | C++ | Sbyner/SSHIVA | /src/graph-lib/homology/_Perseus/Cells/Cube.cpp | UTF-8 | 1,155 | 3.421875 | 3 | [
"MIT"
] | permissive | /*
* Cube.hpp
*
* Contains functions for handling the Cube class
*/
# include "Cube.h"
// set vertices to this point
template <typename C, typename PS, typename BT>
void Cube<C,PS,BT>::setAnchor(const Point<PS>* anch)
{
anchor = anch;
}
// set addin vector to this addin
template <typename C, typename PS, typename BT>
void Cube<C,PS,BT>::setAddin(const std::vector<num>* add) // set addin vector
{
addin = add;
}
template <typename C, typename PS, typename BT>
num Cube<C,PS,BT>::getDim() const // get cube dimension, -1 if addin is NULL or empty
{
return (addin == NULL) ? -1 : addin->size();
}
// check for equality
template <typename C, typename PS, typename BT>
bool Cube<C,PS,BT>::operator == (const Cube<C,PS, BT>& other) const // check equality
{
return (addin == other.addin && anchor == other.anchor);
}
// check for ordering (lexico of anchor points, then dimension)
template <typename C, typename PS, typename BT>
bool Cube<C,PS,BT>::operator < (const Cube<C,PS,BT>& other) const // check vert-lexico order
{
if (anchor == NULL || other.anchor == NULL) return false;
if (*anchor < *(other.anchor)) return true;
return false;
} | true |
496c8971abf7d3fd9d1b344ad79cb2256b5191f6 | C++ | robotchaoX/Qt-tutorial-code | /QT_02/07_Control_TableWidget/widget.cpp | UTF-8 | 2,474 | 2.8125 | 3 | [] | no_license | #include "widget.h"
#include "ui_widget.h"
#include <QMessageBox>
Widget::Widget(QWidget *parent) : QWidget(parent), ui(new Ui::Widget) {
ui->setupUi(this);
// QTableWidget控件使用
//告诉控件 一共有多少列
QStringList list;
list << "姓名"
<< "性别"
<< "年龄";
// 设置列数
ui->tableWidget->setColumnCount(list.size());
//设置水平头
ui->tableWidget->setHorizontalHeaderLabels(list);
//设置行数
ui->tableWidget->setRowCount(5);
//设置正文
// ui->tableWidget->setItem(0,0,new QTableWidgetItem("亚瑟")); // new匿名对象
//准备数据
QStringList nameList;
nameList << "亚瑟"
<< "妲己"
<< "安琪拉"
<< "东皇太一"
<< "李白";
// QList<QString> 等价 QStringList
QList<QString> sexList;
sexList << "男"
<< "女"
<< "女"
<< "男"
<< "男";
for (int i = 0; i < 5; i++) {
int col = 0;
//设置正文
ui->tableWidget->setItem(i, col++, new QTableWidgetItem(nameList[i]));
//添加性别
ui->tableWidget->setItem(
i, col++, new QTableWidgetItem(sexList.at(i))); // at越界抛出异常
//添加年龄
ui->tableWidget->setItem(
i, col++,
new QTableWidgetItem(QString::number(i + 18))); // int 转 QString number
}
//点击按钮 添加赵云
connect(ui->addBtn, &QPushButton::clicked, [=]() {
//先判断有没有赵云,有不添加,没有才添加
bool isEmpty = ui->tableWidget->findItems("赵云", Qt::MatchExactly).empty();
if (isEmpty) {
ui->tableWidget->insertRow(0);
ui->tableWidget->setItem(0, 0, new QTableWidgetItem("赵云"));
ui->tableWidget->setItem(0, 1, new QTableWidgetItem("男"));
ui->tableWidget->setItem(0, 2, new QTableWidgetItem(QString::number(20)));
} else {
QMessageBox::warning(this, "警告!", "赵云有了!");
}
});
//点击按钮 删除赵云
connect(ui->delBtn, &QPushButton::clicked, [=]() {
bool isEmpty = ui->tableWidget->findItems("赵云", Qt::MatchExactly).empty();
if (isEmpty) {
QMessageBox::warning(this, "警告!", "赵云没有了!");
} else {
//先找到赵云所在的行
int row =
ui->tableWidget->findItems("赵云", Qt::MatchExactly).first()->row();
//找到行数 删除掉
ui->tableWidget->removeRow(row);
}
});
}
Widget::~Widget() { delete ui; }
| true |
35932a7ddc8c704a398691e3643bb283c42055c2 | C++ | Marie-Donnie/Projetrpg | /include/Objet.hpp | UTF-8 | 983 | 3.515625 | 4 | [] | no_license | /**
* @name Constructeur complet
* @brief Créé un objet avec son nom et sa description
* @param nom le nom de l'objet
* @param des sa description
* @return Un objet
*/
/**
* @name afficher
* @brief Affiche l'objet
*/
/**
* @name utiliser
* @brief Utilise l'objet sur un personnage
* @param p la référence vers le personnage
*/
//include guard
#ifndef OBJET_HPP
#define OBJET_HPP
// forward declared dependencies
class Personnage;
//included dependencies
#include <string>
#include <iostream>
using namespace std;
class Objet {
protected :
string _nom;
string _description;
public:
//Constructeurs
Objet(string nom, string des);
Objet();
//Getters
virtual string getNom();
virtual string getDescription();
//Setters
virtual void setNom(string nom);
virtual void setDescription(string des);
//Autres méthodes
virtual void afficher();
virtual void utiliser(Personnage& p);
};
#endif //OBJET_HPP
| true |
fa6912889553dbadc4c7de0c0ccb2a8f38669c65 | C++ | Huangyuren/DSA_Pratices | /LowestCommonAncestorofaBT.cpp | UTF-8 | 918 | 3.515625 | 4 | [] | no_license | // Find the division point, a little bit tricky
// In each iteration, check is this a division point by
// recursively finding its left & right subtree for p or q.
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(root==nullptr) return nullptr;
if(root == p || root == q) return root; // return either node p or q
TreeNode* left = lowestCommonAncestor(root->left, p, q);
TreeNode* right = lowestCommonAncestor(root->right, p, q);
if(left != nullptr && right != nullptr) return root; // Most important code, division point, since left & right stem from this point
if(left) return left;
return right;
}
};
| true |
c6f8f5cd403217ad3a3605bbc93e522c03570055 | C++ | smolinag/CarCounting | /CarCountingAlgorithm/CarCountingAlgorithm/DatasetsSelector.h | UTF-8 | 1,406 | 2.609375 | 3 | [] | no_license | #ifndef DatasetsSelector_H
#define DatasetsSelector_H
#include <iostream>
#include "dirent.h"
#include <vector>
#include <string>
#include <opencv2/opencv.hpp>
#include <fstream>
using namespace std;
class DatasetsSelector
{
public:
//--------------------------------Main functions---------------------------------
DatasetsSelector();
~DatasetsSelector();
void Select_Dataset();
void Get_Frame(cv::Mat &Fr);
private:
//-----------------------------Auxiliar functions---------------------------------
void Loop_Options(DIR *dir, string &main_path, int &fmt);
int Check_Extension(string file);
void Display_Menu(vector<string> menu);
void Set_shortcut_DB(int fmt, string path);
void Get_shortcut_DB(int &fmt, string &path);
//-----------------------------------Variables------------------------------------
cv::VideoCapture Source; //Videocapture for video files
struct dirent *ent; //Structure to read directories
DIR *dir_seq; //Directory variable
string main_path_str; //Main string for path directory
char main_path_ch[250]; //Main char array for path directory
int fmt; //Category id (1:image, 2:video, 3:folder, 4:other)
int lvl; //Searching level in directory
bool valid; //If the selected directory has a sequence or video: true
vector<string> img_fmt; //Valid image formats
vector<string> vid_fmt; //Valid video formats
};
#endif; | true |
23df7fa388879b23b3d1af20361df052c3261c68 | C++ | kumarsaurav546/cpp-patterns | /diamond.cpp | UTF-8 | 808 | 3.0625 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main()
{
int n,i,j,k,l,m;
cout<<"ENTER THE HIEGHT OF DIAMOND:"<<endl;
cin>>n;
for(i=0;i<n;i++)
{
cout<<"\n";
for(j=n;j>i;j--)
{
cout<<" ";
}
for(k=0;k<=j;k++)
{
cout<<"*";
}
for(l=0;l<=i;l++)
{
cout<<"*";
}
for(m=n;m>=l;m--)
{
cout<<" ";
}
}
for(i=0;i<n;i++)
{
cout<<"\n";
for(j=0;j<=i;j++)
{
cout<<" ";
}
for(k=n;k>=j;k--)
{
cout<<"*";
}
for(l=n;l>=j;l--)
{
cout<<"*";
}
for(m=0;m<=l;m++)
{
cout<<" ";
}
}
return 0;
}
| true |
36136b438a2b0de8d634b4576cedc6711d2a249e | C++ | FRuiz811/Argentum-Taller | /src/common/TiledMap.h | UTF-8 | 1,089 | 2.765625 | 3 | [] | no_license | #ifndef ARGENTUM_TILEDMAP_H
#define ARGENTUM_TILEDMAP_H
#include <vector>
#include <string>
#include "TileLayer.h"
#include "TileSet.h"
#include "ObjectLayer.h"
class TiledMap {
private:
uint16_t width{};
uint16_t height{};
uint8_t tileWidth{};
uint8_t tileHeight{};
std::vector<TileLayer> tileLayers;
std::vector<ObjectLayer> objectLayers;
std::vector<TileSet> tilesets;
public:
TiledMap();
explicit TiledMap(rapidjson::Document & json);
TiledMap(uint16_t width, uint16_t height, uint8_t tileWidth, uint8_t tileHeight,
std::vector<TileLayer> tileLayers, std::vector<TileSet> tilesets);
~TiledMap();
TiledMap(TiledMap&& other) noexcept ;
TiledMap& operator=(TiledMap&& other) noexcept ;
std::vector<ObjectLayer> getObjectLayers();
const std::vector<TileLayer> &getTileLayers() const;
const std::vector<TileSet> &getTilesets() const;
uint16_t getHeight() const;
uint16_t getWidth() const;
uint8_t getTileHeight() const;
uint8_t getTileWidth() const;
};
#endif //ARGENTUM_TILEDMAP_H
| true |
32adcedba91b196d5e6fbcb7dc6a89162a63b825 | C++ | Anokhi1994/Cpp-Challenges | /SSNumberMyLogic/northeria.hpp | UTF-8 | 785 | 3.34375 | 3 | [] | no_license | #include "DateGenerator.hpp"
class Northeria{
private:
const std::string sex_type_m;
int MM_, DD_, YYYY_;
public:
Northeria() = default;
Northeria(std::string sex_type, int MM, int DD, int YYYY):
sex_type_m(sex_type),
MM_(MM), DD_(DD), YYYY_(YYYY){
if((sex_type != "F") && (sex_type != "M")){
throw "invalid input";
}
}
std::string get_sex_type()const noexcept{
return sex_type_m;
}
std::string generate_number(const std::string& sex_type) const {
std::string s = generate_date_string(MM_, DD_, YYYY_);
if(sex_type == "F"){
s + std::to_string(1);
return s;
}
else if(sex_type == "M"){
s + std::to_string(2);
return s;
}
else throw "invalid input";
}
};
| true |
3c9ed47a4947c0bb5cfe25e5adc5a2cd660e54dc | C++ | VakarisStankus/1952_Uduotis | /main.cpp | UTF-8 | 406 | 3.28125 | 3 | [] | no_license | // 1952. Užduotis
#include <iostream>
using namespace std;
void Sprendimas(int n);
int main() {
int n;
cout <<"Irasykite Skaiciu nuo 1 iki 10000"<< endl;
cin >> n;
Sprendimas(n);
return 0;
}
void Sprendimas(int n) {
int rez;
for(int i=1; i<=n; i++)
{
if(n % i == 0) {
rez++; }
}
if(rez==3)
cout <<"True";
else cout <<"False";
} | true |
faee460aba68d208f41dd36f737e172da243fef7 | C++ | asif001/Aircraft | /player.hpp | UTF-8 | 1,050 | 2.6875 | 3 | [] | no_license | #ifndef PLAYER_HPP
#define PLAYER_HPP
#include <map>
#include "command.hpp"
#include "SFML/Graphics.hpp"
namespace arnml {
/**
* A player class for handling
* inputs.
* Abstracts the input handling from the game processing
* loop in game
*/
class Player
{
public:
///
Player();
~Player() = default;
public:
/**
* Actions to respond to
*/
enum class Action
{
MoveUp = 0,
MoveDown,
MoveLeft,
MoveRight,
};
public:
/**
* Handles event for a player.
*/
void handle_event(sf::Event event, CommandQueue& cmd_q);
/**
* Handle real time inputs for a player
*/
void handle_realtime_input(CommandQueue& cmd_q);
private:
/// Initialize action_2_cmd_bindings_ with relevent actions
void init_actions();
// Check if the event is real time action or not
bool is_real_time_action(Action action);
private:
std::map<sf::Keyboard::Key, Action> key_to_action_bindings_;
std::map<Action, Command> action_2_cmd_bindings_;
};
} // END namespace arnml
#include "impl/player.ipp"
#endif
| true |
f12f8f62d7c5fb431df99cc7941c7d3be8f0b7f5 | C++ | zhufangda/Telecom-Paristech | /IGR202/Project/Mesh.h | UTF-8 | 6,817 | 2.828125 | 3 | [
"Apache-2.0"
] | permissive | // --------------------------------------------------------------------------
// Copyright(C) 2009-2016
// Tamy Boubekeur
//
// Permission granted to use this code only for teaching projects and
// private practice.
//
// Do not distribute this code outside the teaching assignements.
// All rights reserved.
// --------------------------------------------------------------------------
#pragma once
#include <cmath>
#include <vector>
#include "Vec3.h"
#include "Triangle.h"
#include <memory>
#include <map>
using Edge = std::pair<int, int>;
/// A Mesh class, storing a list of vertices and a list of triangles indexed over it.
class Mesh {
public:
inline Mesh () {}
inline virtual ~Mesh () {}
inline std::vector<Vec3f> & positions () {
return m_positions;
}
inline const std::vector<Vec3f> & positions () const {
return m_positions;
}
inline std::vector<Vec3f> & normals () { return m_normals; }
inline const std::vector<Vec3f> & normals () const { return m_normals; }
inline std::vector<Triangle> &triangles () { return m_triangles; }
inline const std::vector<Triangle> & triangles () const { return m_triangles; }
/// Empty the positions, normals and triangles arrays.
void clear ();
/// Loads the mesh from a <file>.off
void loadOFF (const std::string & filename);
void exportOFF(const std::string & filename);
/// Compute smooth per-vertex normals
void recomputeNormals ();
/// scale to the unit cube and center at original
void centerAndScaleToUnit ();
/****************** Filtrage **********************************/
const std::vector<Vec3f>& getFilterPositions() const;
/***
* Filter the mesh by the laplacien topological graph
*/
void topoFilter();
/***
* Filter the mesh by the filtrage of geometrical laplacian
*/
void geoFilter(float alpha);
/************** Simplification ***************************/
//const std::vector<Vec3f>& getSimplifyPositions() const;
//const std::vector<Vec3f>& getSimplifyNormals() const;
//const std::vector<Triangle>& getSimplifyTriangles() const;
/** Simplify the mesh by uniform grill with the resolution
* specified by arguments.
* @param resolution the resolution of grill
**/
void simplify(unsigned resolition);
/** Simplify the mesh by octree with the max vertex
* specified by arguments.
* @param resolution the resolution of grill
**/
void simplifyAdaptiveMesh(unsigned int n);
/****************** Subdivision*******************************/
/***
* Implementation of subdivision.
***/
void subdivide();
private:
std::vector<Vec3f> m_positions;
//std::vector<Vec3f> m_positions_filtrage;
std::vector<Vec3f> m_normals;
std::vector<Triangle> m_triangles;
std::vector< std::vector<int>> m_adjacency_list;
std::vector< std::vector<Triangle>> m_adjacency_triangles_list;
// save the results of filter by laplacian topo
std::vector<Vec3f> Lt;
// save the results of filter by laplacian geo
std::vector<Vec3f> Lg;
/******************** Filtrage ******************************/
/** Create the adjacencyMatrix, if the adjacencyMatrix is not
* empty, this function will clear the old matrix and recreate.
**/
void createAdjacencyMatrix();
void createAdjacencyTrianglesMatrix();
float voronoiRegionSurface(std::vector<Triangle> t_list, int x);
float meanCurvatureOperator(int position_index);
/** Calcule the cot of angle AOB*/
static double cot(const Vec3f& a, const Vec3f& vec2);
/******************** Simplification *************************/
typedef struct {
int celleIndex = -1;
int vecIndex = -1;
Vec3f position;
Vec3f normal;
int weight = 0;
} GrillCelle;
typedef struct {
float x_min;
float x_middle;
float x_max;
float y_min;
float y_middle;
float y_max;
float z_min;
float z_middle;
float z_max;
} BoundingBox;
int resolution;
// Get Cube bounding box
static BoundingBox getBoundingCube(const std::vector<Vec3f>& positions);
/** get reprensentive cells of position specified by argement
* @param index index of position
* @return index of grill celle
*/
unsigned int getCell(unsigned int index, const BoundingBox& bbox, float celle_lenght, std::vector<GrillCelle>& celleList);
/************** Simplification with octree ************************/
typedef struct OctreeNode {
BoundingBox bbox;
int index = -1;
std::vector<std::shared_ptr<OctreeNode>> children;
std::vector<unsigned int> original_index; //data
} OctreeNode;
using OctreeNodePtr = std::shared_ptr<OctreeNode>;
int leavesCounter = -1;
unsigned maxChildrenNbr = 1;
/** Returns a vector contains all info about bounding Box
* {x_min, x_mean, x_max, y_min, y_mean, y_max, z_min, z_mean, z_max}
**/
BoundingBox getBoundingBoxInfo(const std::vector<unsigned int>& datas);
/*** According the bounding box, set the children's bounding boxes ****/
void setChildrenBBoxesList(const BoundingBox& bbox, BoundingBox bboxs[]);
/** Create a octree**/
OctreeNodePtr buildOctree(const std::vector<unsigned int>& datas, const BoundingBox& bbox);
/**
* Returns the new index of the position in the octree
* @param vertex the coordinates of vertex
* @param nodePtr the shared_pointer of the octree node
* @returns the index of the vertex in the octree
*/
static unsigned int findIndexByPosition(const OctreeNodePtr& nodePtr, const Vec3f& vertex);
/**
* Test whether the vertex contained in a node specified by argument.
* @param nodePtr a smart pointer of the node
* @param vertex a coordinates of a vertex
* @return true if the nodePtre containing the vertex, false otherwise.
**/
static bool containsPtr(const OctreeNodePtr& nodePtr, const Vec3f& vertex);
/**
* Get a list cotaining all the leaves in the list and passe it to
* to the vector specified by arguments.
* @param nodePtr the shared_ptr of octree node
* @param leaves the list containing all the leaves
**/
static void getLeaves(const OctreeNodePtr& nodePtr, std::vector<OctreeNodePtr>& leaves);
void initNode(OctreeNodePtr nodePtr, const std::vector<unsigned int>& data);
void dataSpatiaSplite(const std::vector<unsigned int>& datas, std::vector<unsigned int> childrenData[], const BoundingBox& bbox);
/** Returns ture if the data conformes to stop criteria, otherwise false **/
inline bool stopCriteria(const std::vector<unsigned int>& data) {
return data.size() < maxChildrenNbr;
}
/************************* Subdivision ****************************/
std::map<Edge, unsigned int>insertMidPoint();
void updateTriangle(std::map<Edge,unsigned int> midPointMap);
Edge makeEdge(int i, int j);
void averagingPass();
static float corrFact(int n);
};
| true |
b56e0c3510be630bd4a136fbcc0f299581a56fc7 | C++ | wxy3265/NOIP | /1188/main.cpp | UTF-8 | 775 | 3.125 | 3 | [] | no_license | #include <iostream>
int n;
bool boxes[30]; //U:true;L:false
int ans = 0;
int i;
using namespace std;
void dfs(int step);
void dfs(int step)
{
if (step > n) {
cout << boxes << endl;
ans ++;
return ;
}
for (i = 0; i < n - 3; i++) {
boxes[i] = false;
dfs(step + 1);
boxes[i] = true;
}
return ;
}
int main()
{
for (i = 0; i < 30; i++)
boxes[i] = true;
cin >> n;
dfs(0);
ans *= n - 1;
cout << ans;
return 0;
}
/*
算法:从第一个盒子开始判断,如果总铀数大于3,则将面前的盒子改为铅,并算作一种方案;
否则,从上次搜索结束的盒子开始搜索,遇到铅则改为铀,并算作一种方案,
直至面前的盒子是最后一个盒子的下一个盒子,输出总方案数,然后退出.
*/
| true |
b8b704519344fff8489fe9e5dc555e33e2ded3d7 | C++ | wangfudex/practice | /c_cpp/c++_primer/ch3/ex3-10.cpp | UTF-8 | 249 | 3.140625 | 3 | [] | no_license | #include <iostream>
#include <cctype>
int main(void)
{
std::string s; // empty string due to default init.
std::cin >> s;
for (auto &c : s)
if (ispunct(c))
c = ' ';
std::cout << s << std::endl;
return 0;
}
| true |
c05eaaa074ddd54e5c9fce89f0f6a18fba34c9c3 | C++ | RossitsaTasheva/reps | /Struct_C++_task4.cpp | UTF-8 | 1,580 | 3.734375 | 4 | [] | no_license | //============================================================================
// Name : lib_task4.cpp
// Author : t
// Version :
// Copyright : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
/*4. lib function that produces quotient and reminder
* (returning struct)*/
struct PlayerInfo {
int skill_level;
string name;
};
struct EnemyShip {
int x_coordinate;
int y_coordinate;
int weapon_power; //Сила на оръжието
};
EnemyShip getNewEnemy() {
EnemyShip ship;
ship.x_coordinate = 0;
ship.y_coordinate = 0;
ship.weapon_power = 20;
return ship;
}
EnemyShip upgradeWeapons(EnemyShip ship) {
ship.weapon_power += 10;
return ship;
}
int main() {
PlayerInfo players[5];
for (int i = 0; i < 5; i++) {
cout << "Please enter the name for player : " << i << '\n';
cin >> players[i].name;
cout << "Please enter the skill level for " << players[i].name << '\n';
cin >> players[i].skill_level;
}
for (int i = 0; i < 5; ++i) {
cout << players[i].name << " is at skill level "
<< players[i].skill_level << '\n';
}
EnemyShip enemy = getNewEnemy();
enemy = upgradeWeapons(enemy);
//
// div_t output;
//
// output = div(27, 4);
// cout<<"Quotient part of (27/ 4) = %d"<<endl<< output.quot;//Частична част от
// cout<<"Remainder part of (27/4) = %d"<<endl<< output.rem;//Останалата част от
return (0);
}
| true |
5d2b90401582b2bfaf86994e82c86e603cea609d | C++ | thehilmisu/Chess | /Chess/mainwindow.cpp | UTF-8 | 7,323 | 2.953125 | 3 | [] | no_license | #include "mainwindow.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
grid = new QGridLayout();
central = new QWidget();
setCentralWidget(central);
centralWidget()->setLayout(grid);
decorateTable();
}
void MainWindow::decorateTable()
{
for (int i=0;i<ROW;i++) {
for (int j=0;j<COLUMN;j++) {
Square s;
s.x = i;
s.y = j;
s.isVisited=false;
s.label = new QLabel();
//s.label->setStyleSheet("color:white;border:1px solid white;");
s.label->setMinimumWidth(50);
s.label->setMinimumHeight(50);
s.label->setAlignment(Qt::AlignCenter);
if((s.y % 2 == 0)){
if(s.x % 2 == 0)
s.label->setStyleSheet(BLACK_CELL);
else
s.label->setStyleSheet(WHITE_CELL);
}
else{
if(s.x % 2 == 0)
s.label->setStyleSheet(WHITE_CELL);
else
s.label->setStyleSheet(BLACK_CELL);
}
placePieces(&s);
s.index++;
square.append(s);
grid->addWidget(s.getLabel(),i,j);
}
}
}
void MainWindow::placePieces(Square *s)
{
if(s->x == 1){
s->piece = new Pieces(Pawn,White);
s->label->setPixmap(s->piece->getPixmap());
}else if(s->x == ROW - 2){
s->piece = new Pieces(Pawn,Black);
s->label->setPixmap(s->piece->getPixmap());
}else if((s->x == 0) && (s->y == 0)){//WHITE ROOK 1
s->piece = new Pieces(Rook,White);
s->label->setPixmap(s->piece->getPixmap());
}else if((s->x == 0) && (s->y == COLUMN-1)){//WHITE ROOK 2
s->piece = new Pieces(Rook,White);
s->label->setPixmap(s->piece->getPixmap());
}else if((s->x == 0) && (s->y == 1)){//WHITE KNIGHT 1
s->piece = new Pieces(Knight,White);
s->label->setPixmap(s->piece->getPixmap());
}else if((s->x == 0) && (s->y == COLUMN-2)){//WHITE KNIGHT 2
s->piece = new Pieces(Knight,White);
s->label->setPixmap(s->piece->getPixmap());
}else if((s->x == 0) && (s->y == 2)){//WHITE BISHOP 1
s->piece = new Pieces(Bishop,White);
s->label->setPixmap(s->piece->getPixmap());
}else if((s->x == 0) && (s->y == COLUMN-3)){//WHITE BISHOP 2
s->piece = new Pieces(Bishop,White);
s->label->setPixmap(s->piece->getPixmap());
}else if((s->x == 0) && (s->y == 3)){//WHITE QUEEN
s->piece = new Pieces(Queen,White);
s->label->setPixmap(s->piece->getPixmap());
}else if((s->x == 0) && (s->y == 4)){//WHITE KING
s->piece = new Pieces(King,White);
s->label->setPixmap(s->piece->getPixmap());
}
//
else if((s->x == ROW-1) && (s->y == 0)){//BLACK ROOK 1
s->piece = new Pieces(Rook,Black);
s->label->setPixmap(s->piece->getPixmap());
}else if((s->x == ROW-1) && (s->y == COLUMN-1)){//BLACK ROOK 2
s->piece = new Pieces(Rook,Black);
s->label->setPixmap(s->piece->getPixmap());
}else if((s->x == ROW-1) && (s->y == 1)){//BLACK KNIGHT 1
s->piece = new Pieces(Knight,Black);
s->label->setPixmap(s->piece->getPixmap());
}else if((s->x == ROW-1) && (s->y == COLUMN-2)){//BLACK KNIGHT 2
s->piece = new Pieces(Knight,Black);
s->label->setPixmap(s->piece->getPixmap());
}else if((s->x == ROW-1) && (s->y == 2)){//BLACK BISHOP 1
s->piece = new Pieces(Bishop,Black);
s->label->setPixmap(s->piece->getPixmap());
}else if((s->x == ROW-1) && (s->y == COLUMN-3)){//BLACK BISHOP 2
s->piece = new Pieces(Bishop,Black);
s->label->setPixmap(s->piece->getPixmap());
}else if((s->x == ROW-1) && (s->y == 3)){//BLACK QUEEN
s->piece = new Pieces(Queen,Black);
s->label->setPixmap(s->piece->getPixmap());
}else if((s->x == ROW-1) && (s->y == 4)){//BLACK KING
s->piece = new Pieces(King,Black);
s->label->setPixmap(s->piece->getPixmap());
}else{//EMPTY
s->piece = new Pieces(Empty,White);
s->isVisited = false;
}
}
void MainWindow::mousePressEvent(QMouseEvent *event)
{
QPoint p = event->pos();
Square s;
for(int i=0;i<square.size();i++)
{
s = square.at(i);
if(s.label->geometry().contains(p,true)){
if(s.getLabel()->styleSheet() != POSSIBLE_BLACK_CELL && s.getLabel()->styleSheet() != POSSIBLE_WHITE_CELL)
{
qDebug() << "fff if";
s.isSelected = true;
highlightMoves(&s);
if((s.isSelected) && (s.label->styleSheet() == WHITE_CELL)){
s.label->setStyleSheet(SELECTED_WHITE_CELL);
}
else if((s.isSelected) && (s.label->styleSheet() == BLACK_CELL)){
s.label->setStyleSheet(SELECTED_BLACK_CELL);
}
}
else
{
qDebug() << "first if";
//move here
//for (int j=0;j<square.size();j++)
{
if(s.isSelected==true){
qDebug() << "selected";
//square.at(j).piece->setPieceType(Empty,s.piece->getColor());
}
}
}
//qDebug() << s.x << " " << s.y;
}
else
{
s.isSelected = false;
if((!s.isSelected) && (s.label->styleSheet() == SELECTED_BLACK_CELL)){
s.label->setStyleSheet(BLACK_CELL);
}
else if((!s.isSelected) && (s.label->styleSheet() == SELECTED_WHITE_CELL)){
s.label->setStyleSheet(WHITE_CELL);
}
}
}
}
void MainWindow::highlightMoves(Square *s)
{
//Only for pawn
QVector<int> x_values = s->piece->getPossibleMoves(s->piece->getPieceType()).x;
QVector<int> y_values = s->piece->getPossibleMoves(s->piece->getPieceType()).y;
for(auto i : x_values){
int new_x = 0;
if(s->piece->getColor() == White)
{
new_x = s->x + i;
}
else//black
{
new_x = s->x - i;
}
for(int j=0;j<square.size();j++)
{
if((new_x == square.at(j).x) && (s->y == square.at(j).y))
{
if((square.at(j).label->styleSheet() == WHITE_CELL)&&(!square.at(j).isSelected)){
square.at(j).label->setStyleSheet(POSSIBLE_WHITE_CELL);
}
else if((square.at(j).label->styleSheet() == BLACK_CELL)&&(!square.at(j).isSelected)){
square.at(j).label->setStyleSheet(POSSIBLE_BLACK_CELL);
}
}
else if(s->y != square.at(j).y)
{
if((!square.at(j).isSelected) && (square.at(j).label->styleSheet() == POSSIBLE_BLACK_CELL)){
square.at(j).label->setStyleSheet(BLACK_CELL);
}
else if((!square.at(j).isSelected) && (square.at(j).label->styleSheet() == POSSIBLE_WHITE_CELL)){
square.at(j).label->setStyleSheet(WHITE_CELL);
}
}
}
}
}
MainWindow::~MainWindow()
{
}
| true |
856395bf8003d928c3914edaa9a4c6697e82b1fc | C++ | BGCX262/zto-projekt-1-svn-to-git | /trunk/ZTOProjekt1/ZTOProjekt1/Task.h | WINDOWS-1250 | 766 | 3.234375 | 3 | [] | no_license | #pragma once
#include <iostream>
#include "Utils.h"
using namespace std;
class Task {
public:
// liczba osob realizujaca zadanie
int persons;
// czas w ktrym podana liczba osob realizuje zadanie
float hours;
int id;
Task():persons(-1), hours(-1), id(-1) {}
static Task merge(const Task& a, const Task& b){
Task tmp;
//TODO trzeba by zmienic zeby nowo tworzony id mogl byc rozpoznawalny
tmp.id = RAND(1000) + 1000;
tmp.persons = a.persons + b.persons;
tmp.hours = (a.hours*a.persons + b.hours*b.persons)/tmp.persons;
return tmp;
}
friend ostream& operator<<(ostream&,Task&);
};
ostream& operator<<(ostream& os, Task& t)
{
return os << "[(" << t.id << ") " << t.hours << " " << t.persons <<"]";
} | true |
7a1a14621db26e9d64b6cf366007d0f4e76f399c | C++ | hexa4313/lutin | /src/parsing/ast/expression/expsub.cpp | UTF-8 | 1,441 | 3.15625 | 3 | [] | no_license | #include "expsub.h"
#include "numericconst.h"
#include "expmult.h"
void ExpSub::toString(std::ostream &o) const {
o << *m_left << "-" << *m_right;
}
std::shared_ptr<Expression> ExpSub::optimize(std::shared_ptr<Program> program, std::shared_ptr<Instruction> curInst) {
std::shared_ptr<Expression> left = m_left->optimize(program, curInst);
std::shared_ptr<Expression> right = m_right->optimize(program, curInst);
if(left->getType() == SymbolType::E_CNUM &&
right->getType() == SymbolType::E_CNUM) {
auto l = std::dynamic_pointer_cast<NumericConst>(left);
auto r = std::dynamic_pointer_cast<NumericConst>(right);
auto value = l->getValue() - r->getValue();
if(value < 0) {
return std::make_shared<ExpSub>(l, r);
}
else {
return std::make_shared<NumericConst>(value);
}
}
else {
if(left->getType() == SymbolType::E_CNUM) {
auto l = std::dynamic_pointer_cast<NumericConst>(left);
if(l->getValue() == 0) {
return std::make_shared<ExpMult>(std::make_shared<NumericConst>(-1), right);
}
}
else if(right->getType() == SymbolType::E_CNUM) {
auto r = std::dynamic_pointer_cast<NumericConst>(right);
if(r->getValue() == 0) {
return left;
}
}
return std::make_shared<ExpSub>(left, right);
}
}
int ExpSub::eval(std::shared_ptr<SymbolTable> m_table) const {
return m_left->eval(m_table) - m_right->eval(m_table);
} | true |
00c17fd9cbdbd5254a6bfff9094e8eb2e5a22d71 | C++ | worhkd963/oop2016440129 | /HW1-2/HW1_2.cpp | UHC | 222 | 2.578125 | 3 | [] | no_license | #include <stdio.h>
#include <Windows.h>
int main(){
int a;
printf(" Է : ");
scanf("%d", &a);
if(a%2 == 1)
printf("ȦԴϴ.\n");
else
printf("¦Դϴ.\n");
system("pause");
return 0;
} | true |
b260c451bfb48f7a5999eab6b3e5a982eb6504ce | C++ | mustafabar/minimal | /3dp/fmm.cxx | UTF-8 | 7,764 | 2.515625 | 3 | [] | no_license | #include "build_tree.h"
#include "kernel.h"
#include "ewald.h"
#include "timer.h"
#if EXAFMM_EAGER
#include "traverse_eager.h"
#elif EXAFMM_LAZY
#include "traverse_lazy.h"
#endif
using namespace exafmm;
int main(int argc, char ** argv) {
const int numBodies = 1000; // Number of bodies
P = 10; // Order of expansions
ncrit = 64; // Number of bodies per leaf cell
cycle = 2 * M_PI; // Cycle of periodic boundary condition
theta = 0.4; // Multipole acceptance criterion
images = 4; // 3^images * 3^images * 3^images periodic images
ksize = 11; // Ewald wave number
alpha = ksize / cycle; // Ewald real/wave balance parameter
sigma = .25 / M_PI; // Ewald distribution parameter
cutoff = cycle / 2; // Ewald cutoff distance
printf("--- %-16s ------------\n", "FMM Profiling"); // Start profiling
//! Initialize bodies
start("Initialize bodies"); // Start timer
Bodies bodies(numBodies); // Initialize bodies
real_t average = 0; // Average charge
srand48(0); // Set seed for random number generator
for (size_t b=0; b<bodies.size(); b++) { // Loop over bodies
for (int d=0; d<3; d++) { // Loop over dimension
bodies[b].X[d] = drand48() * cycle - cycle * .5; // Initialize positions
} // End loop over dimension
bodies[b].q = drand48() - .5; // Initialize charge
average += bodies[b].q; // Accumulate charge
bodies[b].p = 0; // Clear potential
for (int d=0; d<3; d++) bodies[b].F[d] = 0; // Clear force
} // End loop over bodies
average /= bodies.size(); // Average charge
for (size_t b=0; b<bodies.size(); b++) { // Loop over bodies
bodies[b].q -= average; // Charge neutral
} // End loop over bodies
stop("Initialize bodies"); // Stop timer
//! Build tree
start("Build tree"); // Start timer
Cells cells = buildTree(bodies); // Build tree
stop("Build tree"); // Stop timer
//! FMM evaluation
start("P2M & M2M"); // Start timer
initKernel(); // Initialize kernel
upwardPass(cells); // Upward pass for P2M, M2M
stop("P2M & M2M"); // Stop timer
start("M2L & P2P"); // Start timer
horizontalPass(cells, cells); // Horizontal pass for M2L, P2P
stop("M2L & P2P"); // Stop timer
start("L2L & L2P"); // Start timer
downwardPass(cells); // Downward pass for L2L, L2P
stop("L2L & L2P"); // Stop timer
//! Dipole correction
start("Dipole correction"); // Start timer
real_t dipole[3] = {0, 0, 0}; // Initialize dipole
for (size_t b=0; b<bodies.size(); b++) { // Loop over bodies
for (int d=0; d<3; d++) dipole[d] += bodies[b].X[d] * bodies[b].q;// Accumulate dipole
} // End loop over bodies
real_t coef = 4 * M_PI / (3 * cycle * cycle * cycle); // Domain coefficient
for (size_t b=0; b<bodies.size(); b++) { // Loop over bodies
real_t dnorm = dipole[0] * dipole[0] + dipole[1] * dipole[1] + dipole[2] * dipole[2];// Norm of dipole
bodies[b].p -= coef * dnorm / bodies.size() / bodies[b].q; // Correct potential
for (int d=0; d!=3; d++) bodies[b].F[d] -= coef * dipole[d];// Correct force
} // End loop over bodies
stop("Dipole correction"); // Stop timer
printf("--- %-16s ------------\n", "Ewald Profiling"); // Print message
//! Ewald summation
start("Build tree"); // Start timer
Bodies bodies2 = bodies; // Backup bodies
for (size_t b=0; b<bodies.size(); b++) { // Loop over bodies
bodies[b].p = 0; // Clear potential
for (int d=0; d<3; d++) bodies[b].F[d] = 0; // Clear force
} // End loop over bodies
Bodies jbodies = bodies; // Copy bodies
Cells jcells = buildTree(jbodies); // Build tree
stop("Build tree"); // Stop timer
start("Wave part"); // Start timer
wavePart(bodies, jbodies); // Ewald wave part
stop("Wave part"); // Stop timer
start("Real part"); // Start timer
realPart(&cells[0], &jcells[0]); // Ewald real part
selfTerm(bodies); // Ewald self term
stop("Real part"); // Stop timer
//! Verify result
real_t pSum = 0, pSum2 = 0, FDif = 0, FNrm = 0;
for (size_t b=0; b<bodies.size(); b++) { // Loop over bodies & bodies2
pSum += bodies[b].p * bodies[b].q; // Sum of potential for bodies
pSum2 += bodies2[b].p * bodies2[b].q; // Sum of potential for bodies2
FDif += (bodies[b].F[0] - bodies2[b].F[0]) * (bodies[b].F[0] - bodies2[b].F[0]) +// Difference of force
(bodies[b].F[1] - bodies2[b].F[1]) * (bodies[b].F[1] - bodies2[b].F[1]) +// Difference of force
(bodies[b].F[2] - bodies2[b].F[2]) * (bodies[b].F[2] - bodies2[b].F[2]);// Difference of force
FNrm += bodies[b].F[0] * bodies[b].F[0] + bodies[b].F[1] * bodies[b].F[1] +// Value of force
bodies[b].F[2] * bodies[b].F[2];
} // End loop over bodies & bodies2
real_t pDif = (pSum - pSum2) * (pSum - pSum2); // Difference in sum
real_t pNrm = pSum * pSum; // Norm of the sum
printf("--- %-16s ------------\n", "FMM vs. direct"); // Print message
printf("%-20s : %8.5e s\n","Rel. L2 Error (p)", sqrt(pDif/pNrm));// Print potential error
printf("%-20s : %8.5e s\n","Rel. L2 Error (F)", sqrt(FDif/FNrm));// Print force error
return 0;
}
| true |
3fb6f5094ba09e1ad1f0fb202226124551ad1beb | C++ | XoDeR/AlgoRecap2017 | /Arrays/SubarrayWithGivenSumInGivenArray/SubarrayWithGivenSumInGivenArray03.cpp | UTF-8 | 1,190 | 3.828125 | 4 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
// Function to print sub-array having given sum using Hashing
void findSubarray(int arr[], int n, int sum)
{
// create an empty map
unordered_map<int, int> map;
// insert (0, -1) pair into the set to handle the case when
// sub-array with given sum starts from index 0
map.insert(pair<int, int>(0, -1));
// maintains sum of elements so far
int sum_so_far = 0;
// traverse the given array
for (int i = 0; i < n; i++)
{
// update sum_so_far
sum_so_far += arr[i];
// if (sum_so_far - sum) is seen before, we have found
// the sub-array with sum 'sum'
if (map.find(sum_so_far - sum) != map.end())
{
cout << "Sub-array found [" << map[sum_so_far - sum] + 1 <<
"-" << i << "]" << endl;
return;
}
// insert current sum with index into the map
map.insert(pair<int, int>(sum_so_far, i));
}
}
// main function
int main()
{
// array of integers
int arr[] = { 0, 5, -7, 1, -4, 7, 6, 1, 4, 1, 10 };
int sum = 15;
int n = sizeof(arr)/sizeof(arr[0]);
findSubarray(arr, n, sum);
return 0;
}
| true |
bb1c8180d3c2f2fa1f773cd11a4eff807a955c1a | C++ | khpandya/DataStructuresAssignments | /Assignment1.cpp | UTF-8 | 6,917 | 3.6875 | 4 | [] | no_license | #include<iostream>
#include<forward_list>
#include<vector>
#include<fstream>
#include<algorithm>
using namespace std;
bool contains(vector<std::string> list,std::string toFind){
if(std::find(list.begin(),list.end(),toFind)==list.end()){
return false;
}
return true;
}
class countryStats{
public:
std::string name;
int numCitiesInList;
int totalPopulationInList;
countryStats(){
name="default";
numCitiesInList=-1;
totalPopulationInList=-1;
}
countryStats(std::string countryName,int numCitiesInCountry,int totalPopulationInCountry){
name=countryName;
numCitiesInList=numCitiesInCountry;
totalPopulationInList=totalPopulationInCountry;
}
countryStats (const countryStats &old_obj){
name=old_obj.name;
numCitiesInList=old_obj.numCitiesInList;
totalPopulationInList=old_obj.totalPopulationInList;
}
friend ostream& operator<<(ostream& os, const countryStats& cs);
~countryStats(){
}
};
ostream& operator<<(ostream& os, const countryStats& cs){
os << "Country: "<<cs.name<<", "<<"Number of Cities in List: "<<cs.numCitiesInList<<", "<<"Total Population In List: "<<cs.totalPopulationInList<<endl;
return os;
}
struct cityNode{
string cityName;
string countryName;
int population;
};
forward_list<cityNode> read_record()
{
// File pointer
fstream fin;
// Open the file
fin.open("WorldCities.csv", ios::in);
// Read the Data from the file
int counter=1;
string city, country, population;
// list to store data in
forward_list<cityNode> cityList;
// there are 25590 rows in the file
while (counter<25591) {
getline(fin, city,',');
getline(fin, country,',');
getline(fin, population,'\n');
// cout<<city<<endl;
// cout<<country<<endl;
// cout<<population<<endl;
cityNode cN;
cN.cityName=city;
cN.countryName=country;
cN.population=std::stoi(population);
cityList.push_front(cN);
counter++;
}
return cityList;
}
/*
city not found message if not found
default - get country where the city is located then cout country name endl each city in country with commas endl
if allcountries true - do this for every country with a city named 'city' instead of just the first one you find
if alpha true - cities in each country should be in alpha order
if both true - countries should appear in order. In each country cities should appear in order.
*/
std::vector<countryStats> printAllInSameCountry(std::string city, bool allCountries, bool alphabetical){
// each row (city, country, population) in one node.
// search list for city, if not found print message.
// if found, add country to list of countries. if allcountries true, keep searching and add the other countries with the city (if not already in the list)
// if alpha false - just go through the list again for each country in the list and print the cities everytime you encounter one
// figure out alphabetical sorting
// to get your return data - just go over the list of countries you made again and count the number of cities and total population
// in each country, make an object of type countryStats with the right data and push it to the vector you want to return
vector<countryStats> countryList;
vector<std::string> countryListToPrint;
forward_list<cityNode> cityList;
cityList=read_record();
bool cityFound=false;
for(cityNode&cityNode1:cityList){
// if city is found
if(cityNode1.cityName==city){
// add the country of that city to templist
countryListToPrint.push_back(cityNode1.countryName);
// if all countries is true go through LL again to find all countries with that city
if(allCountries==true){
for(cityNode&cityNode2:cityList){
// check that the country doesn't already exist in the templist
if(cityNode2.cityName==city && !contains(countryListToPrint,cityNode2.countryName)){
countryListToPrint.push_back(cityNode2.countryName);
}
}
}
if(alphabetical==true){
std::sort(countryListToPrint.begin(),countryListToPrint.end());
}
//vector of vector of strings. each vector contains list of cities in a country e.g. 1st vector of cities
//corresponds to in 1st country in countryListToPrint and so on
vector<vector<std::string>> citiesInEachCountry;
for(std::string countryName : countryListToPrint){
vector<std::string> cities;
for(cityNode&cityNode3:cityList){
if(cityNode3.countryName==countryName){
cities.push_back(cityNode3.cityName);
}
}
citiesInEachCountry.push_back(cities);
}
//if alphabetical true sort each city list as well
if (alphabetical==true){
for(vector<string> cities : citiesInEachCountry){
std::sort(cities.begin(),cities.end());
}
}
//do the printing
for (int countryIndex = 0; countryIndex < countryListToPrint.size(); countryIndex++){
cout<<countryListToPrint[countryIndex]<<endl;
for(int cityIndex=0; cityIndex<citiesInEachCountry[countryIndex].size(); cityIndex++){
if(cityIndex==citiesInEachCountry[countryIndex].size()-1){
cout<<citiesInEachCountry[countryIndex][cityIndex]<<endl;
}
else{
cout<<citiesInEachCountry[countryIndex][cityIndex]<<",";
}
}
cout<<endl;
}
//make the countryStats objects
for (int countryIndex = 0; countryIndex < countryListToPrint.size(); countryIndex++){
std::string countryName=countryListToPrint[countryIndex];
int numOfCitiesInList=citiesInEachCountry[countryIndex].size();
int population=0;
for(cityNode&cityNode4:cityList){
if(cityNode4.countryName==countryListToPrint[countryIndex]){
population+=cityNode4.population;
}
}
countryStats country=countryStats(countryName,numOfCitiesInList,population);
countryList.push_back(country);
}
cityFound=true;
break;
}
}
if(!cityFound){
cout<<"This city is not in the list"<<endl;
}
return countryList;
}
int main(){
vector<countryStats> countryList=printAllInSameCountry("Paris",true,true);
return 0;
}
| true |
7f843a462b4e2940968cac47482aa5c437322b4a | C++ | smilu97/hamtris | /common/server/player.h | UTF-8 | 817 | 2.578125 | 3 | [] | no_license | #ifndef __PLAYER_H__
#define __PLAYER_H__
#include <utility>
#include <boost/asio.hpp>
#include "message.h"
using boost::asio::ip::tcp;
namespace tetris {
typedef std::function<void(std::error_code, std::size_t)> ReadHandler;
class TetrisPlayer: std::enable_shared_from_this<TetrisPlayer> {
PlayerId id;
tcp::socket socket;
char readBuffer[128];
void ReadMessage(int len, ReadHandler readHandler);
void ReadHeader();
void ReadTetrisMessage();
void ReadJoinRoomMessage();
void CreateRoom();
public:
TetrisPlayer(PlayerId id, tcp::socket socket);
void Start();
void Deliver(const char* buf, int len);
bool alive;
};
typedef std::shared_ptr<TetrisPlayer> TetrisPlayerPtr;
}
#endif
| true |
b7f3b17b724b6d0f45f4dd12047f0e476c9b49f1 | C++ | JunJun0411/Algorithm | /algorithm/11721번 열 개씩 끊어 출력하기.cpp | UTF-8 | 201 | 2.625 | 3 | [] | no_license | #include <iostream>
#include <cstring>
using namespace std;
int main() {
char c[100];
cin >> c;
int i = 0;
while(i<strlen(c)) {
cout << c[i];
i++;
if (i % 10 == 0) {
cout << '\n';
}
}
} | true |
0128637f4e7c508e6b47af7c6163de21a5d0f525 | C++ | CS126SP20/naive-bayes-SabarNimmagadda | /include/bayes/model.h | UTF-8 | 4,058 | 3.359375 | 3 | [
"MIT"
] | permissive | // Copyright (c) 2020 [Your Name]. All rights reserved.
#ifndef BAYES_MODEL_H_
#define BAYES_MODEL_H_
#include "image.h"
#include <cstdlib>
namespace bayes {
constexpr size_t kNumClasses = 10;
// Shaded or not shaded.
constexpr size_t kNumShades = 2;
/**
* Represents a Naive Bayes classification model for determining the
* likelihood that an individual pixel for an individual class is
* white or black.
*/
class Model {
public:
//This is a vector of image objects.
std::vector<Image> image_objects;
//This is the laplace smoothing factor, which is used in some computations.
double smoothing_factor;
//This is the vector of labels corresponding to the images.
std::vector<int> labels;
//This is the vector corresponding to the prior probabilities.
std::vector<double> prior_probabilities;
//This is the matrix that contains the probability of whether a specific pixel for a specific class is shaded or not.
double probs_[kImageSize][kImageSize][kNumClasses][kNumShades];
/**
* This function is used to get data from the label and image files
* and fill in the respective vectors.
* It is called in the getAccuracyPercentage function of the Classifier.
* @param label_file the file which has all the labels.
* @param image_file the file which has all the images to be classified.
* @param smoothing the laplace smoothing variable used in computation.
*/
void initialize(const string& label_file, const string& image_file, double smoothing);
/**
* This is used to fill in the labels vector from a file.
* @param filepath the file containing the labels.
* @return the boolean checking whether the filepath is valid.
*/
bool GetLabelsFromFile(const string& filepath);
/**
* This is used to fill in the image object vector from a file.
* @param filepath the file containing the images to be classified.
* @return the boolean checking whether the filepath is valid.
*/
bool GetImagesFromFile(const string& filepath);
/**
* This computes the probability of whether
* a specific pixel for a specific class is shaded or not.
* @param row the row of the pixel.
* @param col the column of the pixel.
* @param num_class the label for which the probability is being computed.
* @param color the shade for which the probability is being computed.
* @return the probability for a specific class is shaded or not.
*/
double ComputeProbOfFeature(int row, int col, int num_class, int color);
/**
* The most common shade in a feature, which is used in the ComputeProbOfFeature() function.
* A feature is a part of the grid of row*col dimensions for a given image object.
* @param rows one dimension of the feature.
* @param col the second dimension of the feature.
* @param image the image for which the most common shade is being determined.
* @return the most common shade (0, or 1).
*/
int MostCommonShadeInFeature(int rows, int col, Image image);
/**
* Finds the probability of a certain class to be in the training labels.
* @param numberclass the class whose probability is being calculated.
* @return the probability of a certain class to be in the training labels.
*/
double ComputeProbabilityOfClassInLabels(int numberclass);
/**
* This fills in the probs_ matrix.
*/
void setFeatureProbabilityArray();
/**
* This function sets the prior_probabilities vector.
*/
void setPriorProbabilitiesVector();
/**
* This is called to train the program for classification.
* It is called in the beginning of the execution of this program.
* @param image_file the file of training images.
* @param label_file the file of training labels.
* @param smoothing the smoothing constant.
*/
void train(const string& image_file, const string& label_file, double smoothing);
};
} // namespace bayes
#endif // BAYES_MODEL_H_
| true |
8820f7409ab7c6ec20b0d2228f4d706f7b15bc53 | C++ | ahansaha/CPP-DS-and-Algo | /Lecture 20 Graphs - 1/Get-Path-DFS/main.cpp | UTF-8 | 1,472 | 3.53125 | 4 | [] | no_license | #include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
#include <climits>
using namespace std;
//Get the path b/w tow given vertices using DFS and store it in a vector.
vector<int> getPathDFS (int ** edges, int n, int v1, int v2, bool * visited, vector<int> path) {
if (v1 == v2) {
path.push_back(v1);
return path;
}
visited[v1] = true;
for (int i = 0; i < n; i++) {
if (edges[v1][i] == 1 && visited[i] == false) {
path = getPathDFS(edges, n, i, v2, visited, path);
if (!path.empty()) {
path.push_back(v1);
return path;
}
}
}
return path;
}
int main(){
int n, e;
cin >> n >> e;
int ** edges = new int * [n];
for (int i = 0; i < n; i++) {
edges[i] = new int[n];
fill_n(edges[i], n, 0);
}
for (int i = 0; i < e; i++) {
int f, s;
cin >> f >> s;
edges[f][s] = 1;
edges[s][f] = 1;
}
bool * visited = new bool[n];
for (int i = 0; i < n; i++) {
visited[i] = false;
}
int v1, v2;
cin >> v1 >> v2;
vector<int> path;
path = getPathDFS(edges, n, v1, v2, visited, path);
for (int i = 0; i < path.size(); i++) {
cout << path.at(i) << " ";
}
cout << endl;
for (int i = 0; i < n; i++) {
delete [] edges[i];
}
delete [] edges;
delete [] visited;
return 0;
}
| true |
10931e9cc7169bdb53a1bab41360d2d8b9347412 | C++ | jungahshin/algorithm | /c:c++/1699.cpp | UTF-8 | 505 | 2.921875 | 3 | [] | no_license | //제곱수의 합
//310-320사이정도의 제곱수를 요한다.
#include <iostream>
using namespace std;
int n;
int num;
int DP[100001] = {0, };
//DP[n]은 n이라는 수에서 필요한 가장 작은 제곱 항의 수
void go(){
for(int i=1; i<=n; i++){
DP[i] = i;
//n보다 작은 제곱수를 구한다.
for(int j=1; j*j <= i; j++){
DP[i] = min(DP[i], DP[i-j*j]+1);
}
}
}
//dp[n-a*a]
int main(){
cin>>n;
go();
cout<<DP[n]<<"\n";
} | true |
a23107c988e1cf625b99c6bdd835777f454ec56b | C++ | TheAIBot/Skynet | /linesensor.cpp | UTF-8 | 5,493 | 2.859375 | 3 | [] | no_license | #include <stdio.h>
#include <cstdlib>
#include "includes/linesensor.h"
#include "includes/odometry.h"
#include "includes/robotconnector.h"
#include "includes/commands.h"
#define THRESHOLD_FOR_DETECTED_COLOR 0.80
bool simulateFloor = false;
static lineSensorCalibratedData lineSensorCalibData[LINE_SENSORS_COUNT];
/*
* Loads calibration data for live sensor from fileLoc
*/
bool loadLineSensorCalibrationData(const char* const fileLoc)
{
FILE* const file = fopen(fileLoc, "r");
if (file == NULL)
{
printf("%s NOT FOUND!\n", fileLoc);
return false;
}
//Error the data value pair for each sensor
for (int i = 0; i < LINE_SENSORS_COUNT; i++)
{
double a;
double b;
const int scanStatus = fscanf(file, "%lf %lf\n", &a, &b);
if (scanStatus != 2) //Check if the correct number of items was read
{
printf("Error occured when reading linesensor calibration file. %d numbers expected, but %d was found.", 2, scanStatus);
fclose(file);
return false;
}
lineSensorCalibData[i].a = a;
lineSensorCalibData[i].b = b;
}
fclose(file);
return true;
}
/*
* Returns a random double between min and max
*/
static double floatRandom(const double min, const double max)
{
const double f = (double) rand() / RAND_MAX;
return f * min + (max - min);
}
/*
* Returns a calibrated value of sensorValue that is calibrated with sensorID calibration
* data
*/
static double calibrateLineSensorValue(const int sensorValue, const int sensorID)
{
const double a = lineSensorCalibData[sensorID].a;
const double b = lineSensorCalibData[sensorID].b;
const double calibValue = a * sensorValue + b;
//if true then the calibration of the sensor is incorrect
//as the calibrated value should be a value between 0 and 1
if (calibValue < -0.1 || calibValue > 1.1)
{
printf("Incorrect line sensor callibration. Value = %f\n", calibValue);
}
return calibValue;
}
/*
* Converts value to a number between 0 and 1 where 1 means that the value
* Looks exactly like the color color
*/
double correctCalibratedValue(enum LineColor color, const double value)
{
//black is a 0 and white is 1 so when color is black
//switch it around so black is 1 and white is 0
double correctedValue = (color == LineColor::black) ? (1 - value) : value;
//if simulate floor then take all values below 0.7 and give it a
//random value around 0.6 as that should simulate a wooden floor
if (simulateFloor && correctedValue < 0.70)
{
correctedValue = 0.6 + floatRandom(-0.1, 0.1);
}
return correctedValue;
}
/*
* Returns a value indicating how far off the center of the line sensor the color line is
*/
double getLineOffsetDistance(enum LineCentering centering, enum LineColor color)
{
double min = 2;
double max = -1;
//get the highest and lowest corrected calibrated value
for (int i = 0; i < LINE_SENSORS_COUNT; ++i)
{
const double calibValue = calibrateLineSensorValue(linesensor->data[i], i);
const double correctedValue = correctCalibratedValue(color, calibValue);
max = (correctedValue > max) ? correctedValue : max;
min = (correctedValue < min) ? correctedValue : min;
}
//use linear transformation to make corrected calibrated min 0 and max 1
//as opposed to min ~0.6 and max ~0.95
//This is done to remove the weight the floor has on the
//center of mass function
const double a = -1 / (min - max);
const double b = min / (min - max);
double sum_m = 0;
double sum_i = 0;
static const LineCentering lineC[LINE_SENSORS_COUNT] = { right, right, right, right, left, left, left, left };
//center of mass sum
for (int i = 0; i < LINE_SENSORS_COUNT; ++i)
{
const double trueCalib = calibrateLineSensorValue(linesensor->data[i], i);
const double correctedValue = correctCalibratedValue(color, trueCalib);
//do linear transformation
const double calibValue = a * correctedValue + b;
//add a weight to the sensor values if either right or left lineCentering is chosen
//which makes the robot favor a certain direction if the line splits up into two lines
const double weight = (centering == lineC[i]) ? 2 : 1;
sum_m += calibValue * weight * i;
sum_i += calibValue * weight;
}
//calucate center of mass where the center is 3.5
const double c_m = sum_m / sum_i;
//recalculate the center so the, line sensor center offset, is a value between -6.5 and 6.5 and the center is at 0
return ((double) LINE_SENSOR_WIDTH / (LINE_SENSORS_COUNT - 1)) * c_m - (LINE_SENSOR_WIDTH / 2);
}
/*
* Returns wether the robot is crossing a line with color color and
* only if konf sensors can see the line
*/
bool crossingLine(enum LineColor color, int konf)
{
int count = 0;
for (int i = 0; i < LINE_SENSORS_COUNT; i++)
{
const double calibValue = calibrateLineSensorValue(linesensor->data[i], i);
const double correctedValue = correctCalibratedValue(color, calibValue);
if (correctedValue >= THRESHOLD_FOR_DETECTED_COLOR)
{
count++;
}
}
return count >= konf;
}
/*
* Returns wether there is a parallel line of color color
* in the middle of the robots line sensor
*/
bool parallelLine(enum LineColor color)
{
const double calibValue3 = calibrateLineSensorValue(linesensor->data[3], 3);
const double correctedValue3 = correctCalibratedValue(color, calibValue3);
const double calibValue4 = calibrateLineSensorValue(linesensor->data[4], 4);
const double correctedValue4 = correctCalibratedValue(color, calibValue4);
return correctedValue3 >= THRESHOLD_FOR_DETECTED_COLOR || correctedValue4 >= THRESHOLD_FOR_DETECTED_COLOR;
}
| true |
d471da6c2acfeef1f1b7a068a2dcf2c9fbb8efe8 | C++ | AntonPavlovNN/C-lab-3 | /src/task6.cpp | UTF-8 | 326 | 2.921875 | 3 | [] | no_license | //#include "pch.h"
int getSumMaxMin(int arr[], int N)
{
int i, min = 0, max = 0, sum = 0;
for (i = 1; i < N; i++)
{
if (arr[i] < arr[min])
min = i;
else if (arr[i] > arr[max])
max = i;
}
if (min > max)
{
i = min; min = max; max = i;
}
for (i = min + 1; i < max; i++)
sum += arr[i];
return sum;
} | true |
bd431839d749ee01508966a7a047e661df5f057f | C++ | kamalsirsa/vtp | /TerrainSDK/vtdata/Building.cpp | UTF-8 | 37,854 | 2.53125 | 3 | [
"MIT"
] | permissive | //
// Building.cpp
//
// Implements the vtBuilding class which represents a single built structure.
// This is can be a single building, or any single artificial structure
// such as a wall or fence.
//
// Copyright (c) 2001-2013 Virtual Terrain Project
// Free for all uses, see license.txt for details.
//
#include "Building.h"
#include "vtLog.h"
#include "HeightField.h"
#include "LocalCS.h"
#include "MaterialDescriptor.h"
// Defaults
#define STORY_HEIGHT 3.0f
#define WINDOW_WIDTH 1.3f
#define WINDOW_BOTTOM 0.4f
#define WINDOW_TOP 0.9f
#define DOOR_WIDTH 1.0f
#define DOOR_TOP 0.7f
/////////////////////////////////////
vtEdgeFeature::vtEdgeFeature()
{
SetDefaults();
}
vtEdgeFeature::vtEdgeFeature(int code, float width, float vf1, float vf2)
{
m_code = code;
m_width = width;
m_vf1 = vf1;
m_vf2 = vf2;
}
void vtEdgeFeature::SetDefaults()
{
m_code = WFC_WALL;
m_width = -1.0f;
m_vf1 = 0.0f;
m_vf2 = 1.0f;
}
/////////////////////////////////////
vtEdge::vtEdge()
{
m_Color.Set(255,0,0); // default color: red
m_iSlope = 90; // vertical
m_pMaterial = GetGlobalMaterials()->FindName(BMAT_NAME_PLAIN);
}
vtEdge::vtEdge(const vtEdge &lhs)
{
m_Color = lhs.m_Color;
m_iSlope = lhs.m_iSlope;
for (uint i = 0; i < lhs.m_Features.size(); i++)
m_Features.push_back(lhs.m_Features[i]);
m_pMaterial = lhs.m_pMaterial;
m_Facade = lhs.m_Facade;
}
void vtEdge::Set(int iDoors, int iWindows, const char *material)
{
vtEdgeFeature wall, window, door;
window.m_code = WFC_WINDOW;
window.m_width = WINDOW_WIDTH;
window.m_vf1 = WINDOW_BOTTOM;
window.m_vf2 = WINDOW_TOP;
door.m_code = WFC_DOOR;
door.m_width = DOOR_WIDTH;
door.m_vf1 = 0.0f;
door.m_vf2 = DOOR_TOP;
m_Features.clear();
m_Features.reserve((iDoors + iWindows) * 2 + 1);
m_Features.push_back(wall);
bool do_door, do_window, flip = false;
while (iDoors || iWindows)
{
do_door = do_window = false;
if (iDoors && iWindows)
{
if (flip)
do_door = true;
else
do_window = true;
}
else if (iDoors)
do_door = true;
else if (iWindows)
do_window = true;
if (do_door)
{
m_Features.push_back(door);
iDoors--;
}
if (do_window)
{
m_Features.push_back(window);
iWindows--;
}
m_Features.push_back(wall);
}
m_pMaterial = GetGlobalMaterials()->FindName(material);
}
void vtEdge::AddFeature(int code, float width, float vf1, float vf2)
{
m_Features.push_back(vtEdgeFeature(code, width, vf1, vf2));
}
int vtEdge::NumFeaturesOfCode(int code) const
{
int i, count = 0, size = m_Features.size();
for (i = 0; i < size; i++)
{
if (m_Features[i].m_code == code)
count++;
}
return count;
}
float vtEdge::FixedFeaturesWidth() const
{
float width = 0.0f;
for (uint i = 0; i < m_Features.size(); i++)
{
const float fwidth = m_Features[i].m_width;
if (fwidth > 0)
width += fwidth;
}
return width;
}
float vtEdge::ProportionTotal() const
{
float width = 0.0f;
for (uint i = 0; i < m_Features.size(); i++)
{
const float fwidth = m_Features[i].m_width;
if (fwidth < 0)
width += fwidth;
}
return width;
}
bool vtEdge::IsUniform() const
{
const int windows = NumFeaturesOfCode(WFC_WINDOW);
const int doors = NumFeaturesOfCode(WFC_DOOR);
const int walls = NumFeaturesOfCode(WFC_WALL);
if (doors > 0)
return false;
if (walls != (windows + 1))
return false;
if (m_iSlope != 90)
return false;
if (m_pMaterial != NULL && *m_pMaterial != BMAT_NAME_SIDING)
return false;
return true;
}
/////////////////////////////////////
vtLevel::vtLevel()
{
m_iStories = 1;
m_fStoryHeight = STORY_HEIGHT;
}
vtLevel::~vtLevel()
{
m_Foot.clear();
DeleteEdges();
}
void vtLevel::DeleteEdges()
{
for (uint i = 0; i < m_Edges.GetSize(); i++)
delete m_Edges[i];
m_Edges.SetSize(0);
}
vtLevel &vtLevel::operator=(const vtLevel &v)
{
m_iStories = v.m_iStories;
m_fStoryHeight = v.m_fStoryHeight;
DeleteEdges();
m_Edges.SetSize(v.m_Edges.GetSize());
for (uint i = 0; i < v.m_Edges.GetSize(); i++)
{
vtEdge *pnew = new vtEdge(*v.m_Edges[i]);
m_Edges.SetAt(i, pnew);
}
m_Foot = v.m_Foot;
m_LocalFootprint = v.m_LocalFootprint;
return *this;
}
void vtLevel::DeleteEdge(int iEdge)
{
delete m_Edges[iEdge];
m_Edges.RemoveAt(iEdge);
m_Foot.RemovePoint(iEdge);
}
// Split an edge at the indicated point and clone into two edges
bool vtLevel::AddEdge(const int iEdge, const DPoint2 &Point)
{
int iNumEdges = m_Edges.GetSize();
int iIndex;
vtEdge *pEdge = new vtEdge(*GetEdge(iEdge));
if (NULL == pEdge)
return false;
if (iEdge == iNumEdges - 1)
m_Edges.Append(pEdge);
else
{
for (iIndex = iNumEdges - 1; iIndex > iEdge ; iIndex--)
m_Edges.SetAt(iIndex + 1, m_Edges[iIndex]);
m_Edges.SetAt(iEdge + 1, pEdge);
}
m_Foot.InsertPointAfter(iEdge, Point);
return true;
}
void vtLevel::SetFootprint(const DLine2 &dl)
{
// Safety check: Make sure there is at least an outer polygon
if (m_Foot.size() == 0)
m_Foot.resize(1);
int prev = m_Foot[0].GetSize();
m_Foot[0] = dl;
int curr = dl.GetSize();
if (curr != prev)
RebuildEdges(curr);
}
void vtLevel::SetFootprint(const DPolygon2 &poly)
{
int prev = m_Foot.NumTotalVertices();
m_Foot = poly;
int curr = m_Foot.NumTotalVertices();
if (curr != prev)
RebuildEdges(curr);
}
void vtLevel::SetEdgeMaterial(const char *matname)
{
const vtString *str = GetGlobalMaterials()->FindName(matname);
for (uint i = 0; i < m_Edges.GetSize(); i++)
m_Edges[i]->m_pMaterial = str;
}
void vtLevel::SetEdgeMaterial(const vtString *matname)
{
for (uint i = 0; i < m_Edges.GetSize(); i++)
m_Edges[i]->m_pMaterial = matname;
}
void vtLevel::SetEdgeColor(RGBi color)
{
for (uint i = 0; i < m_Edges.GetSize(); i++)
m_Edges[i]->m_Color = color;
}
vtEdge *vtLevel::GetEdge(uint i) const
{
if (i < m_Edges.GetSize()) // safety check
return m_Edges[i];
else
return NULL;
}
float vtLevel::GetEdgeLength(uint iIndex) const
{
int i = iIndex;
const int ring = m_Foot.WhichRing(i);
if (ring == -1)
return 0.0f;
const DLine2 &dline = m_Foot[ring];
const int j = i+1 == dline.GetSize() ? 0 : i+1;
return (float) (dline[j] - dline[i]).Length();
}
float vtLevel::GetLocalEdgeLength(uint iIndex) const
{
int i = iIndex;
const int ring = m_LocalFootprint.WhichRing(i);
if (ring == -1)
return 0.0f;
const FLine3 &fline = m_LocalFootprint[ring];
const int j = i+1 == fline.GetSize() ? 0 : i+1;
return (float) (fline[j] - fline[i]).Length();
}
void vtLevel::RebuildEdges(uint n)
{
DeleteEdges();
for (uint i = 0; i < n; i++)
{
vtEdge *pnew = new vtEdge;
pnew->Set(0, 0, BMAT_NAME_SIDING);
m_Edges.Append(pnew);
}
}
void vtLevel::ResizeEdgesToMatchFootprint()
{
int curr = m_Foot.NumTotalVertices();
m_Edges.SetSize(curr);
}
bool vtLevel::HasSlopedEdges() const
{
for (uint i = 0; i < m_Edges.GetSize(); i++)
{
if (m_Edges[i]->m_iSlope != 90)
return true;
}
return false;
}
bool vtLevel::IsHorizontal() const
{
for (uint i = 0; i < m_Edges.GetSize(); i++)
{
if (m_Edges[i]->m_iSlope == 0)
return true;
}
return false;
}
void vtLevel::SetRoofType(RoofType rt, int iSlope)
{
int i, edges = NumEdges();
if (rt == ROOF_FLAT)
{
// all edges are horizontal
for (i = 0; i < edges; i++)
m_Edges[i]->m_iSlope = 0;
m_fStoryHeight = 0.0f;
}
if (rt == ROOF_SHED)
{
// all edges are vertical
for (i = 0; i < edges; i++)
m_Edges[i]->m_iSlope = 90;
// except for the first edge
m_Edges[0]->m_iSlope = iSlope;
DetermineHeightFromSlopes();
}
if (rt == ROOF_GABLE)
{
// Algorithm for guessing which edges makes up the gable roof:
if (NumEdges() == 4)
{
// In the case of a rectangular footprint, assume that the
// shorter edge has the gable
if (GetEdgeLength(1) > GetEdgeLength(0))
{
m_Edges[0]->m_iSlope = 90;
m_Edges[1]->m_iSlope = iSlope;
m_Edges[2]->m_iSlope = 90;
m_Edges[3]->m_iSlope = iSlope;
}
else
{
m_Edges[0]->m_iSlope = iSlope;
m_Edges[1]->m_iSlope = 90;
m_Edges[2]->m_iSlope = iSlope;
m_Edges[3]->m_iSlope = 90;
}
}
else
{
// Assume that only convex edges can be gables, and no more than
// one edge in a row is a gable. All other edges are hip.
bool last_gable = false;
for (i = 0; i < edges; i++)
{
if (IsEdgeConvex(i) && !last_gable &&
!((i == edges - 1) && (m_Edges[0]->m_iSlope == 90)))
{
m_Edges[i]->m_iSlope = 90;
last_gable = true;
}
else
{
m_Edges[i]->m_iSlope = iSlope;
last_gable = false;
}
}
}
DetermineHeightFromSlopes();
}
if (rt == ROOF_HIP)
{
for (i = 0; i < edges; i++)
m_Edges[i]->m_iSlope = iSlope;
DetermineHeightFromSlopes();
}
}
void vtLevel::SetEaveLength(float fMeters)
{
int i, edges = NumEdges();
for (i = 0; i < edges; i++)
{
vtEdge *edge = m_Edges[i];
float rise = m_fStoryHeight;
// sin(slope) = rise/length
// length = rise/sin(slope)
float length = rise / sinf(edge->m_iSlope / 180.0f * PIf);
edge->m_Features[0].m_vf1 = -(fMeters / length);
}
}
bool vtLevel::IsEdgeConvex(int i)
{
// get the 2 corner indices of this edge
int edges = NumEdges();
int c1 = i;
int c2 = (i+1 == edges) ? 0 : i+1;
return (IsCornerConvex(c1) && IsCornerConvex(c2));
}
bool vtLevel::IsCornerConvex(int i)
{
int ring = m_Foot.WhichRing(i);
if (ring == -1)
return false;
const DLine2 &dline = m_Foot[ring];
// get the 2 adjacent corner indices
int edges = dline.GetSize();
int c1 = (i-1 < 0) ? edges-1 : i-1;
int c2 = i;
int c3 = (i+1 == edges) ? 0 : i+1;
// get edge vectors
DPoint2 v1 = dline[c2] - dline[c1];
DPoint2 v2 = dline[c3] - dline[c2];
// if dot product is positive, it's convex
double xprod = v1.Cross(v2);
return (xprod > 0);
}
/**
* Returns true if this level consists of edges with identical,
* evenly spaced windows.
*/
bool vtLevel::IsUniform() const
{
for (uint i = 0; i < m_Edges.GetSize(); i++)
{
if (m_Edges[i]->IsUniform() == false)
return false;
}
return true;
}
void vtLevel::DetermineLocalFootprint(float fHeight, const LocalCS &local_cs)
{
const uint rings = m_Foot.size();
FPoint3 lp;
m_LocalFootprint.resize(rings);
for (unsigned ring = 0; ring < rings; ring++)
{
const DLine2 &dline2 = m_Foot[ring];
FLine3 &fline3 = m_LocalFootprint[ring];
const uint edges = dline2.GetSize();
fline3.SetSize(edges);
for (unsigned i = 0; i < edges; i++)
{
const DPoint2 &p = dline2[i];
local_cs.EarthToLocal(p, lp.x, lp.z);
lp.y = fHeight;
fline3.SetAt(i, lp);
}
}
}
void vtLevel::GetEdgePlane(uint i, FPlane &plane)
{
vtEdge *edge = m_Edges[i];
int islope = edge->m_iSlope;
float slope = (islope / 180.0f * PIf);
int index = i;
int ring = m_LocalFootprint.WhichRing(index);
FLine3 &loop = m_LocalFootprint[ring];
uint ring_edges = loop.GetSize();
int next = (index+1 == ring_edges) ? 0 : index+1;
// get edge vector
FPoint3 vec = loop[next] - loop[index];
vec.Normalize();
// get perpendicular (upward pointing) vector
FPoint3 perp;
perp.Set(0, 1, 0);
// create rotation matrix to rotate it upward
FMatrix4 mat;
mat.Identity();
mat.AxisAngle(vec, slope);
// create normal
FPoint3 norm;
mat.TransformVector(perp, norm);
plane.Set(loop[index], norm);
}
//
// Look at the sloped edges to see if they meet at a particular point;
// if so, set that as the Level's story height. Return true on success.
//
bool vtLevel::DetermineHeightFromSlopes()
{
// In order to find a roof point, we need 3 adjacent edges whose
// edges intersect.
int i, edges = NumEdges();
bool bFoundASolution = false;
FPlane *planes = new FPlane[edges];
float fMinHeight = 1E10;
for (i = 0; i < edges; i++)
{
GetEdgePlane(i, planes[i]);
}
for (i = 0; i < edges; i++)
{
int i0 = i;
int i1 = (i+1)%edges;
int i2 = (i+2)%edges;
vtEdge *edge0 = m_Edges[i0];
vtEdge *edge1 = m_Edges[i1];
vtEdge *edge2 = m_Edges[i2];
if (edge0->m_iSlope == 90 &&
edge1->m_iSlope == 90 &&
edge2->m_iSlope == 90)
{
// skip this one; 3 vertical edges aren't useful
continue;
}
FPoint3 point;
bool valid = PlaneIntersection(planes[i0], planes[i1], planes[i2], point);
if (valid)
{
// take this point as the height of the roof
float fHeight = (point.y - m_LocalFootprint[0][0].y);
if (fHeight < 0) // shouldn't happen, but just a safety check
continue;
if (fHeight < fMinHeight)
fMinHeight = fHeight;
bFoundASolution = true;
}
}
if (bFoundASolution)
m_fStoryHeight = fMinHeight;
delete [] planes;
return bFoundASolution;
}
//
// Look at the materials of this level's edges. If they all use the
// same material, return it. Otherwise, return "Multiple".
//
const vtString vtLevel::GetOverallEdgeMaterial()
{
const vtString *most = NULL;
int edges = NumEdges();
for (int i = 0; i < edges; i++)
{
vtEdge *pEdge = GetEdge(i);
const vtString *mat = pEdge->m_pMaterial;
if (mat == NULL)
continue;
if (most == NULL)
most = mat;
else if (*most != *mat)
return "Multiple";
}
if (most)
return *most;
else
return "None";
}
//
// Look at the materials of this level's edges. If they all use the
// same material, return it. Otherwise, return BMAT_UNKNOWN.
//
bool vtLevel::GetOverallEdgeColor(RGBi &color)
{
RGBi col1(-1, -1, -1);
int edges = NumEdges();
for (int i = 0; i < edges; i++)
{
vtEdge *pEdge = GetEdge(i);
RGBi col2 = pEdge->m_Color;
if (col1.r == -1)
col1 = col2;
else if (col1 != col2)
return false;
}
color = col1;
return true;
}
//
// try to guess type of roof from looking at slopes of edges of
// this level
//
RoofType vtLevel::GuessRoofType() const
{
int sloped = 0, vert = 0, hori = 0;
int i, edges = NumEdges();
for (i = 0; i < edges; i++)
{
vtEdge *edge = GetEdge(i);
if (edge->m_iSlope == 0)
hori++;
else if (edge->m_iSlope == 90)
vert++;
else
sloped++;
}
if (hori)
return ROOF_FLAT;
if (sloped == 1 && vert == edges-1)
return ROOF_SHED;
if (sloped == edges)
return ROOF_HIP;
if (sloped > 0 && vert > 0)
return ROOF_GABLE;
return ROOF_UNKNOWN;
}
void vtLevel::FlipFootprintDirection()
{
m_Foot.ReverseOrder();
}
/////////////////////////////////////////////////////////////////////////////
// vtBuilding class implementation
vtBuilding::vtBuilding() : vtStructure()
{
SetType(ST_BUILDING);
m_pCRS = NULL;
}
vtBuilding::~vtBuilding()
{
DeleteLevels();
}
/**
* Delete all the levels for this building.
*/
void vtBuilding::DeleteLevels()
{
for (uint i = 0; i < m_Levels.GetSize(); i++)
delete m_Levels[i];
m_Levels.SetSize(0);
}
/**
* Asignment operator, which makes an explicit copy the entire building
* including each level.
*/
vtBuilding &vtBuilding::operator=(const vtBuilding &v)
{
// copy parent data
vtStructure::CopyFrom(v);
// copy class data
DeleteLevels();
for (uint i = 0; i < v.m_Levels.GetSize(); i++)
m_Levels.Append(new vtLevel(* v.m_Levels[i]));
m_pCRS = v.m_pCRS;
return *this;
}
/**
* Flips the direction of the footprint, which is either clockwise or
* counterclockwise when viewed from above. This affects the footprints
* of all levels.
*/
void vtBuilding::FlipFootprintDirection()
{
// Flip the direction (clockwisdom) of each level
for (uint i = 0; i < m_Levels.GetSize(); i++)
m_Levels[i]->FlipFootprintDirection();
// keep 2d and 3d in synch
DetermineLocalFootprints();
}
/**
* Calculate the elevation at which this building should be placed
* on a given heightfield.
*/
float vtBuilding::CalculateBaseElevation(vtHeightField *pHeightField)
{
const DLine2 &Footprint = m_Levels[0]->GetOuterFootprint();
int iSize = Footprint.GetSize();
float fLowest = 1E9f;
float fAltitude;
for (int i = 0; i < iSize; i++)
{
pHeightField->FindAltitudeOnEarth(Footprint[i], fAltitude);
if (fAltitude < fLowest)
fLowest = fAltitude;
}
return fLowest + m_fElevationOffset;
}
/**
* Transform the coodinates of this building (the footprints of
* each level) by the given coordinate transformation.
*/
void vtBuilding::TransformCoords(OCTransform *trans)
{
uint i, j;
DPoint2 p;
for (i = 0; i < m_Levels.GetSize(); i++)
{
vtLevel *pLev = m_Levels[i];
DPolygon2 foot = pLev->GetFootprint();
for (uint r = 0; r < foot.size(); r++)
{
DLine2 &footline = foot[r];
uint iSize = footline.GetSize();
for (j = 0; j < iSize; j++)
{
p = footline[j];
trans->Transform(1, &p.x, &p.y);
footline[j] = p;
}
}
pLev->SetFootprint(foot);
}
}
/**
* Sets the base footprint of the building to be a circle. A circle
* is represented by a 20-sided polygonal footprint.
*
* \param center The location of the building's center.
* \param fRad The radius of the building.
*/
void vtBuilding::SetCircle(const DPoint2 ¢er, float fRad)
{
DLine2 fp;
int i;
for (i = 0; i < 20; i++)
{
double angle = i * PI2d / 20;
DPoint2 vec(cos(angle) * fRad, sin(angle) * fRad);
fp.Append(center + vec);
}
SetFootprint(0, fp);
}
/**
* Set the colors of the building.
*
* \param which Can be either BLD_BASIC (the overall color of the building)
* or BLD_ROOF (the overall color of the roof).
* \param color The color to set.
*/
void vtBuilding::SetColor(BldColor which, const RGBi &color)
{
int i, levs = m_Levels.GetSize();
for (i = 0; i < levs; i++)
{
vtLevel *pLev = m_Levels[i];
int j, edges = pLev->NumEdges();
for (j = 0; j < edges; j++)
{
vtEdge *edge = pLev->GetEdge(j);
if (edge->m_iSlope < 90)
{
if (which == BLD_ROOF)
edge->m_Color = color;
}
else
{
if (which == BLD_BASIC)
edge->m_Color = color;
}
}
}
}
/**
* Get the color of the building. In the case of multi-colored buildings,
* note that this method returns only the first color encountered.
*
* \param which Can be either BLD_BASIC (color of the building) or BLD_ROOF
* (color of the roof).
*/
RGBi vtBuilding::GetColor(BldColor which) const
{
int i, levs = m_Levels.GetSize();
for (i = 0; i < levs; i++)
{
vtLevel *pLev = m_Levels[i];
int j, edges = pLev->NumEdges();
for (j = 0; j < edges; j++)
{
vtEdge *edge = pLev->GetEdge(j);
if (edge->m_iSlope < 90)
{
if (which == BLD_ROOF)
return edge->m_Color;
}
else
{
if (which == BLD_BASIC)
return edge->m_Color;
}
}
}
return RGBi(0,0,0);
}
/**
* Set the height of the building in stories. If the building has no levels,
* two will be created: for the walls and the roof. If the number of stories
* is greater than before, the additional stories are added to the top-most
* non-roof level. If lesser, stories and levels are removed from the top
* down until the desired number is met.
*
* \param iStories Number of stories to set.
*/
void vtBuilding::SetNumStories(int iStories)
{
vtLevel *pLev;
int previous = NumStories();
if (previous == iStories)
return;
// this method assume each building must have at least two levels: one
// for the walls and one for the roof.
int levels = m_Levels.GetSize();
if (levels == 0)
{
CreateLevel();
levels++;
}
if (levels == 1)
{
vtLevel *pFirstLev = GetLevel(0);
pLev = CreateLevel();
pLev->SetFootprint(pFirstLev->GetFootprint());
pLev->SetRoofType(ROOF_FLAT, 0);
levels++;
}
previous = NumStories(); // Just in case it changed
// increase if necessary
if (iStories > previous)
{
// get top non-roof level
pLev = m_Levels[levels-2];
// added some stories
pLev->m_iStories += (iStories - previous);
}
// decrease if necessary
while (NumStories() > iStories)
{
// get top non-roof level
pLev = m_Levels[levels-2];
pLev->m_iStories--;
if (pLev->m_iStories == 0)
{
delete pLev;
m_Levels.SetSize(levels-1);
levels--;
}
}
// keep 2d and 3d in synch
DetermineLocalFootprints();
}
/**
* Get the total number of stories of this building. The top level is assumed
* to be a roof and does not count toward the total.
*/
int vtBuilding::NumStories() const
{
// this method assume each building must have at least two levels: one
// for the walls and one for the roof.
int stories = 0;
uint levs = m_Levels.GetSize();
if (levs > 0)
{
for (uint i = 0; i < levs - 1; i++)
stories += m_Levels[i]->m_iStories;
}
return stories;
}
float vtBuilding::GetTotalHeight() const
{
float h = 0.0f;
for (uint i = 0; i < m_Levels.GetSize(); i++)
{
vtLevel *lev = m_Levels[i];
h += (lev->m_fStoryHeight * lev->m_iStories);
}
return h;
}
/**
* Set the footprint of the given level of the building.
*
* \param lev The level, from 0 for the base level and up.
* \param foot The footprint.
*/
void vtBuilding::SetFootprint(int lev, const DLine2 &foot)
{
int levs = NumLevels();
if (lev >= levs)
CreateLevel();
m_Levels[lev]->SetFootprint(foot);
// keep 2d and 3d in synch
DetermineLocalFootprints();
}
/**
* Set the footprintf of the given level of the building.
*
* \param lev The level, from 0 for the base level and up.
* \param poly The footprint.
*/
void vtBuilding::SetFootprint(int lev, const DPolygon2 &poly)
{
int levs = NumLevels();
if (lev >= levs)
CreateLevel();
m_Levels[lev]->SetFootprint(poly);
// keep 2d and 3d in synch
DetermineLocalFootprints();
}
/**
* Set the type of roof for this building. In cases of ambiguity, such as
* setting a gable roof, the method will try to make intelligent guesses
* about where to put the roof angles based the length of the roof edges.
*
* \param rt Roof type, one of:
* - ROOF_FLAT
* - ROOF_SHED
* - ROOF_GABLE
* - ROOF_HIP
* \param iSlope For a non-flat roof, this is the slope in degrees of the
* sloped edges. This varies from 0 (horizontal) to 90 (vertical).
* \param iLev (optional) The number of the level to assume is the roof.
* If omitted, the top level is assumed to be the roof.
*/
void vtBuilding::SetRoofType(RoofType rt, int iSlope, int iLev)
{
int i, edges;
if (NumLevels() < 2)
{
// should not occur - this method is intended for buildings with roofs
return;
}
// if there is a roof level, attempt to set its edge angles to match
// the desired roof type
vtLevel *pLev, *below;
if (iLev == -1)
{
pLev = GetLevel(NumLevels()-1);
below = GetLevel(NumLevels()-2);
}
else
{
pLev = GetLevel(iLev);
below = GetLevel(iLev-1);
}
// If roof level has no edges then give it some
edges = pLev->NumEdges();
if (0 == edges)
{
pLev->SetFootprint(below->GetFootprint());
}
edges = pLev->NumEdges();
// provide default slopes for the roof sections
if (iSlope == -1)
{
if (rt == ROOF_SHED)
iSlope = 4;
if (rt == ROOF_GABLE || rt == ROOF_HIP)
iSlope = 15;
}
pLev->SetRoofType(rt, iSlope);
// all horizontal edges of the roof should default to the same material
// as the wall section below them
for (i = 0; i < edges; i++)
{
vtEdge *edge0 = below->GetEdge(i);
vtEdge *edge1 = pLev->GetEdge(i);
if (edge1->m_iSlope == 90)
{
edge1->m_pMaterial = edge0->m_pMaterial;
edge1->m_Color = edge0->m_Color;
}
}
}
RoofType vtBuilding::GetRoofType() const
{
// try to guess type of roof from looking at slopes of edges of
// the top level
const vtLevel *pLev = GetLevel(NumLevels()-1);
return pLev->GuessRoofType();
}
RGBi vtBuilding::GuessRoofColor() const
{
const vtLevel *pRoof = GetLevel(NumLevels()-1);
for (int i = 0; i < pRoof->NumEdges(); i++)
{
if (pRoof->GetEdge(i)->m_iSlope != 90)
return pRoof->GetEdge(i)->m_Color;
}
return RGBi(255, 255, 255);
}
void vtBuilding::SetRoofColor(const RGBi &rgb)
{
vtLevel *pRoof = GetLevel(NumLevels()-1);
for (int i = 0; i < pRoof->NumEdges(); i++)
{
if (pRoof->GetEdge(i)->m_iSlope != 90)
pRoof->GetEdge(i)->m_Color = rgb;
}
}
bool vtBuilding::GetBaseLevelCenter(DPoint2 &p) const
{
DRECT rect;
if (!GetExtents(rect))
return false;
rect.GetCenter(p);
return true;
}
void vtBuilding::Offset(const DPoint2 &p)
{
for (uint i = 0; i < m_Levels.GetSize(); i++)
{
vtLevel *lev = m_Levels[i];
DPolygon2 &foot = lev->GetFootprint();
foot.Add(p);
}
// keep 2d and 3d in synch
DetermineLocalFootprints();
}
//
// Get an extent rectangle around the building.
// It doesn't need to be exact.
//
bool vtBuilding::GetExtents(DRECT &rect) const
{
uint levs = m_Levels.GetSize();
if (levs == 0)
return false;
rect.SetInsideOut();
for (uint i = 0; i < levs; i++)
{
vtLevel *lev = m_Levels[i];
if (lev->GetFootprint().size() != 0) // safety check
rect.GrowToContainLine(lev->GetOuterFootprint());
}
return true;
}
vtLevel *vtBuilding::CreateLevel()
{
vtLevel *pLev = new vtLevel;
m_Levels.Append(pLev);
// We don't have to call DetermineLocalFootprints(), because the new level is empty.
return pLev;
}
vtLevel *vtBuilding::CreateLevel(const DPolygon2 &footprint)
{
vtLevel *pLev = new vtLevel;
pLev->SetFootprint(footprint);
m_Levels.Append(pLev);
// keep 2d and 3d in synch
DetermineLocalFootprints();
return pLev;
}
void vtBuilding::InsertLevel(int iLev, vtLevel *pLev)
{
int levels = NumLevels();
m_Levels.SetSize(levels+1);
for (int i = levels; i > iLev; i--)
{
m_Levels[i] = m_Levels[i-1];
}
m_Levels[iLev] = pLev;
// keep 2d and 3d in synch
DetermineLocalFootprints();
}
void vtBuilding::DeleteLevel(int iLev)
{
int levels = NumLevels();
for (int i = iLev; i < levels-1; i++)
{
m_Levels[i] = m_Levels[i+1];
}
m_Levels.SetSize(levels-1);
// keep 2d and 3d in synch
DetermineLocalFootprints();
}
void vtBuilding::SetRectangle(const DPoint2 ¢er, float fWidth,
float fDepth, float fRotation)
{
vtLevel *pLev;
// this function requires at least one level to exist
if (m_Levels.GetSize() == 0)
{
pLev = new vtLevel;
pLev->m_iStories = 1;
m_Levels.Append(pLev);
}
else
pLev = m_Levels[0];
// if rotation is unset, default to none
if (fRotation == -1.0f)
fRotation = 0.0f;
DPoint2 pt(fWidth / 2.0, fDepth / 2.0);
DPoint2 corner[4];
corner[0].Set(-pt.x, -pt.y);
corner[1].Set(pt.x, -pt.y);
corner[2].Set(pt.x, pt.y);
corner[3].Set(-pt.x, pt.y);
corner[0].Rotate(fRotation);
corner[1].Rotate(fRotation);
corner[2].Rotate(fRotation);
corner[3].Rotate(fRotation);
DLine2 dl;
dl.Append(center + corner[0]);
dl.Append(center + corner[1]);
dl.Append(center + corner[2]);
dl.Append(center + corner[3]);
pLev->SetFootprint(dl);
}
/**
* Find the closest distance from a given point to the interior of a
* building's lowest footprint. If the point is inside the footprint,
* the value 0.0 is returned.
*/
double vtBuilding::GetDistanceToInterior(const DPoint2 &point) const
{
vtLevel *lev = m_Levels[0];
// Ignore holes - a small shortcut, could be be addressed later
const DLine2 &foot = lev->GetOuterFootprint();
if (foot.ContainsPoint(point))
return 0.0;
int i, edges = foot.GetSize();
double dist, closest = 1E8;
for (i = 0; i < edges; i++)
{
DPoint2 p0 = foot[i];
DPoint2 p1 = foot[(i+1)%edges];
dist = DistancePointToLine(p0, p1, point);
if (dist < closest)
closest = dist;
}
return closest;
}
void vtBuilding::WriteXML(GZOutput &out, bool bDegrees) const
{
const char *coord_format = "%.9lg"; // up to 9 significant digits
gfprintf(out, "\t<Building");
if (m_fElevationOffset != 0.0)
gfprintf(out, " ElevationOffset=\"%.2f\"", m_fElevationOffset);
if (m_bAbsolute)
gfprintf(out, " Absolute=\"true\"");
gfprintf(out, ">\n");
int i, j, k;
int levels = NumLevels();
for (i = 0; i < levels; i++)
{
const vtLevel *lev = GetLevel(i);
gfprintf(out, "\t\t<Level FloorHeight=\"%f\" StoryCount=\"%d\">\n",
lev->m_fStoryHeight, lev->m_iStories);
gfprintf(out, "\t\t\t<Footprint>\n");
gfprintf(out, "\t\t\t\t<gml:Polygon>\n");
// Every footprint polygon has at least one outer boundary
gfprintf(out, "\t\t\t\t\t<gml:outerBoundaryIs>\n");
gfprintf(out, "\t\t\t\t\t\t<gml:LinearRing>\n");
gfprintf(out, "\t\t\t\t\t\t\t<gml:coordinates>");
const DPolygon2 &pfoot = lev->GetFootprint();
const DLine2 &outer = pfoot[0];
int points = outer.GetSize();
for (j = 0; j < points; j++)
{
gfprintf(out, coord_format, outer[j].x);
gfprintf(out, ",");
gfprintf(out, coord_format, outer[j].y);
if (j != points-1)
gfprintf(out, " ");
}
gfprintf(out, "</gml:coordinates>\n");
gfprintf(out, "\t\t\t\t\t\t</gml:LinearRing>\n");
gfprintf(out, "\t\t\t\t\t</gml:outerBoundaryIs>\n");
// If we have a compound footprint, write inner rings separately
int rings = pfoot.size();
for (int iring = 1; iring < rings; iring++)
{
gfprintf(out, "\t\t\t\t\t<gml:innerBoundaryIs>\n");
gfprintf(out, "\t\t\t\t\t\t<gml:LinearRing>\n");
gfprintf(out, "\t\t\t\t\t\t\t<gml:coordinates>");
const DLine2 &inner = pfoot[iring];
int points = inner.GetSize();
for (j = 0; j < points; j++)
{
gfprintf(out, coord_format, inner[j].x);
gfprintf(out, ",");
gfprintf(out, coord_format, inner[j].y);
if (j != points-1)
gfprintf(out, " ");
}
gfprintf(out, "</gml:coordinates>\n");
gfprintf(out, "\t\t\t\t\t\t</gml:LinearRing>\n");
gfprintf(out, "\t\t\t\t\t</gml:innerBoundaryIs>\n");
}
gfprintf(out, "\t\t\t\t</gml:Polygon>\n");
gfprintf(out, "\t\t\t</Footprint>\n");
int edges = lev->NumEdges();
for (j = 0; j < edges; j++)
{
vtEdge *edge = lev->GetEdge(j);
gfprintf(out, "\t\t\t<Edge");
if (edge->m_pMaterial)
gfprintf(out, " Material=\"%s\"",
(const char *)*edge->m_pMaterial);
gfprintf(out, " Color=\"%02x%02x%02x\"",
edge->m_Color.r, edge->m_Color.g, edge->m_Color.b);
if (edge->m_iSlope != 90)
gfprintf(out, " Slope=\"%d\"", edge->m_iSlope);
if (!edge->m_Facade.IsEmpty())
gfprintf(out, " Facade=\"%s\"", (pcchar)edge->m_Facade);
gfprintf(out, ">\n");
int features = edge->NumFeatures();
for (k = 0; k < features; k++)
{
gfprintf(out, "\t\t\t\t<EdgeElement");
const vtEdgeFeature &feat = edge->m_Features[k];
gfprintf(out, " Type=\"%s\"",
vtBuilding::GetEdgeFeatureString(feat.m_code));
if (feat.m_vf1 != 0.0f)
gfprintf(out, " Begin=\"%.3f\"", feat.m_vf1);
if (feat.m_vf2 != 1.0f)
gfprintf(out, " End=\"%.3f\"", feat.m_vf2);
gfprintf(out, "/>\n");
}
gfprintf(out, "\t\t\t</Edge>\n");
}
gfprintf(out, "\t\t</Level>\n");
}
WriteTags(out);
gfprintf(out, "\t</Building>\n");
}
void vtBuilding::AddDefaultDetails()
{
// requires at least 2 levels to operate
int numlevels = NumLevels();
while (numlevels < 2)
{
CreateLevel();
numlevels = NumLevels();
}
// add some default windows/doors
for (int i = 0; i < numlevels - 1; i++)
{
vtLevel *lev = m_Levels[i];
const int edges = lev->NumEdges();
for (int j = 0; j < edges; j++)
{
vtEdge *edge = lev->GetEdge(j);
const int doors = 0;
const int windows = (int) (lev->GetLocalEdgeLength(j) / 6.0f);
edge->Set(doors, windows, BMAT_NAME_SIDING);
}
}
// process roof level
vtLevel *roof = m_Levels[numlevels - 1];
int edges = roof->NumEdges();
if (0 == edges)
roof->SetFootprint(m_Levels[0]->GetFootprint());
edges = roof->NumEdges();
for (int j = 0; j < edges; j++)
{
vtEdge *edge = roof->GetEdge(j);
edge->m_iSlope = 0; // flat roof
}
DetermineLocalFootprints();
}
void vtBuilding::DetermineLocalFootprints()
{
DPoint2 center;
GetBaseLevelCenter(center);
// The local conversion will be use to make the local footprints.
LocalCS local_cs;
local_cs.Setup(m_pCRS->GetUnits(), center);
int i;
int levs = m_Levels.GetSize();
float fHeight = 0.0f;
for (i = 0; i < levs; i++)
{
vtLevel *lev = m_Levels[i];
lev->DetermineLocalFootprint(fHeight, local_cs);
fHeight += (lev->m_iStories * lev->m_fStoryHeight);
}
}
const char *vtBuilding::GetEdgeFeatureString(int edgetype)
{
switch (edgetype)
{
case WFC_WALL: return "Wall"; break;
case WFC_GAP: return "Gap"; break;
case WFC_POST: return "Post"; break;
case WFC_WINDOW: return "Window"; break;
case WFC_DOOR: return "Door"; break;
}
return "Bad Value";
}
int vtBuilding::GetEdgeFeatureValue(const char *value)
{
if (!strcmp(value, "Wall"))
return WFC_WALL;
else if (!strcmp(value, "Gap"))
return WFC_GAP;
else if (!strcmp(value, "Post"))
return WFC_POST;
else if (!strcmp(value, "Window"))
return WFC_WINDOW;
else if (!strcmp(value, "Door"))
return WFC_DOOR;
return 0;
}
bool vtBuilding::IsContainedBy(const DRECT &rect) const
{
// It's easier to select buildings using their centers, than using their extents.
DPoint2 center;
GetBaseLevelCenter(center);
return rect.ContainsPoint(center);
}
void vtBuilding::SwapLevels(int lev1, int lev2)
{
vtLevel *pTemp = m_Levels[lev1];
m_Levels[lev1] = m_Levels[lev2];
m_Levels[lev2] = pTemp;
// keep 2d and 3d in sync
DetermineLocalFootprints();
}
void vtBuilding::SetEaves(float fLength)
{
// Assume that the top level is the roof
vtLevel *roof = m_Levels[m_Levels.GetSize()-1];
if (roof->NumEdges() <= 4)
SetEavesSimple(fLength);
else
SetEavesFelkel(fLength);
}
void vtBuilding::SetEavesSimple(float fLength)
{
// Assume that the top level is the roof
vtLevel *roof = m_Levels[m_Levels.GetSize()-1];
float height = roof->m_fStoryHeight;
for (int i = 0; i < roof->NumEdges(); i++)
{
vtEdge *edge = roof->GetEdge(i);
// Ignore vertical walls and flat roofs
if (edge->m_iSlope == 90 || edge->m_iSlope == 0)
continue;
// Assume only one edge feature on each edge of a roof.
if (edge->NumFeatures() != 1)
continue;
// Simple trigonometry to convert the height, angle and length of the
// eave (in meters) to produce the length as a fraction.
float angle = edge->SlopeRadians();
float fraction = fLength / (height / sin(angle));
edge->m_Features[0].m_vf1 = -fraction;
}
}
void vtBuilding::SetEavesFelkel(float fLength)
{
// Assume that the top level is the roof
vtLevel *roof = m_Levels[m_Levels.GetSize()-1];
// Convert meters to local units
DPolygon2 &foot = roof->GetFootprint();
DLine2 &line = foot[0];
DLine2 offset(line.GetSize());
for (int i = 0; i < (int) line.GetSize(); i++)
{
AngleSideVector(line.GetSafePoint(i-1), line[i], line.GetSafePoint(i+1), offset[i]);
}
for (int i = 0; i < (int) line.GetSize(); i++)
{
// Offset points to the left, subtract it to go to the right, which on a
// counter-clockwise polygon, expands the polygon.
line[i] -= (offset[i] * fLength);
}
// keep 2d and 3d in sync
DetermineLocalFootprints();
}
void vtBuilding::CopyStyleFrom(const vtBuilding * const pSource, bool bDoHeight)
{
SetElevationOffset(pSource->GetElevationOffset());
DPolygon2 foot;
// If we will copy height information, then we will make as many levels as
// needed to match the source.
uint from_levels = pSource->NumLevels();
uint copy_levels;
if (bDoHeight)
copy_levels = from_levels;
else
copy_levels = NumLevels();
// Copy the roof angles first.
SetRoofType(pSource->GetRoofType());
for (uint i = 0; i < copy_levels; i++)
{
vtLevel *pLevel = GetLevel(i);
if (pLevel)
foot = pLevel->GetFootprint();
else
pLevel = CreateLevel(foot);
int from_level;
const vtLevel *pFromLevel;
if (bDoHeight)
{
from_level = i;
pFromLevel = pSource->GetLevel(i);
pLevel->m_iStories = pFromLevel->m_iStories;
pLevel->m_fStoryHeight = pFromLevel->m_fStoryHeight;
}
else
{
// The target building may have more more levels than the default.
// Try to guess an appropriate corresponding level.
if (i == 0)
from_level = 0;
else if (i == copy_levels-1)
from_level = from_levels - 1;
else
{
from_level = i;
if (from_levels > 2)
from_level = 1;
else
from_level = 0;
}
pFromLevel = pSource->GetLevel(from_level);
}
int from_edges = pFromLevel->NumEdges();
int to_edges = pLevel->NumEdges();
// Now that we have a source and target level, iterate through the edges.
if (i == copy_levels - 1 && i > 0)
{
// Handle roof specially: do the sloped edges.
vtLevel *below = GetLevel(i - 1);
RGBi color;
const vtString *material;
float vf1; // Used for roof overhang / eaves.
for (int j = 0; j < from_edges; j++)
{
vtEdge *from_edge = pFromLevel->GetEdge(j);
if (from_edge->m_iSlope != 90)
{
color = from_edge->m_Color;
material = from_edge->m_pMaterial;
vf1 = from_edge->m_Features[0].m_vf1;
}
}
for (int j = 0; j < to_edges; j++)
{
vtEdge *to_edge = pLevel->GetEdge(j);
if (to_edge->m_iSlope != 90)
{
to_edge->m_Color = color;
to_edge->m_pMaterial = material;
to_edge->m_Features[0].m_vf1 = vf1;
}
else
{
to_edge->m_Color = below->GetEdge(j)->m_Color;
to_edge->m_pMaterial = below->GetEdge(j)->m_pMaterial;
}
}
continue;
}
// The non-roof case:
for (int j = 0; j < to_edges; j++)
{
const int k = j % from_edges;
vtEdge *from_edge = pFromLevel->GetEdge(k);
vtEdge *to_edge = pLevel->GetEdge(j);
to_edge->m_Color = from_edge->m_Color;
to_edge->m_pMaterial = from_edge->m_pMaterial;
// Try to create similar edge features (walls, windows, doors)
if (from_edge->IsUniform())
{
const int doors = 0;
int windows = (int) (pLevel->GetLocalEdgeLength(j) / 6.0f);
if (windows < 1)
windows = 1;
to_edge->Set(doors, windows, BMAT_NAME_SIDING);
}
else if (from_edge->NumFeatures() == 1)
{
to_edge->m_Features.clear();
to_edge->m_Features.push_back(from_edge->m_Features[0]);
}
else
{
// General case: not uniform, more than one feature
const int num_features1 = from_edge->NumFeatures();
const float length1 = pFromLevel->GetLocalEdgeLength(k);
float features_per_meter = (float) num_features1 / length1;
const float length2 = pLevel->GetLocalEdgeLength(j);
int num_features2 = (int) (features_per_meter * length2);
if (num_features2 < 1)
num_features2 = 1;
to_edge->m_Features.clear();
for (int m = 0; m < num_features2; m++)
to_edge->m_Features.push_back(from_edge->m_Features[m % num_features1]);
}
}
}
}
| true |
d9e8cfcbb6a2b23a1f51c2b9947c22cb78cca59c | C++ | shanadas/VxEventInjector | /External/Pelco/VxSdk-1.2/x86/Debug/Include/IVxMonitor.h | UTF-8 | 4,115 | 2.71875 | 3 | [
"MIT"
] | permissive | #ifndef IVxMonitor_h__
#define IVxMonitor_h__
#include "VxPrimitives.h"
#include "VxMacros.h"
#include "VxCollection.h"
#include "VxUtilities.h"
#include "IVxMonitorCell.h"
namespace VxSdk {
struct IVxDevice;
struct IVxMonitorLock;
/// <summary>
/// Represents a display for view data (typically video).
/// </summary>
struct IVxMonitor {
public:
/// <summary>
/// Deletes this instance.
/// </summary>
/// <returns>The <see cref="VxResult::Value">Result</see> of deleting this instance.</returns>
virtual VxResult::Value Delete() const = 0;
/// <summary>
/// Gets the layouts available for this monitor.
/// </summary>
/// <param name="layoutCollection">A <see cref="VxCollection"/> of the available layouts.</param>
/// <returns>The <see cref="VxResult::Value">Result</see> of the request.</returns>
virtual VxResult::Value GetAvailableLayouts(VxCollection<VxCellLayout::Value*>& layoutCollection) const = 0;
/// <summary>
/// Gets the host device of this monitor.
/// </summary>
/// <param name="hostDevice">The host <see cref="IVxDevice"/>.</param>
/// <returns>The <see cref="VxResult::Value">Result</see> of the request.</returns>
virtual VxResult::Value GetHostDevice(IVxDevice*& hostDevice) const = 0;
/// <summary>
/// Gets the cells currently active on this monitor.
/// </summary>
/// <param name="cellCollection">A <see cref="VxCollection"/> of the active monitor cells.</param>
/// <returns>The <see cref="VxResult::Value">Result</see> of the request.</returns>
virtual VxResult::Value GetMonitorCells(VxCollection<IVxMonitorCell**>& cellCollection) = 0;
/// <summary>
/// Refreshes the member values for this object by retrieving its current information from the VideoXpert system.
/// </summary>
/// <returns>The <see cref="VxResult::Value">Result</see> of refreshing the member values for this object.</returns>
virtual VxResult::Value Refresh() = 0;
/// <summary>
/// Deletes this monitor from the VideoXpert system.
/// </summary>
/// <returns>The <see cref="VxResult::Value">Result</see> of deleting the monitor.</returns>
virtual VxResult::Value RemoveMonitor() const = 0;
/// <summary>
/// Sets the layout property.
/// </summary>
/// <param name="layout">The new layout value.</param>
/// <returns>The <see cref="VxResult::Value">Result</see> of setting the property.</returns>
virtual VxResult::Value SetLayout(VxCellLayout::Value layout) = 0;
/// <summary>
/// Sets the name property.
/// </summary>
/// <param name="name">The new name value.</param>
/// <returns>The <see cref="VxResult::Value">Result</see> of setting the property.</returns>
virtual VxResult::Value SetName(char name[64]) = 0;
/// <summary>
/// Sets the number property.
/// </summary>
/// <param name="number">The new number value.</param>
/// <returns>The <see cref="VxResult::Value">Result</see> of setting the property.</returns>
virtual VxResult::Value SetNumber(int number) = 0;
public:
/// <summary>
/// The unique identifier of the monitor.
/// </summary>
char id[64];
/// <summary>
/// The friendly name of this monitor.
/// </summary>
char name[64];
/// <summary>
/// The number used to designate the monitor.
/// </summary>
int number;
/// <summary>
/// The cell grid layout.
/// </summary>
VxCellLayout::Value layout;
protected:
/// <summary>
/// Clears this instance.
/// </summary>
void Clear() {
VxZeroArray(this->id);
VxZeroArray(this->name);
this->number = 0;
this->layout = VxCellLayout::Value::k1x1;
}
};
}
#endif // IVxMonitor_h__
| true |
47c990961b7f6ef402ec91bc85478d6eafa3720b | C++ | GeoffreyHervet/epitek | /2/piscine/piscine_cpp_d06-2015-hervet_g/ex03/koalanurse.cpp | UTF-8 | 1,751 | 2.8125 | 3 | [] | no_license | //
// koalanurse.cpp for ex03 in /home/hervet_g/piscine/piscine_cpp_d06-2015-hervet_g/ex03
//
// Made by geoffrey hervet
// Login <hervet_g@epitech.net>
//
// Started on Mon Jan 09 16:09:50 2012 geoffrey hervet
// Last update Mon Jan 09 16:09:50 2012 geoffrey hervet
//
#include <fstream>
#include <iomanip>
#include <iostream>
#include <string>
#include "koalanurse.h"
KoalaNurse::KoalaNurse(unsigned int id)
{
this->id = id;
this->is_working = 0;
}
KoalaNurse::~KoalaNurse()
{
if (this->is_working)
this->timeCheck();
std::cout << "Nurse " << this->id << ": Enfin un peu de repos !" << std::endl;
}
void KoalaNurse::giveDrug(std::string drug, SickKoala *koala)
{
if (!this->is_working)
this->timeCheck();
koala->takeDrug(drug);
}
std::string KoalaNurse::readReport(std::string fileName)
{
std::ifstream file;
std::string line = "";
char buf[1024];
if (!this->is_working)
this->timeCheck();
if (std::string::npos == fileName.find(".report"))
return line;
buf[0] = 0;
file.open(fileName.c_str(), std::ifstream::out);
if (false == file.is_open() || !file.eof())
return line;
while (!file.eof())
{
file.read(buf, 1024);
buf[file.gcount()] = 0;
line += buf;
}
file.close();
std::cerr << "\"" << line << "\"" << std::endl;
if (std::string::npos != line.find("\n"))
line.replace(line.find("\n"), 1, (std::string)"\0");
std::cout << "Nurse " << this->id << ": Kreog ! Il faut donner un " << line << " a Mr." << fileName.substr(-7) << " !" << std::endl;
return line;
}
void KoalaNurse::timeCheck(void)
{
std::cout << "Nurse " << this->id << ((this->is_working) ? " Je rentre dans ma foret d’eucalyptus !" : ": Je commence le travail !") << std::endl;
this->is_working = !this->is_working;
}
| true |
9449c64681be7018cd08f67cfb985403a99a4581 | C++ | solomonlu/Cocos2dx-Points24 | /Classes/Util.cpp | UTF-8 | 1,200 | 2.546875 | 3 | [] | no_license | #include "Util.h"
#include "cocos2d.h"
USING_NS_CC;
extern std::set<std::string> g_SolutionSet;
std::string getRandom4CardsString()
{
std::string originalCardNums;
std::string cardNums;
int cardNum1,cardNum2,cardNum3,cardNum4;
int sortCardNum1,sortCardNum2,sortCardNum3,sortCardNum4;
srand((unsigned)time(0));
do
{
cardNum1 = (rand()%9)+1;
cardNum2 = (rand()%9)+1;
cardNum3 = (rand()%9)+1;
cardNum4 = (rand()%9)+1;
char str[64] = {0};
sprintf(str,"%d%d%d%d",cardNum1,cardNum2,cardNum3,cardNum4);
originalCardNums = std::string(str);
std::multiset<int> cardSet;
cardSet.insert(cardNum1);
cardSet.insert(cardNum2);
cardSet.insert(cardNum3);
cardSet.insert(cardNum4);
auto iter = cardSet.begin();
sortCardNum1 = *(iter++);
sortCardNum2 = *(iter++);
sortCardNum3 = *(iter++);
sortCardNum4 = *(iter);
sprintf(str,"%d%d%d%d",sortCardNum1,sortCardNum2,sortCardNum3,sortCardNum4);
cardNums = std::string(str);
CCLOG("random 4 card:%d%d%d%d",sortCardNum1,sortCardNum2,sortCardNum3,sortCardNum4);
}while(g_SolutionSet.find(cardNums) == g_SolutionSet.end());
CCLOG("return random 4 card string:%s",originalCardNums.c_str());
return originalCardNums;
} | true |
71c863dc1aca88cd8eead7c8147a3e0b4ce835fe | C++ | roadev/IPOO_Alcancia | /Alcancia.h | UTF-8 | 1,644 | 2.859375 | 3 | [] | no_license | /* Autor: Hecho por Juan David Roa Valencia
* Fecha de creación: 02/09/14
* Versión: 0.71
*
* Nombre del archivo: Alcancia.h
* Responsabilidad:
* Colaboración:
*/
#include <iostream>
#include <string>
using namespace std;
#ifndef ALCANCIA_H
#define ALCANCIA_H
class Alcancia {// aquí se crea la clase Alcancia
public://metodos
Alcancia();//constructor
~Alcancia();// destructor
void agregar20();
void agregar50();
void agregar100();
void agregar200();
void agregar500();
void agregarBitCoins ();
void ingresarMarca(string brand);
void calcularTotalCop();
void calcularTotalBtc();
void calcularCantidadesCop();
void calcularTotalAlcancia();
void calcular3X1000();
void estadoAlcancia();
void romperAlcancia();
void setCant20(int cant);
void setCant50(int cant);
void setCant100(int cant);
void setCant200(int cant);
void setCant500(int cant);
void setBitcoin (double btc );
int getCant20();
int getCant50();
int getCant100();
int getCant200();
int getCant500();
double getBitcoin();
double getTotalAlcancia();
double getTresXmil();
string getEstadoAlcancia();
string getMarca();
private://atributos de la clase
int cant20;
int cant50;
int cant100;
int cant200;
int cant500;
int totalDinero;
double bitcoin;
int totalBtc;// totalBtc es la cantidad de pesos en Bitcoins.
int totalCop;//totalCop es la cantidad total de dinero en pesos colombianos.
double valorBtcCop;
double totalAlcancia;
double tresXmil;
string marca;
};
#endif /* ALCANCIA_H */
| true |
0dea618dffae9e4b5aed0c228bb319cfefaa1ff9 | C++ | AnaA-Rocha/URI-solution-cpp | /Iniciante/URI 1185.cpp | UTF-8 | 431 | 2.671875 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main ()
{
float M[12][12];
int l,c;
char s;
float soma=0,media=0.0;
cin>>s;
for(l=0;l<12;l++)
{
for(c=0;c<12;c++)
{
cin>>M[l][c];
}
}
for(l=0;l<12;l++)
{
for(c=0;c<11-l;c++)
{
soma+=M[l][c];
media=soma/66.0;
}
}
if(s=='S')
{
cout.precision(1);
cout<<fixed<<(soma*10.0)/10<<endl;
}
else
{
cout.precision(1);
cout<<fixed<<media<<endl;
}
}
| true |
f57cc787d54926687bdefd266a9c3c7309d0f78e | C++ | a-kashirin-official/spbspu-labs-2018 | /zasyadko.vladislav/A1/rectangle.hpp | UTF-8 | 511 | 2.75 | 3 | [] | no_license | #ifndef RECTANGLE_HEADER
#define RECTANGLE_HEADER
#include "shape.hpp"
class Rectangle :
public Shape
{
public:
Rectangle(const point_t & center, const double & height, const double & width);
double getArea() const override;
rectangle_t getFrameRect() const override;
void move(const point_t & Center) override;
void move(const double add_x, const double add_y) override;
void print() const override;
private :
point_t cntr_;
double height_;
double width_;
};
#endif
| true |
2f5b7ef4a4ca03e414d716cdde3d5b526c79d338 | C++ | davidposs/ObjectCodeGenerator | /Syntax.cpp | UTF-8 | 26,367 | 2.84375 | 3 | [] | no_license | /******************************************************************************
* File: Syntax.cpp
* Authors: David Poss, Douglas Galm
*
* Usage: implements methods defined in Syntax.h
*
******************************************************************************/
//TODO:
// when non terminal symbols accepted
// print out token and lexeme
#include "Lexer.h"
#include "Syntax.h"
#include "Pair.h"
#include "Helpers.h"
#include "globals.h"
#include "OCGenerator.h"
#include <iostream>
#include <fstream>
int line_count = 1;
/* Writes to results file. Probably could be implemented better if time permits */
void printHelper::write(std::string message) {
std::cout << "Printing to " << this->filename << "\n\n";
if (!message.empty()) {
std::fstream fileWriter;
fileWriter.open(this->filename, std::ios::out | std::ios::app);
fileWriter << message;
fileWriter.close();
}
}
void generateInstruction(std::string inst, printHelper printer) {
static std::string filename = "object-code.txt";
printer.filename = filename;
return;
}
/* Prints out which line an error occurred on, if any */
void retError() {
std::cout << "\n\n\nError on line: " << line_count << std::endl;
}
/* Gets token at the top of the list */
std::string getCurrentToken(std::list<Pair>& lexemes) {
if (lexemes.size() == 0) return "";
std::string token = lexemes.front().getToken();
while (token == "\\n" || token == "\\t") {
if (token == "\\n") line_count++;
lexemes.pop_front();
token = lexemes.front().getToken();
}
token = lexemes.front().getToken();
std::string tokenType = lexemes.front().getType();
//printer.write("Token: " + temp.getType() + "\t Lexeme: " + temp.getToken() + "\n");
lexemes.pop_front();
return token;
}
/* Gets the token+type pair at the top of the list */
Pair getPair(std::list<Pair> lexemes) {
if (lexemes.size() == 0) return Pair("", "");
std::string token = lexemes.front().getToken();
while (token == "\\n" || token == "\\t") {
lexemes.pop_front();
token = lexemes.front().getToken();
}
token = lexemes.front().getToken();
std::string type = lexemes.front().getType();
lexemes.pop_front();
return Pair(token, type);
}
/* Shows front of the lexemes list, used for debugging */
void showTop(std::string fn, std::list<Pair>& lexemes) {
std::cout << fn << " " << lexemes.front().getToken() << std::endl;
}
bool functionA(std::list<Pair> lexemes, printHelper printer) {
printer.write("<Rat17F>\n");
std::string token;
Pair temp = getPair(lexemes);
if (printer.print) printer.write("A-> B %% CD\n");
std::cout << "test";
if (functionB(lexemes, printer)) {
token = getCurrentToken(lexemes);
if (token == "%%") {
printer.write("Token: " + temp.getType() + "\n");
printer.write("Lexeme: " + temp.getToken() + "\n");
if (functionC(lexemes, printer)) {
if (functionD(lexemes, printer)) {
std::cout << "\n\nCorrectly parsed!\n";
}
else { retError(); return false; }
}
else { retError(); return false; }
}
else {
lexemes.push_front(temp);
retError(); return false;
}
}
else { retError(); return false; }
return true;
}
bool functionB(std::list<Pair>& lexemes, printHelper printer) {
if (printer.print) printer.write("B-> E | E'\n");
return (functionE(lexemes, printer) || functionEprime(printer));
}
bool functionE(std::list<Pair>& lexemes, printHelper printer) {
if (printer.print) printer.write("E-> F | FE \n");
if (functionF(lexemes, printer)) {
if (functionE2(lexemes, printer)) return true;
else return true;
}
else return false;
}
bool functionE2(std::list<Pair>& lexemes, printHelper printer) {
if (printer.print) printer.write("E2 -> E' | E");
return (functionE(lexemes, printer) || functionEprime(printer));
}
bool functionF(std::list<Pair>& lexemes, printHelper printer) {
if (printer.print) printer.write("F-> @ G (H) C I\n");
Pair temp = getPair(lexemes);
std::string token = getCurrentToken(lexemes);
if (token == "@") {
printer.write("Token: " + temp.getType() + "\t Lexeme: "
+ temp.getToken() + "\n");
if (functionG(lexemes, printer)) {
temp = getPair(lexemes);
token = getCurrentToken(lexemes);
if (token == "(") {
printer.write("Token: " + temp.getType() + "\t Lexeme: "
+ temp.getToken() + "\n");
if (functionH(lexemes, printer)) {
temp = getPair(lexemes);
token = getCurrentToken(lexemes);
if (token == ")") {
printer.write("Token: " + temp.getType() + "\t Lexeme: " + temp.getToken() + "\n");
if (functionC(lexemes, printer)) {
return functionI(lexemes, printer);
}
}
else {
lexemes.push_front(temp);
}
}
}
else {
lexemes.push_front(temp);
}
}
}
else {
lexemes.push_front(temp);
}
return false;
}
bool functionH(std::list<Pair>& lexemes, printHelper printer) {
if (printer.print) printer.write("H-> J | E' \n");
if (functionJ(lexemes, printer) || functionEprime(printer)) {
return true;
}
else return false;
}
bool functionJ(std::list<Pair>& lexemes, printHelper printer) {
if (printer.print) printer.write("J-> K | K, J \n");
if (functionK(lexemes, printer)) {
Pair temp = getPair(lexemes);
std::string token = getCurrentToken(lexemes);
if (token == ",") {
printer.write("Token: " + temp.getType() + "\t Lexeme: " + temp.getToken() + "\n");
if (functionJ(lexemes, printer)) { return true; }
}
else {
lexemes.push_front(temp);
return true;
}
}
return false;
}
bool functionK(std::list<Pair>& lexemes, printHelper printer) {
if (printer.print) printer.write("K-> L:M\n");
Pair temp = getPair(lexemes);
if (functionL(lexemes, printer)) {
std::string token = getCurrentToken(lexemes);
if (token == ":") {
printer.write("Token: " + temp.getType() + "\t Lexeme: " + temp.getToken() + "\n");
if (functionM(lexemes, printer)) {
return true;
}
else return false;
}
else {
lexemes.push_front(temp);
return false;
}
return true;
}
else {
return false;
}
}
bool functionM(std::list<Pair>& lexemes, printHelper printer) {
if (printer.print) printer.write("M-> integer | boolean | floating\n");
Pair temp = getPair(lexemes);
std::string token = getCurrentToken(lexemes);
if ((token == "integer")
|| (token == "boolean")
|| (token == "real")) {
printer.write("Token: " + temp.getType() + "\t Lexeme: " + temp.getToken() + "\n");
return true;
}
else {
lexemes.push_front(temp);
return false;
}
}
bool functionI(std::list<Pair>&lexemes, printHelper printer) {
if (printer.print) printer.write("I->{ D }\n");
Pair temp = getPair(lexemes);
std::string token = getCurrentToken(lexemes);
if (token == "{") {
printer.write("Token: " + temp.getType() + "\t Lexeme: " + temp.getToken() + "\n");
if (functionD(lexemes, printer)) {
temp = getPair(lexemes);
token = getCurrentToken(lexemes);
if (token == "}") {
printer.write("Token: " + temp.getType() + "\t Lexeme: " + temp.getToken() + "\n");
return true;
}
else {
lexemes.push_front(temp);
}
}
else {
return false;
}
}
else {
lexemes.push_front(temp);
return false;
}
}
bool functionC(std::list<Pair>& lexemes, printHelper printer) {
if (printer.print) printer.write("C-> N | E\n");
if (functionN(lexemes, printer) || functionEprime(printer)) {
return true;
}
}
bool functionN(std::list<Pair>& lexemes, printHelper printer) {
if (printer.print) printer.write("N-> O\n");
if (functionO(lexemes, printer)) {
Pair temp = getPair(lexemes);
std::string token = getCurrentToken(lexemes);
if (token == ";") {
printer.write("Token: " + temp.getType() + "\t Lexeme: " + temp.getToken() + "\n");
if (functionN2(lexemes, printer)) {
return true;
}
}
else {
lexemes.push_front(temp);
return false;
}
}
return false;
}
bool functionN2(std::list<Pair>& lexmes, printHelper printer) {
if (printer.print) printer.write("N | E'\n");
if (functionN(lexmes, printer) || functionEprime(printer)) {
return true;
}
}
bool functionO(std::list<Pair>&lexemes, printHelper printer) {
if (printer.print) printer.write("0-> ML\n");
if (functionM(lexemes, printer)) {
if (functionL(lexemes, printer)) {
return true;
}
}
else {
return false;
}
}
bool functionL(std::list<Pair>& lexemes, printHelper printer) {
if (printer.print) printer.write("L->G | G, L\n");
std::string token;
if (functionG(lexemes, printer)) {
Pair temp = getPair(lexemes);
token = getCurrentToken(lexemes);
if (token == ",") {
printer.write("Token: " + temp.getType() + "\t Lexeme: " + temp.getToken() + "\n");
if (functionL(lexemes, printer)) { return true; }
else {
return false;
}
}
else {
lexemes.push_front(temp);
return true;
}
}
else {
return false;
}
return true;
}
bool functionD(std::list<Pair>& lexemes, printHelper printer) {
if (printer.print) printer.write("D-> P D2\n");
if (functionP(lexemes, printer)) {
if (functionD2(lexemes, printer)) {
return true;
}
else return false;
}
else return false;
}
bool functionD2(std::list<Pair>& lexemes, printHelper printer) {
if (printer.print) printer.write("D2-> D | E\n");
if (functionD(lexemes, printer) || functionEprime(printer)) {
return true;
}
}
bool functionP(std::list<Pair>&lexemes, printHelper printer) {
if (printer.print) printer.write("P-> Q | R | S | T | U | V | W\n");
if (functionQ(lexemes, printer)) { return true; }
if (functionR(lexemes, printer)) { return true; }
if (functionS(lexemes, printer)) { return true; }
if (functionT(lexemes, printer)) { return true; }
if (functionU(lexemes, printer)) { return true; }
if (functionV(lexemes, printer)) { return true; }
if (functionW(lexemes, printer)) { return true; }
return false;
}
bool functionQ(std::list<Pair>&lexemes, printHelper printer) {
if (printer.print) printer.write("Q-> { D }\n");
std::string token;
Pair temp = getPair(lexemes);
token = getCurrentToken(lexemes);
if (token == "{") {
printer.write("Token: " + temp.getType() + "\t Lexeme: " + temp.getToken() + "\n");
if (functionD(lexemes, printer)) {
temp = getPair(lexemes);
token = getCurrentToken(lexemes);
if (token == "}") {
printer.write("Token: " + temp.getType() + "\t Lexeme: " + temp.getToken() + "\n");
return true;
}
else {
lexemes.push_front(temp);
return false;
}
}
else {
return false;
}
}
else {
lexemes.push_front(temp);
return false;
}
}
bool functionR(std::list<Pair>&lexemes, printHelper printer) {
if (printer.print) printer.write("R->G := X\n");
std::string token;
Pair temp = getPair(lexemes);
if (functionG(lexemes, printer)) {
token = getCurrentToken(lexemes);
if (token == ":=") {
printer.write("Token: " + temp.getType() + "\t Lexeme: " + temp.getToken() + "\n");
if (functionX(lexemes, printer)) {
temp = getPair(lexemes);
token = getCurrentToken(lexemes);
if (token == ";") {
printer.write("Token: " + temp.getType() + "\t Lexeme: " + temp.getToken() + "\n");
return true;
}
else {
lexemes.push_front(temp);
return false;
}
}
else { return false; }
}
else {
lexemes.push_front(temp);
return false;
}
}
else return false;
}
bool functionS(std::list<Pair>&lexemes, printHelper printer) {
if (printer.print) printer.write("S-> if ( Y ) P S'\n");
std::string token;
Pair temp = getPair(lexemes);
token = getCurrentToken(lexemes);
if (token == "if") {
printer.write("Token: " + temp.getType() + "\t Lexeme: " + temp.getToken() + "\n");
temp = getPair(lexemes);
token = getCurrentToken(lexemes);
if (token == "(") {
printer.write("Token: " + temp.getType() + "\t Lexeme: " + temp.getToken() + "\n");
if (functionY(lexemes, printer)) {
temp = getPair(lexemes);
token = getCurrentToken(lexemes);
if (token == ")") {
printer.write("Token: " + temp.getType() + "\t Lexeme: " + temp.getToken() + "\n");
if (functionP(lexemes, printer)) {
if (functionSprime(lexemes, printer)) {
return true;
}
}
}
else {
lexemes.push_front(temp);
return false;
}
}
}
else {
lexemes.push_front(temp);
return false;
}
}
else {
lexemes.push_front(temp);
return false;
}
}
bool functionSprime(std::list<Pair>&lexemes, printHelper printer) {
if (printer.print) printer.write("Sprime -> fi | else P fi\n");
Pair temp = getPair(lexemes);
std::string token = getCurrentToken(lexemes);
if (token == "fi") {
printer.write("Token: " + temp.getType() + "\t Lexeme: " + temp.getToken() + "\n");
return true;
}
else if (token == "else") {
printer.write("Token: " + temp.getType() + "\t Lexeme: " + temp.getToken() + "\n");
if (functionP(lexemes, printer)) {
temp = getPair(lexemes);
token = getCurrentToken(lexemes);
if (token == "fi") {
printer.write("Token: " + temp.getType() + "\t Lexeme: " + temp.getToken() + "\n");
return true;
}
else {
lexemes.push_front(temp);
return false;
}
}
}
else {
lexemes.push_front(temp);
return false;
}
return false;
}
bool functionT(std::list<Pair>&lexemes, printHelper printer) {
if (printer.print) printer.write("T-> return T'\n");
std::string token;
Pair temp = getPair(lexemes);
token = getCurrentToken(lexemes);
if (token == "return") {
printer.write("Token: " + temp.getType() + "\t Lexeme: " + temp.getToken() + "\n");
if (functionTprime(lexemes, printer)) {
return true;
}
else return false;
}
else {
lexemes.push_front(temp);
return false;
}
return false;
}
bool functionTprime(std::list<Pair>&lexemes, printHelper printer) {
if (printer.print) printer.write("Tprime-> ; | X;\n");
Pair temp = getPair(lexemes);
if (functionX(lexemes, printer)) {
std::string token = getCurrentToken(lexemes);
if (token == ";") {
printer.write("Token: " + temp.getType() + "\t Lexeme: " + temp.getToken() + "\n");
return true;
}
else {
lexemes.push_front(temp);
return false;
}
}
temp = getPair(lexemes);
std::string token = getCurrentToken(lexemes);
if (token == ";") {
printer.write("Token: " + temp.getType() + "\t Lexeme: " + temp.getToken() + "\n");
return true;
}
else {
lexemes.push_front(temp);
return false;
}
}
bool functionU(std::list<Pair>&lexemes, printHelper printer) {
if (printer.print) printer.write("U-> write ( X );\n");
Pair temp = getPair(lexemes);
std::string token = getCurrentToken(lexemes);
if (token == "write") {
printer.write("Token: " + temp.getType() + "\t Lexeme: " + temp.getToken() + "\n");
temp = getPair(lexemes);
token = getCurrentToken(lexemes);
if (token == "(") {
printer.write("Token: " + temp.getType() + "\t Lexeme: " + temp.getToken() + "\n");
if (functionX(lexemes, printer)) {
temp = getPair(lexemes);
token = getCurrentToken(lexemes);
if (token == ")") {
printer.write("Token: " + temp.getType() + "\t Lexeme: " + temp.getToken() + "\n");
temp = getPair(lexemes);
token = getCurrentToken(lexemes);
if (token == ";") {
printer.write("Token: " + temp.getType() + "\t Lexeme: " + temp.getToken() + "\n");
return true;
}
else {
lexemes.push_front(temp);
return false;
}
}
else {
lexemes.push_front(temp);
return false;
}
}
}
else {
lexemes.push_front(temp);
return false;
}
}
else {
lexemes.push_front(temp);
return false;
}
return false;
}
bool functionV(std::list<Pair>&lexemes, printHelper printer) {
if (printer.print) printer.write("V-> read ( L ); \n");
Pair temp = getPair(lexemes);
std::string token = getCurrentToken(lexemes);
if (token == "read") {
printer.write("Token: " + temp.getType() + "\t Lexeme: " + temp.getToken() + "\n");
temp = getPair(lexemes);
token = getCurrentToken(lexemes);
if (token == "(") {
printer.write("Token: " + temp.getType() + "\t Lexeme: " + temp.getToken() + "\n");
if (functionL(lexemes, printer)) {
temp = getPair(lexemes);
token = getCurrentToken(lexemes);
if (token == ")") {
printer.write("Token: " + temp.getType() + "\t Lexeme: " + temp.getToken() + "\n");
temp = getPair(lexemes);
token = getCurrentToken(lexemes);
if (token == ";") {
printer.write("Token: " + temp.getType() + "\t Lexeme: " + temp.getToken() + "\n");
return true;
}
else {
lexemes.push_front(temp);
return false;
}
}
else {
lexemes.push_front(temp);
return false;
}
}
else return false;
}
else {
lexemes.push_front(temp);
return false;
}
}
else {
lexemes.push_front(temp);
return false;
}
return false;
}
bool functionW(std::list<Pair>&lexemes, printHelper printer) {
if (printer.print) printer.write("W-> while ( Y ) P\n");
Pair temp = getPair(lexemes);
std::string token = getCurrentToken(lexemes);
if (token == "while") {
printer.write("Token: " + temp.getType() + "\t Lexeme: " + temp.getToken() + "\n");
temp = getPair(lexemes);
token = getCurrentToken(lexemes);
if (token == "(") {
printer.write("Token: " + temp.getType() + "\t Lexeme: " + temp.getToken() + "\n");
if (functionY(lexemes, printer)) {
temp = getPair(lexemes);
token = getCurrentToken(lexemes);
if (token == ")") {
printer.write("Token: " + temp.getType() + "\t Lexeme: " + temp.getToken() + "\n");
if (functionP(lexemes, printer)) {
return true;
}
}
else {
lexemes.push_front(temp);
return false;
}
}
}
else {
lexemes.push_front(temp);
return false;
}
}
else {
lexemes.push_front(temp);
return false;
}
return false;
}
bool functionY(std::list<Pair>&lexemes, printHelper printer) {
if (printer.print) printer.write("Y-> X Z X\n");
if (functionX(lexemes, printer)) {
if (functionZ(lexemes, printer)) {
if (functionX(lexemes, printer)) {
return true;
}
else return false;
}
else return false;
}
else return false;
}
bool functionZ(std::list<Pair>&lexemes, printHelper printer) {
if (printer.print) printer.write("Z-> = | /= | > | < | => | <=\n");
Pair temp = getPair(lexemes);
std::string token = getCurrentToken(lexemes);
if ((token == "=") || (token == "/=") || (token == ">")
|| (token == "<") || (token == "=>") || (token == "<=")) {
std::string instr = "EQU"; // default
if(token == ">") instr = "GRT";
if(token == "<") instr = "LES";
instructions.addInstruction(instr, symbolTable.getAddress(token));
printer.write("Token: " + temp.getType() + "\t Lexeme: " + temp.getToken() + "\n");
return true;
}
else {
lexemes.push_front(temp);
return false;
}
}
bool functionX(std::list<Pair>&lexemes, printHelper printer) {
if (printer.print) printer.write("X-> A' | A'X'\n");
if (functionAprime(lexemes, printer)) {
if (functionX2(lexemes, printer)) {
return true;
}
else return false;
}
else return false;
}
bool functionX2(std::list<Pair>& lexemes, printHelper printer) {
if (printer.print) printer.write("X2 --> X' | E'\n");
if (functionXprime(lexemes, printer) || functionEprime(printer)) {
return true;
}
}
bool functionXprime(std::list<Pair>&lexemes, printHelper printer) {
if (printer.print) printer.write("Xprime-> +A'X' | -A'X' | E'\n");
Pair temp = getPair(lexemes);
std::string token = getCurrentToken(lexemes);
if (token == "+") {
printer.write("Token: " + temp.getType() + "\t Lexeme: " + temp.getToken() + "\n");
if (functionAprime(lexemes, printer)) {
if (functionXprime(lexemes, printer)) {
//symbolTable.addEntry(temp);
instructions.addInstruction("ADD", symbolTable.getAddress(token));
return true;
}
else return false;
}
else return false;
}
else if (token == "-") {
printer.write("Token: " + temp.getType() + "\t Lexeme: " + temp.getToken() + "\n");
if (functionAprime(lexemes, printer)) {
if (functionXprime(lexemes, printer)) {
symbolTable.addEntry(temp);
instructions.addInstruction("SUB", symbolTable.getAddress(token));
return true;
}
else return false;
}
else return false;
}
else {
lexemes.push_front(temp);
return functionEprime(printer);
}
}
bool functionAprime(std::list<Pair>&lexemes, printHelper printer) {
if (printer.print) printer.write("A' -> B'A'2\n");
if (functionBprime(lexemes, printer)) {
if (functionAprime2(lexemes, printer)) {
return true;
}
else return false;
}
else return false;
}
bool functionAprime2(std::list<Pair>& lexemes, printHelper printer) {
if (printer.print) printer.write("A'2 --> A2 | E");
if (functionA2(lexemes, printer) || functionEprime(printer)) {
return true;
}
}
bool functionA2(std::list<Pair>&lexemes, printHelper printer) {
if (printer.print) printer.write("A2-> *B'A2 | /B'A2 | E'\n");
Pair temp = getPair(lexemes);
std::string token = getCurrentToken(lexemes);
if (token == "*") {
printer.write("Token: " + temp.getType() + "\t Lexeme: " + temp.getToken() + "\n");
if (functionBprime(lexemes, printer)) {
if (functionA2(lexemes, printer)) {
symbolTable.addEntry(temp);
instructions.addInstruction("MUL", symbolTable.getAddress(token));
return true;
}
else { return false; }
}
else { return false; }
}
else if (token == "/") {
printer.write("Token: " + temp.getType() + "\t Lexeme: " + temp.getToken() + "\n");
if (functionBprime(lexemes, printer)) {
if (functionA2(lexemes, printer)) {
symbolTable.addEntry(temp);
instructions.addInstruction("DIV", symbolTable.getAddress(token));
return true;
}
else { return false; }
}
else { return false; }
}
else {
lexemes.push_front(temp);
return functionEprime(printer);
}
}
bool functionBprime(std::list<Pair>&lexemes, printHelper printer) {
if (printer.print) printer.write("Bprime -> -C' | C'\n");
Pair temp = getPair(lexemes);
std::string token = getCurrentToken(lexemes);
if (token == "-") {
printer.write("Token: " + temp.getType() + "\t Lexeme: " + temp.getToken() + "\n");
if (functionCprime(lexemes, printer)) {
symbolTable.addEntry(temp);
instructions.addInstruction("SUB", symbolTable.getAddress(token));
return true;
}
else { return false; }
}
else {
lexemes.push_front(temp);
return functionCprime(lexemes, printer);
}
}
bool functionCprime(std::list<Pair>&lexemes, printHelper printer) {
if (printer.print) printer.write("Cprime-> G | D' | G[L] | (X) | F' | true | false\n");
Pair temp;
std::string token;
if (functionG(lexemes, printer)) {
temp = getPair(lexemes);
token = getCurrentToken(lexemes);
if (token == "[") {
printer.write("Token: " + temp.getType() + "\t Lexeme: " + temp.getToken() + "\n");
if (functionL(lexemes, printer)) {
temp = getPair(lexemes);
token = getCurrentToken(lexemes);
if (token == "]") {
printer.write("Token: " + temp.getType() + "\t Lexeme: " + temp.getToken() + "\n");
return true;
}
else {
lexemes.push_front(temp);
}
}
}
else {
lexemes.push_front(temp);
}
return true;
}
if (functionDprime(lexemes, printer)) {
return true;
}
if (functionFprime(lexemes, printer)) {
return true;
}
temp = getPair(lexemes);
token = getCurrentToken(lexemes);
if (token == "(") {
printer.write("Token: " + temp.getType() + "\t Lexeme: " + temp.getToken() + "\n");
if (functionX(lexemes, printer)) {
temp = getPair(lexemes);
token = getCurrentToken(lexemes);
if (token == ")") {
printer.write("Token: " + temp.getType() + "\t Lexeme: " + temp.getToken() + "\n");
return true;
}
else {
lexemes.push_front(temp);
return false;
}
}
}
else {
lexemes.push_front(temp);
return false;
}
if ((token == "true") || (token == "false")) {
printer.write("Token: " + temp.getType() + "\t Lexeme: " + temp.getToken() + "\n");
return true;
}
else {
lexemes.push_front(temp);
return false;
}
}
bool functionEprime(printHelper printer) {
if (printer.print) printer.write("Eprime -> epsilon\n");
return true;
}
bool functionDprime(std::list<Pair>& lexemes, printHelper printer) {
if (printer.print) printer.write("Dprime -> integer\n");
Pair temp = getPair(lexemes);
std::string token = getCurrentToken(lexemes);
std::string type = temp.getType();
if (type == "integer") {
symbolTable.addEntry(temp);
instructions.addInstruction("PUSHM", symbolTable.getAddress(token));
return true;
}
else {
lexemes.push_front(temp);
return false;
}
}
bool functionFprime(std::list<Pair>& lexemes, printHelper printer) {
if (printer.print) printer.write("Fprime-> real\n");
Pair temp = getPair(lexemes);
std::string token = getCurrentToken(lexemes);
std::string type = temp.getType();
if (type == "real") {
symbolTable.addEntry(temp);
instructions.addInstruction("PUSHI", symbolTable.getAddress(token));
return true;
}
else {
lexemes.push_front(temp);
return false;
}
return true;
}
/* Returns true if the current token is an identifier */
bool functionG(std::list<Pair>& lexemes, printHelper printer) {
if (printer.print) printer.write("Gprime-> identifier\n");
Pair temp = getPair(lexemes);
std::string token = getCurrentToken(lexemes);
std::string currType = temp.getType();
if (currType == "identifier") {
symbolTable.addEntry(temp);
instructions.addInstruction("POPM", symbolTable.getAddress(token));
return true;
}
else {
lexemes.push_front(temp);
return false;
}
}
| true |
75a7c7c3170f31cad0f2ca9b3f1fa48cb47e113f | C++ | akalinow/TPCReco | /MonteCarlo/UtilsMC/include/TPCReco/ObjectRegistrator.h | UTF-8 | 3,101 | 3.234375 | 3 | [] | no_license | #ifndef TPCSOFT_OBJECTREGISTRATOR_H
#define TPCSOFT_OBJECTREGISTRATOR_H
/**
\file
Automatic registration of objects
\author Lukas Nellen
\version $Id$
\date 12 Mar 2004
Modified by Piotr.Podlaski@fuw.edu.pl
01.2023
*/
#include "ObjectFactory.h"
namespace utl {
/**
\class StandardCreator ObjectRegistrator.h "utl/ObjectRegistrator.h"
\brief Class for the automatic creation of an object.
This class provide the creator function for a class that provides
a \c Create functions to create itself.
*/
template<class ObjectType, class ObjectFactory>
class StandardCreator {
public:
static typename ObjectFactory::CreatorType GetCreator() { return ObjectType::Create; }
};
/**
\class ObjectRegistrator ObjectRegistrator.h "utl/ObjectRegistrator.h"
\brief Class for the automatic registration of an object.
This class can be used as a mix-in with private inheritance or by
instantiating it in a (private) member variable.
The object is registerd in an ObjectFactory of the appropriate type.
For a class to be registrable, it has to provide the following static
function:
* \c GetRegisteredId() to return the identifier under which the
type is registered in the \c ObjectFactory.
When using the default \c CPolicy, the class also has to provide
a static \c Create() function that creates the class with the
default constructor.
*/
template<class ObjectType,
class ObjFactoryType,
class CreatorPolicy = StandardCreator<ObjectType, ObjFactoryType> >
class ObjectRegistrator {
public:
/// The type of the ObjectFactory we register with
typedef ObjFactoryType ObjectFactoryType;
typedef typename ObjFactoryType::ObjectPtrType ObjectPtrType;
// The default constructor is required to force the instantiation
// of the static member variable fgAutoRegistrar whose
// initialization triggers the registration with the factory
ObjectRegistrator() {
if (!fgAutoRegistrar)
fgAutoRegistrar = new ObjectRegistrator(true);
}
private:
// This constructor in needed to avoid recursion during
// initialization of fgAutoRegistrar. The bool argument is ignored
explicit ObjectRegistrator(bool) {}
static
ObjectRegistrator *
AutoRegister() {
ObjectFactoryType::Register(ObjectType::GetRegistrationId(),
CreatorPolicy::GetCreator());
return new ObjectRegistrator(true);
}
static const ObjectRegistrator *fgAutoRegistrar;
}; // ObjectRegistrator
template<class Object, class ObjectFactory, class CreatorPolicy>
const ObjectRegistrator<Object, ObjectFactory, CreatorPolicy> *
ObjectRegistrator<Object, ObjectFactory, CreatorPolicy>::fgAutoRegistrar =
ObjectRegistrator<Object, ObjectFactory, CreatorPolicy>::AutoRegister();
}
#endif //TPCSOFT_OBJECTREGISTRATOR_H
| true |
9da11ff647f1b22771178ecac8ee6dd8bdc82c2c | C++ | NirajRasal/C- | /OPRATOR.CPP | UTF-8 | 281 | 2.75 | 3 | [] | no_license | #include<iostream.h>
#include<conio.h>
int x=79;
class test
{
int count;
public:
void getdata(int x)
{
count=x;
}
void operator +()
{
count=count+2;
}
void display()
{
cout<<"count:"<<count<<"\n";
cout<<"x="<<x;
}
};
void main()
{
test t;
t.getdata(10);
+t;
t.display();
getch();
} | true |
495f6ff74fff7a71e7f2bf4446fe8379fb2ae056 | C++ | vlhs-beep/SetsumeiDiscord | /setsumei-bot/commands/hellocommand.cpp | UTF-8 | 2,299 | 3.109375 | 3 | [] | no_license | #include "hellocommand.hpp"
HelloCommand::HelloCommand(QDiscord& discord)
:Command(discord)
{
}
void HelloCommand::dispatch(QDiscordMessage message, QStringList args)
{
std::ifstream file("data/txt/firstname.txt"); // Create an input file stream to read from the file named firstname.txt.
if (!file) { // If firstname.txt does not exist.
std::cout << "Error: Can't open the file named firstname.txt\n";
exit(1);
}
if (file.is_open()) // If file firstname.txt it's open.
{
std::string firstname[22]; // Array of 22 strings to hold the first names.
for (int i = 0; i < 22; ++i)
{
file >> firstname[i];
}
std::ifstream file2("data/txt/lastname.txt"); // Create an input file stream to read from the file named lastname.txt.
if (!file2) { // If lastname.txt does not exist.
std::cout << "Error: Can't open the file named lastname.txt\n";
exit(1);
}
if(file2.is_open()) // If file lastname.txt it's open.
{
std::string lastname[22]; // Array of 21 strings to hold the last names.
for (int i = 0; i < 22; ++i)
{
file2 >> lastname[i];
}
srand(time(0)); // Generate random numbers by seeding rand with a starting value, in this case time(0) gives the time in seconds, to be used as seed.
//char gName;
//cout << "Generated Name: " << firstname[rand() % 22] << " " << lastname[rand() % 22] << endl;
std::stringstream buffer;
//buffer << "Hello Im " << firstname[rand() % 22] << " " << lastname[rand() % 22] << endl;
buffer<< "Hello i'm " << firstname[rand() % 22] << " " << lastname[rand() % 22];
//buffer.str();
// QString s now have the random name
//QString s = buffer.str();
QString s = QString::fromStdString(buffer.str());
Q_UNUSED(args);
// Send the message to Discord.
_discord.rest()->sendMessage(s, message.channelId(),false);
}
}
}
QString HelloCommand::commandName()
{
return "hello";
}
QString HelloCommand::helpText()
{
return "Gives your greeting.";
}
QStringList HelloCommand::argumentText()
{
return QStringList();
}
| true |
6fdc8eeed6c169d2b759444267651ab9400d9d98 | C++ | GongZhihui/LearnQT | /Learnqt/reflection.h | GB18030 | 1,900 | 2.78125 | 3 | [
"Apache-2.0"
] | permissive | #pragma once
#include <qstring>
#include <qmetatype>
#include <qobject>
#include <qdebug>
class ReflectionObject : public QObject
{
Q_OBJECT
Q_PROPERTY(int Id READ Id WRITE setId)
Q_PROPERTY(QString Name READ Name WRITE setName)
Q_PROPERTY(QString Address READ Address WRITE setAddress)
Q_PROPERTY(PriorityType Priority READ Priority WRITE setPriority)
Q_ENUMS(PriorityType)
public:
enum PriorityType { High, Low, VeryHigh, VeryLow };
Q_INVOKABLE int Id() { return m_ID; }
Q_INVOKABLE QString Name() { return m_Name; }
Q_INVOKABLE QString Address() { return m_Address; }
Q_INVOKABLE PriorityType Priority() const { return m_Priority; }
Q_INVOKABLE void setId(const int& id) { m_ID = id; }
Q_INVOKABLE void setName(const QString& name) { m_Name = name; }
Q_INVOKABLE void setAddress(const QString& address) { m_Address = address; }
Q_INVOKABLE void setPriority(PriorityType priority) { m_Priority = priority; }
private:
int m_ID;
QString m_Name;
QString m_Address;
PriorityType m_Priority;
};
//1 .̳ QObject
class TestObject : public QObject
{
Q_OBJECT // 2.Q_OBJECT
Q_PROPERTY(QString text READ text WRITE setText NOTIFY textChange) //3. Q_PROPERTY עԱ
Q_PROPERTY(QString text MEMBER m_text NOTIFY textChange) //4. עijԱܹӦԶsignals textChange
public:
TestObject(QObject* parent = nullptr);
~TestObject();
void init();
//------
Q_INVOKABLE QString text(); //5.עijԱ
Q_INVOKABLE void setText(const QString& strText); //5.עijԱ
QString m_text; //ijԱ
signals:
void textChange(); //Զsignals
public slots:
void textslot() { qDebug() << "textslot"; } //ԶsignalsӦIJۺ
};
void test_testobject();
void test_ReflectionObject(); | true |
686d4a3634fbcd08e2b7cf6317bd2f8b656613d3 | C++ | HandongProblemSolvers/Problem-Solving | /problems/DFS and BFS/BOJ 9205/박하윤.cpp | UTF-8 | 1,253 | 2.984375 | 3 | [] | no_license | // 9205
#include<iostream>
#include<vector>
using namespace std;
int t = 0, n = 0;
vector<pair<int, int> > v;
vector<vector<int> > map;
int abs(int n){
return ((n < 0) ? -n : n); //절댓값
}
bool distance(int x1, int y1, int x2, int y2){
return ((abs(x1 - x2) + abs(y1 - y2)) <= 1000 ? true : false); // 1000 이상 or 이하?
}
int main(void){
cin >> t; // case 갯수
while (t--){
cin >> n; // 편의점 갯수
v = vector<pair<int, int> > (n + 2, home_pair(0, 0));
map = vector<vector<int> >(n + 2, vector<int>(n + 2, 0)); // ?
for (int i = 0; i < n + 2; i++)
cin >> v[i].first >> v[i].second; // 좌표 입력
for (int i = 0; i < n + 2; i++)
for (int j = 0; j < n + 2; j++)
if (distance(v[i].first, v[i].second, v[j].first, v[j].second))
map[i][j] = map[j][i] = 1;
for (int k = 0; k < n + 2; k++)
for (int i = 0; i < n + 1; i++)
for (int j = 1; j < n + 2; j++)
if (map[i][k] && map[k][j])
map[i][j] = map[j][i] = 1;
cout << (map[0][n + 1] ? "happy" : "sad") << endl;
}
return 0;
} | true |
e0d34ed1af18417fc26704411ceaaf3a3b9a143d | C++ | programmingo/Guide_to_Scientific_Computing_in_CPP | /ch4/examples/newdel.cpp | UTF-8 | 361 | 3.46875 | 3 | [] | no_license | /*
* Example
* Dynamically allocated memory for arrays
*/
#include<iostream>
using namespace std;
int main(int argc, char* argv[])
{
double *x;
double *y;
x= new double [10];
y= new double [10];
for (int i=1; i<=10; i++)
{
x[i]= (double)(i);
y[i]= 2.0*x[i];
cout << x[i] << " " << y[i] << endl;
}
delete [] x;
delete [] y;
return 0;
}
| true |
f14449dd9b1c92f1fe74a16c0d39245bf2444b4b | C++ | wpilibsuite/allwpilib | /wpilibc/src/main/native/include/frc/simulation/DCMotorSim.h | UTF-8 | 2,849 | 2.640625 | 3 | [
"BSD-3-Clause"
] | permissive | // Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
#pragma once
#include <units/angle.h>
#include <units/angular_velocity.h>
#include <units/moment_of_inertia.h>
#include "frc/simulation/LinearSystemSim.h"
#include "frc/system/LinearSystem.h"
#include "frc/system/plant/DCMotor.h"
namespace frc::sim {
/**
* Represents a simulated DC motor mechanism.
*/
class DCMotorSim : public LinearSystemSim<2, 1, 2> {
public:
/**
* Creates a simulated DC motor mechanism.
*
* @param plant The linear system representing the DC motor. This
* system can be created with
* LinearSystemId::DCMotorSystem().
* @param gearbox The type of and number of motors in the DC motor
* gearbox.
* @param gearing The gearing of the DC motor (numbers greater than
* 1 represent reductions).
* @param measurementStdDevs The standard deviation of the measurement noise.
*/
DCMotorSim(const LinearSystem<2, 1, 2>& plant, const DCMotor& gearbox,
double gearing,
const std::array<double, 2>& measurementStdDevs = {0.0, 0.0});
/**
* Creates a simulated DC motor mechanism.
*
* @param gearbox The type of and number of motors in the DC motor
* gearbox.
* @param gearing The gearing of the DC motor (numbers greater than
* 1 represent reductions).
* @param moi The moment of inertia of the DC motor.
* @param measurementStdDevs The standard deviation of the measurement noise.
*/
DCMotorSim(const DCMotor& gearbox, double gearing,
units::kilogram_square_meter_t moi,
const std::array<double, 2>& measurementStdDevs = {0.0, 0.0});
using LinearSystemSim::SetState;
/**
* Sets the state of the DC motor.
*
* @param angularPosition The new position
* @param angularVelocity The new velocity
*/
void SetState(units::radian_t angularPosition,
units::radians_per_second_t angularVelocity);
/**
* Returns the DC motor position.
*
* @return The DC motor position.
*/
units::radian_t GetAngularPosition() const;
/**
* Returns the DC motor velocity.
*
* @return The DC motor velocity.
*/
units::radians_per_second_t GetAngularVelocity() const;
/**
* Returns the DC motor current draw.
*
* @return The DC motor current draw.
*/
units::ampere_t GetCurrentDraw() const override;
/**
* Sets the input voltage for the DC motor.
*
* @param voltage The input voltage.
*/
void SetInputVoltage(units::volt_t voltage);
private:
DCMotor m_gearbox;
double m_gearing;
};
} // namespace frc::sim
| true |
cd67ce53a9840227df15655d348372852dde9e2c | C++ | rooooooooob/ggj14 | /src/ggj14/ColourChanger.cpp | UTF-8 | 840 | 2.578125 | 3 | [] | no_license | #include "ggj14/ColourChanger.hpp"
#include "jam-engine/Utility/Math.hpp"
#include "ggj14/Level.hpp"
namespace ggj14
{
const float COLOUR_CHANGE_RATE = 2;
ColourChanger::ColourChanger(Level *level, Colour colour)
:level(level)
,colour(colour)
,active(0)
{
}
void ColourChanger::update()
{
if (colour != Colour::White)
{
if (level->getActiveColour() != colour)
{
if (active > 0.f)
active -= COLOUR_CHANGE_RATE;
else
active = 0.f;
}
else
{
if (active < 255.f)
active += COLOUR_CHANGE_RATE;
else
active = 255.f;
}
}
je::limit(active, 0.f, 255.f);
}
bool ColourChanger::isActive() const
{
return colour == Colour::White || active > 0.3f;
}
sf::Color ColourChanger::getSFColor() const
{
sf::Color col = sfColours[colour];
if (colour != Colour::White)
col.a = active;
return col;
}
}
| true |
e7fbaab00cbfd5de409286fd76ac5fc69562a350 | C++ | RoseLeBlood/CsOS-i386 | /include/klibc/cxx/ios.hpp | UTF-8 | 2,856 | 2.75 | 3 | [
"MIT"
] | permissive | #ifndef _STD_IOS_HPP_
#define _STD_IOS_HPP_
#include <cxx/common.hpp>
#include <cxx/utility.hpp>
#include <cxx/string.hpp>
#include <cxx/streambuf.hpp>
extern "C"
{
#include <stdio.h>
}
namespace std
{
template<typename _char_t, typename _traits_t> class basic_ios
{
public:
typedef _char_t char_type;
protected:
basic_streambuf<_char_t, _traits_t>* _m_streambuf;
public:
basic_streambuf<_char_t, _traits_t>* rdbuf()
{
return _m_streambuf;
}
protected:
void init(basic_streambuf<_char_t, _traits_t>* _streambuf)
{
_m_streambuf = _streambuf;
}
};
template<typename _char_t, typename _traits_t> class basic_ostream;
typedef basic_ostream<char, char> ostream;
template<typename _char_t, typename _traits_t> class basic_ostream : virtual public basic_ios<_char_t, _traits_t>
{
public:
typedef char char_type;
typedef basic_ostream<_char_t, _traits_t> _current_ostream_t;
explicit basic_ostream(basic_streambuf<_char_t, _traits_t>* streambuf)
{
this->init(streambuf);
}
_current_ostream_t& put(char_type c)
{
if(this->rdbuf())
{
this->rdbuf()->sputc(c);
}
return *this;
}
_current_ostream_t& write(const char_type* str, streamsize size)
{
if(this->rdbuf())
{
this->rdbuf()->sputn(str, size);
}
return *this;
}
_current_ostream_t& flush()
{
if(this->rdbuf())
{
this->rdbuf()->pubsync();
}
return *this;
}
_current_ostream_t& operator<<(unsigned int number)
{
char str[256];
sprintf(str, "%u", number);
write(str, strlen(str));
delete str;
return *this;
}
_current_ostream_t& operator<<(signed int number)
{
char str[256];
sprintf(str, "%d", number);
write(str, strlen(str));
delete str;
return *this;
}
_current_ostream_t& operator<< (_current_ostream_t& (*pf)(_current_ostream_t&))
{
return pf(*this);
}
};
ostream& operator<< (ostream& out, const char* s);
template<typename _char_t, typename _traits_t>
basic_ostream<_char_t, _traits_t>& endl(basic_ostream<_char_t, _traits_t>& out)
{
out.put('\n');
out.flush();
return out;
}
template<typename _char_t, typename _traits_t>
basic_ostream<_char_t, _traits_t>& ends(basic_ostream<_char_t, _traits_t>& out)
{
out.put('\0');
out.flush();
return out;
}
}
#endif | true |
98a81c6246de613b7c0b166a5ec93a03e6785766 | C++ | amits91/coursera_algo_analysis1 | /assignment3/main.cpp | UTF-8 | 6,273 | 2.984375 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include <stdint.h>
#include <errno.h>
#include <list>
#include <vector>
#include <map>
#include <time.h>
#include <algorithm>
using namespace std;
int sz = 0;
int m = 0;
typedef vector<int> vertexT;
typedef vector<vertexT> graphT;
graphT oG;
#define VECTOR_ITERATE( iter, l ) \
for (std::vector<int>::iterator (iter) = (l)->begin(); \
(iter) != (l)->end(); \
++(iter))
#define GRAPH_ITERATE( iter, l ) \
for (std::vector<vertexT>::iterator (iter) = (l)->begin(); \
(iter) != (l)->end(); \
++(iter))
#define EDGE_ITERATE( iter, l ) \
for (std::vector<int>::iterator (iter) = (l)->begin() + 1; \
(iter) != (l)->end(); \
++(iter))
static void parse(char* file)
{
char *line = NULL;
size_t len = 0;
ssize_t read;
FILE* f = fopen(file, "r");
int n;
if (!f) {
printf("Error: File: %s not opened\n", file);
exit(EXIT_FAILURE);
}
while ((read = getline(&line, &len, f)) != -1) {
char *endptr, *str;
long val;
bool first = true;
int node = -1;
str = line;
//printf("\nP: ");
while( 1 ) {
errno = 0; /* To distinguish success/failure after call */
val = strtol(str, &endptr, 10);
if( errno ) exit(EXIT_FAILURE);
if( !str ) break;
if( str == endptr ) break;
str = endptr;
if( first ) {
first = false;
node = (int)val;
oG[node].push_back(node);
} else {
int v = (int)val;
oG[node].push_back(v);
++m;
}
//printf(" %ld", val);
}
//printf("\nL:\t");
//printf("%s", line);
}
free(line);
fclose(f);
}
void print_vector( vector <int> l )
{
bool first= true;
VECTOR_ITERATE(vi, &l) {
int e = *vi;
if (first) {
first = false;
printf("%d =>", e);
} else {
printf(" %d", e);
}
}
printf("\n");
}
void print_gi( vector<vertexT> g)
{
for (int i = 0; i < g.size(); ++i) {
if (!g[i].empty()) {
print_vector(g[i]);
}
}
printf("\n");
}
int choose_random_num( int n )
{
return (rand() % n);
}
void get_random_edge( graphT &g, int &u, int &v )
{
int ri = choose_random_num( g.size() );
vertexT er = g[ri];
if( er.size() > 0 ) {
u = er[0];
int ei = choose_random_num( (er.size() - 1) ) + 1;
v = er[ei];
}
}
int lookup( map<int, int> *tab, int i)
{
return tab->find(i)->second;
}
/*********************************************************
* Random Contraction Algorithm *
* While there are more than 2 vertices: *
* • pick a remaining edge (u,v) uniformly at random *
* • merge (or “contract” ) u and v into a single vertex *
* • remove self-loops *
* return cut represented by final 2 vertices. *
*********************************************************/
int find_edge( vector<int> &v, int j )
{
for (int i = 1; i < v.size(); ++i) {
if( v[i] == j ) return j;
}
return 0;
}
void merge(graphT &g, map<int, int> *tab, int u, int v)
{
int t = u;
if (u > v) {
t = u;
u = v;
v = t;
}
int ui = lookup(tab,u);
int vi = lookup(tab,v);
// printf("(%d, %d)\n", u, v);
// print_vector(g[ui]);
// print_vector(g[vi]);
for (int i = 1; i < g[ui].size(); ++i) {
if (g[ui][i] == v) {
g[ui][i] = u;
}
}
// printf("changing conns: { \n");
for (int i = 1; i < g[vi].size(); ++i) {
g[ui].push_back(g[vi][i]);
// if (g[vi][i] != u) {
// if (!find_edge(g[ui], g[vi][i])) {
// }
int vvi = lookup(tab,g[vi][i]);
bool refo = false;
// printf("cons of %d => %d => %d \n", v, g[vi][i], vvi);
// print_vector(g[vvi]);
refo = find_edge(g[vvi], u);
// Change references to v from all its connections
for (int j = 1; j < g[vvi].size(); ++j) {
if (g[vvi][j] == v) {
// if (refo) {
// g[vvi][j] = g[vvi].back();
// g[vvi].pop_back();
// } else {
g[vvi][j] = u;
// }
}
}
// print_vector(g[vvi]);
// }
}
// printf(" } \n");
// printf("Newv %d:\n", u );
// print_vector(g[ui]);
// printf("after removing self loops:\n");
#if 1
vertexT nv;
nv.push_back(u);
for (int i = 1; i < g[ui].size(); ++i) {
if (g[ui][i] != u) {
nv.push_back(g[ui][i]);
}
}
g[ui] = nv;
#endif
// print_vector(g[ui]);
g[vi] = g.back();
// printf("changing id of %d to %d\n", g[vi].front(), vi );
(*tab)[g[vi].front()] = vi;
g.pop_back();
}
int rca(graphT &g )
{
graphT lG;;
int cnt = 1;
int n = sz;
map<int, int> tab;
lG.resize(sz);
for (int i = 1; i <= sz; ++i) {
lG[i-1] = g[i];
tab[i] = i - 1;
}
// printf( "Graph\n" );
// print_gi(lG);
while( lG.size() > 2 ) {
// while( m > 2 ) {
int u = -1;
int v = -1;
get_random_edge(lG, u, v);
// printf("(%d, %d)\n", u, v);
merge(lG, &tab, u, v);
// --m;
}
// printf( "Mincut Graph\n" );
// print_gi(lG);
return max(lG[0].size(), lG[1].size()) - 1;
}
int main(int argc, char* argv[])
{
char *file = argv[1];
int minc = 100000000;
sz = atoi(argv[2]);
oG.resize(sz + 1);
printf("File: %s, arr size: %d\n", file, sz);
srand ( time(NULL) ); //initialize the random seed
parse(file);
for( int i = 0; i < sz*sz; ++i) {
int mi = rca(oG);
printf(" mi : %d \t %d\n", mi, minc);
if( mi < minc ) minc = mi;
}
//printf("Original Graph: \n");
//print_gi(oG);
printf(" minc : %d\n", minc);
return 0;
}
| true |
f7e8cd3bd364010c0aba6aad433297f4afefb10f | C++ | anuvazhayil/Algorithms | /LinkedList/linkedListMult.cpp | UTF-8 | 1,996 | 3.609375 | 4 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
struct Node{
int data;
Node *next;
};
Node* create(int val){
Node *newNode = (Node*)malloc(sizeof(Node));
newNode->data = val;
newNode->next = NULL;
return newNode;
}
void insertBeg(Node **head, int val){
Node *newNode = (Node*)malloc(sizeof(Node));
newNode->data = val;
newNode->next = NULL;
if(*head == NULL){
*head = newNode;
return;
}
newNode->next = *head;
*head = newNode;
}
void reverseRec(Node *p, Node **head){
if(p->next == NULL){
*head = p;
return;
}
reverseRec(p->next, head);
p->next->next = p;
p->next = NULL;
}
void multiplyRow(Node *num1, Node *num2, Node*res){
int mult, carry = 0;
while(num2){
mult = num1->data * num2->data + carry + res->data;
int val = mult % 10;
carry = mult / 10;
res->data = val;
num1 = num1->next;
if(!res->next){
res->next = create(0);
}
res = res->next;
}
if(carry){
res->data += carry;
}
}
Node* multiply(Node *head1, Node *head2){
if(!head1 || !head2){
return NULL;
}
Node* res = create(0);
Node* temp = res;
//each row of multiplied part
while(head1){
multiplyRow(head1, head2, temp);
head1 = head1->next;
temp = temp->next;
}
reverseRec(res, &res);
if(res->data == 0 && res->next){
Node* temp = res;
res = res->next;
delete(temp);
}
return res;
}
void print(Node *head){
cout<<"\n";
while(head != NULL){
cout<<head->data<<" ";
head = head->next;
}
cout<<"\n";
}
int main(){
Node* num1 = NULL;
Node* num2 = NULL;
insertBeg(&num1,1);
insertBeg(&num1,2);
insertBeg(&num1,3);
insertBeg(&num2,4);
insertBeg(&num2,5);
insertBeg(&num2,6);
//123 * 456
Node *res = multiply(num1, num2);
print(res);
return 0;
}
| true |
41adb4ab9d9af158ac5480f016293133d3bda716 | C++ | xDuraid/Codeforces | /376B - B. I.O.U..cpp | UTF-8 | 916 | 2.5625 | 3 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
#define IOS ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
int main()
{
IOS
int n = 0, m = 0;
cin >> n >> m;
vector<vector<int>> g(n+1,vector<int>(n+1,0));
int a = 0, b = 0, c = 0;
for(int i = 0; i < m; i++){
cin >> a >> b >> c;
g[a][b] = c;
}
for(int i = 1; i <= n; i++){
for(int j = 1; j <= n; j++){
if(g[i][j] > 0){
for(int k = 1; k <= n; k++){
int t = min(g[j][k],g[i][j]);
g[i][j] -= t;
g[i][k] += t;
g[j][k] -= t;
}
}
}
}
int sum = 0;
for(int i = 1; i <= n; i++){
for(int j = 1; j <= n; j++){
if(i == j)
continue;
sum += g[i][j];
}
}
cout << sum;
return 0;
}
| true |
d5621b25f9403c4893d5504937ff5a74f8425475 | C++ | kinetickansra/algorithms-in-C-Cplusplus-Java-Python-JavaScript | /Algorithms/Implementation/Pattern-Problems/cpp/pattern33.cpp | UTF-8 | 528 | 3.28125 | 3 | [
"MIT"
] | permissive | #include <iostream>
using namespace std;
int main(){
cout<<"Enter n : ";
int n;
cin>>n;
for(int row=1; row<=n; row++){
for(int spaces=1; spaces<=row-1; spaces++){
cout<<" ";
}
cout<<row<<" ";
for(int col=1; col<=n-row+1; col++){
cout<<"* ";
}
cout<<endl;
}
for(int row=n-1; row>=1; row--){
for(int spaces=1; spaces<=row-1; spaces++){
cout<<" ";
}
cout<<row<<" ";
for(int col=1; col<=n-row+1; col++){
cout<<"* ";
}
cout<<endl;
}
}
| true |
c0c1e59610d24dc147a547241f3f6cff724aaa26 | C++ | cccyf/15-466-f20-base1 | /PlayMode.hpp | UTF-8 | 1,010 | 2.515625 | 3 | [
"CC0-1.0"
] | permissive | #include "PPU466.hpp"
#include "Mode.hpp"
#include <glm/glm.hpp>
#include <vector>
#include <deque>
struct PlayMode : Mode {
PlayMode();
virtual ~PlayMode();
//functions called by main loop:
virtual bool handle_event(SDL_Event const &, glm::uvec2 const &window_size) override;
virtual void update(float elapsed) override;
virtual void draw(glm::uvec2 const &drawable_size) override;
void random_target();
void clear_status();
//----- game state -----
//input tracking:
struct Button {
uint8_t downs = 0;
uint8_t pressed = 0;
} left, right, down, up, space;
//some weird background animation:
float background_fade = 0.0f;
//player position:
glm::vec2 player_at = glm::vec2(0.0f);
glm::vec2 target_at = glm::vec2(0.0f);
float target_y = 0.f;
float up_speed = 100.f;
std::vector<float> grid_timestamps;
int grid_row = 10;
int grid_col = 8;
float time_limit = 3.0f;
int target_index = 0;
float show_target = -1.f;
//----- drawing handled by PPU466 -----
PPU466 ppu;
};
| true |
4d3c9ba562657d90ff43fd2c30b5825fdccb170d | C++ | theozornelas/throw-catch | /src/source/stadium.cpp | UTF-8 | 8,015 | 3.078125 | 3 | [] | no_license | #include "stadium.h"
#include <iostream>
#include <QDebug>
/**
* C O N S T R U C T O R & D E S T R U C T O R
*/
/**
* @brief Stadium::Stadium Non-default constructor
* @param id
* @param name
* @param team
* @param address
* @param number
* @param capacity
* @param surf
* @param league
*/
Stadium::Stadium() {
}
Stadium::Stadium(int id, QString name,
QString team, QString street, QString city,
QString state, QString zipCode,
QString number, QString date, unsigned int capacity,
QString surf, QString league, QString typo, double revenue)
{
stadiumID = id;
stadiumName = name;
teamName = team;
// Sets up address
stadiumAddress.streetAddress = street + '\n';
stadiumAddress.city = city;
stadiumAddress.state = state;
stadiumAddress.zipCode = zipCode;
boxOfficeNumber = number;
dateOpened = date;
seatingCapacity = capacity;
surface = surf;
leagueType = league;
typology = typo;
totalRevenue = revenue;
}
/**
* @brief Stadium::~Stadium Destructor
*/
Stadium::~Stadium() {
seatingCapacity = 0;
boxOfficeNumber.clear();
leagueType.clear();
stadiumName.clear();
teamName.clear();
surface.clear();
}
/**
* A C C E S S O R S
*/
/**
* @brief getStadiumID id is based off it's id in database table.
* @return an unsigned int stadium id
*/
unsigned int Stadium::getStadiumID() const {
return stadiumID;
}
/**
* @brief Stadium::getStadiumName
* @return a QString stadium name
*/
QString Stadium::getStadiumName() const {
return stadiumName;
}
/**
* @brief Stadium::getTeamName
* @return a QString team name
*/
QString Stadium::getTeamName() const {
return teamName;
}
/**
* @brief Stadium::getAddress returns address in qstring form
* ex: 12345 streetName,
* cityName, ST zipCode
* @return a QString address
*/
Address Stadium::getAddress() const {
return stadiumAddress;
}
/**
* @brief getBoxOfficeNumber returns box office number in qstring form
* @return a QString box office number
*/
QString Stadium::getBoxOfficeNumber() const {
return boxOfficeNumber;
}
/**
* @brief Stadium::getDateOpened returns date opened in qstring form
* @return a QString date openeed
*/
QString Stadium::getDateOpened() const {
return dateOpened;
}
/**
* @brief Stadium::getSeatingCapacity
* @return an unsigned int seating capacity
*/
unsigned int Stadium::getSeatingCapacity() const {
return seatingCapacity;
}
/**
* @brief Stadium::getSurface
* @return a QString surface
*/
QString Stadium::getSurface() const {
return surface;
}
/**
* @brief Stadium::getLeagueType
* @return a QString league type
*/
QString Stadium::getLeagueType() const {
return leagueType;
}
/**
* @brief Stadium::getTypology
* @return a QString typology
*/
QString Stadium::getTypology() const {
return typology;
}
/**
* @brief Stadium::getTotalRevenue
* @return a double totalRevenue
*/
double Stadium::getTotalRevenue() const {
return totalRevenue;
}
/**
* M U T A T O R S
*/
/**
* @brief Stadium::setStadiumName Changes the stadium name to newName
* @param newName
*/
void Stadium::setStadiumName(QString newName) {
stadiumName = newName;
}
/**
* @brief setTeamName Changes the team name to newTeam
* @param newTeam
*/
void Stadium::setTeamName(QString newTeam) {
teamName = newTeam;
}
/**
* @brief Stadium::setAddress Changes the address to new address
* @param address
* @param city
* @param state
* @param zipCode
*/
void Stadium::setAddress(QString streetAddress, QString city,
QString state, QString zipCode) {
stadiumAddress.streetAddress = streetAddress;
stadiumAddress.city = city;
stadiumAddress.state = state;
stadiumAddress.zipCode = zipCode;
}
/**
* @brief Stadium::setAddress Changes the address to new address
* @param newAddress
*/
void Stadium::setAddress(Address newAddress) {
stadiumAddress = newAddress;
}
/**
* @brief Stadium::setBoxOfficeNumber Changes the box office number to newNumber.
* @param newNumber
*/
void Stadium::setBoxOfficeNumber(QString newNumber) {
boxOfficeNumber = newNumber;
}
/**
* @brief Stadium::setDateOpened Changes the date opened to newDate.
* @param newDate
*/
void Stadium::setDateOpened(QString newDate) {
dateOpened = newDate;
}
/**
* @brief Stadium::setSeatingCapacity Changes seating capacity to newCapacity
* @param newCapacity
*/
void Stadium::setSeatingCapacity(unsigned int newCapacity) {
seatingCapacity = newCapacity;
}
/**
* @brief Stadium::setSurface Changes surface to newSurface
* @param newSurface
*/
void Stadium::setSurface(QString newSurface) {
surface = newSurface;
}
/**
* @brief Stadium::setLeagueType Changes league type to newLeagueType
* @param newLeagueType
*/
void Stadium::setLeagueType(QString newLeagueType) {
leagueType = newLeagueType;
}
/**
* @brief Stadium::setTypology Changes typology to typo
* @param typo
*/
void Stadium::setTypology(QString typo) {
typology = typo;
}
/**
* @brief returns this stadium as a JSON object
*/
QJsonObject Stadium::toJSON() {
// Create the stadium JSON object with nested Address Object
QJsonObject stadiumJSON;
stadiumJSON["ObjType"] = "stadium";
stadiumJSON["stadiumName"] = this->stadiumName;
stadiumJSON["teamName"] = this->teamName;
// Address Information
stadiumJSON["streetAddress"] = this->stadiumAddress.streetAddress;
stadiumJSON["city"] = this->stadiumAddress.city;
stadiumJSON["state"] = this->stadiumAddress.state;
stadiumJSON["zipCode"] = this->stadiumAddress.zipCode;
stadiumJSON["boxOfficeNumber"] = this->boxOfficeNumber;
stadiumJSON["dateOpened"] = this->dateOpened;
stadiumJSON["seatingCapacity"] = int(this->seatingCapacity);
stadiumJSON["surface"] = this->surface;
stadiumJSON["leagueType"] = this->leagueType;
stadiumJSON["typology"] = this->typology;
return stadiumJSON;
}
/**
* @brief Stadium::setTotalRevenue Changes totalRevenue to revenue
* @param revenue
*/
void Stadium::setTotalRevenue(double revenue) {
totalRevenue = revenue;
}
void Stadium::addToTotalRevenue(double addToRevenue) {
totalRevenue += addToRevenue;
}
/**
* @brief Stadium::addSouvenir Adds a souvenir to the current stadium's list of souvenirs.
* @param name
* @param price
* @param quantity
*/
void Stadium::addSouvenir(Souvenir *newSouvenir) {
souvenirs.push_back(*newSouvenir);
}
/**
* @brief Stadium::removeSouvenir Removes a souvenir from the current stadium's list of souvenirs.
* @param name
*/
void Stadium::removeSouvenir(QString name) {
bool found = false;
int i = 0;
while(!found && i < souvenirs.size()) {
if(name == souvenirs[i].getName()) {
souvenirs.remove(i);
found = true;
}
else {
i++;
}
}
if(i >= souvenirs.size()) {
qDebug() << "Souvenir item was not found.";
}
}
/**
* @brief Gets all the Souvenirs associated with this stadium
* @return vector of Souvenir objects
*/
QVector<Souvenir> Stadium::getSouvenirs() const {
return souvenirs;
}
/**
* @brief Stadium::findSouvenir
* @param name [IN] the name of the Souvenir to find
* @return the Souvenir object with name 'name'
*/
Souvenir* Stadium::findSouvenir(QString name) {
bool found = false;
Souvenir *foundSouvenir = NULL;
int i = 0;
while(!found && i < souvenirs.size()) {
if(name == souvenirs[i].getName()) {
foundSouvenir = &souvenirs[i];
found = true;
}
else {
i++;
}
}
return foundSouvenir;
}
| true |
9125b762d7e71e80ebfd79b2c983ce18dfa4870b | C++ | linuxgnuru/arduino_projects | /old.d/BareMinimum/BareMinimum.ino | UTF-8 | 384 | 2.59375 | 3 | [] | no_license | void setup() {
// put your setup code here, to run once:
pinMode(12, INPUT);
pinMode(11, INPUT);
pinMode(10, OUTPUT);
pinMode(LED_BUILTIN, OUTPUT);
digitalWrite(LED_BUILTIN, LOW);
}
void loop() {
// put your main code here, to run repeatedly:
if (digitalRead(12) == HIGH)
{
digitalWrite(10, HIGH);
}
if (digitalRead(11) == HIGH)
{
digitalWrite(10, LOW);
}
}
| true |
9be7a7bf7da514813453d7103cc9214f8a3947e2 | C++ | MechaniUm/radio | /AccelStepper.h | UTF-8 | 6,849 | 2.78125 | 3 | [] | no_license | #ifndef _ACCELSTEPPER_H_
#define _ACCELSTEPPER_H_
#include <wiringPi.h>
#include <cmath>
#include <iostream>
using namespace std;
class AccelStepper {
public:
AccelStepper(int pin_1, int pin_2, int pin_3, bool en) {
wiringPiSetupGpio();
pinMode(pin_1, OUTPUT);
pinMode(pin_2, OUTPUT);
pinMode(pin_3, OUTPUT);
max_speed = 1.0;
min_pulse_width = 3;
pin[0] = pin_1;
pin[1] = pin_2;
enable_pin = pin_3;
c_min = 1.0;
direction = DIRECTION_CCW;
if (en) {
// enable();
}
setAcceleration(1);
}
void enable() {
digitalWrite(enable_pin, LOW);
}
void disable() {
digitalWrite(enable_pin, HIGH);
}
void setAcceleration(float a) {
if (a == 0.0) {
return;
}
if (a < 0.0) {
a = -a;
}
if (acceleration != a) {
n *= acceleration / a;
c_0 = 0.676 * sqrt(2.0 / a) * 1000000.0;
acceleration = a;
computeNewSpeed();
}
}
void computeNewSpeed() {
long distance_to = distanceToGo();
long steps_to_stop = (long)((speed * speed) / (2.0 * acceleration));
if (distance_to == 0 && steps_to_stop <= 1) {
step_interval = 0;
speed = 0.0;
n = 0;
return;
}
if (distance_to > 0) {
if (n > 0) {
if ((steps_to_stop >= distance_to) || direction == DIRECTION_CCW)
n = -steps_to_stop;
} else if (n < 0) {
if ((steps_to_stop < distance_to) && direction == DIRECTION_CW)
n = -n;
}
} else if (distance_to < 0) {
if (n > 0) {
if ((steps_to_stop >= -distance_to) || direction == DIRECTION_CW)
n = -steps_to_stop;
} else if (n < 0) {
if ((steps_to_stop < -distance_to) && direction == DIRECTION_CCW)
n = -n;
}
}
if (n == 0) {
c_n = c_0;
direction = distance_to > 0 ? DIRECTION_CW : DIRECTION_CCW;
} else {
c_n = c_n - ((2.0 * c_n) / ((4.0 * n) + 1));
c_n = c_n > c_min ? c_n : c_min;
}
n++;
step_interval = c_n;
speed = 1000000.0 / c_n;
if (direction == DIRECTION_CCW) {
speed = -speed;
}
}
long distanceToGo() {
return target_pos - current_pos;
}
void moveTo(long absolute) {
if (target_pos != absolute) {
target_pos = absolute;
computeNewSpeed();
}
}
void move(long relative) {
moveTo(current_pos + relative);
}
bool runSpeed() {
if (!step_interval) {
return false;
}
unsigned long time = micros();
if (labs(time - last_step_time) >= step_interval) {
if (direction == DIRECTION_CW) {
current_pos++;
} else {
current_pos--;
}
doStep();
last_step_time = time;
return true;
}
return false;
}
void doStep() {
setOutputPins(direction ? 0b10 : 0b00);
delayMicroseconds(min_pulse_width);
setOutputPins(direction ? 0b11 : 0b01);
delayMicroseconds(min_pulse_width);
setOutputPins(direction ? 0b10 : 0b00);
}
void setOutputPins(unsigned int mask) {
digitalWrite(pin[0], (mask & (1 << 0)) ? (HIGH ^ pin_inverted[0]) : (LOW ^ pin_inverted[0]));
delayMicroseconds(5);
digitalWrite(pin[1], (mask & (1 << 1)) ? (HIGH ^ pin_inverted[1]) : (LOW ^ pin_inverted[1]));
}
long targetPosition() {
return target_pos;
}
long currentPosition() {
return current_pos;
}
void setCurrentPositionOnly(long pos) {
int offset = pos - current_pos;
current_pos = pos;
moveTo(target_pos + offset);
}
void setCurrentPosition(long pos) {
target_pos = pos;
current_pos = pos;
n = 0;
step_interval = 0;
speed = 0.0;
}
bool run() {
if (runSpeed()) {
computeNewSpeed();
}
return speed != 0.0 || distanceToGo() != 0;
}
void setMaxSpeed(float s) {
if (s < 0.0)
s = -s;
if (max_speed != s) {
max_speed = s;
c_min = 1000000.0 / s;
if (n > 0) {
n = (speed * speed) / (2.0 * acceleration);
computeNewSpeed();
}
}
}
float maxSpeed() {
return max_speed;
}
void setSpeed(float s) {
if (speed == s)
return;
if (s > max_speed) {
s = max_speed;
} else if (s < -max_speed) {
s = -max_speed;
}
if (s == 0.0)
step_interval = 0;
else {
step_interval = fabs(1000000.0 / s);
direction = s > 0 ? DIRECTION_CW : DIRECTION_CCW;
}
speed = s;
}
float currentSpeed() {
return speed;
}
void setMinPulseWidth(unsigned int w) {
min_pulse_width = w;
}
void runToPosition() {
while (run()) {}
}
bool runSpeedToPosition() {
if (target_pos == current_pos) {
return false;
}
if (target_pos > current_pos) {
direction = DIRECTION_CW;
} else {
direction = DIRECTION_CCW;
}
return runSpeed();
}
void runToNewPosition(long pos) {
moveTo(pos);
runToPosition();
}
void stop() {
if (speed != 0.0) {
long steps_to_stop = (speed * speed) / (2.0 * acceleration) + 1;
if (speed > 0) {
move(steps_to_stop);
} else {
move(-steps_to_stop);
}
}
}
bool isRunning() {
return !(speed == 0.0 && target_pos == current_pos);
}
void debugInfo() {
cout << current_pos << ' ' << target_pos << endl;
cout << speed << ' ' << max_speed << endl;
cout << acceleration << endl;
cout << c_0 << ' ' << c_n << ' ' << c_min << endl;
cout << n << endl;
}
private:
typedef enum
{
DIRECTION_CCW = 0, ///< Counter-Clockwise
DIRECTION_CW = 1 ///< Clockwise
} Direction;
Direction direction;
long current_pos, target_pos;
float speed, max_speed;
float acceleration;
unsigned long last_step_time, step_interval;
unsigned int min_pulse_width;
bool enable_inverted;
int enable_pin, pin[2], pin_inverted[2];
long n;
float c_0, c_n, c_min;
};
#endif
| true |
661d948bc26d308c8612c48c4968f69d07f8a29b | C++ | zmsunnyday/Cpp-Primer | /exc10_13.cpp | UTF-8 | 506 | 3.265625 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <algorithm>
#include <vector>
using std::cout;
using std::endl;
using std::vector;
using std::string;
using std::partition;
bool longer5(const string& s)
{
return s.size() >=5;
}
int main()
{
vector<string> words = {"nihao", "haha", "what?", "thanks", "hola"};
auto iterEnd = partition(words.begin(), words.end(), longer5);
for(auto iter = words.cbegin(); iter != iterEnd; iter++)
{
cout << *iter << endl;
}
return 0;
}
| true |
91a0e9b8dfee50cd8e52e1dcdefa8d8ac1b1d6e5 | C++ | szakosevi/polygonRoundness | /Point.h | UTF-8 | 567 | 3.015625 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <string>
#include <math.h>
#include <vector>
#ifndef POINT_H
#define POINT_H
class Point
{
private:
double x,y;
public:
Point(double x = 0.0, double y = 0.0);
Point(const Point &p);
double getX() const;
double getY() const;
void setX(double x);
void setY(double y);
void setXY(double x, double y);
double distance(Point theOther);
friend std::istream& operator>>(std::istream& is, Point& p);
friend std::ostream& operator<<(std::ostream& out, const Point& p);
};
#endif | true |
a2a157d010752c6757df6f393280e5396235c9e4 | C++ | virtyaluk/leetcode | /problems/2083/solution.cpp | UTF-8 | 279 | 2.53125 | 3 | [] | no_license | class Solution {
public:
long long numberOfSubstrings(string s) {
long long ans = 0;
unordered_map<char, int> freq;
for (const char& ch: s) {
freq[ch]++;
ans += freq[ch];
}
return ans;
}
}; | true |
262620773d8f540490a31a896a432b60b0a152af | C++ | xinfushe/lullaby | /src/lullaby/base/serialize.h | UTF-8 | 7,283 | 2.75 | 3 | [
"Apache-2.0"
] | permissive | /*
Copyright 2017 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef LULLABY_BASE_SERIALIZE_H_
#define LULLABY_BASE_SERIALIZE_H_
#include "lullaby/base/detail/serialize_traits.h"
#include "lullaby/util/hash.h"
namespace lull {
// Wraps a Serializer class with functionality that allows it to inspect/visit
// the member variables of objects being serialized.
//
// The Archiver is not meant to be used directly. Instead, you should call the
// global function:
//
// template <typename Serializer, typename Value>
// lull::Serialize(Serializer* serializer, Value* value, HashValue key);
//
// which will wrap the Serializer in the Archiver and start the serialization
// process.
//
// An example will help demonstrate its usage. Given the following classes:
//
// struct BaseClass {
// int base_value;
// template <typename Archive>
// void Serialize(Archive archive) {
// archive(&base_value, Hash("base_value"));
// }
// };
//
// struct ChildClass : BaseClass {
// int child_value;
// template <typename Archive>
// void Serialize(Archive archive) {
// BaseClass::Serialize(archive);
// archive(&child_value, Hash("child_value"));
// }
// };
//
// struct CompositeClass {
// ChildClass child1;
// ChildClass child2;
// std::string value;
// template <typename Archive>
// void Serialize(Archive archive) {
// archive(&child1, Hash("child1"));
// archive(&child2, Hash("child2"));
// archive(&value, Hash("value"));
// }
// };
//
// The following code snippet:
// Serializer s;
// CompositeClass cc;
// Serialize(&s, &cc, Hash("cc"));
//
// Will be the equivalent of the following function calls:
// s.Begin(Hash("cc"));
// s.Begin(Hash("child1"));
// s(&cc.child1.base_value, Hash("base_value"));
// s(&cc.child1.child_value, Hash("child_value"));
// s.End();
// s.Begin(Hash("child2"));
// s(&cc.child2.base_value, Hash("base_value"));
// s(&cc.child2.child_value, Hash("child_value"));
// s.End();
// s(&cc.value, Hash("value"));
// s.End();
//
// What's happening is that, if the Value instance being serialized has a member
// function with the signature:
// template <typename Archive>
// void Serialize(Archive archive);
//
// the Archiver will call that function, passing itself to it. Otherwise, if
// the Value instance has no such function the Archiver will pass the Value
// instance directly to the Serializer.
//
// Additionally, the Archiver will also call Begin()/End() functions on a
// Serializer when visiting/serializing a new Value type that has a Serialize
// member function. Note: the Begin()/End() functions for the Serializer are
// optional. If they are not defined, the Archiver will simply forego calling
// these functions.
//
// It is also expected for the Serializer to provide a function:
// bool IsDestructive() const;
//
// This allows objects that are being serialized to provide special handling
// depending on whether the serialization is a "save" operation (ie. the data
// in the object is being serialized to a wire format) or a "load" operation
// (ie. the data in the object will be overridden by the data from the
// Serializer.)
//
// Most importantly, the Serializer is expected to implement one or more
// functions with the signature:
// template <typename T>
// void operator()(T* ptr, HashValue key);
//
// This is the function that performs the actual serialization. It is strongly
// recommended that specific overloads be implemented for this function to
// handle value types explicitly. For example, while fundamental types (eg.
// bools, floats, ints, etc.) and even mathfu types (eg. vec3, quat, etc.) can
// be serialized by memcpy'ing there values, values-types like pointers and
// STL containers cannot. As such, a purely generic operator() that can
// handle all types will likely result in errors.
template <typename Serializer>
class Archiver {
// This type is used in determining if |U| has a member function with the
// signature: void U::Serialize(Archive<Serializer> archive);
template <typename U>
using IsSerializable = detail::IsSerializable<U, Archiver<Serializer>>;
// This type is used in determining if |U| has a member function with the
// signature: void U::Begin(HashValue);
template <typename U>
using IsScopedSerializer = detail::IsScopedSerializer<U>;
public:
explicit Archiver(Serializer* serializer) : serializer_(serializer) {}
// If |Value| has a Serialize member function, defer the serialization to it.
template <typename Value>
typename std::enable_if<IsSerializable<Value>::value, void>::type operator()(
Value* value, HashValue key) {
Begin(key);
value->Serialize(*this);
End();
}
// If |Value| does not have a Serialize function, allow the Serializer to
// process the object directly.
template <typename Value>
typename std::enable_if<!IsSerializable<Value>::value, void>::type operator()(
Value* value, HashValue key) {
(*serializer_)(value, key);
}
// Returns whether or not the wrapped Serializer is destructive (ie. will
// overwrite the values in the objects being serialized).
bool IsDestructive() const { return serializer_->IsDestructive(); }
private:
// If |Serializer| has a Begin(HashValue) function, call it before a new
// serializable Value type is being serialized.
template <typename U = Serializer>
typename std::enable_if<IsScopedSerializer<U>::value, void>::type Begin(
HashValue key) {
serializer_->Begin(key);
}
// If |Serializer| has a Begin(HashValue) function, call End() after a
// serializable Value type has been serialized.
template <typename U = Serializer>
typename std::enable_if<IsScopedSerializer<U>::value, void>::type End() {
serializer_->End();
}
// If |Serializer| does not have a Begin(HashValue) function, do nothing
// before a new serializable Value type is being serialized.
template <typename U = Serializer>
typename std::enable_if<!IsScopedSerializer<U>::value, void>::type Begin(
HashValue key) {}
// If |Serializer| does not have a Begin(HashValue) function, call End() after
// a serializable Value type has been serialized.
template <typename U = Serializer>
typename std::enable_if<!IsScopedSerializer<U>::value, void>::type End() {}
Serializer* serializer_; // The wrapped Serializer instance.
};
// Serializes the |value| with the |key| using the provided |serializer|.
template <typename Serializer, typename Value>
void Serialize(Serializer* serializer, Value* value, HashValue key) {
Archiver<Serializer> archive(serializer);
archive(value, key);
}
} // namespace lull
#endif // LULLABY_BASE_SERIALIZE_H_
| true |
ad661c41ba624ca228b403685a6856be328a1a0e | C++ | MoamenHomoumz7/problem-solving-with-c- | /sheets/Sheet #1 (Data type - Conditions)/O. Calculator.cpp | UTF-8 | 766 | 3.21875 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int main()
{
string equ; // "15-150" size = 5
cin>>equ;
int indexOpr;
char charOpr;
string num1,num2;
int num1Int,num2Int;
for(int i=0;i<=equ.size()-1;i++){
if(equ[i] == '+' || equ[i] =='-' || equ[i] =='*' || equ[i] == '/'){
indexOpr = i; // 2
charOpr = equ[i]; // -
break;
}
}
num1 = equ.substr(0,indexOpr);
num2 = equ.substr(indexOpr+1);
stringstream ss1;
ss1 << num1;
ss1 >> num1Int;
stringstream ss2;
ss2 << num2;
ss2 >> num2Int;
switch(charOpr){
case '+':
cout<<num1Int + num2Int<<endl;
break;
case '-':
cout<<num1Int - num2Int<<endl;
break;
case '*':
cout<<num1Int * num2Int<<endl;
break;
case '/':
cout<<num1Int / num2Int<<endl;
break;
}
}
| true |
19b59fe752f835e3316e67e42f49b34c3b8da287 | C++ | JulianPinto/Tatsy | /desktopApp/Controls/mlink.cpp | UTF-8 | 2,255 | 3.234375 | 3 | [] | no_license | // included libraries
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <cstdint>
using namespace std;
// define section
#define SPEED_OFFSET 1
#define SPEED_MULTIPLIER 100
// function definitions
void motorMovementMessage(float power);
uint8_t motorSpeedMessageConverter(float speed);
uint16_t calculateCheckSum(uint8_t* message_ptr, uint8_t messageOffset, uint8_t length);
void sendMessage(uint8_t* message, uint8_t messageLength);
bool checkAck(uint8_t* message, uint8_t* ackMessage);
uint8_t createAckMessage(uint8_t* message);
void motorMovementMessage(float power) {
uint8_t * message = new uint8_t[12];
message[0] = 0xA0; // message start
message[1] = 0xA1; // message start
message[2] = 0x00; // message length
message[3] = 0x02; // mesage length
message[4] = 0x11; // poll status
message[5] = motorSpeedMessageConverter(power); // left motor speed
// message[6] = motorSpeedMessageConverter(rightPower); // right motor speed
uint16_t checksum = calculateCheckSum(message, 4, 2);
message[6] = checksum >> 8;
message[7] = checksum;
message[8] = 0xB0;
message[90] = 0xB1;
sendMessage(message, 10);
}
// controller settings will give speeds from -1 to 1
// returns speed offset by SPEED_OFFSET to give new range that is in positive for unsigned (0 to 200)
uint8_t motorSpeedMessageConverter(float speed) {
uint8_t speedConverted = abs(int((speed + SPEED_OFFSET) * SPEED_MULTIPLIER));
return speedConverted;
}
// input message array, message offset to skip message start and length bytes, and message length
// returns yint16_t with checksum value calculated
uint16_t calculateCheckSum(uint8_t* message, uint8_t messageOffset, uint8_t length) {
uint8_t index = 0;
uint16_t checksum = 0;
while (index < length) {
checksum += message[messageOffset + index];
index++;
}
return checksum & ((2 ^ 15) - 1);
}
// input message array and total message length
void sendMessage(uint8_t* message, uint8_t messageLength) {
// send message
}
// checks ack message for correctness
// returns false if ack is not what was expected
bool checkAck(uint8_t* message, uint8_t* ackMessage) {
return false;
}
// input message and creates ack for the message
uint8_t createAckMessage(uint8_t * message) {
return NULL;
} | true |
8d23f05470c8e9940c3b8df160be965221b6b3a1 | C++ | DEVECLOVER/LeetCodeFighting_CPP | /LeetCode400---900/594.最长和谐子序列.cpp | UTF-8 | 2,822 | 3.5 | 4 | [] | no_license | /*
* @lc app=leetcode.cn id=594 lang=cpp
*
* [594] 最长和谐子序列
*/
// @lc code=start
class Solution {
public:
int findLHS(vector<int>& nums) {
//dp 数组即可
int len = nums.size();
int maxlen = 0;
//int 数组初始化问题,一定整明白,这次又是野值
// int dp[len];
// memset(dp,1,sizeof(dp));
//第一遍思路,问题很严重,拘泥于单例 没有认识到 [1 2 3 4]的情况
//太过操之过急,没有沉下心分析思考
// for(int i = 1;i < len;++i)
// {
// for(int j = 0;j < i;++j)
// {
// if(abs(nums[i] - dp[j].first) < 2)
// {
// dp[i] = max(dp[i],dp[j] + 1);
// }
// }
// maxlen = max(maxlen,dp[i].second);
// }
//下标为末尾的 对应的子序列的最小值和子序列的长度
// vector<pair<int,int>> dp;
// for(int i = 0;i < len;++i)
// {
// // dp[i].first = nums[i]; //初始化最小值为自身 ,长度为1 即自身
// // dp[i].second = 1;
// dp.push_back(make_pair(nums[i],1));
// }
//第二遍还是有问题,因为,每个位置都存储再次之前的最小值,而答案可能是以改值为最小值
// for(int i = 1;i < len;++i)
// {
// for(int j = 0;j < i;++j)
// {
// if(abs(nums[i] - dp[j].first) < 2)
// {
// dp[i].first = min(dp[i].first,dp[j].first);
// dp[i].second = max(dp[i].second,dp[j].second + 1);
// }
// }
// maxlen = max(maxlen,dp[i].second);
// }
// return maxlen;
//因为计算的是长度,所以如果拍完序在统计就没有问题了,自己已经忘记了这一点
//如果题目改为求此子序列的左右边界,也还是可以查找到位置的,排序这一点很重要,是自己鬼迷心窍了
sort(nums.begin(),nums.end());
//拍完序后使用滑动窗口便是可以的了,因为left的移动是清晰的了,如果diff 大于了1,后面的
//元素便更是大于了,此时便可以删除掉front元素
//拍完序,能想到下面这样简洁的思路也是很不容易的
int left = 0;
int right = 0;
while(right < len)
{
if(nums[right] - nums[left] > 1)
++left;
if(nums[right] - nums[left] == 1)
maxlen = max(maxlen,right - left + 1);
++right;
}
return maxlen;
}
};
// @lc code=end
| true |
741e94169b6bf1a8140665ed5b76580eaea74ef4 | C++ | carriez0705/leetcode | /122-BestTimetoBuyandSellStockII.cpp | UTF-8 | 682 | 2.953125 | 3 | [] | no_license | class Solution {
public:
int maxProfit(vector<int>& prices) {
if(prices.size()<=1) return 0;
int bot= INT_MAX;
int peak = INT_MIN;
if(prices[1]>=prices[0])
bot = prices[0];
int diff = 0;
for(int i = 1; i<prices.size(); i++){
if(i<prices.size()-1 && prices[i-1]>prices[i] &&prices[i]<=prices[i+1]){
bot = prices[i];
}
else if((i==prices.size()-1&&prices[i]>bot) ||(prices[i-1]<=prices[i]&&prices[i]>prices[i+1])){
peak = prices[i];
diff += peak-bot;
bot = INT_MAX;
}
}
return diff;
}
};
| true |
f87ddd4d10ff4421e61ed9aa575e46e430abd7d2 | C++ | paulrahul/algo | /leetcode/852_mountain_peak.cc | UTF-8 | 818 | 3.171875 | 3 | [] | no_license | class Solution {
public:
int binSearch(vector<int>& arr, int start, int end) {
if (start >= end) {
return start;
}
int mid = (start + end) / 2;
if (mid == 0) {
return binSearch(arr, mid + 1, end);
}
if (mid == arr.size() - 1) {
return binSearch(arr, start, mid - 1);
}
if (arr[mid - 1] < arr[mid] && arr[mid] < arr[mid + 1]) {
return binSearch(arr, mid + 1, end);
} else if (arr[mid - 1] > arr[mid] && arr[mid] > arr[mid + 1]) {
return binSearch(arr, start, mid - 1);
} else {
return mid;
}
}
int peakIndexInMountainArray(vector<int>& arr) {
return binSearch(arr, 0, arr.size() - 1);
}
}; | true |
09aee1c14f08e20904524d0371ecce20ef13ec06 | C++ | shadowplay7/SPOJ | /Test3.cpp | UTF-8 | 323 | 2.796875 | 3 | [] | no_license | #include <iostream>
int main() {
int input, flag = 0, counter = 0;
while (std::cin >> input)
{
if (input == 42 && flag == 1) counter++;
if (input != 42) {
flag = 1;
std::cout << input << std::endl;
}
else {
flag = 0;
std::cout << input << std::endl;
}
if (counter == 3) break;
}
return 0;
} | true |
a2381edaa119e732f19484dc6347fe3829812233 | C++ | trxo/cpp_study_notes | /chapter8-Polymorphism and virtual function/8.3在构造函数和析构函数中调用虚函数/C.cpp | UTF-8 | 254 | 2.78125 | 3 | [
"AFL-3.0"
] | permissive | class C : public B {
public:
C(){}
void func(){
cout << "class C"<<endl;
}
~C()
{
fund();
}
void fund()
{
cout << "destruct C " << endl;
}
};
| true |
0e9fbd242e97717e8d0a7fab13cf53df677024be | C++ | trialley/TAlib | /src/Reactor/EventLoopThreadPool.h | UTF-8 | 1,154 | 2.6875 | 3 | [
"MIT"
] | permissive | #ifndef _EVENTLOOPTHREADPOOL_H
#define _EVENTLOOPTHREADPOOL_H
#include <Logger/ptr_vector.h>
#include <functional>
#include <memory>
#include <vector>
namespace TA {
class EventLoop;
class EventLoopThread;
class EventLoopThreadPool {
public:
//typedef std::function<void(EventLoop*)> ThreadInitCallback;
EventLoopThreadPool(EventLoop* m_baseLoop, const std::string& nameArg, int numThreads = 3);
~EventLoopThreadPool();
void setThreadNum(int numThreads) { m_numThreads = numThreads; }
void start();
// valid after calling start()
/// round-robin
EventLoop* getNextLoop();
/// with the same hash code, it will always return the same EventLoop
EventLoop* getLoopForHash(size_t hashCode);
std::vector<EventLoop*> getAllLoops();
bool started() const { return m_started; }
const std::string& name() const { return _name; }
private:
EventLoop* m_baseLoop;
std::string _name;
bool m_started;
int m_numThreads;
int m_next;
myself::ptr_vector<EventLoopThread> m_threads;
std::vector<EventLoop*> m_loops;
};
} // namespace TA
#endif // TA_NET_EVENTLOOPTHREADPOOL_H
| true |
3eab0437ad787e65ca29bed762a52bd3b6d6c798 | C++ | mrFlatiron/Employment | /src/kernel/ssn_handle.cpp | UTF-8 | 1,395 | 2.9375 | 3 | [] | no_license | #include "ssn_handle.h"
#include <cstring>
#include <QRegExp>
ssn_handle::ssn_handle ()
{
m_is_valid = false;
}
ssn_handle::~ssn_handle ()
{
}
ssn_handle::ssn_handle (const QString &ssn)
{
set_from_string (ssn);
}
void ssn_handle::set_from_string (const QString &ssn)
{
QString ssn_parsed = ssn;
ssn_parsed.remove ('-');
ssn_parsed.remove (' ');
if (QRegExp ("^[0-9]{9}$").indexIn (ssn_parsed) != 0)
{
m_is_valid = false;
return;
}
strcpy (m_first, ssn_parsed.left (3).toUtf8 ().data ());
strcpy (m_second, ssn_parsed.left (5).right (2).toUtf8 ().data ());
strcpy (m_third, ssn_parsed.right (4).toUtf8 ().data ());
m_is_valid = true;
}
bool ssn_handle::is_valid () const
{
return m_is_valid;
}
QString ssn_handle::pretty () const
{
return QString ("%1-%2-%3").arg (m_first, m_second, m_third);
}
QString ssn_handle::simple () const
{
return QString ("%1%2%3").arg (m_first, m_second, m_third);
}
bool ssn_handle::operator < (const ssn_handle &rhs) const
{
if (strcmp (m_first, rhs.m_first) < 0)
return true;
if (strcmp (m_first, rhs.m_first) > 0)
return false;
if (strcmp (m_second, rhs.m_second) < 0)
return true;
if (strcmp (m_second, rhs.m_second) > 0)
return false;
if (strcmp (m_third, rhs.m_third) < 0)
return true;
if (strcmp (m_third, rhs.m_third) > 0)
return false;
return false;
}
| true |
9a4ac72353dd1aa2f16854127205e913aedd3be1 | C++ | koisto/commander | /commander.cpp | UTF-8 | 1,524 | 2.84375 | 3 | [] | no_license | #include "commander.h"
#include "ui_commander.h"
Commander::Commander(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::Commander)
, proc(new QProcess(parent))
{
ui->setupUi(this);
connect(proc, SIGNAL(readyReadStandardOutput()), this, SLOT(write_output()));
connect(proc, SIGNAL(readyReadStandardError()), this, SLOT(write_error()));
connect(proc, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(command_finished(int, QProcess::ExitStatus)));
}
Commander::~Commander()
{
delete ui;
}
void Commander::command_finished(int exitCode, QProcess::ExitStatus exitStatus)
{
ui->textEdit->setTextColor(Qt::black);
if (exitStatus == QProcess::NormalExit)
{
QString txt = "Exit code: ";
txt += QString::number(exitCode);
ui->textEdit->append(txt);
}
else
{
ui->textEdit->append("Command crashed.");
}
ui->pushButton->setEnabled(true);
ui->lineEdit->setEnabled(true);
}
void Commander::write_output()
{
ui->textEdit->setTextColor(Qt::black);
ui->textEdit->insertPlainText(proc->readAllStandardOutput());
}
void Commander::write_error()
{
ui->textEdit->setTextColor(Qt::red);
ui->textEdit->insertPlainText(proc->readAllStandardError());
}
void Commander::on_pushButton_clicked()
{
QString cmd = ui->lineEdit->text();
if (!cmd.isEmpty())
{
ui->textEdit->clear();
ui->pushButton->setEnabled(false);
ui->lineEdit->setEnabled(false);
proc->start(cmd);
}
}
| true |
9573b49d7596c9d97f3577c6f9e9ba4e9cf93894 | C++ | DeshErBojhaa/sports_programming | /lightoj/1054 - Efficient Pseudocode System.cpp | UTF-8 | 2,329 | 2.671875 | 3 | [] | no_license | #include<stdio.h>
#include<iostream>
#include<string.h>
#include<math.h>
using namespace std;
#define range 47000
#define n_prime 4951
typedef long long ll;
bool flag[range];
ll prime[n_prime],T,nn,mm;
int mod=1000000007;
void sieve()
{
int count=1;
prime[0]=2;
for(int i=3; i<range; i+=2)
{
if(!flag[i])
{
prime[count++]=i;
if(i<range/i)
for(int j=i*i; j<range; j+=(i+i))
flag[j]=1;
}
}
return;
}
void extEuclid(ll a, ll b, ll &x, ll &y, ll &gcd)
{
x = 0;
y = 1;
gcd = b;
ll m, n, q, r;
for (ll u=1, v=0; a != 0; gcd=a, a=r)
{
q = gcd / a;
r = gcd % a;
m = x-u*q;
n = y-v*q;
x=u;
y=v;
u=m;
v=n;
}
}
// The result could be negative, if it's required to be positive, then add "m"
int modInv(ll n, ll m)
{
ll x, y, gcd;
extEuclid(n, m, x, y, gcd);
if (gcd == 1) return ((x % m)+m)%m;
return 0;
}
int take_to_pow(ll base,ll topow)
{
ll ret=1;
while(topow>0)
{
if(topow%2)
ret=(ret*base)%mod;
topow/=2;
base=(base*base)%mod;
}
return (int) ret;
}
ll sum_of_divisors(ll base,ll power)
{
ll lob=take_to_pow(base,power+1);
lob--;
ll hor=modInv(base-1,mod);
///cout<<hor<<" *** "<<endl;
ll ret=(lob*hor)%mod;
return ret;
}
ll power_factorize()
{
ll base=sqrt((double)nn);
ll use=nn;
ll ans=1;
for(int i=0; prime[i]<=base; i++)
{
if(use%prime[i]==0)
{
int pour=0;
while(use%prime[i]==0)
{
use/=prime[i];
pour++;
}
ans*=sum_of_divisors(prime[i],pour*mm);
ans%=mod;
}
}
if(use>1)
ans*=sum_of_divisors(use,mm);
ans%=mod;
return ans;
}
int main()
{
sieve();
scanf(" %lld",&T);
for(int tt=1; tt<=T; tt++)
{
scanf(" %lld %lld",&nn,&mm);
ll ans = power_factorize();
if(ans<0) ans=ans+mod;
ans%=mod;
printf("Case %d: %lld\n",tt,ans);
}
return 0;
}
| true |
15a7c805752ecaaa4eb4dfefdece50e2b094bae6 | C++ | shiponcs/My-codes-for-UVa-problems | /11152.cpp | UTF-8 | 604 | 3.046875 | 3 | [] | no_license | //for in-circle area = rs
//for out circle area = a*b*c/4R
#include <iostream>
#include <cstdio>
#include <math.h>
using namespace std;
#define PI acos(-1)
double ans[3];
int main()
{
int a, b, c;
while(scanf("%d %d %d", &a, &b, &c) == 3){
double s = (double)(a + b + c) / 2;
double area = sqrt(s * (s - a) * (s - b) * (s - c));
double r = (a * b * c) / (4 * area);
ans[0] = PI * r *r;
ans[1] = area;
r = area / s;
ans[2] = PI * r * r;
printf("%.4lf %.4lf %.4lf\n", ans[0] - ans[1], ans[1] - ans[2], ans[2]);
}
return 0;
}
| true |
3c9d653ed72a0ea5f78827a5461b6c1541bedec5 | C++ | salj4215/C-College-Work | /Studyguide9.cpp | UTF-8 | 1,131 | 3.8125 | 4 | [] | no_license | #include <stdio.h>
#define NUM 5
//prototype
void displayGrade(int[]);
int calcGrade(int[], int *, float *);
int main()
{
int grades[NUM];
int x, high, low;
float avg;
for(x = 0; x < NUM; x++)
{
printf("Enter a grade: ");
scanf("%d", &grades[x]);
}
displayGrade(grades);
high = calcGrade(grades, &low, &avg);
printf("\nHighest is %d", high);
printf("\nLowest is %d", low);
printf("\nAverage is %.2f", avg);
return 0;
}
void displayGrade(int grades[])
{
int x;
for (x = 0; x < NUM; x++)
{
printf("\n%d --", grades[x]);
if (grades[x] >= 90)
printf("A");
else if (grades[x] >= 80)
printf("B");
else if (grades[x] >= 70)
printf("C");
else if (grades[x] >= 60)
printf("D");
else printf("E");
}
}
int calcGrade(int grades[], int *low, float *average)
{
int high;
int x, sum;
high = grades[0];
*low = grades[0];
for (x = 1; x < NUM; x++)
{
if (high < grades[x])
high = grades[x];
if (*low > grades[x])
*low = grades[x];
sum += grades[x];
}
*average = (float)sum / NUM;
return high;
}
| true |
8f9bb0d96a662733cf43aac6da3d531a9de3b2a4 | C++ | Alaxe/noi2-ranking | /2018/solutions/C/KKK-Sofia/maze.cpp | UTF-8 | 3,145 | 3.0625 | 3 | [] | no_license | #include<iostream>
#include<queue>
struct path
{
int x,y,len;
bool bombed;
bool operator <(path compared)const
{
return this->len>compared.len;
}
};
int m,n;
int bx,by,ex,ey;
int maze[101][101];
bool visited[101][101][2];
std::priority_queue<path>current;
int main()
{
std::cin.tie(nullptr);
std::cout.sync_with_stdio(false);
std::cin>>m>>n;
char a;
for(int y=0; y<m; y++)
{
for(int x=0; x<n; x++)
{
std::cin>>a;
switch(a)
{
case '.':
maze[x][y]=0;
break;
case '#':
maze[x][y]=1;
break;
case 'B':
maze[x][y]=1;
bx=x;
by=y;
break;
case 'E':
maze[x][y]=1;
ex=x;
ey=y;
break;
}
}
}
current.push({bx,by,0,0});
int ans=-1;
while(!current.empty())
{
path cPath=current.top();
//std::cout<<cPath.x<<" "<<cPath.y<<" "<<cPath.len<<" "<<cPath.bombed<<std::endl;
current.pop();
if(visited[cPath.x][cPath.y][cPath.bombed]){
continue;
}
visited[cPath.x][cPath.y][cPath.bombed]=1;
if(cPath.x==ex && cPath.y==ey)
{
ans=cPath.len;
break;
}
if(cPath.x>0 && !visited[cPath.x-1][cPath.y][cPath.bombed])
{
if(maze[cPath.x-1][cPath.y]!=0)
{
current.push({cPath.x-1,cPath.y,cPath.len+1,cPath.bombed});
}
if(maze[cPath.x-1][cPath.y]==0 && !cPath.bombed)
{
current.push({cPath.x-1,cPath.y,cPath.len+3,1});
}
}
if(cPath.y>0 && !visited[cPath.x][cPath.y-1][cPath.bombed])
{
if(maze[cPath.x][cPath.y-1]!=0)
{
current.push({cPath.x,cPath.y-1,cPath.len+1,cPath.bombed});
}
if(maze[cPath.x][cPath.y-1]==0 && !cPath.bombed)
{
current.push({cPath.x,cPath.y-1,cPath.len+3,1});
}
}
if(cPath.x<n-1 && !visited[cPath.x+1][cPath.y][cPath.bombed])
{
if(maze[cPath.x+1][cPath.y]!=0)
{
current.push({cPath.x+1,cPath.y,cPath.len+1,cPath.bombed});
}
if(maze[cPath.x-1][cPath.y]==0 && !cPath.bombed)
{
current.push({cPath.x+1,cPath.y,cPath.len+3,1});
}
}
if(cPath.y<m-1 && !visited[cPath.x][cPath.y+1][cPath.bombed])
{
if(maze[cPath.x][cPath.y+1]!=0)
{
current.push({cPath.x,cPath.y+1,cPath.len+1,cPath.bombed});
}
if(maze[cPath.x][cPath.y+1]==0 && !cPath.bombed)
{
current.push({cPath.x,cPath.y+1,cPath.len+3,1});
}
}
}
std::cout<<ans<<std::endl;
return 0;
}
| true |
a8b6fec9e9a05795d3ee7f8d0ab903c1853d9861 | C++ | xiehaibin/study | /C++/读书笔记/C ++/C++ Primer 5/第 14 章 代码的重用/多重继承.cpp | GB18030 | 943 | 3.3125 | 3 | [] | no_license | #include <iostream>
using namespace std;
class A
{
private :
int ca;
public :
A(int a) : ca(a) {}
virtual void Show(void)
{
cout<<"ca: "<<ca<<endl;
}
virtual~A(){}
};
class B : public A
{
private :
int cb;
public :
B(int b, int a) : A(a)
{
cb = b;
}
virtual void Show(void)
{
cout<<"cb: "<< cb <<endl;
}
virtual~B(){}
};
class C : public A
{
private :
int cc;
public :
C(int c, int a) : A(a)
{
cc = c;
}
virtual void Show(void)
{
cout<<"cc: "<< cc <<endl;
}
virtual~C() {}
};
class D : public B, public C
{
private :
int dd;
public :
D(int a, int b, int c) : B(a, b), C(a, b)
{
dd = c;
}
virtual void Show(void)
{
cout<<"dd: "<< dd <<endl;
}
};
int main(void)
{
D d(1,2,3);
A* pa = NULL;
//pa = &d; // dA ַѡ תȷ ػָѮ
pa = (B*)&d; // BA
pa->Show();
pa = (C*)&d; // CA
pa->Show();
return 0;
} | true |
85d88b387fe3ee82dc710a5d42a94ba8e24da6f8 | C++ | saravsoftnet/Hackerrank_solutions | /Warmup/compare-the-triplets.cpp | UTF-8 | 763 | 2.921875 | 3 | [] | no_license | /*******************************************************
* Copyright (C) 2017 Haotian Wu
*
* This file is the solution to the question:
* https://www.hackerrank.com/challenges/compare-the-triplets
*
* Redistribution and use in source and binary forms are permitted.
*******************************************************/
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
// Just compare!
int main() {
int a[3], b[3];
cin >> a[0] >> a[1] >> a[2] >> b[0] >> b[1] >> b[2];
int ascore = 0, bscore = 0;
for (int i=0; i<3; i++)
if (a[i] > b[i])
ascore++;
else if (a[i] < b[i])
bscore++;
printf("%d %d\n",ascore,bscore);
return 0;
}
| true |
bc61b9811d9adfac8983d3e4c34c3b58a73623ca | C++ | semerdzhiev/oop-2020-21 | /inf-2-practical/06. Object Lifetime, RAII, Rule of 3/Headers/beer.hpp | UTF-8 | 298 | 2.59375 | 3 | [] | no_license | class Beer {
private:
char* brand;
unsigned volume{};
double abv{};
void copyFrom(const Beer& other);
void free();
public:
Beer();
Beer(const char* _brand, unsigned _volume, double _abv);
Beer& operator=(const Beer& other);
~Beer();
void print();
};
| true |
d864f7093b2863e74117d87f1749b31fc8c15317 | C++ | zmaker/arduino_cookbook | /live/live-2022-11-10/webserver_esp32/webserver_esp32.ino | UTF-8 | 1,538 | 2.609375 | 3 | [] | no_license | #include <WiFi.h>
#include "wifi_passwords.h"
WiFiServer server(80);
void setup() {
Serial.begin(115200);
delay(1000);
analogReadResolution(10);
WiFi.disconnect(true);
WiFi.begin(WIFI_SSID, WIFI_PASS);
while(WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.print("\nConnesso: ");
Serial.println(WiFi.localIP());
server.begin();
}
void loop() {
WiFiClient client = server.available();
if (client) {
Serial.println("nuova richiesta");
String line = "";
while (client.connected()) {
if (client.available()) {
char c = client.read();
Serial.print(c);
if (c == '\n') {
if (line.length() == 0) {
//genero la risposta di ESP32
client.println("HTTP/1.1 200 OK");
client.println("Content-type:text/html");
client.println("");
client.println("<html><head><title>ESP32</title>");
client.println("<meta http-equiv=\"refresh\" content=\"2;url=http://192.168.1.99/\" />");
client.println("</head>");
client.println("<body><h1>Hello ESP32!</h1>");
int v = analogRead(34);
client.println("Sensor: ");client.println(v);
client.println("</body></html>");
client.println("");
break;
} else {
line = "";
}
} else if (c != '\r') {
line += c;
}
}
}
client.stop();
Serial.println("Scollego il client");
}
}
| true |
a06c1c73b863bff9e080a4fdcb5481c0748e2aa9 | C++ | koziuberda/labs | /lab1/c++/main.cpp | UTF-8 | 285 | 3.078125 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main() {
float a = 0;
cout << "Enter cube edge length:";
cin >> a;
cout << "Lateral surface area = " << 4 * a * a << endl;
cout << "Volume of the cube = " << a * a * a << endl;
system("pause");
return 0;
} | true |
d4359aa31a1b1e557ccc62793a3100d8101c8a1f | C++ | reposhelf/playground | /cpp-lang/primer/ch13/examples/strvec/strvec.cpp | UTF-8 | 2,332 | 3.21875 | 3 | [] | no_license | #include "strvec.h"
using namespace std;
StrVec::StrVec()
: _elements(nullptr),
_first_free(nullptr),
_cap(nullptr)
{
}
StrVec::StrVec(const StrVec &other)
{
auto newdata = alloc_n_copy(other.begin(), other.end());
_elements = newdata.first;
_first_free = _cap = newdata.second;
}
StrVec::StrVec(StrVec &&other) noexcept
: _elements(other._elements),
_first_free(other._first_free),
_cap(other._cap)
{
other._elements = other._first_free = other._cap = nullptr;
}
StrVec &StrVec::operator=(const StrVec &rhs)
{
auto newdata = alloc_n_copy(rhs.begin(), rhs.end());
free();
_elements = newdata.first;
_first_free = _cap = newdata.second;
return *this;
}
StrVec &StrVec::operator=(StrVec &&rhs) noexcept
{
if (this != &rhs) {
free();
_elements = rhs._elements;
_first_free = rhs._first_free;
_cap = rhs._cap;
rhs._elements = rhs._first_free = rhs._cap = nullptr;
}
return *this;
}
StrVec::~StrVec()
{
free();
}
void StrVec::push_back(const std::string &s)
{
chk_n_alloc();
_alloc.construct(_first_free++, s);
}
void StrVec::push_back(string &&s)
{
chk_n_alloc();
_alloc.construct(_first_free++, std::move(s));
}
size_t StrVec::size() const
{
return _first_free - _elements;
}
size_t StrVec::capacity() const
{
return _cap - _elements;
}
std::string *StrVec::begin() const
{
return _elements;
}
std::string *StrVec::end() const
{
return _first_free;
}
void StrVec::chk_n_alloc()
{
if (size() == capacity())
reallocate();
}
std::pair<std::string *, std::string *> StrVec::alloc_n_copy(const std::string *b, const std::string *e)
{
auto data = _alloc.allocate(e - b);
return {data, std::uninitialized_copy(b, e, data)};
}
void StrVec::free()
{
if (_elements) {
for (auto p = _first_free; p != _elements; /* empty */)
_alloc.destroy(--p);
_alloc.deallocate(_elements, _cap - _elements);
}
}
void StrVec::reallocate()
{
auto newcapacity = size() ? 2 * size() : 1;
auto first = _alloc.allocate(newcapacity);
auto last = uninitialized_copy(make_move_iterator(begin()), make_move_iterator(end()), first);
free();
_elements = first;
_first_free = last;
_cap = _elements + newcapacity;
}
| true |
ea562a7b997bbfd7db7b94f54788fb6743327268 | C++ | Thomaw/Project-Euler | /600-700/606.cpp | UTF-8 | 1,740 | 2.703125 | 3 | [
"MIT"
] | permissive | #include <bits/stdc++.h>
using ll = long long;
inline ll sqr(ll x) {return x * x;}
inline ll cub(ll x) {return x * x * x;}
const int SZ = 100000000, mod = 1e9;
int pi[SZ], pl[SZ], p3[SZ], m;
void sieve() {
m = 0; for (int i = 2; i < SZ; ++ i) pi[i] = 1;
for (int i = 2; i < SZ; ++i) {
if (pi[i]) pl[m++] = i;
for (int j = 0; j < m && pl[j] * i < SZ; ++j) {
pi[pl[j] * i] = 0;
if (i % pl[j] == 0) break;
}
}
for (int i = 0; i < m; ++i) {
p3[i] = 1ll * pl[i] * pl[i] % mod * pl[i] % mod;
}
for (int i = 2; i < SZ; ++ i) {
if (pi[i]) pi[i] = 1ll * i * i % mod * i % mod;
pi[i] += pi[i - 1];
pi[i] %= mod;
}
}
ll sum3(ll n) {
ll x = n, y = n + 1;
if (x % 2 == 0) x >>= 1;
else y >>= 1;
x %= mod, y %= mod;
x = x * y % mod;
return x * x % mod - 1;
}
std::map<ll, ll> cache[1000000];
ll S(ll v, int x) {
while (x && 1ll * pl[x] * pl[x] > n) --x;
if (x == 0) return (sum3(v) - 8 * sum3(v / 2) % mod + mod) % mod;
if (cache[x].count(v)) return cache[x][v];
ll ret = S(v, x - 1);
ret -= p3[x] * (S(v / pl[x], x - 1) - S(pl[x] - 1, x - 1)) % mod;
ret %= mod; ret += mod; ret %= mod;
return cache[x][v] = ret;
}
ll count(ll n) {
if (n < SZ) return pi[n];
int i = 0;
while (1ll * pl[i] * pl[i] <= n) ++i;
return S(n, i - 1);
}
ll solve(ll n) {
ll ret = 0;
for (int i = 0; 1ll * pl[i] * pl[i] <= n; ++i) {
ret += 1ll * p3[i] * (count(n / pl[i]) - count(pl[i])) % mod;
ret %= mod;
}
return ret;
}
int main() {
sieve();
std::cout << solve(100) << std::endl;
std::cout << solve(10000) << std::endl;
std::cout << solve(1000000000000ll) << std::endl;
return 0;
} | true |
caf7c11cda3a2cdf515069d7363eff46e84df4ab | C++ | babaliaris/HazelBabaliaris | /Hazel/src/Hazel/Renderer/Shader.h | UTF-8 | 1,079 | 2.71875 | 3 | [
"Apache-2.0"
] | permissive | #pragma once
#include <iostream>
#include <glm/glm.hpp>
namespace Hazel
{
class Shader
{
public:
virtual ~Shader() = default;
virtual void Bind() = 0;
virtual void Unbind() = 0;
virtual const std::string& GetName() const = 0;
virtual void SetUniform(const std::string& name, int x) = 0;
virtual void SetUniform(const std::string& name, float x) = 0;
virtual void SetUniform(const std::string& name, const glm::vec3& vec3) = 0;
virtual void SetUniform(const std::string& name, const glm::vec4& vec4) = 0;
virtual void SetUniform(const std::string& name, const glm::mat4& mat4) = 0;
static Ref<Shader> Create(const char* v_path, const char* f_path);
};
class ShaderLibrary
{
public:
void Add(const Ref<Shader>& shader);
Ref<Shader> Load(const std::string& vert_path, const std::string& frag_path);
Ref<Shader> Get(const std::string& name);
private:
std::unordered_map<std::string, Ref<Shader>> m_shaders;
};
} | true |
6ec7617676c74504338cf38381c4edfe89644f09 | C++ | tahmidrana/UvaOjProblemsSollutions | /406 accepted.cpp | UTF-8 | 1,275 | 2.984375 | 3 | [] | no_license | #include <iostream>
#include <cmath>
#define N 1010
using namespace std;
int status[N];
int prime[N];
void Sieve(){
status[1]=0;
status[2]=0;
for(int i=4 ; i<=N ; i+=2)
status[i]=1;
for(int i=3 ; i*i<=N ; i+=2){
if(status[i]==0){
for(int j=i*i ; j<=N ; j+=i+i)
status[j]=1;
}
}
int p=0;
for(int i=1 ; i<=N ; i++){
if(status[i]==0){
prime[p]=i;
p++;
}
}
}
int main()
{
int n,c,count,mid;
Sieve();
while(cin>>n>>c){
cout<<n <<" " <<c <<": ";
count=0;
for(int i=0 ; prime[i]<=n ; i++)
count++;
if(count%2==0)
c=c*2;
else
c=(c*2)-1;
mid=(count-c)/2;
if(c>=count){
cout<<prime[0];
for(int i=1 ; prime[i]<=n ; i++){
if(prime[i-1]<prime[i])
cout<<" ";
cout<<prime[i];
}
}
else{
cout<<prime[mid];
for(int i=mid+1 ; i<mid+c ; i++){
if(prime[i-1]<prime[i])
cout<<" ";
cout<<prime[i];
}
}
cout<<endl;
cout<<endl;
}
return 0;
}
| true |