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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
fd9ede65efec2e8e83b0ce472b3906c62e515f71 | C++ | wes5510/codeforces | /357/A/main.cxx | UTF-8 | 477 | 2.9375 | 3 | [] | no_license | #include <iostream>
int c[100];
int main()
{
int m, x, y, beginnerGrp = 0, intermediateGrp = 0;
std::cin >> m;
for(int i = 0; i < m; i++)
{
std::cin >> c[i];
intermediateGrp += c[i];
}
std::cin >> x >> y;
for(int i = 0; i < m; i++)
{
if(beginnerGrp >= x && beginnerGrp <= y && intermediateGrp >= x && intermediateGrp <=y)
{
std::cout << i+1 << '\n';
return 0;
}
beginnerGrp+= c[i];
intermediateGrp -= c[i];
}
std::cout << "0\n";
return 0;
}
| true |
2c5022275e188dba1c3c31ff705a495cb3927b3b | C++ | sysfce2/SFML_Addons | /modules/ParticleSystem/ParticleSystem.hpp | UTF-8 | 4,952 | 3.28125 | 3 | [] | no_license | #ifndef PARTICLE_SYSTEM_HPP
#define PARTICLE_SYSTEM_HPP
#include <map>
#include <list>
#include <SFML/Graphics.hpp>
/**
* ParticleSystem is singleton which stores, updates and draws particles
*/
class ParticleSystem: public sf::Drawable, sf::NonCopyable
{
public:
class Particle;
/**
* Emitters launch particles and control their properties over their lifetime
*/
class Emitter
{
public:
Emitter();
virtual ~Emitter();
/**
* Duration of a particle
* @param duration: time to live in seconds. set to 0 for persistent particle.
*/
void setLifetime(float duration);
/**
* If looping is enabled, particle will not be removed after its lifetime expired and be reset instead
*/
void setLooping(bool looping);
bool isLooping() const;
/**
* Set the particle color (default: white)
* If two colors are used, particle will fade from \p start to \p end color
*/
void setParticleColor(const sf::Color& color);
void setParticleColor(const sf::Color& start, const sf::Color& end);
/**
* Set the particle direction (default: [0:360])
* @param variation: angle can vary from angle - variation to angle + variation
*/
void setAngle(float angle, float variation = 0.f);
/**
* Set the particle speed
* @param variation: speed can vary from speed - variation to speed + variation
*/
void setSpeed(float speed, float variation = 0.f);
/**
* Particle scale (default: 1)
* Particles will scale from \p start to \p end
*/
void setScale(float start, float end = 1.f);
/**
* Set the texture rect for the particles
* If a texture is set in the particle system, whole texture is used by default.
* Otherwise, particles default to a 1px wide square.
*/
void setTextureRect(const sf::IntRect& rect);
const sf::IntRect& getTextureRect() const;
/**
* Create particles linked to this emitter in the particle system
*/
void createParticles(size_t count = 100);
/**
* Remove all particles emitted by this emitter
*/
void removeParticles() const;
/**
* Reset a particle with this emitter's properties
* @param particle: particle to be initialized
*/
void resetParticle(Particle& particle) const;
/**
* Set the emitter position (where particles will be spawn at)
*/
void setPosition(const sf::Vector2f& position);
void setPosition(float x, float y);
const sf::Vector2f& getPosition() const;
/**
* Move the emitter position
*/
void move(const sf::Vector2f& delta);
void move(float dx, float dy);
/**
* Compute color transition between start color and end color
*/
sf::Color modulateColor(float lifespan, float elapsed) const;
/**
* Compute scale transition between start scale and end scale
*/
float modulateScale(float lifespan, float elapsed) const;
/**
* Override this method to implement a new behavior when particle is inserted in the particle system
*/
virtual void onParticleCreated(Particle&) const {};
/**
* Override this method to implement a new behavior when particle is updated
*/
virtual void onParticleUpdated(Particle&, float) const {};
private:
sf::Vector2f m_position;
bool m_looping;
float m_lifetime;
sf::Color m_start_color;
sf::Color m_end_color;
float m_start_scale;
float m_end_scale;
float m_angle;
float m_angle_variation;
float m_speed;
float m_speed_variation;
sf::IntRect m_texture_rect;
};
// -------------------------------------------------------------------------
/**
* A single particle in the particle system
*/
struct Particle
{
Particle(const ParticleSystem::Emitter& e);
const Emitter& emitter;
sf::Vector2f position;
float angle;
sf::Vector2f velocity;
float lifespan;
float elapsed;
};
// -------------------------------------------------------------------------
/**
* Get singleton instance
*/
static ParticleSystem& getInstance();
/**
* Attach a texture to the particle system
* All the particles are rendered using the same texture
*/
void setTexture(const sf::Texture* texture);
const sf::Texture* getTexture() const;
/**
* Delete all particles emitted by a given emitter
*/
void removeByEmitter(const Emitter& emitter);
/**
* Insert a new particle in the particle system
*/
void addParticle(const Particle& particle);
/**
* Update all particles
*/
void update(float frametime);
/**
* Delete all particles
*/
void clear();
private:
ParticleSystem();
~ParticleSystem();
void draw(sf::RenderTarget& target, sf::RenderStates states) const override;
typedef std::list<Particle> ParticleList;
ParticleList m_particles;
typedef std::map<std::string, Emitter> EmitterMap;
EmitterMap m_emitters;
sf::VertexArray m_vertices;
const sf::Texture* m_texture;
};
#endif // PARTICLE_SYSTEM_HPP
| true |
51754b963170d6d65d01bba65e4bb27b7ed192da | C++ | nrupprecht/OpenGLAnimals | /vec2d.hpp | UTF-8 | 1,391 | 3.25 | 3 | [] | no_license | /*
* Author: Nathaniel Rupprecht
* Start Data: May 12, 2017
*
*/
#ifndef __VEC_2D_HPP__
#define __VEC_2D_HPP__
#include "Utility.hpp"
typedef float RealType;
/*
* @class vec2
* Two dimensional vector class
*
*/
struct vec2 {
// Default constructor
vec2() : x(0), y(0) {};
// Initialized constructor
vec2(RealType x, RealType y) : x(x), y(y) {};
// The actual vector data
RealType x, y;
// Operators
vec2 operator-() const;
vec2 operator-(const vec2&) const;
vec2& operator-=(const vec2&);
vec2 operator+(const vec2&) const;
vec2& operator+=(const vec2&);
RealType operator*(const vec2&) const;
RealType operator^(const vec2&) const;
friend vec2 operator*(const RealType, const vec2&);
friend std::ostream& operator<<(std::ostream&, const vec2&);
bool operator==(const vec2&) const;
bool operator!=(const vec2&) const;
};
const vec2 Zero(0,0);
// Special squaring function for vectors (not a reference so we can use lvalues)
inline RealType sqr(const vec2 v) { return v*v; }
// Normalization function
inline void normalize(vec2 &v) {
RealType mag = sqrt(sqr(v));
v.x /= mag; v.y /= mag;
}
// (not a reference so we can use lvalues)
inline RealType length(const vec2 v) {
return sqrt(sqr(v));
}
// Get a random unit vector
inline vec2 randV() {
float a = drand48();
return vec2(sinf(2*PI*a), cosf(2*PI*a));
}
#endif // __VEC_2D_HPP__ | true |
f221525f834c99287710447663c86c5838af131f | C++ | wasimsurjo/basicCppProgramming | /Methods - Constructors.cpp | UTF-8 | 632 | 3.8125 | 4 | [] | no_license | #include <iostream>
#include <string>
using namespace std;
class WasA{
public:
WasA(string z){ /*Constructors with Same Class Name/Used For Easy Communication Between Object & Function & Setting Auto Functions*/
findName(z);
}
void findName (string y){ //This value was sent to constructor
x=y;}
string getName(){
return x;}
private:
string x;
};
int main(){
WasA wo("Private & Public!\n"); /*By using class name, the constructor was used. */
cout<< wo.getName()<<endl;
WasA wo2("Create Again!");
cout<< wo2.getName()<<endl;
return 0;
}
| true |
9ca6ec0fa2028911a39ef6e63ad142f63a307cc6 | C++ | voladoddi/ctci | /ch3_Stacks/general/balancedParantheses.cc | UTF-8 | 1,362 | 3.859375 | 4 | [] | no_license | /*
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.
Return 0 / 1 ( 0 for false, 1 for true ) for this problem
*/
bool isPair(char a, char b)
{
if(a=='{' && b=='}') return true;
else if(a=='(' && b==')') return true;
else if(a=='[' && b==']') return true;
return false;
}
int Solution::isValid(string A) {
std::stack<char> st;
char ch;
for (int i = 0; i < A.size();i++)
{
if (A[i]=='{' || A[i]=='(' || A[i]=='[')
st.push(A[i]);
else if (A[i]=='}' || A[i]==')' || A[i]==']')
{
if (st.empty() || !isPair(st.top(),A[i]))
return false;
else
st.pop();
}
}
int val = (st.empty() ? true:false);
return val;
}
/* COMMENTS, NOTES and OBSERVATIONS.
[1]. Time = O(n) since every character of the string has to be looked at.
[2]. Mistakes made:
-> implementation of isPair. Double check the order of params passed and args.
-> implementation of isPair. switch logic is not needed, have to compare a pair. No use in storing the complement in a variable, store the result of comparison in a variable instead.
*/ | true |
a64b5a4ac117ea296b7b5d8ec1cddec28f37944b | C++ | cigui/lab-cse | /lab5/lock_server.cc | UTF-8 | 1,609 | 2.859375 | 3 | [] | no_license | // the lock server implementation
#include "lock_server.h"
#include <sstream>
#include <stdio.h>
#include <unistd.h>
#include <arpa/inet.h>
lock_server::lock_server():
nacquire (0)
{
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&cond, NULL);
}
lock_protocol::status
lock_server::stat(int clt, lock_protocol::lockid_t lid, int &r)
{
lock_protocol::status ret = lock_protocol::OK;
printf("stat request from clt %d\n", clt);
r = nacquire;
return ret;
}
lock_protocol::status
lock_server::acquire(int clt, lock_protocol::lockid_t lid, int &r)
{
lock_protocol::status ret = lock_protocol::OK;
// Your lab4 code goes here
r = lid;
// A "coarse-granularity" mutex
pthread_mutex_lock(&mutex);
// If the lock has been created
if (locks.find(lid) != locks.end()) {
if (locks[lid] == FREE) {
locks[lid] = LOCKED;
}
else {
while (locks[lid] == LOCKED) {
pthread_cond_wait(&cond, &mutex);
}
locks[lid] = LOCKED;
}
}
// If the lock hasn't been created
else {
locks[lid] = LOCKED;
}
printf("ls: acq get here, id: %lld\n", lid);
pthread_mutex_unlock(&mutex);
return ret;
}
lock_protocol::status
lock_server::release(int clt, lock_protocol::lockid_t lid, int &r)
{
lock_protocol::status ret = lock_protocol::OK;
// Your lab4 code goes here
r = lid;
pthread_mutex_lock(&mutex);
if (locks.find(lid) != locks.end()) {
locks[lid] = FREE;
}
else {
ret = lock_protocol::NOENT;
}
printf("ls: rel get here, id: %lld\n", lid);
pthread_mutex_unlock(&mutex);
pthread_cond_signal(&cond);
return ret;
}
| true |
d62a34cc7204f8b7573c4f09d3ad672498d79d66 | C++ | paulrahul/algo | /codechef/FROGV1.cc | UTF-8 | 915 | 2.984375 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <algorithm>
#include <map>
using namespace std;
struct t {
int v;
int idx;
};
bool compare_t(const t& a, const t& b) {
return a.v < b.v;
}
int main() {
int n, k, p;
cin >> n >> k >> p;
vector<t> arr(n, t());
for(int i = 0; i < n; ++i) {
cin >> arr[i].v;
arr[i].idx = i + 1;
}
sort(arr.begin(), arr.end(), &compare_t);
map<int, int> m;
for (int i = 0; i < n; ++i) {
m[arr[i].idx] = i;
}
vector<int> hcount(n, 0);
for (int i = 1; i < n; ++i) {
hcount[i] = hcount[i - 1];
if (arr[i].v - arr[i - 1].v > k) {
++hcount[i];
}
}
int s, e;
for (int i = 0; i < p; ++i) {
cin >> s >> e;
int start = m[s];
int end = m[e];
if (start > end) {
int tmp = start;
start = end;
end = tmp;
}
if (hcount[end] > hcount[start]) {
cout << "No";
} else {
cout << "Yes";
}
cout << endl;
}
return 0;
} | true |
24d0e8521272a2176a569539a3aae2be96512be8 | C++ | Plkjaan/Data-structure | /selection_sort.cpp | UTF-8 | 409 | 2.875 | 3 | [] | no_license | //selection sort:w
#include<iostream>
#define n 10
using namespace std;
int main()
{
int min,i,j;
int a[n];
for(i=0;i<n;i++)
{
a[i]=rand()%10;
cout<<a[i]<<" ";
}
cout<<" Sorted array "<<endl;
for(i=0;i<n;i++)
{
min=i;
{
for(j=i+1;j<n;j++)
{
if(a[j]<a[min])
min=j;
swap(a[min],a[i]);
// cout<<a[i];
}
// cout<<a[i]<<" ";
}
cout<<a[i]<<" ";
}
return 0;
}
| true |
9dd6d176cc8570c5e1c715a6f61daca1432956d6 | C++ | eklavaya2208/practice-ml-cp | /Data Structures/week2_priority_queues_and_disjoint_sets/build_heap.cpp | UTF-8 | 1,425 | 3.078125 | 3 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
int min(int a,int b){
if(a<b)
return a;
else
return b;
}
int swap(int arr[],int i){
int temp = arr[i];
arr[i]=min(arr[2*i],arr[2*i+1]);
if(arr[i]==arr[2*i]){
arr[2*i]=temp;
return 2*i;
}
else{
arr[2*i+1]=temp;
return 2*i+1;
}
}
void swap(int *a,int *b){
int temp = *a;
*a = *b;
*b = temp;
}
int main(){
int n;
cin>>n;
int arr[n+1];
int count=0;
int count2=0;
vector<pair<int,int>> a;
for(int i=1;i<n+1;i++){
cin>>arr[i];
}
do{
count2=count;
for(int i=1;i<n+1;i++){
if(2*i<n+1 && 2*i+1<n+1){
if(arr[i]>arr[2*i] || arr[i]>arr[2*i+1]){
a.push_back(make_pair(i,swap(arr,i)));
count++;
}
}
else if(2*i<n+1){
if(arr[i]>arr[2*i]){
swap(arr+i,arr+2*i);
a.push_back(make_pair(i, 2*i));
count++;
}
}
else if(2*i+1<n+1){
if(arr[i]>arr[2*i+1]){
swap(arr+i,arr+2*i+1);
a.push_back(make_pair(i,2*i+1));
count++;
}
}
}
}while(count2-count!=0);
cout<<count<<endl;
for(auto i=a.begin();i<a.end();i++){
cout<<(i->first)-1<<" "<<(i->second)-1<<endl;
}
}
| true |
cb0b243742a3765d390e3f56adaaed8777498ebc | C++ | hamstache/ExpressionOperatorOverloading | /main.cpp | UTF-8 | 1,065 | 3.21875 | 3 | [] | no_license | #include "Expr_node.h"
#include "Expr.h"
#include <iostream>
using namespace std;
void display(Expr const& e){
cout << e << " = " << e.eval() << endl;
}
int main(){
Expr n(7);
Expr unary("-", 5);
Expr binary("+", 3, 4);
Expr e(Expr("*", unary, binary));
Expr ternary("!=", unary != binary, Expr("*", 20, 10), Expr("/", 20, 10) );
cout << "==================================================" << endl;
display(n);
display(unary);
display(binary);
display(e);
display(ternary);
cout << "==================================================" << endl << endl;
Expr unary1("-", 75);
Expr unary2("+", 25);
Expr binary1("*", unary1, unary2);
Expr binary2("/", unary1, unary2);
Expr ternary1("==", unary1 == unary2, binary1, binary2);
Expr ternary2("<", unary1 < unary2, binary1, binary2);
Expr ternary3("<", 5 - 3 < 5 + 3, Expr("+", 22, 17), Expr("-", 100, 80));
display(unary1);
display(unary2);
display(binary1);
display(binary2);
display(ternary1);
display(ternary2);
display(ternary3);
//cin.get();
return 0;
} | true |
46bfc17d54a9c6b876eeaf793faee89031ee4512 | C++ | mohityadav7/CP-Code | /CodeShala/Trees/Assignment questions/Balance Tree or Not.cpp | UTF-8 | 1,922 | 3.75 | 4 | [] | no_license | #include <iostream>
#include <algorithm>
#include <queue>
using namespace std;
struct node {
int data;
struct node * left;
struct node * right;
} * root = NULL;
struct node * insertNode(struct node * tNode, int value) {
if(tNode == NULL) {
struct node * newNode = (struct node *)malloc(sizeof(struct node));
newNode->data = value;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
if(tNode->data > value)
tNode->left = insertNode(tNode->left, value);
else
tNode->right = insertNode(tNode->right, value);
return tNode;
}
void buildTree(int a[], int N) {
for(int i = 0; i < N; i++) {
if(i) {
insertNode(root, a[i]);
} else {
root = insertNode(NULL, a[i]);
}
}
}
int height(node *root){
if(root == NULL)
return -1;
int lh=-1, rh=-1;
if(root->left)
lh = height(root->left);
if(root->right)
rh = height(root->right);
return ((lh>rh)?lh:rh) + 1;
}
// bool isBalancedTree(struct node * root) {
// if(root == NULL)
// return true;
// if(abs(height(root->left) - height(root->right)) > 1)
// return false;
// return isBalancedTree(root->left) && isBalancedTree(root->right);
// }
bool isBalancedTree(struct node * root, int &height) {
if(root == NULL){
height = -1;
return true;
}
int lHeight, rHeight;
bool isLeftBalanced, isRightBalanced;
isLeftBalanced = isBalancedTree(root->left, lHeight);
isRightBalanced = isBalancedTree(root->right, rHeight);
height = ((lHeight > rHeight) ? lHeight : rHeight) + 1;
if(abs(lHeight - rHeight) > 1)
return false;
else return isLeftBalanced && isRightBalanced;
}
int main() {
int N, height = 0;
cin >> N;
int arr[N];
for(int i = 0; i < N; i++) {
cin >> arr[i];
}
buildTree(arr, N);
if(isBalancedTree(root, height))
cout << "YES" << endl;
else
cout << "NO" << endl;
} | true |
29b9a2fc82505c52c2df2a468cb36c20910f73a4 | C++ | raisazaman02/Sales-System-for-a-Fast-Food-Restaurant | /Project #2/Project2/Project2/Sandwiches.cpp | UTF-8 | 1,124 | 3.390625 | 3 | [] | no_license | #include <iostream>
#include <string>
#include "Sandwiches.h"
//Implementation of default constructor
sandwiches::sandwiches()
{
sandwicheType = " ";
}
//Implementation of constructor with parameters
sandwiches::sandwiches(string Sn, double Sp, int Sc, int Sq, string St)
:Item(Sn, Sp, Sc, Sq)
{
sandwicheType = St;
}
//Implementation of setSandwiches
void sandwiches::setSandwiches(string Sn, double Sp, int Sc, int Sq, string St)
{
setName(Sn);
setPrice(Sp);
setCalories(Sc);
setQuantities(Sq);
setsandwicheType(St);
}
//Implementation of setsandwicheType
void sandwiches::setsandwicheType(string St)
{
sandwicheType = St;
}
//Implementation of getsandwicheType
string sandwiches::getsandwicheType() const
{
return sandwicheType;
}
//Implementation of printSandwiches
void sandwiches::printItem() const
{
Item::printItem();
cout << "Sandwich type: " << sandwicheType << endl;
cout << endl;
}
//Implementation of operator overload
ostream& operator<< (ostream& cout, const sandwiches& sandwichesobject)
{
sandwichesobject.printItem();
return cout;
} | true |
ddb740e48c7bb1ccf7ccb5b19e09fdeae008e271 | C++ | zeph7/Competitive_Programming | /Basic-programming/basics-of-input-output/play_with_numbers.cpp | UTF-8 | 540 | 2.859375 | 3 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
int main()
{
long long i, q, l, r, n, x, y, sum;
vector <long long> v;
cin >> n >> q;
for(i=0; i<n; i++){
cin >> x;
if(i >= 1)
y = v.at(i-1) + x;
else if(i == 0)
y = x;
v.push_back(y);
}
for(i=0; i<q; i++){
cin >> l >> r;
if(l == 1)
sum = v.at(r-1);
else
sum = v.at(r-1) - v.at(l-2);
cout << sum/(r-l+1) << endl;
}
return 0;
}
| true |
7777535a72de62e2f740b39dee559138eba871f5 | C++ | Yashvishnoi/Cpp | /lab2.cpp | UTF-8 | 230 | 2.90625 | 3 | [] | no_license | #include<iostream>
using namespace std;
class fun
{
public:
int n[100],i=0;
int function(int x)
{
for(int k=x;k>0;k=k/2)
{
n[i++]=k%2;
}
for(int j=i-1;j>=0;j--)
cout<< n[j];
}
};
int main()
{
fun f;
f.function(7);
return 0;
}
| true |
662d38f8f99468781d3e3235e30728870dbe00ed | C++ | SandoKaravelovRado/UP-1-vi-kurs | /Zadachi_3sedmica.cpp | UTF-8 | 3,650 | 3.5625 | 4 | [] | no_license | #include<iostream>
#include <stdbool.h>
#include <math.h>
#include <string>
using namespace std;
int main(){
//редицата ai = a^i +3i.
int number, ai = 0;
cin>>number;
for(int index = 1; index <= number; index++){
ai = pow(index,2) + 3*index;
cout<<ai<<endl;
}
//Най-голямо отрицателно число.
int numbers, currentNumber, biggestNegativeNumber;
cin >> numbers >> currentNumber;
biggestNegativeNumber = currentNumber;
for(int index = 0; index < numbers-1; index++){
cin >> currentNumber;
if((biggestNegativeNumber >= 0 && currentNumber < 0) ||
(biggestNegativeNumber < 0 && currentNumber > biggestNegativeNumber && currentNumber < 0)){
biggestNegativeNumber = currentNumber;
}
}
cout<<biggestNegativeNumber;
// Фибоначи редиа.
int n, firstNumber = 0, secondNumber = 1, nextNumber = 0;
cin>>n;
for(int index = 1; index <= n; index++){
if(index == 1) {
cout << firstNumber << ", ";
continue;
}
else if(index == 2) {
cout << secondNumber << ", ";
continue;
}
nextNumber = firstNumber + secondNumber;
firstNumber = secondNumber;
secondNumber = nextNumber;
cout << nextNumber << ", ";
}
// Събиране на всички числа до въвеждане на 0.
int summary = 0, currentNumber;
do{
cin >> currentNumber;
summary+=currentNumber;
}while( currentNumber );
cout<<summary;
// Сбор на цифрите на дадено число
int summary = 0, number;
cin >> number;
while(number){
summary += (number % 10);
number /= 10;
}
cout << summary;
// число N на сепен M.
int number, powerBy, answer;
cin >> number >> powerBy;
answer = number;
if(powerBy==0){
answer = 1;
}else if(powerBy==1){
answer = number;
}else{
for(int index = 1; index < powerBy; index++){
answer *= number;
}
}
cout << answer;
// Дали дадено число е просто
int number;
bool isPrime = true;
cout << "Enter a positive integer: ";
cin >> number;
if (number == 0 || number == 1) {
isPrime = false;
}else {
for (int index = 2; index <= number / 2; ++index) {
if (number % index == 0) {
isPrime = false;
break;
}
}
}
if (isPrime){
cout << "YES";
}else{cout << "NO";}
// Всички главни букви без гласните
for(int index = 65; index <= 90 ; index++){
if(index != 65 && index != 69 && index != 73 && index != 79 && index != 85){
cout << char(index) << endl;
}
}
// Квадрат NxN, главен диагонал 0, над него + и под него -
int n;
printf("Enter an integer:\n");
cin >> n;
for(int indexRow = 0; indexRow < n; indexRow++){
for(int indexColumn = 0; indexColumn < n; indexColumn++){
if(indexColumn == indexRow){
cout << '0';
}else if(indexColumn < indexRow){
cout << '-';
}else {
cout << '+';
}
}
cout << endl;
}
return 0;
}
| true |
c2f9b5625801380616886494a9b29947db0f8373 | C++ | YusefBM/Algorithms-and-Data-Structures | /Iterative-Algorithms/8/Problema8RescateAereo.cpp | UTF-8 | 1,369 | 2.953125 | 3 | [] | no_license | // Nombre del alumno:Eduardo Martínez Martín
// Usuario del Juez: E31
// La solucion obtenida tiene un coste O(n), siendo "n" la longitud del vector
#include <iostream>
#include <iomanip>
#include <fstream>
#include <vector>
using namespace std;
// función que resuelve el problema
void resolver(vector <int> const& edificios, int &ini, int&fin, int alturaTransporte) {
int maxLong = 0;
int ultimoIni = 0;
ini = 0;
fin = 0;
for (int i = 0; i < edificios.size(); i++) {
if (edificios[i] > alturaTransporte) {
if (maxLong < i - ultimoIni + 1) {
maxLong = i - ultimoIni + 1;
ini = ultimoIni;
}
}
else {
ultimoIni = i + 1;
}
}
fin = ini + maxLong - 1;
}
void resuelveCaso() {
// leer los datos de la entrada
int numeroEdificios;
int alturaTransporte;
int ini;
int fin;
cin >> numeroEdificios;
cin >> alturaTransporte;
vector <int> edificios(numeroEdificios);
for (int i = 0; i < edificios.size(); i++) {
cin >> edificios[i];
}
// resolver
resolver(edificios,ini,fin,alturaTransporte);
// escribir sol
cout << ini << " " << fin << endl;
}
int main() {
#ifndef DOMJUDGE
std::ifstream in("datos.txt");
auto cinbuf = std::cin.rdbuf(in.rdbuf());
#endif
int numCasos;
cin >> numCasos;
for (int i = 0; i < numCasos; ++i)
resuelveCaso();
#ifndef DOMJUDGE
std::cin.rdbuf(cinbuf);
system("PAUSE");
#endif
return 0;
} | true |
50852ba58b5d49726cddf516c6f48b60d0b00f8d | C++ | keymanky/sites | /UNO/Marcos/Archivos/C++/GRAFICACION/1.cpp | UTF-8 | 1,251 | 2.78125 | 3 | [] | no_license | #include <iostream.h>
#include <conio.h>
#include <graphics.h>
#include <dos.h>
//#include <winbgim.h>
class Circulo
{
private:
float radio;
float x,y;
float pi;
int ver;
public:
//constructor
Circulo(float orad, float ox, float oy)
{
radio=orad;
x=ox;
y=oy;
pi=3.14159;
ver=0;
}
float Area()
{
return (pi*radio*radio);
}
float Perimetro()
{
return (pi*2*radio);
}
void Dibujar()
{
circle(x,y,radio);
ver=1;
}
void Ocultar()
{
unsigned guardacolor;
guardacolor= getcolor();
setcolor(getbkcolor());
ver=0;
setcolor(guardacolor);
}
void Mover(float nx, float ny)
{
if(ver)
{
Ocultar();
x=nx;
y=ny;
Dibujar();
}
else
{
x=nx;
y=ny;
Dibujar();
}
}
};
void main()
{
Circulo Cir1(80,100,120);
Circulo Cir2(120,300,250);
int a,b,i;
a=DETECT;
initgraph(&a,&b," ");
Cir1.Dibujar();
Cir1.Area();
Cir1.Perimetro();
Cir2.Dibujar();
for(i=0;i<300;i++)
{
Cir1.Mover(100+i,120);
delay(50);
}
getch();
closegraph();
}
| true |
9acd039dbc0445fcf2251490996da51a55159982 | C++ | sony0905/Data-Structures- | /circular_queue_using_linked_list.cpp | UTF-8 | 3,239 | 3.4375 | 3 | [] | no_license | #include<iostream>
using namespace std;
class Node{
public:
int data;
Node *next;
};
Node *front=NULL;
Node *rear= NULL;
Enqueue(){
Node *newNode= new Node();
cout<"\nEnter data to be inserted:\t";
cin>>newNode->data;
if(front==NULL && rear==NULL){
front= newNode;
}
else{
rear->next= newNode;
}
rear= newNode;
rear->next= front;
}
Dequeue(){
if(front==NULL){
cout<<"\nQueue is empty\n";
}
else if(front==rear){
Node *temp= front;
front= NULL;
rear= NULL;
delete(temp);
}
else{
Node *temp= front;
front= front->next;
rear->next= front;
cout<<"\n"<<temp->data<<" deleted successfully\n";
delete(temp);
}
}
display(){
Node *temp= front;
while(temp->next!=front){
cout<<temp->data<<"\t";
temp= temp->next;
}
cout<<temp->data<<endl;
}
Peek(){
if(front==NULL){
cout<<"\nQueue is empty\n";
}
else{
cout<<"\nPeek value is: "<<front->data;
}
}
int main(){
int ch;
do{
cout<<"\nPress\n 0->Exit \n 1->Enqueue() \n 2->Dequeue() \n 3->Peek() \n 4->display() \n";
cin>>ch;
switch(ch){
case 0: display();
break;
case 1: Enqueue();
break;
case 2: Dequeue();
break;
case 3: Peek();
break;
case 4: display();
break;
default: cout<<"Invalid choice\n";
}
}while(ch);
}
/*
Press
0->Exit
1->Enqueue()
2->Dequeue()
3->Peek()
4->display()
1
451
Press
0->Exit
1->Enqueue()
2->Dequeue()
3->Peek()
4->display()
1
461
Press
0->Exit
1->Enqueue()
2->Dequeue()
3->Peek()
4->display()
1
5620
Press
0->Exit
1->Enqueue()
2->Dequeue()
3->Peek()
4->display()
4
451 461 5620
Press
0->Exit
1->Enqueue()
2->Dequeue()
3->Peek()
4->display()
1
7820
Press
0->Exit
1->Enqueue()
2->Dequeue()
3->Peek()
4->display()
2
451 deleted successfully
Press
0->Exit
1->Enqueue()
2->Dequeue()
3->Peek()
4->display()
2
461 deleted successfully
Press
0->Exit
1->Enqueue()
2->Dequeue()
3->Peek()
4->display()
4
5620 7820
Press
0->Exit
1->Enqueue()
2->Dequeue()
3->Peek()
4->display()
1
78520
Press
0->Exit
1->Enqueue()
2->Dequeue()
3->Peek()
4->display()
4
5620 7820 78520
Press
0->Exit
1->Enqueue()
2->Dequeue()
3->Peek()
4->display()
2
5620 deleted successfully
Press
0->Exit
1->Enqueue()
2->Dequeue()
3->Peek()
4->display()
2
7820 deleted successfully
Press
0->Exit
1->Enqueue()
2->Dequeue()
3->Peek()
4->display()
2
Press
0->Exit
1->Enqueue()
2->Dequeue()
3->Peek()
4->display()
2
Queue is empty
Press
0->Exit
1->Enqueue()
2->Dequeue()
3->Peek()
4->display()
1
84
Press
0->Exit
1->Enqueue()
2->Dequeue()
3->Peek()
4->display()
1
9663
Press
0->Exit
1->Enqueue()
2->Dequeue()
3->Peek()
4->display()
0
84 9663
*/
| true |
520ab14ea95cfbb77103c37b74adf78039dc50d6 | C++ | mrnglory/C-Plus-Plus-OOP | /GraphicEditor/GraphicEditor/Shape.h | UTF-8 | 376 | 3.140625 | 3 | [] | no_license | #pragma once
#include <iostream>
#include <string>
using namespace std;
class Shape
{
Shape* next;
protected:
virtual void draw() = 0;
public:
Shape() { next = NULL; }
virtual ~Shape(){}
void paint() { draw(); }
Shape* add(Shape* p) { this->next = p; return p; }
Shape* getNext() { return next; }
void setNext(Shape* p) { this->next = p->next; }
};
| true |
ea07578eeda86da0b366496eafc55d450bfd76c4 | C++ | vipulchhabra99/In-Memory-KvStore | /comparisions/trie/a.cpp | UTF-8 | 9,606 | 3.3125 | 3 | [] | no_license | /*
SPECIFICATIONS:
Max key size: 64 bytes
Each key char can be (a-z) or (A-Z): Total 52 possible chars
Max Value Size: 256 bytes, any ASCII value
No DS/boost/STL etc Libraries to be used
Only pthread to be used for multithreading
Keys to be in strcmp (cstring) Order
API calls would be blocking
EVALUATION:
Benchmark would first load data via put calls (10 million entries, 2 min time limit)
Perform Single Threaded Transactions to verify kvStore functionality
Multiple Transaction Threads with each thread calling one of the APIs
Metrics:
TPS (Transactions Per Second)
Average CPU Usage
Peak Memory Usage
Normalize all 3 metrics with Avg
Score = (TPS*TPS)/(CPU*Mem)
*/
// remove later, just for testing
#include <cstdlib>
#include <ctime>
#include <iostream>
//_____
#include <pthread.h>
#include <cstring>
#include <cstdint>
#define ALPHABET_SIZE 52
using namespace std;
struct TrieNode
{
struct TrieNode *children[ALPHABET_SIZE];
uint64_t nChildren[ALPHABET_SIZE]; // Number of children.
char *value;
};
struct Slice
{
uint8_t size;
char *data;
};
struct TrieNode *getNode();
bool insert(struct TrieNode *root, char *key, uint8_t ksize, char *value, uint8_t vsize);
bool search(struct TrieNode *root, char *key, uint8_t ksize, char *value, uint8_t *vsize);
bool searchn(struct TrieNode *root, uint64_t n, char *key, uint8_t *ksize, char *value, uint8_t *vsize);
static inline bool isEmpty(TrieNode *root);
void removenn(struct TrieNode *root, uint64_t n);
bool removen(struct TrieNode *root, uint64_t n);
struct TrieNode *remove(struct TrieNode *root, char *key, uint8_t ksize, bool *keyFound, int depth);
class kvStore
{
private:
TrieNode *root;
uint64_t max_entries;
pthread_mutex_t lock;
public:
kvStore(uint64_t max_entries);
bool get(Slice &key, Slice &value); //returns false if key didn’t exist
bool put(Slice &key, Slice &value); //returns true if value overwritten
bool del(Slice &key);
bool get(int N, Slice &key, Slice &value); //returns Nth key-value pair
bool del(int N); //free( Nth key-value pair)
};
/*
// remove later, just for testing
void gen_random(char *s, const int len) {
static const char alphanum[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";
for (int i = 0; i < len; ++i) {
s[i] = alphanum[rand() % (sizeof(alphanum) - 1)];
}
s[len] = 0;
}
//______
// remove code inside main() later, just for testing
int main(int argc, char const *argv[])
{
if (argc != 2)
return 1;
uint64_t N = atoi(argv[1]);
srand(time(NULL));
const int key_len = 64;
const int val_len = 256;
kvStore kv(N);
struct Slice key, value;
key.data = (char *)malloc( sizeof(char) * (key_len+1));
value.data = (char *)malloc( sizeof(char) * (val_len+1));
// cout << "::put::" << endl;
// also check for overwrite cases
for (int i=0; i<N; i++)
{
gen_random(key.data, key_len);
key.size = strlen(key.data);
gen_random(value.data, val_len);
value.size = strlen(value.data);
kv.put(key, value); // comment this if uncommenting below line
// cout << kv.put(key, value) << "\t" << key.data << "\t" << (int)key.size << "\t" << value.data << "\t" << (int)value.size << endl;
}
cout << "::get n::" << endl;
for (int i=0; i<N; i++)
{
cout << kv.get(i, key, value) << "\t" << key.data << "\t" << (int)key.size << "\t" << value.data << "\t" << (int)value.size << endl;
}
cout << "::del n::" << endl;
for (int i = 0; i < N; i+=2)
{
cout << kv.del(i) << endl;
}
cout << "::get n::" << endl;
for (int i=0; i<N/2+1; i++)
{
cout << kv.get(i, key, value) << "\t" << key.data << "\t" << (int)key.size << "\t" << value.data << "\t" << (int)value.size << endl;
}
cout << "::get::" << endl;
struct Slice value2;
value2.data = malloc( sizeof(char) * (val_len+1));
for (int i = 0; i < N/2; ++i)
{
kv.get(i, key, value);
cout << kv.get(key, value2) << "\t" << key.data << "\t" << (int)key.size << "\t" << value2.data << "\t" << (int)value2.size << endl;
}
cout << "::del::" << endl;
return 0;
}
*/
kvStore::kvStore(uint64_t max_entries)
{
this->max_entries = max_entries;
this->root = getNode();
pthread_mutex_init(&this->lock, NULL);
}
bool kvStore::get(Slice &key, Slice &value)
{
return search(this->root, key.data, key.size, value.data, &value.size);
}
bool kvStore::put(Slice &key, Slice &value)
{
pthread_mutex_lock (&this->lock); // Shift this lock to data structure
bool ret = insert(this->root, key.data, key.size, value.data, value.size);
pthread_mutex_unlock (&this->lock);
return ret;
}
bool kvStore::del(Slice &key)
{
bool keyFound = false;
pthread_mutex_lock (&this->lock);
remove(this->root, key.data, key.size, &keyFound, 0);
pthread_mutex_unlock (&this->lock);
return keyFound;
}
bool kvStore::get(int N, Slice &key, Slice &value)
{
*(key.data) = '\0';
return searchn(this->root, N, key.data, &key.size, value.data, &value.size);
}
bool kvStore::del(int N)
{
pthread_mutex_lock (&this->lock);
bool ret = removen(this->root, N);
pthread_mutex_unlock (&this->lock);
return ret;
}
struct TrieNode *getNode()
{
struct TrieNode *pNode = (struct TrieNode *)malloc( sizeof(TrieNode) );
memset(pNode, 0, sizeof(TrieNode));
return pNode;
}
bool insert(struct TrieNode *root, char *key, uint8_t ksize, char *value, uint8_t vsize)
{
struct TrieNode *pCrawl = root;
for (int i = 0; i < ksize; i++)
{
int index = key[i] > 'Z' ? key[i]-'a'+26 : key[i]-'A';
pCrawl->nChildren[index]++;
if (!pCrawl->children[index])
pCrawl->children[index] = getNode();
pCrawl = pCrawl->children[index];
}
if (pCrawl->value == NULL) // No value overwrite.
{
pCrawl->value = (char *)malloc( sizeof(char) * (vsize+1));
strcpy(pCrawl->value, value);
return false;
}
else // Value overwrite.
{
free( pCrawl->value );
pCrawl->value = (char *)malloc( sizeof(char) * (vsize+1));
strcpy(pCrawl->value, value);
pCrawl = root;
for (int i = 0; i < ksize; i++) // Take number of children to previous state.
{
int index = key[i] > 'Z' ? key[i]-'a'+26 : key[i]-'A';
pCrawl->nChildren[index]--;
pCrawl = pCrawl->children[index];
}
return true;
}
// replace strncpy if errernous
// pCrawl->value[vsize] = '\0';
}
bool search(struct TrieNode *root, char *key, uint8_t ksize, char *value, uint8_t *vsize) // NULL root value check
{
/*
if (!root)
return false;
*/
struct TrieNode *pCrawl = root;
for (int i = 0; i < ksize; i++)
{
int index = key[i] > 'Z' ? key[i]-'a'+26 : key[i]-'A';
if (!pCrawl->children[index])
return false;
pCrawl = pCrawl->children[index];
}
if (pCrawl == NULL || pCrawl->value == NULL)
return false;
else
{
strcpy(value, pCrawl->value); // Assuming value has enough space allocated
*vsize = strlen(pCrawl->value); // replace pCrawl->value with value for speed
return true;
}
}
bool searchn(struct TrieNode *root, uint64_t n, char *key, uint8_t *ksize, char *value, uint8_t *vsize)
{
/*
if (!root)
return false;
*/
if (root->value)
{
if (n)
n--;
else
{ // found
*ksize = strlen(key);
*vsize = strlen(root->value);
strcpy(value, root->value);
return true;
}
}
struct TrieNode *pCrawl = root;
int csum = 0; // Children sum
for (int i = 0; i < ALPHABET_SIZE; ++i)
{
csum += pCrawl->nChildren[i];
if (csum > n)
{
int keylen = strlen(key);
key[keylen] = i >= 26 ? i - 26 + 'a' : i + 'A';
key[keylen+1] = '\0';
return searchn(root->children[i], n-csum+pCrawl->nChildren[i], key, ksize, value, vsize);
}
}
return false;
}
static inline bool isEmpty(TrieNode *root)
{
const static char *zero[ALPHABET_SIZE] = {0};
return !memcmp(zero, root->children, ALPHABET_SIZE * sizeof(char *));
}
void removenn(struct TrieNode *root, uint64_t n)
{
if (root->value)
{
if (n)
n--;
else
{
free( root->value );
root->value = NULL;
return;
}
}
struct TrieNode *pCrawl = root;
int csum = 0; // Children sum
for (int i = 0; i < ALPHABET_SIZE; ++i)
{
csum += pCrawl->nChildren[i];
if (csum > n)
{
root->nChildren[i]--;
if (root->nChildren[i] == 0)
{
TrieNode *delptr = root->children[i];
root->children[i] = NULL;
while (!delptr->value)
{
TrieNode *temp = delptr;
for (int j = 0; j < ALPHABET_SIZE; ++j)
if (delptr->children[j])
delptr = delptr->children[j];
free( temp );
}
free( delptr->value );
free( delptr );
}
else
removenn(root->children[i], n-csum+pCrawl->nChildren[i]+1);
return;
}
}
}
bool removen(struct TrieNode *root, uint64_t n)
{
int count = 0; // Children count.
for (int i = 0; i < ALPHABET_SIZE; ++i)
count += root->nChildren[i];
if (n >= count)
return false;
else
{
removenn(root, n);
return true;
}
}
struct TrieNode *remove(struct TrieNode *root, char *key, uint8_t ksize, bool *keyFound, int depth = 0)
{
if (!root)
return NULL;
else if (depth != ksize)
{
int index = key[depth] > 'Z' ? key[depth]-'a'+26 : key[depth]-'A';
root->children[index] = remove(root->children[index], key, ksize, keyFound, depth + 1);
if (*keyFound == true)
root->nChildren[index]--;
if (isEmpty(root) && root->value == NULL)
{
free( (root) );
root = NULL;
}
return root;
}
else // If last character of key is being processed
{
if (root->value)
{
*keyFound = true;
free( root->value );
root->value = NULL;
if (isEmpty(root)) // see whether this if has to go outside parent if, change was made to bring it inside.
{
free( root );
root = NULL;
}
}
return root;
}
}
| true |
e988ddcfac938ac1136bd83a9acda05c48352505 | C++ | awais987123/Libarary-Management-System-with-complete-GUI | /books.h | UTF-8 | 1,895 | 3.5 | 4 | [] | no_license | #pragma once
#ifndef BOOKS_H
#define BOOKS_H
#include<string>
#include<sstream>
#include<iomanip>
using namespace std;
class books // declaration of class
{
private://members variables
string title,
author,
publisher,
status;
int production_year,
copies,
item_id;
public://member functions
books();//default constructor
books(string t, string a, string p, int prd, int c, string s, int i);//parameterized constructor
books(string t, string a);//overloaded parameterized constructor for two parameters
books& setbook(string t, string a, string p, int prd, int c, string s, int id);//setter for all variables
string tostring() const;//return a string having all the values of member variables
string sptostring()const;//return a string having all the values of member variables seperated by ','
friend bool operator ==(const books& left, const books& right);//operator overload for comparison
bool copiesdecrement();//to decrease one from no of copies
string getbooktitle() const;//getter for title
string getbookauthor() const;//getter for author
string getbookstatus() const;//getter for status
string getbookpublisher() const;//getter for publisher
int getbookprodyear() const;//getter for production year
int getbookcopies() const;//getter for copies
int getbookitemid() const;//getter for item id
string isValidAuthor(string);//validation check for author
string isValidPublisher(string);//validation check for publisher
int isValidProductionYear(int);//validation check for production year
int isValidCopies(int);//validation check for copies
void incresebookcopies(int itemid);//increase the number of copies when an book is returned
void decreaseoneinitemid();//decrese in item id by one when an book is deleted
friend bool operator<(books& left, books& right);//operater overload for '<'
};
#endif // !BOOKS_H
| true |
7dcfc2f29a4b85ef6b9cb449230fdae36d583eb6 | C++ | hero1796/C-Cplus2 | /codeAcm/P171PROD.cpp | UTF-8 | 1,688 | 2.921875 | 3 | [] | no_license | #include <stdio.h>
#include <bits/stdc++.h>
#include <iostream>
using namespace std;
void import_array(long a[], long b[], long n) {
for(long i = 0; i < n; i++)
scanf("%ld %ld", &a[i], &b[i]);
}
void export_array(long a[], long b[], long n) {
printf("\n");
for(long i = 0; i < n; i++)
printf("%ld %ld\n", a[i], b[i]);
}
void heapify(long arr[], long b[], long n, long i)
{
long largest = i;
long l = 2*i + 1;
long r = 2*i + 2;
long tmp;
if (l < n && arr[l] > arr[largest])
largest = l;
if (r < n && arr[r] > arr[largest])
largest = r;
if (largest != i)
{
tmp = arr[i];
arr[i] = arr[largest];
arr[largest] = tmp;
tmp = b[i];
b[i] = b[largest];
b[largest] = tmp;
heapify(arr, b, n, largest);
}
}
void heapSort(long arr[], long b[], long n)
{
long tmp;
for (long i = n / 2 - 1; i >= 0; i--)
heapify(arr, b, n, i);
for (long i=n-1; i>=0; i--)
{
tmp = arr[0];
arr[0] = arr[i];
arr[i] = tmp;
tmp = b[0];
b[0] = b[i];
b[i] = tmp;
heapify(arr, b, i, 0);
}
}
long max(long a, long b) {
if(a > b) return a;
else return b;
}
int main() {
long n, cnt = 0;
scanf("%ld", &n);
long a[n], b[n];
import_array(a, b, n);
heapSort(a, b, n);
export_array(a, b, n);
long max1 = b[0], max2 = 0;
for(long i = 1; i < n; i++) {
//if(a[i] != a[]) max2 = max1;
max1 = max(max1, b[i-1]);
//printf("max1 la %ld\n",max1);
//printf("max2 la %ld\n",max2);
if(a[i] != a[i-1]) {
max2 = max1;
if(b[i] < max1) cnt++;
} else {
if(b[i] < max2) cnt++;
}
}
printf("%ld", cnt);
return 0;
}
| true |
ce062ed158ca46d88e184bbe7d5f24df1652ec0d | C++ | krishna-NIT/100DaysCodingChallenege | /Day55/A chessboard.cpp | UTF-8 | 375 | 2.8125 | 3 | [] | no_license | /*
Platform :- Hackerearth
Problem :- A Chessboard
Hint :- Brute Force
*/
#include<bits/stdc++.h>
using namespace std;
int main(){
int t;
cin>>t;
while(t--){
int x1,y1,x2,y2;
cin>>x1>>y1>>x2>>y2;
int d=abs(x2-x1);
d=max(d,abs(y2-y1));
if(d==0){
cout<<"SECOND"<<endl;
}
else if(d==1) {
cout<<"FIRST"<<endl;
}
else cout<<"DRAW"<<endl;
}
}
| true |
f00aff334b12d384ab76f06d5d7eddce17b70796 | C++ | ghworld/algorithm | /最大乘积子序列/maxProduct.cpp | UTF-8 | 640 | 3.21875 | 3 | [] | no_license | //
// Created by mi on 2/24/18.
//
#include <iostream>
#include <vector>
// 最大乘积子序列问题
using namespace std;
class Solution{
public:
int maxProduct(vector<int> A){
int maxPro=0 ;
int minPro=0 ;
for(int i=0; i<A.size();i++){
maxPro=max(max(A[i],maxPro*A[i]),minPro*A[i]);
minPro=min(min(A[i],maxPro*A[i]),minPro*A[i]);
maxPro=max(maxPro,minPro);
}
return maxPro;
}
};
/*
int main(){
cout<<"max product !"<<endl;
Solution* solution;
vector<int> A={1,2,3,4};
cout<<"max product is : "<<solution->maxProduct(A);
}*/
| true |
229770fe93c02cbabcad5f836cfefdfeb5393c04 | C++ | hamko/sample | /tbb/comparison.cpp | UTF-8 | 2,777 | 2.703125 | 3 | [] | no_license | #include <iostream>
#include <ctime>
#include <omp.h>
#include <cmath>
#include <cstdlib>
#include "tbb/task_scheduler_init.h"
#include "tbb/blocked_range.h"
#include "tbb/parallel_for.h"
#include "tbb/tick_count.h"
using namespace std;
using namespace tbb;
const int task_num = 100;
const int rep = 100000000;
class Parallel
{
private:
long long *v;
public:
void operator() (const blocked_range<int>& range) const
{
for (int i = range.begin(); i < range.end(); i++) {
long long sum = 0; for (int j = 0; j < rep; j++) { sum += j; }
cout << sum << " ";
v[i] = sum;
}
}
Parallel(long long buf[task_num]) : v(buf) {};
};
int main()
{
task_scheduler_init init;
long long ccc[task_num];
tick_count start, finish;
// TBB
start = tick_count::now();
parallel_for( blocked_range<int>(0, task_num), Parallel(ccc));
cout << endl;
finish = tick_count::now();
cout << "tbb=" << (finish - start).seconds() << endl;
// TBB with Lambda
start = tick_count::now();
parallel_for( blocked_range<int>(0, task_num),
[&](const blocked_range<int>& range) {
for (int i = range.begin(); i < range.end(); i++) {
long long sum = 0; for (int j = 0; j < rep; j++) { sum += j; }
cout << sum << " ";
ccc[i] = sum;
}
});
cout << endl;
finish = tick_count::now();
cout << "tbb with lambda=" << (finish - start).seconds() << endl;
// TBB with Lambda Simple
start = tick_count::now();
parallel_for(0, task_num,
[&](size_t i) {
long long sum = 0; for (int j = 0; j < rep; j++) { sum += j; }
ccc[i] = sum;
cout << sum << " ";
}
, tbb::auto_partitioner());
cout << endl;
finish = tick_count::now();
cout << "tbb with lambda simple=" << (finish - start).seconds() << endl;
// Serial
start = tick_count::now();
for (int i = 0; i < task_num; i++) {
long long sum = 0; for (int j = 0; j < rep; j++) { sum += j; }
cout << sum << " ";
}
cout << endl;
finish = tick_count::now();
cout << "serial=" << (finish - start).seconds() << endl;
// OpenMP
start = tick_count::now();
long long sum;
int j;
#pragma omp parallel for private(sum, j)
for (int i = 0; i < task_num; i++) {
sum = 0; for (j = 0; j < rep; j++) { sum += j; }
cout << sum << " ";
ccc[i] = sum;
}
cout << endl;
finish = tick_count::now();
cout << "openmp=" << (finish - start).seconds() << endl;
init.terminate();
return 0;
}
| true |
0e1f83bbf1e4251439160a384a859af1e3a08ff6 | C++ | Thomas-Malcolm/Conways-Game-of-Life-Recreation | /src/Life.cpp | UTF-8 | 1,414 | 2.828125 | 3 | [] | no_license | #include "Life.h"
#include "olcPixelGameEngine.h"
#include <vector>
#include <random>
void Life::ResetLife()
{
for (int i = 0; i < boardWidth; i++)
{
for (int j = 0; j < boardHeight; j++)
{
LifeMap[j][i] = 0;
}
}
}
void Life::NextGen()
{
int neighbours;
for (int i = 1; i < boardWidth - 2; i++)
{
for (int j = 1; j < boardHeight - 2; j++)
{
neighbours = 0;
if (LifeMap[j - 1][i - 1] == 1) neighbours++;
if (LifeMap[j - 1][i] == 1) neighbours++;
if (LifeMap[j - 1][i + 1] == 1) neighbours++;
if (LifeMap[j][i - 1] == 1) neighbours++;
if (LifeMap[j][i + 1] == 1) neighbours++;
if (LifeMap[j + 1][i - 1] == 1) neighbours++;
if (LifeMap[j + 1][i] == 1) neighbours++;
if (LifeMap[j + 1][i + 1] == 1) neighbours++;
//printf("Neighboours: %d\n", neighbours);
if (LifeMap[j][i] == 1)
{
if (neighbours < 2 || neighbours > 3)
{
SetDead(j, i);
}
else
{
SetAlive(j, i);
}
}
else if ((LifeMap[j][i] == 0) && neighbours == 3)
{
SetAlive(j, i);
}
}
}
genCount++;
}
void Life::SetAlive(int x, int y)
{
LifeMap[x][y] = 1;
}
void Life::SetDead(int x, int y)
{
LifeMap[x][y] = 0;
}
void Life::RandomiseBoard()
{
for (int i = 0; i < boardWidth; i++)
{
for (int j = 0; j < boardHeight; j++)
{
LifeMap[j][i] = rand() % 2;
}
}
} | true |
f1d0d836ee6168507dd810e94f56d82d062ef4c5 | C++ | copyzerov3/JackOne | /JackLumberOne/Screen.h | UTF-8 | 668 | 2.765625 | 3 | [] | no_license | #pragma once
#ifndef __SCREEN_H
#define __SCREEN_H
#include <SDL.h>
#include "Texture.h"
#include "Managers.h"
class Screen
{
public:
Screen();
~Screen();
virtual void Update() = 0;
virtual void Draw() = 0;
virtual bool Init() = 0;
bool GetLeave()
{
return mLeave;
}
Screen* GetNextScreen()
{
return nextScreen;
}
void MakeTTFTexture(std::string words, Texture* &texture, SDL_Color colour= { 0, 0, 0 })
{
if (texture == nullptr)
texture = new Texture();
texture->LoadFromRenderedText(words, colour, Managers::GetGraphicsManager()->GetFont());
}
protected:
bool mLeave;
Screen* nextScreen;
SDL_Renderer* r;
InputManager* im;
};
#endif
| true |
3eebee4a62323bba89381cd20a13c3a5ff2496a9 | C++ | shuichih/oreoren | /src/vecmath/color4.h | UTF-8 | 3,463 | 3.109375 | 3 | [] | no_license | #ifndef SEVERE3D_COLOR4_H
#define SEVERE3D_COLOR4_H
//#include "severe3d/base.h"
#include "vecmath_def.h"
/**
* ARGB色を表現するクラスです。
*/
class Color4
{
public:
/** 透明度 (透明 < 不透明) */
float a;
/** 赤成分 */
float r;
/** 緑成分 */
float g;
/** 青成分 */
float b;
Color4(): a(0), r(0), g(0), b(0) {}
Color4(float sr, float sg, float sb): a(1.0f), r(sr), g(sg), b(sb) {}
Color4(float sa, float sr, float sg, float sb): a(sa), r(sr), g(sg), b(sb) {}
inline uint32 to32BitARGB() const {
uint32 uc_a = static_cast<uint32>(a * 255.999f);
uint32 uc_r = static_cast<uint32>(r * 255.999f);
uint32 uc_g = static_cast<uint32>(g * 255.999f);
uint32 uc_b = static_cast<uint32>(b * 255.999f);
return (uc_a << 24) | (uc_r << 16) | (uc_g << 8) | uc_b;
}
inline void from32BitARGB(int32 color32) {
a = ((color32 >> 24) & 0x000000ff) / 255.0f;
r = ((color32 >> 16) & 0x000000ff) / 255.0f;
g = ((color32 >> 8) & 0x000000ff) / 255.0f;
b = ( color32 & 0x000000ff) / 255.0f;
}
inline void mul(const Color4& color) {
r *= color.r;
g *= color.g;
b *= color.b;
}
inline void mul(const Color4& c1, const Color4& c2) {
r = c1.r * c2.r;
g = c1.g * c2.g;
b = c1.b * c2.b;
}
inline void scaleAdd(const Color4& c1, const Color4& c2, float scale) {
// alias safe
r = c1.r + scale * c2.r;
g = c1.g + scale * c2.g;
b = c1.b + scale * c2.b;
}
inline void scaleAdd(const Color4& c1, float scale) {
r += scale * c1.r;
g += scale * c1.g;
b += scale * c1.b;
}
inline void scale(float scale) {
r *= scale;
g *= scale;
b *= scale;
}
inline void add(const Color4& c1) {
r += c1.r;
g += c1.g;
b += c1.b;
}
inline void sub(const Color4& c1) {
r -= c1.r;
g -= c1.g;
b -= c1.b;
}
inline Color4& clamp() {
if (r < 0) r = 0; else if (r > 1.0f) r = 1.0f;
if (g < 0) g = 0; else if (g > 1.0f) g = 1.0f;
if (b < 0) b = 0; else if (b > 1.0f) b = 1.0f;
return *this;
}
inline void zero() {
a = 0;
r = 0;
g = 0;
b = 0;
}
// NOTE:コピーコンストラクタおよび = 演算子はコンパイラによって生成されます。
inline unsigned char a_byte() {
return static_cast<unsigned char>(a * 255);
}
inline unsigned char r_byte() {
return static_cast<unsigned char>(r * 255);
}
inline unsigned char g_byte() {
return static_cast<unsigned char>(g * 255);
}
inline unsigned char b_byte() {
return static_cast<unsigned char>(b * 255);
}
Color4& operator+=(const Color4& c1) {
add(c1);
return *this;
}
Color4& operator-=(const Color4& c1) {
sub(c1);
return *this;
}
Color4& operator*=(const Color4& c1) {
mul(c1);
return *this;
}
Color4& operator*=(float s) {
scale(s);
return *this;
}
Color4 operator+(const Color4& c1) const {
return (Color4(*this)).operator+=(c1);
}
Color4 operator-(const Color4& c1) const {
return (Color4(*this)).operator-=(c1);
}
Color4 operator*(const Color4& c1) const {
return (Color4(*this)).operator*=(c1);
}
Color4 operator*(float s) const {
return (Color4(*this)).operator*=(s);
}
};
// グローバル演算子
template <class T>
inline
severe3d::Color4 operator*(T s, const severe3d::Color4& c1) {
return c1 * s;
}
#endif // SEVERE3D_COLOR4_H
| true |
b2ff8c127a9758eccf61a909ad51badbf861c329 | C++ | teddy-hoo/leetcode | /palindrome_partitioning_2.cpp | UTF-8 | 867 | 3.109375 | 3 | [] | no_license | class Solution {
private:
bool isPalindrome(string s, int begin, int len){
int end = begin + len - 1;
while(begin <= end){
if(s[begin] != s[end]){
return false;
}
begin++;
end--;
}
return true;
}
public:
int minCut(string s) {
int len = s.size();
int minSplit = 1000;
if(len <= 0){
return minSplit;
}
vector<int> mins(len);
mins[0] = 0;
for(int i = 1; i < len; i++){
int min = 1000;
for(int j = i; j > 0; j--){
if(mins[j - 1] < min && isPalindrome(s, j, i - j + 1)){
int curStep = mins[j - 1] + 1;
min = curStep > min ? min : curStep;
}
}
if(isPalindrome(s, 0, i + 1)){
min = 0;
}
mins[i] = min;
}
return mins[len - 1];
}
};
| true |
08471292b5380babb78b2582bdde29cf63e7567e | C++ | sebasqr22/TEC-File-System | /text_box.cpp | UTF-8 | 2,689 | 3.640625 | 4 | [] | no_license | /**
* @file text_box.cpp
* @title Text Box
* @brief Class that creates a text box
* */
#pragma once
#include <SFML/Graphics.hpp>
using namespace std;
using namespace sf;
class text_box {
private:
Text text;
string textStr;
RectangleShape textbox;
bool isSelected = false;
public:
/**
* @brief Class' main constructor
* */
text_box(int charSize, Vector2f textboxSize, Color charColor, Color textboxColor, bool selected, Vector2f position, Font &font) {
text.setCharacterSize(charSize);
text.setFillColor(charColor);
text.setFont(font);
textbox.setSize(textboxSize);
textbox.setFillColor(textboxColor);
textbox.setPosition(position);
text.setPosition(Vector2f(textbox.getPosition().x, textbox.getPosition().y));
isSelected = selected;
}
/**
* @brief Method to set the selected
* */
void setSelected(bool selected) {
isSelected = selected;
}
/**
* @brief Method to draw the text box
* */
void draw(RenderWindow &window) {
window.draw(textbox);
window.draw(text);
}
/**
* @brief Method to update the text box
* */
void update(Vector2f mousepos) {
if (textbox.getGlobalBounds().contains(mousepos) && Mouse::isButtonPressed(Mouse::Left)) {
isSelected = true;
}
}
/**
* @brief Method to see if it is selected
* @return Bool value
* */
bool getSelected() {
return isSelected;
}
/**
* @brief Method to set a string
**/
void setString(Event input) {
if (isSelected) {
int chartyped = input.text.unicode;
if (chartyped != 8 && chartyped != 13 && chartyped != 27)
textStr += static_cast<char>(chartyped);
else if (chartyped == 8)
textStr.pop_back();
else if (chartyped == 13)
isSelected = false;
text.setString(textStr + "_");
}
text.setString(textStr);
}
/**
* @brief Method to set the whole string
**/
void setString2(string input) {
textStr = input;
text.setString(textStr);
}
/**
* @brief Method to get the string
* @return A string
* */
string getString() {
return textStr;
}
}; | true |
e69d84630369054d81dcc733c0015606e4a4f6e9 | C++ | soumya-ranjan7/Algorithms | /Sorting/bubbleSort/cpp/bubble_sort.cpp | UTF-8 | 517 | 3.890625 | 4 | [
"MIT"
] | permissive | /* Bubble Sort implementation in C++
* Author : Manvi Gupta
* Input : array length and elements
* Output : Sorted array elements
*/
#include <iostream>
using namespace std;
int n;
void bubble_Sort(int a[])
{
for(int i=0; i<n-1; i++)
for(int j=0; j<n-1-i; j++)
if(a[j] > a[j+1])
{
swap(a[j+1], a[j]);
}
}
int main()
{
cin >> n;
int a[n];
for(int i=0; i<n; i++)
cin >> a[i];
bubble_Sort(a);
for (int i = 0; i < n; i++) {
std::cout << a[i] << '\n';
}
return 0;
}
| true |
aa0f65ea274852b931e54e627c43933129ff82c3 | C++ | lheckemann/namic-sandbox | /UNCShapeAnalysisLONIpipeline/StatNonParamTestPDM/PvalToRGB.cxx | UTF-8 | 2,920 | 2.78125 | 3 | [] | no_license |
#include <algorithm>
#include <vector>
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <ctime>
#include <string>
#include <cmath>
#include <cstdio>
#include "argio.h"
using namespace std;
int main (int argc, const char ** argv)
{
if (argc <=1 || ipExistsArgument(argv, "-usage")) {
cout << argv[0] << endl;
cout << " reads in a file with a white-space (space, tab, CR, LF) separated list of Pvalues and write a 'comma' separated list of RGB values(each space separated)" << endl;
cout << " Colors assigned: non-significant (> 0.05) -> blue" << endl;
cout << " Colors assigned: significant -> from red (0.001) to green (0.05)" << endl;
cout << "usage: infile [-o outfile] [-signLevel <alpha>] [-minSignLevel <minVal>] [-iv]"<< endl;
cout << endl;
cout << "infile input data set " << endl;
cout << "-out outfile output data set, if omitted then 'output_def.colors'" << endl;
cout << "" << endl;
cout << endl << endl;
exit(0);
}
char *infile = strdup(argv[1]);
char *outfile = ipGetStringArgument(argv, "-out", "output_def.colors");
if (!infile) {
cerr << " no input file specified " << endl;exit(1);
}
const double significanceLevel = ipGetDoubleArgument(argv, "-signLevel", 0.05);
const double significanceMinLevel = ipGetDoubleArgument(argv, "-minSignLevel", 0.001);
double signDiff = (significanceLevel - significanceMinLevel)/2;
bool doOIVstyle = ipExistsArgument(argv, "-iv");
FILE * infile_file = fopen(infile,"r");
if (!infile_file) {
cerr << " Cannot open file " << infile_file << endl;
exit (-1);
}
ofstream efile(outfile, ios::out);
const int GATHER_ITEMS = 10;
int numFeatures = 0;
double curPval;
float colorR, colorG, colorB;
int first = 1;
if (doOIVstyle) {
efile << " Material { diffuseColor [ " << endl;
}
while (fscanf(infile_file," %lf ", &curPval) > 0) {
if (first) {
first = 0;
} else {
efile << ",";
if (numFeatures % GATHER_ITEMS == 0 ) efile << endl;
else efile << " ";
}
colorR = 0; colorG = 0; colorB = 0;
if (curPval > significanceLevel) {
colorR = 0; colorG = 0; colorB = 1;
} else if (curPval < significanceMinLevel){
colorR = 1; colorG = 0; colorB = 0;
} else if (curPval < significanceMinLevel + signDiff ) {
double part = (curPval - significanceMinLevel)/signDiff;
colorR = 1; colorG = part; colorB = 0;
} else {
double part = (curPval - significanceMinLevel - signDiff)/signDiff;
colorR = 1-part; colorG = 1; colorB = 0;
}
efile << colorR << " " << colorG << " " << colorB ;
numFeatures++;
}
cout << "numFeatures: " << numFeatures << endl;
fclose(infile_file);
efile << endl;
if (doOIVstyle) {
efile << " ] }" << endl;
efile << " MaterialBinding { value PER_VERTEX_INDEXED }" << endl;
}
efile.close();
}
| true |
f2afd1e8b0a3ffb6bdc91a67feed1bd0d17c304d | C++ | guilhermegals/asteroids-sdl | /Fonte/Asteroides.hpp | ISO-8859-1 | 5,160 | 2.875 | 3 | [] | no_license | /*
* Asteroides.hpp
*
* Created on: 11/06/2016
* Author: Guilherme
*/
#ifndef ASTEROIDES_HPP_
#define ASTEROIDES_HPP_
#include"Nave.hpp"
//Asteroids
class AsteroideGrande {
public:
SDL_Texture *pedraGrande;
float velocidadeGrande;
float anguloPedraGrande;
float vxP, vyP;
float anguloRadiano;
bool invisivel;
SDL_Rect oPedraGrande;
SDL_RendererFlip flip;
AsteroideGrande() {
defineAngulo();
iniciaPedraGrande();
}
//Define o angulo
void defineAngulo() {
anguloPedraGrande = rand() % 360;
}
//Inicia as variaveis
void iniciaPedraGrande() {
velocidadeGrande = 1.0;
defineAngulo();
oPedraGrande.x = rand() % 1000;
oPedraGrande.y = rand() % 650;
oPedraGrande.h = 146;
oPedraGrande.w = 132;
invisivel = false;
}
//Load imagem
void loadPedraGrande(Imagens *imagem) {
pedraGrande = IMG_LoadTexture(imagem->render,
"Imagens/Pedras/PedraGrande.png");
}
//Movimenta a pedra
void movePedra(SDL_Rect *oRect) {
if (invisivel == false) {
float seno, cosseno;
anguloRadiano = grausRadiano(anguloPedraGrande);
cosseno = floatToInt(cos(anguloRadiano));
seno = floatToInt(sin(anguloRadiano));
vxP = round(velocidadeGrande * cosseno);
vyP = round(velocidadeGrande * seno);
verificaParede(oRect);
oRect->x += vxP;
oRect->y += vyP;
SDL_Delay(1);
}
}
//Converte graus para radiano
float grausRadiano(float anguloGraus) {
float anguloRadiano;
anguloRadiano = 3.14 * (anguloGraus / 180);
return anguloRadiano;
}
//Converte float para int
float floatToInt(float numero) {
int aux;
aux = numero * 100;
numero = ((aux * 1.0) / 100);
return numero;
}
//Verifica se no est na parede
void verificaParede(SDL_Rect *oRect) {
if (oRect->x > 1000) {
oRect->x = 0;
}
if (oRect->x < 0) {
oRect->x = 1000;
}
if (oRect->y > 650) {
oRect->y = 0;
}
if (oRect->y < 0) {
oRect->y = 650;
}
}
//Atualiza a pedra
void atualizaPedra(SDL_Renderer *render, Jogador *jogador) {
if (invisivel == false) {
oPedraGrande.h = 146;
oPedraGrande.w = 132;
SDL_RenderCopyEx(render, pedraGrande, NULL, &oPedraGrande,
anguloPedraGrande, NULL, flip);
} else {
jogador->mudouScore = true;
jogador->nScore = jogador->mudouScore + 100;
}
}
bool operator==(const AsteroideGrande& a) {
if ((a.oPedraGrande.x == this->oPedraGrande.x)
&& (a.oPedraGrande.y == this->oPedraGrande.y)) {
return true;
} else {
return false;
}
}
};
//Asteroide Medio
class AsteroideMedio: public AsteroideGrande {
public:
SDL_Texture *pedraMedia;
float velocidadeMedia;
float anguloMedia;
float vxM, vyM;
float anguloMedioRadiano;
bool invisivel2;
SDL_Rect oPedraMedia;
//SDL_RendererFlip flip2;
//Construtor
AsteroideMedio() {
defineAnguloMedio();
iniciaPedraMedia();
}
//Define o angulo da Pedra Media
void defineAnguloMedio() {
anguloMedia = rand() % 360;
}
//Inicia as variaveis de Pedra Media
void iniciaPedraMedia() {
velocidadeMedia = 2.0;
defineAnguloMedio();
oPedraMedia.x = oPedraGrande.x;
oPedraMedia.y = oPedraGrande.y;
oPedraMedia.h = 27;
oPedraMedia.w = 25;
invisivel2 = false;
}
//Load Pedra media
void loadPedraMedia(Imagens *imagem) {
pedraMedia = IMG_LoadTexture(imagem->render,
"Imagens/Pedras/PedraMedia.png");
}
//Movimenta a pedra Media
void movePedra(SDL_Rect *oRect) {
if (invisivel2 == false) {
float seno, cosseno;
anguloMedioRadiano = grausRadiano(anguloMedia);
cosseno = floatToInt(cos(anguloMedioRadiano));
seno = floatToInt(sin(anguloMedioRadiano));
vxM = round(velocidadeMedia * cosseno);
vyM = round(velocidadeMedia * seno);
verificaParede(oRect);
oRect->x += vxP;
oRect->y += vyP;
SDL_Delay(1);
}
}
bool operator==(const AsteroideMedio& b) {
if ((b.oPedraGrande.x == this->oPedraGrande.x)
&& (b.oPedraGrande.y == this->oPedraGrande.y)) {
return true;
} else {
return false;
}
}
};
//Ufo
class Ufo: public AsteroideGrande {
public:
float anguloUfo, anguloUfoRadiano;
SDL_Texture *ufo;
SDL_Rect oUfo;
float vxF, vyF;
bool someUfo;
float velocidadeUfo;
Ufo() {
defineAnguloUfo();
iniciaUfo();
}
//Define o angulo
void defineAnguloUfo() {
anguloUfo = rand() % 360;
}
//Inicia as variaveis
void iniciaUfo() {
velocidadeUfo = 1.0;
defineAnguloUfo();
oUfo.x = rand() % 1000;
oUfo.y = rand() % 650;
oUfo.h = 50;
oUfo.w = 40;
someUfo = false;
}
//Load imagem
void loadUfo(Imagens *imagem) {
ufo = IMG_LoadTexture(imagem->render, "Imagens/Nave/Ufo.png");
}
//Movimenta o Ufo
void moveUfo(SDL_Rect *oRect) {
if (invisivel == false) {
float seno, cosseno;
anguloUfoRadiano = grausRadiano(anguloUfo);
cosseno = floatToInt(cos(anguloUfoRadiano));
seno = floatToInt(sin(anguloUfoRadiano));
vxF = round(velocidadeUfo * cosseno);
vyF = round(velocidadeUfo * seno);
verificaParede(oRect);
oRect->x += vxF;
oRect->y += vyF;
}
}
//Atualiza o Ufo
void atualizaUfo(SDL_Renderer *render) {
if (someUfo == false) {
oUfo.h = 50;
oUfo.w = 40;
SDL_RenderCopy(render, ufo, NULL, &oUfo);
}
}
};
#endif /* ASTEROIDES_HPP_ */
| true |
8f490309b7c3cc29aaf10ca13817fdee809ca44c | C++ | arorasam/adhoc | /CodingBlocks/CodingBlocks/BackTrack_StringPermutations.cpp | UTF-8 | 1,418 | 3.375 | 3 | [] | no_license | #include "stdafx.h"
#include <set>
static int counter;
void ExecPrintStringPerms()
{
char arr[100];
cout << "Enter a string to permute" << endl;
cin >> arr;
set<string> s;
s.insert(arr);
//PrintStringPerms(arr, boolArr, strlen(arr), 0);
int count = PrintStringPerms_InClass(arr, 0);
cout << count << " permutations" << endl;
}
int PrintStringPerms_InClass(char *a, int i)
{
int result = 0;
// Base case, stop when reached end of string.
if (a[i] == '\0')
{
cout << "---" << endl;
cout << a << endl;
return 1 ;
}
// Place one char at the front and cball the remaining part
for (int j = i; a[j] != '\0'; j++)
{
//if (i != j)
{
cout << "i: " << i << " j: " << j << endl;
swap(a[i], a[j]);
result += PrintStringPerms_InClass(a, i+1);
// Restore to backtrack
swap(a[j], a[i]);
}
}
return result;
}
void PrintStringPerms(const char* str, bool availableOptions[], int len, int currIdx)
{
//ToDo: Use Bitmask instead of bool array
// terminating condition
if (str[currIdx] == '\0')
{
// assuming str remains null terminated across recursive calls
cout << endl;
}
// Real Work -- chose next character from available options
for (int i = 0; i < len; i++)
{
if (availableOptions[i])
{
cout << str[i];
availableOptions[i] = false;
PrintStringPerms(str, availableOptions, len, currIdx + 1);
availableOptions[i] = true;
}
}
// recursive case
} | true |
1b49475f3a0d6b2ead5b9d0d7d02b1287fb8ccda | C++ | huashuolin/DesignModel | /单例模式/Singleton.h | UTF-8 | 354 | 2.78125 | 3 | [] | no_license | #pragma once
class CSingleton
{
private:
CSingleton()
: m_iCount(0)
{
}
virtual ~CSingleton()
{
}
int m_iCount;
public:
static CSingleton* GetInstance()
{
static CSingleton inst;
return &inst;
}
void CountAdd(int iNum)
{
m_iCount += iNum;
}
int GetCountNum()
{
return m_iCount;
}
}; | true |
7fee096ba5ea79bf82e8fa5ab2e3a3090750408c | C++ | OtemPsych/Slide-Puzzle | /Slide Puzzle/Grid.h | UTF-8 | 793 | 2.890625 | 3 | [] | no_license | #ifndef Grid_H_
#define Grid_H_
#include <SFML/System/NonCopyable.hpp>
#include <SFML/Graphics/RectangleShape.hpp>
#include <vector>
class Grid : public sf::Drawable,
private sf::NonCopyable
{
private:
// Private Member(s)
sf::RectangleShape mOutline;
std::vector<sf::Vector2f> mTilePositions;
private:
// Private Method(s)
void setupTilePositions();
void setupOutline(sf::IntRect windowBounds);
public:
// Constructor(s)
Grid(int tilesInRow, sf::IntRect windowBounds);
// Public Method(s)
virtual void draw(sf::RenderTarget& target, sf::RenderStates states) const;
// Public Getter Method(s)
inline sf::FloatRect getOutlineRect() const { return mOutline.getGlobalBounds(); }
inline sf::Vector2f getTilePos(int tileNb) const { return mTilePositions[tileNb]; }
};
#endif | true |
680181ba524fe4f3865e457334d9fd6935cee29e | C++ | boga95/shared_ptr | /BG_share_ptr/BG_share_ptr/graph.hpp | UTF-8 | 884 | 3.09375 | 3 | [] | no_license | /*
Created by Borsik Gabor
gabor.borsik@gmail.com
*/
#ifndef GRAPH_HPP_INCLUDED
#define GRAPH_HPP_INCLUDED
#include <iostream>
#include "shared_ptr.hpp"
template <class T>
class Graph
{
public:
Graph() {}
Graph(T *object_) : _object(object_) {}
Graph(const Graph<T>& graph);
~Graph() {}
void set_ptr1(const shared_ptr<Graph<T>>& ptr1_) { _ptr1 = ptr1_; }
void set_ptr2(const shared_ptr<Graph<T>>& ptr2_) { _ptr2 = ptr2_; }
const shared_ptr<T>& get_object() const { return _object; }
const shared_ptr<Graph<T>>& get_ptr1() const { return _ptr1; }
const shared_ptr<Graph<T>>& get_ptr2() const { return _ptr2; }
private:
shared_ptr<Graph<T>> _ptr1;
shared_ptr<Graph<T>> _ptr2;
shared_ptr<T> _object;
};
template<class T>
Graph<T>::Graph(const Graph<T>& graph)
{
_object = graph.get_object();
_ptr1 = graph.get_ptr1();
_ptr2 = graph.get_ptr2();
}
#endif // GRAPH_HPP_INCLUDED | true |
c6e3d48bd892286d016d4d97ae571fa68f3d2777 | C++ | schaefer-dev/embeddedSystems | /project01/src/collector/CollectorLineSensors.cpp | UTF-8 | 2,876 | 2.609375 | 3 | [] | no_license | #include "stdint.h"
#include "Arduino.h"
#include "CollectorLineSensors.h"
#include "Zumo32U4LineSensors.h"
#include "CollectorState.h"
Zumo32U4LineSensors CollectorLineSensors::lineSensors;
bool CollectorLineSensors::onLine;
const uint8_t CollectorLineSensors::threshold;
void CollectorLineSensors::init(CollectorState *collectorState) {
collectorState->drivingDisabled = false;
lineSensors.initThreeSensors();
calibrate(collectorState);
#ifdef COLLECTOR_DEBUG
Serial1.print(messageInitLineSensors);
#endif
}
void CollectorLineSensors::calibrate(CollectorState *collectorState, int duration) {
int calibrationSpeed = collectorState->forwardSpeed / 2;
collectorState->drivingDisabled = false;
long start = millis();
while (millis() - start < duration / 2) {
collectorState->setSpeeds(calibrationSpeed, calibrationSpeed);
lineSensors.calibrate();
delay(20);
}
while (millis() - start < duration) {
collectorState->setSpeeds(-calibrationSpeed, -calibrationSpeed);
lineSensors.calibrate();
delay(20);
}
collectorState->setSpeeds(0, 0);
collectorState->drivingDisabled = true;
#ifdef COLLECTOR_DEBUG
Serial1.print(messageInitLineSensors);
#endif
}
bool CollectorLineSensors::detectLine() {
uint16_t sensorReadings[3] = {0, 0, 0};
bool lineDetected = false;
lineSensors.readCalibrated(sensorReadings);
delay(10);
Serial1.print(sensorReadings[1]);
Serial1.print("\n");
/*
for (unsigned int sensorReading : sensorReadings) {
Serial1.print(sensorReading);
Serial1.print("\n");
}*/
if (sensorReadings[1] > threshold) {
if (!onLine) {
lineDetected = true;
}
onLine = true;
} else {
onLine = false;
}
return lineDetected;
}
void CollectorLineSensors::driveOverLines(CollectorState *collectorState) {
/*int serialMessageLength = 0;
char serialMessage[2];
serialMessageLength = CollectorSerial::readMessageFromSerial(serialMessage);
if (serialMessageLength < 1) {
return;
}*/
#ifdef COLLECTOR_DEBUG
Serial1.write(serialMessage);
Serial1.write("\n");
#endif
int number = 0;
/*
int number = serialMessage[0] - 48;
if (serialMessageLength > 1) {
number *= 10;
number += serialMessage[1] - 48;
}*/
#ifdef COLLECTOR_DEBUG
Serial1.write("drive lines: ");
Serial1.write(number);
#endif
collectorState->drivingDisabled = false;
while (true) {
detectLine();
continue;
collectorState->setSpeeds(collectorState->forwardSpeed, collectorState->forwardSpeed);
if (detectLine()) {
Serial1.write("Found a line\n");
--number;
}
}
collectorState->setSpeeds(0, 0);
collectorState->drivingDisabled = true;
}
| true |
305c13aa3ca140015c1b2f4ed46bd57f929cdfe3 | C++ | MsNahid/Uva-Problem-Solutions | /uva-10469-solution.cpp | UTF-8 | 224 | 2.625 | 3 | [] | no_license | #include <iostream>
#include <cstdio>
#include <cmath>
using namespace std;
int main(){
unsigned int a, b;
while(scanf("%u%u", &a, &b) == 2){
printf("%u\n", a ^ b);
}
return 0;
}
| true |
6caae9c6918edb2d1e62282c9497b4c6a6b5d7e4 | C++ | Farkash/Arduino | /9x16-matrix/9x16-matrix.ino | UTF-8 | 4,026 | 2.65625 | 3 | [] | no_license | #include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_IS31FL3731.h>
#include <Adafruit_NeoPixel.h>
int neoPixelCount = 12;
int neoPixelPin = 13;
// If you're using the full breakout...
Adafruit_IS31FL3731 ledmatrix = Adafruit_IS31FL3731();
// If you're using the FeatherWing version
//Adafruit_IS31FL3731_Wing ledmatrix = Adafruit_IS31FL3731_Wing();
Adafruit_NeoPixel strip = Adafruit_NeoPixel(neoPixelCount, neoPixelPin, NEO_GRB + NEO_KHZ800);
// The lookup table to make the brightness changes be more visible
uint8_t sweep[] = {1, 2, 3, 4, 6, 8, 10, 15, 20, 30, 40, 60, 60, 40, 30, 20, 15, 10, 8, 6, 4, 3, 2, 1};
unsigned long randomLast = 0;
unsigned long colorWipeLast = 0;
int i = 0;
uint32_t c;
int cycleTracker = 0;
int sensorPin = A0; // select the input pin for the potentiometer
int sensorValue = 0; // variable to store the value coming from the sensor
long r;
long g;
long b;
unsigned long randomPixelLast;
int randomIteration = 0;
void setup() {
Serial.begin(9600);
Serial.println("ISSI swirl test");
if (! ledmatrix.begin()) {
Serial.println("IS31 not found");
while (1);
}
Serial.println("IS31 found!");
randomSeed(analogRead(0));
strip.begin();
strip.show(); // Initialize all pixels to 'off'
}
void loop() {
// animate over all the pixels, and set the brightness from the sweep table
// for (uint8_t incr = 0; incr < 24; incr++)
// for (uint8_t x = 0; x < 16; x++)
// for (uint8_t y = 0; y < 9; y++)
// ledmatrix.drawPixel(x, y, sweep[(x+y+incr)%24]);
// delay(20);
randomPixel(10);
//randomColorWipe(100, 0);
randomColorPixel(30, 100);
}
long randomColorPicker(int a, int b)
{
int rint = random(a,b);
int diff = b - a;
float interval = 256 / diff;
int intervalInt = (int)interval;
return rint * intervalInt;
}
void randomPixel(int wait)
{
unsigned long randomClock = millis();
if(randomClock - randomLast > wait)
{
int x = random(0,16);
int y = random(0,9);
int state = random(2);
int bright = random(1, 4);
// int brightLevel = bright * 127;
int brightLevel;
switch(bright)
{
case 1: brightLevel = 10;
break;
case 2: brightLevel = 50;
break;
case 3: brightLevel = 100;
break;
// case 4: brightLevel = 150;
// break;
}
if(state == 0)
ledmatrix.drawPixel(x, y, brightLevel);
else
ledmatrix.drawPixel(x, y, 0);
randomLast = randomClock;
}
}
void randomColorPixel(uint8_t wait, int x)
{
unsigned long colorWipeClock = millis();
if(colorWipeClock - randomPixelLast >= wait)
{
if(randomIteration == 0) // only change the color at beginning of cycle
{
long randomRed = randomColorPicker(0,5);
long randomGreen = randomColorPicker(0,5);
long randomBlue = randomColorPicker(0,5);
c = strip.Color((int)(randomRed/10), (int)(randomGreen/10), (int)(randomBlue/10));
}
// Random pixel indexing logic goes here
int pixel = random(12);
int state = random(2);
if(state == 0) // pixel off
{
strip.setPixelColor(pixel, strip.Color(0, 0, 0));
}
else
{
strip.setPixelColor(pixel, c);
}
strip.show();
randomPixelLast = colorWipeClock;
if(randomIteration < x)
{
randomIteration++;
}
else
{
randomIteration = 0;
}
}
}
void randomColorWipe(uint8_t wait, int d)
{
unsigned long colorWipeClock = millis();
if(colorWipeClock - colorWipeLast >= wait)
{
if(i == 0) // only change the color at beginning of cycle
{
long randomRed = randomColorPicker(0,5);
long randomGreen = randomColorPicker(0,5);
long randomBlue = randomColorPicker(0,5);
c = strip.Color(randomRed, randomGreen, randomBlue);
}
strip.setPixelColor(i, c);
if(d != 0)
{
strip.setPixelColor(i-d, strip.Color(0,0,0));
}
strip.show();
colorWipeLast = colorWipeClock;
if(i < strip.numPixels()-1)
{
i++;
}
else
{
i = 0;
}
}
}
| true |
994714a77e60e841de3626fd84003e962ad7e720 | C++ | hangyu0100/pplp | /include/pplp_ray.h | UTF-8 | 760 | 2.78125 | 3 | [] | no_license | /*******************************************************************************
* Copyright (c) 2016 Dec. Verimag. All rights reserved.
* @author Hang YU
* A ray starts from a point and goes to infinity along a direction.
* As in the raytraing method all the rays start from the same point which is
* stored in Raytracing class, a Ray object only contains the direction.
*******************************************************************************/
#ifndef _RAYTRACING_RAY
#define _RAYTRACING_RAY
#include "pplp_point.h"
#include "pplp_polyhedron.h"
namespace PPLP {
class Ray {
public:
Ray(const Vector& direction) ;
Ray(const Point& p1, const Point& p2) ;
const Vector& get_direction() const ;
private:
Vector _direction ;
} ;
}
#endif
| true |
81e406941fcbadd1a5e967d7ded512ef94e885a8 | C++ | el-bart/WiFiChopper | /commons/src/Net/ClientServer.t.cpp | UTF-8 | 1,530 | 2.734375 | 3 | [] | no_license | #include <tut/tut.hpp>
#include <string>
#include <iterator>
#include <algorithm>
#include "Net/Server.hpp"
#include "Net/connectToServer.hpp"
using namespace std;
using namespace Net;
namespace
{
struct TestClass
{
TestClass(void):
addr_( {{127,0,0,1}}, 9666 )
{ }
const Address addr_;
};
typedef tut::test_group<TestClass> factory;
typedef factory::object testObj;
factory tf("Net/Client+Server");
} // unnamed namespace
namespace tut
{
// test connection to non-opened port
template<>
template<>
void testObj::test<1>(void)
{
try
{
connectToServer(addr_);
fail("connection didn't failed");
}
catch(const CallError&)
{ }
}
// test opening the same port twice
template<>
template<>
void testObj::test<2>(void)
{
const Server s1(addr_);
try
{
const Server s2(addr_);
fail("no error when opening the same address:port twice");
}
catch(const CallError&)
{ }
}
// test connection to the server and transmition of small data pack
template<>
template<>
void testObj::test<3>(void)
{
// setup connection
Server ss(addr_);
Channel cln=connectToServer(addr_);
Channel srv=ss.accept();
// write some data
const string msg="hello network";
Channel::Data in( msg.begin(), msg.end() );
cln.write(in);
// read on the other side
Channel::Data out;
srv.read(out, 2.0);
// check the result
string msgOut;
copy( out.begin(), out.end(), back_insert_iterator<string>(msgOut) );
ensure_equals("invalid message", msgOut, msg);
}
} // namespace tut
| true |
e315ab10eee5317dc1cbbce7490652569c3dcd4c | C++ | MihaiAnghelin/StepIT-C | /13) 20.01.2019/Sir Subsir.cpp | UTF-8 | 867 | 3.109375 | 3 | [] | no_license | //program pentru a cauta numarul de aparitii
#include <cstdio>
#include <cstdlib>
#include <cstring>
#define N 100
int functie(const char* sir, const char* subsir)
{
int l1 = strlen(sir);
int l2 = strlen(subsir);
int contor = 0;
for (int i = 0; i <= l1 - l2 + 1; i++)
{
int j = 0;
int i2 = i;
while (sir[i2] == subsir[j] && i2 < l1)
{
i2++;
j++;
}
if (j == l2)
contor++;
}
return contor;
}
int main()
{
char a[N], b[N];
printf("Introduceti sirul de caractere: ");
fgets(a, sizeof(a), stdin);
a[strlen(a) - 1] = '\0';
printf("Introduceti subsirul: ");
fgets(b, sizeof(b), stdin);
b[strlen(b) - 1] = '\0';
int nr = functie(a, b);
printf("Numarul de aparitii este: %d \n", nr);
system("pause");
return 0;
} | true |
b94b59e2cb8d12885b1477589d9fc6d7691244b8 | C++ | nolanderc/school-n- | /N++/Ninja.h | ISO-8859-1 | 3,507 | 2.703125 | 3 | [] | no_license | #pragma once
#include "ConvexHull.h"
#include "Collider.h"
#include "Interpolate.h"
// De olika stt en Ninja kan rra sig p
enum NinjaMovement {
NINJA_STILL,
NINJA_LEFT,
NINJA_RIGHT,
NINJA_JUMP,
NINJA_CANCEL_JUMP,
NINJA_DROP
};
// De olika stt en ninja kan gra en pose
enum NinjaPose
{
POSE_NONE,
POSE_VICTORY
};
// Variabler fr att justera parametrar fr ninjans rrelse
const double MOVE_SPEED = 6.25;
const double GRAVITY = 4.2;
const Vector2 DRAG = {1.0, 0.5};
const double WALL_FRICTION = 6;
const double JUMP_FORCE = 6.2;
const double MAX_JUMP_DURATION = 1.0;
class Ninja
{
// Ett konvext skal fr kollision
ConvexHull hull;
struct SkeletonData
{
BoundingBox bounds;
double width, height;
double backLength, armLength, legLength;
Vector2 mid;
Vector2 velocity;
Vector2* groundNormal, * wallNormal;
NinjaPose pose;
};
// Positioner fr en ninjas alla leder
struct Skeleton {
Vector2 head[2];
Vector2 shoulder;
Vector2 elbows[2];
Vector2 hands[2];
Vector2 hip;
Vector2 knees[2];
Vector2 feet[2];
Skeleton() = default;
// Berkna skelettets strutkur utifrn en bunt parametrar
Skeleton(SkeletonData data);
// Rita skelettet
void draw(Renderer& renderer);
// Spegla skelettet runt en punkt i x-led
void mirrorX(double x);
private:
// Skapar skelettets huvud
void createHead(SkeletonData data);
/*
* Alla dessa funktioner ger skelettet sin form genom att
* beskriva vinkeln mellan alla kroppdelar
*/
// Skapar ett skelett som str stilla
void stand(SkeletonData data);
// Skapar ett skelett som klttrar
void climb(SkeletonData data);
// Skapar ett skelett som faller
void fall(SkeletonData data);
// Skapar ett skelett som str i en vinnarpose
void victory(SkeletonData data);
} skeleton;
// Den nuvarande hastigheten och riktningen
Vector2 velocity;
// Lagrar markens normal relativt till spelaren, om ninjan nuddar marken
Vector2* groundNormal;
// Lagrar vggens normal relativt till spelaren, om ninjan nuddar vggen
Vector2* wallNormal;
// t vilket hll ninjan ska rra p sig
NinjaMovement movement;
// Borde ninjan hoppa?
bool jump;
// Hller ninjan p att hoppa?
bool jumping;
// Hur lnge ninjan har hoppat
double jumpDuration;
// Den nuvarande pose ninjan har
NinjaPose currentPose;
public:
Ninja();
Ninja(Vector2 start);
~Ninja();
// Anger att ninjan ska rra sig t ett hll nsta uppdatering
void move(NinjaMovement movement);
// Uppdaterar ninjans position, hanterar kollision, etc
void update(double deltaTime, const std::vector<const Collider*>& colliders);
// Ritar ninjan till en ritare
void render(Renderer& renderer);
// Returnerar ninjans konvexa skal
const ConvexHull& getConvexHull() const;
// Anger att ninjan ska anta en pose
void pose(NinjaPose ninjaPose);
// Avgr om ninjan gr en pose
bool isPosing();
private:
// Frflytta ninjan ur kollisioner
void resolveCollisions(const std::vector<const Collider*>& colliders);
// Vid varje kollision, frsker frflytta ninjan ur kollisionen
void handleOverlap(Vector2 overlap);
// Anpassa hastigheten och frdriktningen efter en kollision
void handleCollision(Vector2 normal);
// Uppdatera ninjans leder beroende p dess rrelse
void updateSkeleton(double deltaTime);
// Returnera den nuvarande strukturen av ninjans leder
// TODO: Dela upp i mindre delar
Skeleton getSkeleton();
};
| true |
8d7372dffa881e1d4a59458a7dccfb83cf725cdd | C++ | joaopedroxavier/Competitive-Programming | /imeplusplus/2018-tryouts/i.cpp | UTF-8 | 1,831 | 2.796875 | 3 | [] | no_license | //
// 내가 나인 게 싫은 날
// 영영 사라지고 싶은 날
// 문을 하나 만들자 너의 맘 속에다
// 그 문을 열고 들어가면
// 이 곳이 기다릴 거야
// 믿어도 괜찮아 널 위로해줄 magic shop
//
#include <bits/stdc++.h>
using namespace std;
#define mp make_pair
#define pb push_back
#define st first
#define nd second
typedef long long ll;
typedef long double ld;
typedef pair<int,int> ii;
const ld EPS = 1e-9;
const ld PI = acos(-1);
const int N = 1e5+5;
const int MOD = 1e9+7;
const int INF = 0x3f3f3f3f;
struct point {
ll x, y;
point() : x(0), y(0) {}
point(ll x, ll y) : x(x), y(y) {}
point operator+(point p) const { return point(x+p.x, y+p.y); }
point operator-(point p) const { return point(x-p.x, y-p.y); }
ll operator%(point p) const { return x*p.y - y*p.x; }
};
vector<point> sheena, rose, maria;
int s, r, m;
bool inside(vector<point>& wall, point p, int sz) {
for(int i=0; i<sz; i++) {
if((wall[(i+1)%sz] - wall[i]) % (p - wall[i]) < 0) return false;
}
return true;
}
string wall_belonging(point p) {
if(inside(sheena, p, s)) return "Sheena";
if(inside(rose, p, r)) return "Rose";
if(inside(maria, p, m)) return "Maria";
return "Outside";
}
int main(){
//freopen("in", "r", stdin);
//freopen("out", "w", stdout);
scanf("%d %d %d", &s, &r, &m);
for(int i=0; i<s; i++) {
ll x, y; scanf("%lld %lld", &x, &y);
sheena.push_back(point(x, y));
}
for(int i=0; i<r; i++) {
ll x, y; scanf("%lld %lld", &x, &y);
rose.push_back(point(x, y));
}
for(int i=0; i<m; i++) {
ll x, y; scanf("%lld %lld", &x, &y);
maria.push_back(point(x, y));
}
int n; scanf("%d", &n);
for(int i=0; i<n; i++) {
point p; scanf("%lld %lld", &p.x, &p.y);
printf("%s\n", wall_belonging(p).c_str());
}
return 0;
}
| true |
77fcba746084c69b53463982beffd907d0f9e8da | C++ | eitilabs/proi0-robot | /include/RobotDrive.h | UTF-8 | 330 | 2.5625 | 3 | [] | no_license | #ifndef ROBOTDRIVE_H
#define ROBOTDRIVE_H
class RobotDrive
{
public:
RobotDrive();
virtual ~RobotDrive();
void driveForward(double distance);
void driveBackwards(double distance);
double getPosition();
protected:
private:
double position;
};
#endif // ROBOTDRIVE_H
| true |
2e47f02342db7ef2b3bebb19b5b53ef9196e558a | C++ | Ch3shireDev/WIT-Zajecia | /semestr-2/Programowanie/2020/kolokwium-2/zad12.cpp | UTF-8 | 399 | 3.640625 | 4 | [] | no_license | #include <iostream>
using namespace std;
void clock(int hours, int minutes, double &x, double &y)
{
x = hours % 12 * 30 + minutes / 60. * 30;
y = minutes % 60 * 6;
}
int main()
{
int hours, minutes;
cout << "Podaj godziny: ";
cin >> hours;
cout << "Podaj minuty: ";
cin >> minutes;
double x, y;
clock(hours, minutes, x, y);
cout << x << " " << y << endl;
} | true |
5a1a5c1041c64bc03502a69f73e26476de57a728 | C++ | Sysreqx/Cpp | /itstep/HW/17.05.2018 PrintQueue, List/singleLinkedList/Source.cpp | UTF-8 | 294 | 2.703125 | 3 | [] | no_license | #include "singleLinkedList.h"
#include <ctime>
int main()
{
srand(time(0));
singleLinkedList<int> l;
int tmp;
for (int i = 0; i < 10; i++)
l.push_back(tmp = rand() % 10);
l.print();
std::cout << std::endl;
l.printReverse();
std::cout << std::endl;
system("pause");
return 0;
} | true |
418e0b4107003de5ebe62ffdaf4d0bd63846e975 | C++ | pelican/pelican | /pelican/server/test/src/LockableStreamDataTest.cpp | UTF-8 | 1,842 | 2.515625 | 3 | [
"BSD-3-Clause",
"BSD-2-Clause"
] | permissive | #include "server/test/LockableStreamDataTest.h"
#include "server/LockableStreamData.h"
#include "server/LockableServiceData.h"
#include "server/LockedData.h"
#include "comms/StreamData.h"
#include <QtCore/QString>
namespace pelican {
CPPUNIT_TEST_SUITE_REGISTRATION( LockableStreamDataTest );
/**
*@details LockableStreamDataTest
*/
LockableStreamDataTest::LockableStreamDataTest()
: CppUnit::TestFixture()
{
}
/**
*@details
*/
LockableStreamDataTest::~LockableStreamDataTest()
{
}
void LockableStreamDataTest::setUp()
{
}
void LockableStreamDataTest::tearDown()
{
}
void LockableStreamDataTest::test_addAssociates()
{
std::vector<char> data(10);
QString name("locked1");
LockableServiceData ld(name,&data[0],data.size()); // dummy associate data
LockedData lockedData(name, &ld); // lock the dummy
LockableStreamData d("test", &data[0], data.size()); // create test object
CPPUNIT_ASSERT_EQUAL( true, d.isValid() );
// Use Case:
// Add a single associuate
// Expect local copy and underlying StreamData to
// have the associate
CPPUNIT_ASSERT_EQUAL( 0, (int)d.associateData().size() );
CPPUNIT_ASSERT_EQUAL( 0, (int)d.streamData()->associateData().size() );
d.addAssociatedData(lockedData);
CPPUNIT_ASSERT_EQUAL( 1, (int)d.associateData().size() );
CPPUNIT_ASSERT_EQUAL( 1, (int)d.streamData()->associateData().size() );
CPPUNIT_ASSERT_EQUAL( true, d.isValid() );
// Use Case:
// reset(0) should empty the associatedData
// of both lockedData and its underlying StreamData
// object, object should not be valid
d.reset(0);
CPPUNIT_ASSERT_EQUAL( 0, (int)d.associateData().size() );
CPPUNIT_ASSERT_EQUAL( 0, (int)d.streamData()->associateData().size() );
CPPUNIT_ASSERT_EQUAL( false, d.isValid() );
}
} // namespace pelican
| true |
a9897e5bbd7c56ac4f3341dee5d91583d1983da3 | C++ | Giantpizzahead/comp-programming | /Other/Google/Kick Start 2020/Round E/highbuildings.cpp | UTF-8 | 1,966 | 2.859375 | 3 | [] | no_license | #include <iostream>
using namespace std;
const int MAXN = 100;
int N, A, B, C;
int arr[MAXN];
void solve(int tn) {
cin >> N >> A >> B >> C;
A -= C;
B -= C;
if (A + B + C > N) {
cout << "Case #" << tn << ": IMPOSSIBLE\n";
return;
}
int leftOver = N - A - B - C;
if (N > 2) {
if (leftOver > N - 2) {
cout << "Case #" << tn << ": IMPOSSIBLE\n";
return;
}
int i = 0;
for (int j = 0; j < A; i++, j++) {
arr[i] = 2;
}
bool leftOverPlaced = false;
if (A != 0) {
leftOverPlaced = true;
for (int j = 0; j < leftOver; i++, j++) {
arr[i] = 1;
}
}
arr[i++] = 3;
if (!leftOverPlaced) {
leftOverPlaced = true;
for (int j = 0; j < leftOver; i++, j++) {
arr[i] = 1;
}
}
for (int j = 1; j < C; i++, j++) {
arr[i] = 3;
}
for (int j = 0; j < B; i++, j++) {
arr[i] = 2;
}
} else if (N == 1) {
if (C != 1) {
cout << "Case #" << tn << ": IMPOSSIBLE\n";
return;
} else arr[0] = 1;
} else {
if (C == 2) {
arr[0] = 1;
arr[1] = 1;
} else if (C == 0) {
cout << "Case #" << tn << ": IMPOSSIBLE\n";
return;
} else if (A == 1 && B == 0) {
arr[0] = 1;
arr[1] = 2;
} else if (B == 1 && A == 0) {
arr[0] = 2;
arr[1] = 1;
} else {
cout << "Case #" << tn << ": IMPOSSIBLE\n";
return;
}
}
cout << "Case #" << tn << ": ";
for (int i = 0; i < N; i++) {
cout << arr[i] << (i == N-1 ? '\n' : ' ');
}
}
int main() {
ios::sync_with_stdio(false);
int T;
cin >> T;
for (int i = 1; i <= T; i++) solve(i);
return 0;
} | true |
9405fc10d6070560c0e1c5cc874b0fbe47bc618b | C++ | lyleshaw/Cpp | /stand/1.1 奇数阶魔阵.cpp | GB18030 | 1,295 | 3.421875 | 3 | [] | no_license | #include <iostream>
#include <fstream>
using namespace std;
int main()
{
int n, k;
while (cin >> n) {
int *p = new int [n*n];
for (k = 0; k < n *n; k++)
p [k] = 0;
int row = 0, col = n / 2;
for (k = 1; k <= n*n; k++) {
p [ row *n+col] = k;
int newRow, newCol;
newRow = (row - 1 + n) % n;
newCol = (col + 1) % n;
if (p [ newRow *n + newCol] == 0) {
row = newRow; col = newCol;
} else {
row = (row +1) % n;
}
}
for (row = 0; row < n; row ++) {
for (col = 0; col < n; col ++) {
cout.width (5);
cout << p [row *n+col];
}
cout << endl;
}
cout << endl;
delete [] p;
}
return 0;
}
/*ħ
Ŀ
ÿһnһn X n(ħ), Ԫ1~nƽ, ÿһ֮͡ÿһ֮͡Խ֮;ȡҪʹö̬洢.
n
ÿռ5λÿкһ
7
30 39 48 1 10 19 28
38 47 7 9 18 27 29
46 6 8 17 26 35 37
5 14 16 25 34 36 45
13 15 24 33 42 44 4
21 23 32 41 43 3 12
22 31 40 49 2 11 20
*/
| true |
d6b2ad6028b8f095cb75cbfca40178552b1cb968 | C++ | xiaoqixian/Wonderland | /leetcode/threeSum.cpp | GB18030 | 1,243 | 3.40625 | 3 | [] | no_license | /*
Leetcode: 15.֮
vectorеÿαΪ֮͵СֵȻȽֻҪ˫ָԺ
*/
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> res;
sort(nums.begin(), nums.end());
int i;
int mid, max;
unordered_map<int, int*> m;
for (i = 0; i < nums.size(); i++) {
if (nums[i] > 0) break;
if (i > 0 && nums[i] == nums[i-1]) continue;
int comp = 0 - nums[i];
mid = i + 1, max = nums.size() - 1;
while (mid < max) {
if (nums[mid] + nums[max] == comp) {
printf("i = %d\n", i);
res.push_back({nums[i], nums[mid], nums[max]});
while (mid < max && nums[mid] == nums[mid+1]) mid++;
while (mid < max && nums[max] == nums[max-1]) max--;
mid++; max--;
}
else {
if (nums[mid] + nums[max] < comp) mid++;
else max--;
}
}
}
return res;
}
};
| true |
90a8b00c167ae29a89296eb2f4da121bdd24c00b | C++ | FloopCZ/forge | /src/api/cpp/exception.cpp | UTF-8 | 2,317 | 2.625 | 3 | [
"BSD-3-Clause"
] | permissive | /*******************************************************
* Copyright (c) 2014, ArrayFire
* All rights reserved.
*
* This file is distributed under 3-clause BSD license.
* The complete license agreement can be obtained at:
* http://arrayfire.com/licenses/BSD-3-Clause
********************************************************/
#include <fg/exception.h>
#include <err_common.hpp>
#include <string>
#include <iostream>
#include <sstream>
#include <algorithm>
#include <cstring>
using std::string;
using std::stringstream;
using std::cerr;
namespace forge
{
void stringcopy(char* dest, const char* src, size_t len)
{
#if defined(OS_WIN)
strncpy_s(dest, forge::common::MAX_ERR_SIZE, src, len);
#else
strncpy(dest, src, len);
#endif
}
Error::Error() : mErrCode(FG_ERR_UNKNOWN)
{
stringcopy(mMessage, "Unknown Exception", sizeof(mMessage));
}
Error::Error(const char * const pMessage)
: mErrCode(FG_ERR_UNKNOWN)
{
stringcopy(mMessage, pMessage, sizeof(mMessage));
mMessage[sizeof(mMessage) - 1] = '\0';
}
Error::Error(const char * const pFileName, int pLine, ErrorCode pErrCode)
: mErrCode(pErrCode)
{
snprintf(mMessage, sizeof(mMessage) - 1,
"Forge Exception (%s:%d):\nIn %s:%d",
fg_err_to_string(pErrCode), (int)pErrCode, pFileName, pLine);
mMessage[sizeof(mMessage)-1] = '\0';
}
Error::Error(const char * const pMessage,
const char * const pFileName, const int pLine, ErrorCode pErrCode)
: mErrCode(pErrCode)
{
snprintf(mMessage, sizeof(mMessage) - 1,
"Forge Exception (%s:%d):\n%s\nIn %s:%d",
fg_err_to_string(pErrCode), (int)pErrCode, pMessage, pFileName, pLine);
mMessage[sizeof(mMessage)-1] = '\0';
}
Error::Error(const char * const pMessage, const char * const pFuncName,
const char * const pFileName, const int pLine, ErrorCode pErrCode)
: mErrCode(pErrCode)
{
snprintf(mMessage, sizeof(mMessage) - 1,
"Forge Exception (%s:%d):\n%sIn function %s\nIn file %s:%d",
fg_err_to_string(pErrCode), (int)pErrCode, pMessage, pFuncName, pFileName, pLine);
mMessage[sizeof(mMessage)-1] = '\0';
}
Error::Error(const Error& error)
{
this->mErrCode = error.err();
memcpy(this->mMessage, error.what(), 1024);
}
Error::~Error() throw() {}
}
| true |
1af62c14c553d6e22d3bc27e424c9e1256724053 | C++ | moy/cours-tlm | /code/smartpointer/main_refcount.cpp | UTF-8 | 1,182 | 2.71875 | 3 | [] | no_license | /********************************************************************
* Copyright (C) 2009 by Verimag *
* Initial author: Matthieu Moy *
********************************************************************/
#include "refcount_ptr.h"
#define PRINT(x) do { cout << #x << " = " << x << endl; } while (false)
using namespace std;
refcount_ptr<int> get_ptr() {
return refcount_ptr<int>(new int(100));
}
void buggy() {
throw 42;
}
void calling_buggy () {
refcount_ptr<int> p(new int(33));
cout << "Going to call buggy()" << endl;
buggy();
cout << "end of calling_buggy" << endl;
}
int main () {
refcount_ptr<int> p1(new int(42));
PRINT(*p1);
REFCOUNT_PTR_DEBUG(p1);
{
refcount_ptr<int> p2 = p1;
refcount_ptr<int> p3(new int(666));
p3 = p1;
REFCOUNT_PTR_DEBUG(p1);
REFCOUNT_PTR_DEBUG(p2);
REFCOUNT_PTR_DEBUG(p3);
*p1 = 12;
PRINT(*p2);
}
REFCOUNT_PTR_DEBUG(p1);
{
refcount_ptr<int> retval = get_ptr();
REFCOUNT_PTR_DEBUG(retval);
PRINT(*retval);
}
try {
calling_buggy();
} catch (int i) {
cout << "exception cought" << endl;
}
cout << "end of main" << endl;
return 0;
}
| true |
a5c0b2d760ee267ea42aa9ea9f0625f920115979 | C++ | Svilensk/Unity_Tool_DLL | /VSProject/code/UTool_StaticLib/sources/BrushPainting.cpp | ISO-8859-1 | 9,625 | 3.09375 | 3 | [] | no_license | /*
* // Made By: Santiago Arribas Maroto
* // 2018/2019
* // Contact: Santisabirra@gmail.com
*/
#include "BrushPainting.hpp"
typedef unsigned char uint8_t;
//Establece el color de los pxeles al color introducido en el rea y posicin indicada
uint8_t* UTool::BrushPainting::paint_pixel_buffer(int size_x, int size_y, uint8_t* input_color_values, float mouse_x, float mouse_y, uint8_t* input_brush_values, int brush_size)
{
//Valor absoluto en bytes de la textura
int absolute_byte_size = (size_x * size_y) * 4;
int absolute_byte_row_size = size_x * 4;
int local_mouse_x_relative_pos = static_cast<int> (size_x * (mouse_x * 0.01f));
int local_mouse_y_relative_pos = static_cast<int> (size_y * (mouse_y * 0.01f));
//Clculo del offset en la textura para la posicin del cursor
size_t mouse_local_coordinates = local_mouse_y_relative_pos * size_x + (local_mouse_x_relative_pos);
size_t mouse_absolute_coordinates = mouse_local_coordinates * 4;
uint8_t *output_color_values = new uint8_t[absolute_byte_size];
for (size_t byte_iterator = 0; byte_iterator < absolute_byte_size; byte_iterator += 4)
{
if (brush_size_area_comprobation(byte_iterator, brush_size, mouse_absolute_coordinates, absolute_byte_row_size))
{
output_color_values[byte_iterator + 0] = input_brush_values[0];
output_color_values[byte_iterator + 1] = input_brush_values[1];
output_color_values[byte_iterator + 2] = input_brush_values[2];
output_color_values[byte_iterator + 3] = input_brush_values[3];
}
else
{
output_color_values[byte_iterator + 0] = input_color_values[byte_iterator + 0];
output_color_values[byte_iterator + 1] = input_color_values[byte_iterator + 1];
output_color_values[byte_iterator + 2] = input_color_values[byte_iterator + 2];
output_color_values[byte_iterator + 3] = input_color_values[byte_iterator + 3];
}
}
return output_color_values;
}
//Establece los pxeles en la localizacin y rea hacia la textura original
uint8_t* UTool::BrushPainting::erase_pixel_buffer(int size_x, int size_y, uint8_t* default_color_values, uint8_t* input_color_values, float mouse_x, float mouse_y, int brush_size)
{
//Valor absoluto en bytes de la textura
int absolute_byte_size = (size_x * size_y) * 4;
int absolute_byte_row_size = size_x * 4;
int local_mouse_x_relative_pos = static_cast<int> (size_x * (mouse_x * 0.01f));
int local_mouse_y_relative_pos = static_cast<int> (size_y * (mouse_y * 0.01f));
//Clculo del offset en la textura para la posicin del cursor
size_t mouse_local_coordinates = local_mouse_y_relative_pos * size_x + (local_mouse_x_relative_pos);
size_t mouse_absolute_coordinates = mouse_local_coordinates * 4;
uint8_t *output_color_values = new uint8_t[absolute_byte_size];
for (size_t byte_iterator = 0; byte_iterator < absolute_byte_size; byte_iterator += 4)
{
if (brush_size_area_comprobation(byte_iterator, brush_size, mouse_absolute_coordinates, absolute_byte_row_size))
{
output_color_values[byte_iterator + 0] = default_color_values[byte_iterator + 0];
output_color_values[byte_iterator + 1] = default_color_values[byte_iterator + 1];
output_color_values[byte_iterator + 2] = default_color_values[byte_iterator + 2];
output_color_values[byte_iterator + 3] = default_color_values[byte_iterator + 3];
}
else
{
output_color_values[byte_iterator + 0] = input_color_values[byte_iterator + 0];
output_color_values[byte_iterator + 1] = input_color_values[byte_iterator + 1];
output_color_values[byte_iterator + 2] = input_color_values[byte_iterator + 2];
output_color_values[byte_iterator + 3] = input_color_values[byte_iterator + 3];
}
}
return output_color_values;
}
//Comprobacin de si el pxel indicado est en el rea del pincel/borrador
bool UTool::BrushPainting::brush_size_area_comprobation(size_t byte_iterator, int brush_size, size_t mouse_absolute_coordinates, size_t absolute_byte_row_size)
{
//La siguiente estructura permite crear cualquier forma de pincel que se desee, modificando directamente estructura que tendr el pincel
switch (brush_size)
{
case 1:
//3 X 3 Pixel SQUARE Brush
if (byte_iterator == (mouse_absolute_coordinates + 4)
|| byte_iterator == (mouse_absolute_coordinates - 4)
|| byte_iterator == (mouse_absolute_coordinates + absolute_byte_row_size)
|| byte_iterator == (mouse_absolute_coordinates - absolute_byte_row_size)
|| byte_iterator == (mouse_absolute_coordinates + absolute_byte_row_size + 4)
|| byte_iterator == (mouse_absolute_coordinates + absolute_byte_row_size - 4)
|| byte_iterator == (mouse_absolute_coordinates - absolute_byte_row_size + 4)
|| byte_iterator == (mouse_absolute_coordinates - absolute_byte_row_size - 4)
|| byte_iterator == (mouse_absolute_coordinates)
) return true;
else return false;
break;
case 2:
//5 X 5 Pixel SQUARE Brush
if (byte_iterator == (mouse_absolute_coordinates + 4)
|| byte_iterator == (mouse_absolute_coordinates - 4)
|| byte_iterator == (mouse_absolute_coordinates + 8)
|| byte_iterator == (mouse_absolute_coordinates - 8)
|| byte_iterator == (mouse_absolute_coordinates + absolute_byte_row_size)
|| byte_iterator == (mouse_absolute_coordinates - absolute_byte_row_size)
|| byte_iterator == (mouse_absolute_coordinates + absolute_byte_row_size * 2)
|| byte_iterator == (mouse_absolute_coordinates - absolute_byte_row_size * 2)
|| byte_iterator == (mouse_absolute_coordinates + absolute_byte_row_size + 4)
|| byte_iterator == (mouse_absolute_coordinates + absolute_byte_row_size - 4)
|| byte_iterator == (mouse_absolute_coordinates - absolute_byte_row_size + 4)
|| byte_iterator == (mouse_absolute_coordinates - absolute_byte_row_size - 4)
|| byte_iterator == (mouse_absolute_coordinates + absolute_byte_row_size + 8)
|| byte_iterator == (mouse_absolute_coordinates + absolute_byte_row_size - 8)
|| byte_iterator == (mouse_absolute_coordinates - absolute_byte_row_size + 8)
|| byte_iterator == (mouse_absolute_coordinates - absolute_byte_row_size - 8)
|| byte_iterator == (mouse_absolute_coordinates + absolute_byte_row_size * 2 + 4)
|| byte_iterator == (mouse_absolute_coordinates + absolute_byte_row_size * 2 - 4)
|| byte_iterator == (mouse_absolute_coordinates - absolute_byte_row_size * 2 + 4)
|| byte_iterator == (mouse_absolute_coordinates - absolute_byte_row_size * 2 - 4)
|| byte_iterator == (mouse_absolute_coordinates + absolute_byte_row_size * 2 + 8)
|| byte_iterator == (mouse_absolute_coordinates + absolute_byte_row_size * 2 - 8)
|| byte_iterator == (mouse_absolute_coordinates - absolute_byte_row_size * 2 + 8)
|| byte_iterator == (mouse_absolute_coordinates - absolute_byte_row_size * 2 - 8)
|| byte_iterator == (mouse_absolute_coordinates)
) return true;
else return false;
break;
case 3:
//7 X 7 Pixel ROUND Brush
if (byte_iterator == (mouse_absolute_coordinates + 4)
|| byte_iterator == (mouse_absolute_coordinates - 4)
|| byte_iterator == (mouse_absolute_coordinates + 8)
|| byte_iterator == (mouse_absolute_coordinates - 8)
|| byte_iterator == (mouse_absolute_coordinates + 12)
|| byte_iterator == (mouse_absolute_coordinates - 12)
|| byte_iterator == (mouse_absolute_coordinates + absolute_byte_row_size)
|| byte_iterator == (mouse_absolute_coordinates - absolute_byte_row_size)
|| byte_iterator == (mouse_absolute_coordinates + absolute_byte_row_size * 2)
|| byte_iterator == (mouse_absolute_coordinates - absolute_byte_row_size * 2)
|| byte_iterator == (mouse_absolute_coordinates + absolute_byte_row_size * 3)
|| byte_iterator == (mouse_absolute_coordinates - absolute_byte_row_size * 3)
|| byte_iterator == (mouse_absolute_coordinates + absolute_byte_row_size + 4)
|| byte_iterator == (mouse_absolute_coordinates + absolute_byte_row_size - 4)
|| byte_iterator == (mouse_absolute_coordinates - absolute_byte_row_size + 4)
|| byte_iterator == (mouse_absolute_coordinates - absolute_byte_row_size - 4)
|| byte_iterator == (mouse_absolute_coordinates + absolute_byte_row_size + 8)
|| byte_iterator == (mouse_absolute_coordinates + absolute_byte_row_size - 8)
|| byte_iterator == (mouse_absolute_coordinates - absolute_byte_row_size + 8)
|| byte_iterator == (mouse_absolute_coordinates - absolute_byte_row_size - 8)
|| byte_iterator == (mouse_absolute_coordinates + absolute_byte_row_size + 12)
|| byte_iterator == (mouse_absolute_coordinates + absolute_byte_row_size - 12)
|| byte_iterator == (mouse_absolute_coordinates - absolute_byte_row_size + 12)
|| byte_iterator == (mouse_absolute_coordinates - absolute_byte_row_size - 12)
|| byte_iterator == (mouse_absolute_coordinates + absolute_byte_row_size * 2 + 4)
|| byte_iterator == (mouse_absolute_coordinates + absolute_byte_row_size * 2 - 4)
|| byte_iterator == (mouse_absolute_coordinates - absolute_byte_row_size * 2 + 4)
|| byte_iterator == (mouse_absolute_coordinates - absolute_byte_row_size * 2 - 4)
|| byte_iterator == (mouse_absolute_coordinates + absolute_byte_row_size * 2 + 8)
|| byte_iterator == (mouse_absolute_coordinates + absolute_byte_row_size * 2 - 8)
|| byte_iterator == (mouse_absolute_coordinates - absolute_byte_row_size * 2 + 8)
|| byte_iterator == (mouse_absolute_coordinates - absolute_byte_row_size * 2 - 8)
|| byte_iterator == (mouse_absolute_coordinates)
) return true;
else return false;
break;
default:
return false;
break;
}
}
| true |
c3b7ec2684d4ecb55ca1dd5485285f7e9e65b2b5 | C++ | ToLoveToFeel/LeetCode | /Cplusplus/_0032_Longest_Valid_Parentheses/_0032_main.cpp | UTF-8 | 1,259 | 3.4375 | 3 | [] | no_license | #include <iostream>
#include <stack>
using namespace std;
/**
* https://www.bilibili.com/video/BV1PK4y147uk 14:00
* 思路:如果某段中右括号比左括号多一个,则可以将该段切分开,最长的有效括号不会跨越该段
* 执行用时:8 ms, 在所有 C++ 提交中击败了52.63%的用户
* 内存消耗:7.4 MB, 在所有 C++ 提交中击败了61.19%的用户
*/
class Solution {
public:
int longestValidParentheses(string s) {
stack<int> stk;
int res = 0;
for (int i = 0, start = -1; i < s.size(); i++) {
if (s[i] == '(') stk.push(i);
else {
if (stk.size()) {
stk.pop();
if (stk.size()) res = max(res, i - stk.top());
else res = max(res, i - start);
} else { // 说明遇到右括号但是没有可以匹配的左括号,该段结束,进行下一段
start = i;
}
}
}
return res;
}
};
int main() {
cout << Solution().longestValidParentheses("(()") << endl;
cout << Solution().longestValidParentheses(")()())") << endl;
cout << Solution().longestValidParentheses("") << endl;
return 0;
} | true |
625283aed8df62fbc7bd202b8b4209f5188a37c7 | C++ | FelixKirmse/ProjectR | /src/ProjectR.MapGen/Generators/HallwayGenerator.cpp | UTF-8 | 1,195 | 2.84375 | 3 | [] | no_license | #include "HallwayGenerator.hpp"
#include "ProjectR.Model/RMap.hpp"
namespace ProjectR
{
HallwayGenerator::HallwayGenerator(int minWidth, int minHeight, int maxWidth, int maxHeight, std::shared_ptr<RMap> map)
: Generator(minWidth, minHeight, maxWidth, maxHeight, map)
{
}
void HallwayGenerator::GenerateImpl(int row, int col, Direction dir)
{
int topRow = row;
int leftCol = col;
int length = GetWidth() > GetHeight() ? GetWidth() : GetHeight();
if(dir & (West | East))
{
SetHeight(3);
SetWidth(length);
}
if(dir & (South | North))
{
SetWidth(3);
SetHeight(length);
}
GetTopLeftCorner(topRow, leftCol, dir);
int maxRow = topRow + GetHeight();
int maxCol = leftCol + GetWidth();
for(int r = topRow; r < maxRow; ++r)
{
for(int c = leftCol; c < maxCol; ++c)
{
auto& cell = Map()->Get(r, c);
if(r == row && c == col)
{
if(cell & Important)
cell = Door | Important | Locked;
else
cell = Floor | Corridor;
}
else if(r == topRow || c == leftCol || r == maxRow - 1 || c == maxCol -1)
cell = Wall | Corridor;
else
cell = Floor | Corridor;
}
}
}
}
| true |
b6b04f50209c53a4c2a6fdcd45023453e1ada0b9 | C++ | zhouxiaoy/pat | /王道数据结构/线性表/2-2 链表/2-2.25.cpp | GB18030 | 982 | 3.734375 | 4 | [] | no_license | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct node {
int data;
node* next;
};
//ҵм
node* fun(node* root) {
if (root == NULL) return NULL;
node* p = root, *q = root;
//Ҫq->next ֽΪֻʣһ
while (q->next != NULL && q->next->next != NULL)
{
p = p->next;
q = q->next->next;
}
if (q->next != NULL)p = p->next;
return p;
}
void fun2(node *root){
node* p = fun(root);//ǰεβ
node* q = p->next;//ε
node* r,*s;
p->next = NULL;
while(q!=NULL){//ηת
r= q->next;
r->next = q;
}
}
int main() {
node* root = new node();
int n;
cin >> n;
//ݲ β
node* rear = root;//β
for (int i = 0; i < n; i++) {
node* q = new node();
cin >> q->data;
q->next = NULL;
rear->next = q;
rear = q;
}
rear = fun(root);
cout << rear->data << endl;
return 0;
}
| true |
180efa9ecf95fa95b2a0bc3d4f4a86b3ed835fb5 | C++ | Michael-K-Stein/Sound-Classifier | /Backup/ClassifyFrequencyArray Template/ClassifyFrequencyArray.cpp | UTF-8 | 2,936 | 2.640625 | 3 | [] | no_license | // ClassifyFrequencyArray.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include <iostream>
#include <time.h>
#include <fstream>
#include "AudioFile.h"
#include <direct.h>
#define GetCurrentDir _getcwd
std::string get_current_dir() {
char buff[FILENAME_MAX]; //create string buffer to hold path
GetCurrentDir(buff, FILENAME_MAX);
std::string current_working_dir(buff);
return current_working_dir;
}
/*int mainBROKEN()
{
std::cout << "Started WAV Analyzer" << std::endl;
std::string WAV_File_Path;
std::cout << "Path for WAV file: " << std::endl;
std::cout << get_current_dir() << "\\";
WAV_File_Path = get_current_dir() + "\\";
std::cin >> WAV_File_Path;
std::cout << std::endl << std::endl;
AudioFile<double> * audioFile = new AudioFile<double>();
if (audioFile->load(WAV_File_Path)) { std::cout << "Loaded File!" << std::endl; };
audioFile->printSummary();
std::cout << "CH: " << audioFile->getNumChannels() << " | " << "SAMP: " << audioFile->getNumSamplesPerChannel() * audioFile->getNumChannels() << std::endl;
FFT * FT = new FFT();
uint8_t channelInd = 0;
for (int sampInd = 0; sampInd < audioFile->getNumSamplesPerChannel(); sampInd++) {
FT->AppendToWave(audioFile->samples[channelInd][sampInd]);
}
int actInd = 0;
std::cout << ++actInd << ") " << "Loaded \"" << WAV_File_Path << "\" into Fourier Transform!" << std::endl;
/// Create an array of the frequencies
for (int x = 0; x < audioFile->getNumSamplesPerChannel() / audioFile->getSampleRate(); x++) {
char * freqArr /*[4500];// /= (/*unsigned/ char *)malloc(4500 * sizeof(/*unsigned char));
std::vector<Complex> * liveFreq = FT->FourierTransfer_Part(audioFile->getSampleRate(), x);
std::vector<std::vector<double> * > * ordFreqOut = FT->OrderFrequencyOutputs(liveFreq);
for (int freqInd = 0; freqInd < FT->MaxFrequency(); freqInd++) {
freqArr[freqInd] = liveFreq->at(freqInd).real() * 2.55;
}
std::ofstream fout;
char * fileName = (char *)malloc(20 * sizeof(char));
sprintf(fileName, "Toca_D_Minor/Toca_D_Minor_Freq_%x.wavfft", x);
fout.open(fileName, std::ios::binary |std::ios::out);
fout.write(freqArr, 4500);
fout.close();
}
std::cout << "Hello World!\n";
return 0;
}*/
int mainpoop() {
//mainKNN();
return 0;
}
// Run program: Ctrl + F5 or Debug > Start Without Debugging menu
// Debug program: F5 or Debug > Start Debugging menu
// Tips for Getting Started:
// 1. Use the Solution Explorer window to add/manage files
// 2. Use the Team Explorer window to connect to source control
// 3. Use the Output window to see build output and other messages
// 4. Use the Error List window to view errors
// 5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project
// 6. In the future, to open this project again, go to File > Open > Project and select the .sln file
| true |
216ce96f32a55d05565b1705b47136ba22a6babf | C++ | AlbinStenqvist/Programmering-1 | /Bonus3/main.cpp | ISO-8859-2 | 614 | 3.1875 | 3 | [] | no_license | #include <iostream>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
using namespace std;
int main() {
float t1, m1, s1, t2, m2, s2, t3, m3, s3;
cout << "Ange tiden fr lopp 1 (TT MM SS): ";
cin >> t1;
cin >> m1;
cin >> s1;
cout << "Ange tiden fr lopp 2 (TT MM SS): ";
cin >> t2;
cin >> m2;
cin >> s2;
t3 = t1 + t2;
m3 = m1 + m2;
s3 = s1 + s2;
if (s3 >= 60) {
m3 = m3 + 1;
s3 = s3 - 60;
}
if (m3 >= 60) {
t3 = t3 + 1;
m3 = m3 - 60;
}
cout << t3 << " timmar " << m3 << " minuter " << s3 << " sekunder ";
}
| true |
bae58fcbf34f11a389a1c305518c719ef884e5c2 | C++ | piotrek6598/ASD | /mid-term tasks/jablka/main.cpp | UTF-8 | 2,117 | 2.859375 | 3 | [] | no_license | #include <iostream>
#include <cmath>
using namespace std;
const int M = 1e9;
const int MAX_N = 1e6 + 1;
static int ile_el[MAX_N]; // Liczba elementów drzewa o numerze i.
static int poziom [MAX_N][2]; // Liczba drzew o numerze i na pewnym i nastepnym poziomie
int main()
{
ios_base::sync_with_stdio(0);
int n, d, ak, bk;
int str = 1; // Parametr do sprawdzania który poziom jest aktualny
cin >> n >> d;
int dane[n + 1][2];
ile_el[0] = 1;
for (int i = 1; i <= n; i++){
cin >> ak >> bk;
dane[i][0] = ak;
dane[i][1] = bk;
ile_el[i] = (ile_el[ak] + ile_el[bk] + 1) % M;
}
for (int i = 0; i <= n; i++){
poziom[i][0] = 0;
poziom[i][1] = 0;
}
poziom[n][0] = 1;
// Obliczaenie drzew na kolejnych poziomach
for (int i = 1; i <= d; i++){
if (str == 1){
poziom[0][0] = 0;
for (int j = 1; j <= n; j++){
poziom[dane[j][0]][1] += poziom[j][0];
poziom[dane[j][0]][1] %= M;
poziom[dane[j][1]][1] += poziom[j][0];
poziom[dane[j][0]][1] %= M;
poziom[dane[j][1]][1] %= M;
poziom[j][0] = 0;
}
}
else {
poziom[0][1] = 0;
for (int j = 1; j <= n; j++){
poziom[dane[j][0]][0] += poziom[j][1];
poziom[dane[j][0]][0] %= M;
poziom[dane[j][1]][0] += poziom[j][1];
poziom[dane[j][0]][0] %= M;
poziom[dane[j][1]][0] %= M;
poziom[j][1] = 0;
}
}
str *= -1;
}
long long int ans = 0;
if (str == -1) {
for (int i = 0; i <= n; i++){
ans += (static_cast<long long>(ile_el[i]) * static_cast<long long>(poziom[i][1])) % M;
ans %= M;
}
}
else {
for (int i = 0; i <= n; i++){
ans += (static_cast<long long>(ile_el[i]) * static_cast<long long>(poziom[i][0])) % M;
ans %= M;
}
}
cout << ans % M << endl;
return 0;
}
| true |
57fbc4047f3079158e79cc1685c92899ac78b8d6 | C++ | wesmail/hydra | /old_hydra/hydra/trunk/base/util/hgeantfilter.cc | UTF-8 | 3,337 | 2.609375 | 3 | [] | no_license | //*-- AUTHOR : R. Holzmann
//*-- Modified : 31/03/2004 by
//_HADES_CLASS_DESCRIPTION
///////////////////////////////////////////////////////////////////////////////
//
// HGeantFilter
//
// Reconstructor to filter the simulated event data produced by HGeant
// rescaling the multiplcity of particle id by acc.
//
// This is done by throwing a rundom number for each occurance of a particle
// id in the kine branch and deleting all associated hits from all categories
// of type hgeantxxx.
// The kine branch entries are not removed however, just set 'inactive'.
//
///////////////////////////////////////////////////////////////////////////////
#include "hgeantfilter.h"
#include "hades.h"
#include "hgeantkine.h"
#include "hlinkeddataobject.h"
#include "hgeantmdc.h"
#include "hgeanttof.h"
#include "hgeantshower.h"
#include "hgeantrich.h"
ClassImp(HGeantFilter)
//////////////////////////////////////////////////////////////////////////////////////////////
//
// This filter class does the actual filtering of HGeant hits that are to be suppressed
// from the categories
//
HHitFilter::HHitFilter(HCategory* pCat) {
pKineCat = pCat;
}
HHitFilter::~HHitFilter() {}
Bool_t HHitFilter::check(TObject* obj) {
// check if hit was made by a suppressed track
Int_t track = ((HLinkedDataObject*)obj)->getTrack(); // get track number
HGeantKine* pKine = (HGeantKine*)(pKineCat->getObject(track-1)); // get corresponding kine object
return(!pKine->isSuppressed());
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
ClassImp(HGeantFilter)
HGeantFilter::HGeantFilter(Text_t *name,Text_t *title, Int_t id, Float_t acc)
: HReconstructor(name,title) {
particleId = id;
accepted = acc;
catKine = NULL;
catMdc = NULL;
catTof = NULL;
catShower = NULL;
catRichPhoton = NULL;
catRichDirect = NULL;
catRichMirror = NULL;
}
HGeantFilter::HGeantFilter(HGeantFilter &filter) {
// copy constructor not implemented!
Error("HGeantFilter","Copy constructor not defined");
}
HGeantFilter::~HGeantFilter(void) {
}
Bool_t HGeantFilter::init(void) {
//
// Set up pointers to the Geant cats and their iterators
//
HEvent* ev = (HEvent*)(gHades->getCurrentEvent());
if (!ev) return kFALSE;
if ((catKine = ev->getCategory(catGeantKine)) == NULL) return kFALSE;
catMdc = ev->getCategory(catMdcGeantRaw);
catTof = ev->getCategory(catTofGeantRaw);
catShower = ev->getCategory(catShowerGeantRaw);
catRichPhoton = ev->getCategory(catRichGeantRaw);
catRichDirect = ev->getCategory(catRichGeantRaw+1);
catRichMirror = ev->getCategory(catRichGeantRaw+2);
return kTRUE;
}
Int_t HGeantFilter::execute(void) {
//
// Do the filtering for each hit category
//
HGeantKine::suppressTracks(particleId,accepted,(HLinearCategory*)catKine);
HHitFilter filt;
filt.setKine(catKine);
if (catMdc) catMdc->filter(filt);
if (catTof) catTof->filter(filt);
if (catShower) catShower->filter(filt);
if (catRichPhoton) catRichPhoton->filter(filt);
if (catRichDirect) catRichDirect->filter(filt);
if (catRichMirror) catRichMirror->filter(filt);
return 0;
}
Bool_t HGeantFilter::reinit(void) {
return kTRUE;
}
Bool_t HGeantFilter::finalize(void) {
return kTRUE;
}
| true |
1090a8493f6e54901222d769177226167ca59496 | C++ | savicci/algorithms-homework | /sorted lists/merging.cxx | UTF-8 | 1,971 | 3.390625 | 3 | [] | no_license | //by Grzegorz Koziol
#include<iostream>
#include<string>
#include<list>
#include"sortedArrayList.hxx"
#include"SortedLinkedList.hxx"
using std::cout;
using std::cin;
using std::endl;
main(int argc, char const *argv[])
{
if(argc!=3){
cout<<"Podaj wielkosci list tablicowych"<<endl;
exit(-1);
}
int num1=std::stoi(argv[1]);
int num2=std::stoi(argv[2]);
SortedArrayList arrList1=SortedArrayList(num1);
SortedArrayList arrList2=SortedArrayList(num2);
SortedLinkedList linkList1=SortedLinkedList();
SortedLinkedList linkList2=SortedLinkedList();
std::list<int> stdList1;
std::list<int> stdList2;
std::string input;
//najpierw arraylist
cin>>input;
int ops=std::stoi(input);
int num;
for(int i=0;i<ops;i++){
cin>>input;
num=std::stoi(input);
arrList1.push(num);
linkList1.push(num);
stdList1.push_back(num);
}
//przesortuj liste standardowa
stdList1.sort();
cin>>input;
ops=std::stoi(input);
for(int i=0;i<ops;i++){
cin>>input;
num=std::stoi(input);
arrList2.push(num);
linkList2.push(num);
stdList2.push_back(num);
}
//przesortuj liste standardowa
stdList2.sort();
//merge
SortedArrayList newArrList=SortedArrayList::merge(arrList1,arrList2);
SortedLinkedList newLinkList=SortedLinkedList::merge(linkList1,linkList2);
stdList1.merge(stdList2);
//wypisywanie
newArrList.print();
newLinkList.print();
for(auto i : stdList1)
cout<<i<<" ";
cout<<endl;
newArrList.unique();
newLinkList.unique();
stdList1.unique();
//wypisywanie po unique()
cout<<"Po operacji unique()"<<endl;
newArrList.print();
newLinkList.print();
for(auto i : stdList1)
cout<<i<<" ";
cout<<endl;
return 0;
}
| true |
ecf3bcfb61277fb6fc30ef856e3a5a7b4e5bfdce | C++ | KushnirDmytro/SocketServerLab3 | /ServerBoost.cpp | UTF-8 | 5,722 | 2.8125 | 3 | [] | no_license |
#include <cstdlib>
#include <iostream>
#include <boost/bind.hpp>
#include <boost/asio.hpp>
// forward declarations
class serverUDP;
class serverTCP;
class session;
const std::string currentTime() {
time_t now = time(0);
struct tm tstruct;
char buf[20];
tstruct = *localtime(&now);
strftime(buf, sizeof(buf), "%X", &tstruct);
return buf;
}
const std::string currentDate() {
time_t now = time(0);
struct tm tstruct;
char buf[40];
tstruct = *localtime(&now);
strftime(buf, sizeof(buf), "%Y-%m-%d", &tstruct);
return buf;
}
using boost::asio::ip::tcp;
class session
{
public:
session(boost::asio::io_service& io_service)
: socket_(io_service)
{
}
tcp::socket& socket()
{
return socket_;
}
void start()
{
socket_.async_read_some(boost::asio::buffer(data_, 1),
boost::bind(&session::handle_read, this,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}
private:
void handle_read(const boost::system::error_code& error,
size_t bytes_transferred)
{
if (!error )
{
if (strcmp(data_, "h") == 0){
std::string st = "Hello\n";
strcpy(data_, st.c_str());
bytes_transferred = st.size();
}
if (strcmp(data_, "t") == 0){
std::string st = currentTime();
strcpy(data_, st.c_str());
bytes_transferred = st.size();
}
if (strcmp(data_, "d") == 0){
std::string st = currentDate();
strcpy(data_, st.c_str());
bytes_transferred = st.size();
}
if (strcmp(data_, "m") == 0){
socket_.async_read_some(boost::asio::buffer(data_, 2),
boost::bind(&session::handle_read, this,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
if (isdigit(data_[0]) && isdigit(data_[1]) ){
printf("TCP got two digits %s\n", data_);
bytes_transferred = atoi(data_);
socket_.async_read_some(boost::asio::buffer(data_, atoi(data_)),
boost::bind(&session::handle_read, this,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
printf("TCP got following msg %s of len %u\n", data_, bytes_transferred );
}
else {
printf("Two digits expected\n");
delete this;
}
}
if (strlen(data_) > 0)
{
printf("TCP sending %s to %s port %d\n",
data_,
socket_.remote_endpoint().address().to_string().c_str(),
socket_.remote_endpoint().port());
boost::asio::async_write(socket_,
boost::asio::buffer(data_, bytes_transferred),
boost::bind(&session::handle_write, this,
boost::asio::placeholders::error));
memset(data_, 0, sizeof data_);
readSize = 0;
}
}
else
{
delete this;
}
}
void handle_write(const boost::system::error_code& error)
{
if (!error)
{
socket_.async_read_some(boost::asio::buffer(data_, readSize),
boost::bind(&session::handle_read, this,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}
else
{
delete this;
}
}
tcp::socket socket_;
enum { max_length = 1024 };
size_t readSize = 0;
char data_[max_length];
};
class serverTCP
{
public:
serverTCP(boost::asio::io_service& io_service, short port)
: io_service_(io_service),
acceptor_(io_service, tcp::endpoint(tcp::v4(), port))
{
start_accept();
}
private:
void start_accept()
{
session* new_session = new session(io_service_);
acceptor_.async_accept(new_session->socket(),
boost::bind(&serverTCP::handle_accept, this, new_session,
boost::asio::placeholders::error));
}
void handle_accept(session* new_session,
const boost::system::error_code& error)
{
if (!error)
{
new_session->start();
}
else
{
delete new_session;
}
start_accept();
}
boost::asio::io_service& io_service_;
tcp::acceptor acceptor_;
};
int main(int argc, char* argv[])
{
size_t sizePlaceholder = 0;
try
{
boost::asio::io_service io_service;
using namespace std; // For atoi.
serverTCP sTCP(io_service, 2017);
io_service.run();
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << "\n";
}
return 0;
} | true |
11584fed221af922034c020b13aa097b1af234d3 | C++ | viatom-develop/Hyt | /lpble/src/main/cpp/offline/main.cpp | UTF-8 | 2,071 | 2.875 | 3 | [] | no_license | #include <iostream>
#include <cstdio>
#include "swt.h"
#include <deque>
#include <string>
#include <fstream>
#include "commalgorithm.h"
#include "streamswtqua.h"
#include <cmath>
using namespace std;
StreamSwtQua streamSwtQua;
void readfile(string path, deque <double> & data)
{
ifstream infile(path.c_str());
string tempstr;
data.clear();
while (getline(infile, tempstr))
{
data.push_back(StringToDouble(tempstr));
}
infile.close();
}
void writefile(string path, deque <double> & data)
{
ofstream outfile(path.c_str());
for (int i = 0; i < data.size(); ++i)
{
outfile << data[i] << endl;
}
outfile.close();
}
int main()
{
deque <double > inputt;
readfile("F:/1.txt",inputt);
int i;
deque <double> outputPoints;
deque <double> allSig;
deque <double> outputsize;
int lenthOfData;
int ReduntLength;
int MultipleSize;
lenthOfData = inputt.size();
MultipleSize = lenthOfData/256;
ReduntLength = lenthOfData - 256 * MultipleSize;
if(ReduntLength != 0)
{
for(i = lenthOfData; i < (MultipleSize+1)*256; i++)
{
inputt.push_back(0);
}
}
if(ReduntLength == 0)
{
for (i = 0; i < 256 * MultipleSize; ++i)
{
streamSwtQua.GetEcgData(inputt[i], outputPoints);
for (int j = 0; j < outputPoints.size(); ++j)
{
allSig.push_back(outputPoints[j]);
}
}
}
else{
for(i = 0; i < inputt.size(); i++)
{
streamSwtQua.GetEcgData(inputt[i], outputPoints);
for (int j = 0; j < outputPoints.size(); ++j)
{
allSig.push_back(outputPoints[j]);
}
}
if(ReduntLength < 192)
{
for(i = 0; i < 192 -ReduntLength; i++)
{
allSig.pop_back();
}
}
}
writefile("F:/10.txt", allSig);
writefile("F:/size.txt",outputsize);
std::cout << "Hello, World!" << std::endl;
return 0;
}
| true |
c86969a1851b3ad301b1b9cf2e28cad080db2886 | C++ | shruthi019/lean-in-interview-prep | /arrays/wiggle_sort.cpp | UTF-8 | 669 | 3.859375 | 4 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
// Problem: https://www.lintcode.com/problem/wiggle-sort/description (MEDIUM level)
void wiggleSort(vector<int>& nums) {
int size = nums.size();
for (int i = 0; i < size; i += 2) {
if (i > 0 && nums[i] > nums[i - 1]) {
swap(nums[i], nums[i - 1]);
}
if (i < size - 1 && nums[i] > nums[i + 1]) {
swap(nums[i], nums[i + 1]);
}
}
return;
}
int main() {
vector<int> v = {3, 5, 2, 1, 6, 4};
wiggleSort(v);
for (int x: v) {
cout << x << " ";
}
cout << endl;
return 0;
} | true |
05a8b0ca59169e608e0775a161f67651c3016f1a | C++ | mehmetozbek26/SoftWareEng | /otomasyon/main.cpp | ISO-8859-9 | 2,635 | 3.015625 | 3 | [] | no_license | #include <cstdlib>
#include <iostream>
using namespace std;
//hastane otomasyon sistemi
typedef struct hastakimlik {
char *ad;
char *soyad;
int no;
int tcno;
int id;
}Kimlik;
typedef struct polkimlik {
char *poladi;
int numara;
int id;
char *doktorad;
}Poliklinik;
int main(int argc, char *argv[])
{
Kimlik adam[3];
Poliklinik nayer[3];
int a;
adam[0].ad="ahmet";
adam[0].soyad="mutlu";
adam[0].no=12;
adam[0].tcno=12345;
adam[0].id=1;
adam[1].ad="veli";
adam[1].soyad="dertsiz";
adam[1].no=13;
adam[1].tcno=17325;
adam[1].id=2;
adam[2].ad="halit";
adam[2].soyad="kutlu";
adam[2].no=21;
adam[2].tcno=19875;
adam[2].id=3;
//poliklinik bilgileri giriliyor.....
nayer[0].poladi="kulak";
nayer[0].id=1;
nayer[0].numara=89;
nayer[0].doktorad="faik";
nayer[1].poladi="dahiliye";
nayer[1].id=2;
nayer[1].numara=99;
nayer[1].doktorad="utku";
nayer[2].poladi="goz";
nayer[2].id=3;
nayer[2].numara=83;
nayer[2].doktorad="ceng";
printf("1-3 arasinda bir id numarasi giriniz\n");
//kaytl olan id bilgilerinin bulunmas.....
do { scanf("%d",&a);
printf("\n\n");
if(a!=1&&a!=2&&a!=3)
printf("girilen id de kayit bulunamadi \n");}
while(a!=1&&a!=2&&a!=3);
//otomasyon sisteminin listelendirme ekli....
printf("hasta adi hasta soyadi id numarasi poliklinik adi doktor adi\n\n");
//id numarasna gre hasta ve doktorilgileriekrana yazdirilsin....
if(a==1){
printf("%s\t ",adam[0].ad);
printf("%s\t\t ",adam[0].soyad);
printf("%d\t ",adam[0].id);
printf("%s\t\t ",nayer[0].poladi);
printf("%s \n\n",nayer[0].doktorad);}
if(a==2){
printf("%s\t ",adam[1].ad);
printf("%s\t\t ",adam[1].soyad);
printf("%d\t ",adam[1].id);
printf("%s\t\t ",nayer[1].poladi);
printf("%s \n\n",nayer[1].doktorad);}
if(a==3){
printf("%s\t ",adam[2].ad);
printf("%s\t\t ",adam[2].soyad);
printf("%d\t ",adam[2].id);
printf("%s\t\t ",nayer[2].poladi);
printf("%s \n\n",nayer[2].doktorad);}
system("PAUSE");
return EXIT_SUCCESS;
}
| true |
e3d4f44fc836dd962b62067ecc5591ac5760d66c | C++ | nathanlo99/daily-coding-problem | /cpp/problem001.cpp | UTF-8 | 1,381 | 4.21875 | 4 | [] | no_license | /*
This problem was recently asked by Google.
Given a list of numbers and a number k, return whether any two numbers from the
list add up to k.
For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17.
Bonus: Can you do this in one pass?
*/
#include <iostream>
#include <unordered_set> // For std::unordered_set<T> (hash-maps)
#include <vector> // For std::vector<T> (dynamic arrays)
// Overall complexity: O(n), where (n == arr.size()).
bool two_sum(const std::vector<int> &arr, const int target) {
std::unordered_set<int> seen; // A set of numbers seen so far
for (const int num : arr) {
// If we've seen our 'corresponding number', return true.
if (seen.count(target - num))
return true;
// Otherwise, continue and update our seen list.
seen.insert(num);
}
// If we get to this point, we found no pairs, so return false
return false;
}
int main() {
assert(two_sum({}, 0) == false); // Empty lists work
assert(two_sum({2}, 4) == false); // Doesn't take (2, 2) as a valid pair
assert(two_sum({2, 3}, 5) == true); // Small debuggable example
assert(two_sum({2, 3}, 4) == false); // Small debuggable example
assert(two_sum({10, 15, 3, 7}, 17) == true); // Sample example
assert(two_sum({11, 15, 3, 7}, 17) == false); // Sample example, modified
std::cout << "Passed all test!" << std::endl;
}
| true |
2c0cc0ce33febeb3229772f52c46718c9fe0f447 | C++ | mihail-m/CP-implementations | /1-Searching/c++/3-exponential-search.cpp | UTF-8 | 823 | 3.078125 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
bool bin_search(vector<int> arr, int l, int r, int num) {
while (l <= r) {
int mid = (l + r) / 2;
if (arr[mid] == num) {
return true;
}
if (arr[mid] < num) {
l = mid + 1;
} else {
r = mid - 1;
}
}
return false;
}
bool exp_search(vector<int>& arr, int num) {
if (arr[0] == num) {
return true;
}
int i = 1;
while (i < arr.size() && arr[i] < num) {
i *= 2;
}
return bin_search(arr, i / 2, min(i, (int)arr.size() - 1), num);
}
void test() {
vector<int> testVector({1, 5, 9, 17, 33, 75});
assert(exp_search(testVector, 17));
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
test();
return 0;
} | true |
5a0cff56866c5a76dac051330565f14f05730cd0 | C++ | anishanainani/workspace-Cplusplus | /Sorting/Selection Sort/selection_sort.h | UTF-8 | 1,147 | 3.609375 | 4 | [] | no_license | /*
* selection_sort.h
*
* Created on: Jan 28, 2015
* Author: Komani
*
* n-1 + n-2 + n-3 + ..... = O(n^2)
*
* Advantage:
* atmost n-1 swaps, the situations in which moving data elements is more expensive than comparing, selection sort is good.
*
* Not stable
* inplace
*/
#ifndef SELECTION_SORT_H_
#define SELECTION_SORT_H_
#include<iostream>
using namespace std;
template<typename item_type>
class selection_sort{
public:
selection_sort() : array(NULL), length(0) {};
selection_sort(item_type* a, int l) : array(a), length(l){};
void sort();
void swap(int, int);
private:
item_type* array;
int length;
};
template<typename item_type>
void selection_sort<item_type> :: sort(){
cout<<sizeof(array);
for(int i = 0; i < length-1; ++i){
int min_index = i;
for(int j = i+1; j < length; ++j){
if(array[j] < array[min_index]){
min_index = j;
}
}
swap(i, min_index);
}
};
template<typename item_type>
void selection_sort<item_type> :: swap(int index1, int index2){
item_type temp = array[index1];
array[index1] = array[index2];
array[index2] = temp;
}
#endif /* SELECTION_SORT_H_ */
| true |
8bed04d174503a52df071a7e2826624a1253f2b9 | C++ | thegamer1907/Code_Analysis | /scrape/data/Organized/LJlessthanme/LJlessthanme_A.cpp | UTF-8 | 966 | 2.546875 | 3 | [] | no_license | //HDU2196 求树中每个点能达到的最大距离,结合解题报告看
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int MAX= 2e5 + 50;
typedef long long LL;
LL a[MAX];
int main(int argc, char const *argv[])
{
LL n, m, k;
scanf("%I64d%I64d%I64d", &n, &m, &k);
for(LL i = 0; i < m; i++){
scanf("%I64d", &a[i]);
}
LL top = k;
LL cnt = 0;
LL flag = 0;
for(LL i = 0; i < m; i++){
//printf("top = %I64d\n", top);
if(a[i] <= top){
//printf("i = %d\n", i);
flag++;
}
if(a[i] > top && flag){
i--;
top += flag;
//printf("top = %I64d a[%I64d] = %I64d\n", top, i, a[i]);
cnt++;
flag = 0;
}
if(a[i] > top && flag == 0){
LL d = a[i] - top;
i--;
if(d % k == 0LL){
//printf("d = %I64dd\n", d);
top += d;
} else{
top += (d / k + 1LL) * k;
//printf("99\n");
}
}
//printf("top = %I64d\n", top);
}
if(flag){
cnt++;
}
printf("%I64d\n", cnt);
return 0;
} | true |
f1a82d5c04c7ec5fa1f4540b6b603637d895f29a | C++ | fjola17/VLN1 | /homap/controller/adminmenucontroller.cpp | UTF-8 | 7,433 | 3.21875 | 3 | [] | no_license | #include "adminmenucontroller.h"
using namespace std;
AdminMenuController::AdminMenuController()
{
AdminMenuController::init();
}
AdminMenuController::~AdminMenuController()
{
//dtor
}
//Get user input
void AdminMenuController::init(){
// Pre
Topping newTopping;
Item newItem;
Pizza newPizza;
Location newLocation;
int user_input;
GlobalTools::clearConsole();
GlobalTools::displayHeader();
AdminView::displayAdminMenu();
// Main
cin >> user_input;
GlobalTools::clearCin();
if(user_input == 1){
// Display All
GlobalTools::clearConsole();
GlobalTools::displayHeader();
AdminMenuController::analytics();
AdminView::displayToppings(ToppingModel::readToppings());
AdminView::displayItems(ItemModel::readItems());
AdminView::displayLocations(LocationModel::readLocations());
AdminView::displayPizzaMenu(PizzaModel::readPizzaMenu());
system("pause");
AdminMenuController::init();
}
else if(user_input == 2){
// Register Pizza
newPizza = AdminMenuController::userNewPizza();
PizzaModel::writePizza(newPizza);
GlobalTools::attention("The Pizza has been written to PizzaMenu.dat");
AdminMenuController::init();
}
else if(user_input == 3){
// Register Topping
cin >> newTopping;
ToppingModel::writeTopping(newTopping);
GlobalTools::attention("The topping has been written to Toppings.txt");
AdminMenuController::init();
}
else if(user_input == 4){
// Register Item
cin >> newItem;
ItemModel::writeItem(newItem);
GlobalTools::attention("The Item has been written to Items.txt");
AdminMenuController::init();
}
else if(user_input == 5){
// Register Location
cin >> newLocation;
LocationModel::writeLocation(newLocation);
AdminMenuController::init();
}
else if(user_input == 6){
// Remove from Menu menu
AdminMenuController::removefromMenu();
AdminMenuController::init();
}
else if(user_input == 7){
// Return To Main Menu
MainMenuController MMC;
}
else{
//ERROR state
GlobalTools::optionWarning();
AdminMenuController::init();
}
}
//Create a new pizza
Pizza AdminMenuController::userNewPizza(){
Pizza newPizza;
vector<Topping> selected_toppings;
cout << "Input Pizza name (50):\t";
cin.getline(newPizza.name, 50);
cout << "Input Pizza price:\t";
cin >> newPizza.price;
selected_toppings = ToppingModel::selectTopping();
for(unsigned int i = 0; i < selected_toppings.size();i++){
newPizza.toppings[i] = selected_toppings[i];
newPizza.sizeOfToppings++;
}
return newPizza;
}
//Select which menu you want to remove from.
void AdminMenuController::removefromMenu()
{
GlobalTools::clearConsole();
GlobalTools::displayHeader();
AdminView::displayRemoveMenu();
int user_input;
cin >> user_input;
GlobalTools::clearCin();
if(user_input == 1){
//Remove from Pizza Menu
AdminMenuController::removefrommenu();
AdminMenuController::init();
}
else if(user_input == 2){
//Remove from Toppings menu
AdminMenuController::removefromtoppings();
AdminMenuController::init();
}
else if(user_input == 3){
//Remove from Items
AdminMenuController::removefromitem();
AdminMenuController::init();
}
else if(user_input == 4){
//Exit to Admin Controller
AdminMenuController::init();
}
else{
//ERROR state
GlobalTools::optionWarning();
AdminMenuController::init();
}
}
//Remove pizza from menu
void AdminMenuController::removefrommenu()
{
vector<Pizza> menu = PizzaModel::readPizzaMenu();
GlobalTools::clearConsole();
AdminView::displayPizzaMenu(menu);
unsigned int user_input;
//Selecting which pizzs from menu should be removed.
cout << "Select element to remove from menu" << endl;
cout << endl << "HINT : Input 0 or anything out side of scope to return to previous menu" << endl;
cin >> user_input;
//Checks which pizza from menu should be removed and removes it.
if(user_input > 0 && user_input < (menu.size() + 1)){
PizzaModel::cleanPizza();
for(unsigned int i = 0; i < menu.size(); i++){
if(i != user_input-1) {
PizzaModel::writePizza(menu[i]);
}
}
GlobalTools::attention("The Pizza has been removed from PizzaMenu.dat");
}
}
//Remove topping from menu.
void AdminMenuController::removefromtoppings()
{
vector<Topping> toppings = ToppingModel::readToppings();
GlobalTools::clearConsole();
AdminView::displayToppings(toppings);
unsigned int user_input;
//Input which topping should be removed
cout << "Select element to remove from menu" << endl;
cout << endl << "HINT : Input 0 or anything out side of scope to return to previous menu" << endl;
cin >> user_input;
//Checks which topping should be removed and removes it.
if(user_input > 0 && user_input < (toppings.size() + 1)){
ToppingModel::cleanTopping();
for(unsigned int i = 0; i < toppings.size(); i++){
if(i != user_input-1) {
ToppingModel::writeTopping(toppings[i]);
}
}
GlobalTools::attention("The Topping has been removed from Toppings.txt");
}
}
//Remove item from menu
void AdminMenuController::removefromitem()
{
vector<Item> item = ItemModel::readItems();
GlobalTools::clearConsole();
AdminView::displayItems(item);
unsigned int user_input;
//Input which item should be removed from menu
cout << "Select element to remove from menu" << endl;
cout << endl << "HINT : Input 0 or anything out side of scope to return to previous menu" << endl;
cin >> user_input;
if(user_input > 0 && user_input < (item.size() + 1)){
ItemModel::cleanItem();
//Checks which item should be removed and removes it.
for(unsigned int i = 0; i < item.size(); i++){
if(i != user_input - 1) {
ItemModel::writeItem(item[i]);
}
}
GlobalTools::attention("The Item has been removed from Items.txt");
}
}
//Analytics of orders
void AdminMenuController::analytics()
{
vector<Order> allorders = OrderModel::readNonConditionalOrderMenu();
int average;
int sum = 0;
int pizzasum = 0;
for(unsigned int i = 0; i < allorders.size(); i++) {
sum += allorders[i].price;
for(int j = 0; j < allorders[i].sizeOfPizzas; j++) {
pizzasum++;
}
}
average = sum / allorders.size();
//Displays number of order, total pizzas, total price of all orders and average of each order
cout << "\tPizza analytics!" << endl;
cout << "The Total amount of orders: " << allorders.size() << endl;
cout << "The Total amount of pizzas ordered: " << pizzasum << endl;
cout << "The Total profit from orders: " << sum << endl;
cout << "The average order price: " << average << endl << endl;
}
void AdminMenuController::baseprice()
{
ofstream fout;
fout.open("Baseprice.txt");
fout.close();
cout << "";
}
| true |
4e180f7a222c201faaeb04d34719a964153e3912 | C++ | lougithub/libguiex | /tools/LibguiexResourceEditor/Core/ReModelBase.h | UTF-8 | 4,073 | 2.921875 | 3 | [] | no_license | // -----------------------------------------------------------------------------
// Author: GameCrashDebug.
// Date: 20101120.
// -----------------------------------------------------------------------------
#ifndef _RE_MODEL_BASE_H_
#define _RE_MODEL_BASE_H_
// -----------------------------------------------------------------------------
// A model has two pools: a data pool that holds data that user expects it to
// posses, and a recycle pool where unused data is stored and could be retrieved
// later when new data requests are issued.
// User calls CreateData to create a new data item inside this model, and use the
// returned pointer for further operations ( except trying to release it ).
// When a model is being released from memory, it makes sure that all data items
// in both pools are properly released as well.
// A model also provides an interface for garbage collection in case we shall
// practically run short of memory.
// -----------------------------------------------------------------------------
#include "Core\RePool.h"
namespace RE
{
template< class T >
class ReModelBase
{
// ----------------------------------------------------------------------------
// General.
// ----------------------------------------------------------------------------
public:
typedef T TData;
typedef typename RePool< TData > TPool;
typedef typename TPool::TItemListItor TPoolItor;
typedef typename TPool::TItemListCItor TPoolCItor;
virtual ~ReModelBase();
// ----------------------------------------------------------------------------
// Interfaces.
// ----------------------------------------------------------------------------
public:
virtual T* CreateData();
virtual void RecycleData( T* _data );
virtual bool FindData( T* _data ) const;
virtual int GetDataCount() const;
virtual void ClearData(); // Recycle all data.
virtual void DestroyData(); // Recycle all data then release the recycle pool.
virtual void CollectGarbage(); // Release the recycle pool.
// ----------------------------------------------------------------------------
// Variables.
// ----------------------------------------------------------------------------
protected:
RePool< T > m_dataPool;
RePool< T > m_recyclePool;
};
template< class T >
ReModelBase< T >::~ReModelBase()
{
DestroyData();
}
template< class T >
T* ReModelBase< T >::CreateData()
{
T* result = m_recyclePool.Pop();
if( NULL == result )
result = new T();
if( NULL != result )
m_dataPool.Push( result );
return result;
}
template< class T >
void ReModelBase< T >::RecycleData( T* _data )
{
// Only recycle data that belongs to this model.
if( FindData( _data ) )
{
m_dataPool.Erase( _data );
m_recyclePool.Push( _data );
}
}
template< class T >
bool ReModelBase< T >::FindData( T* _data ) const
{
bool result = false;
if( NULL != _data )
{
TPoolCItor itor = m_dataPool.Begin();
TPoolCItor itorEnd = m_dataPool.End();
for( ; itor != itorEnd; ++itor )
{
if( _data == *itor )
{
result = true;
break;
}
}
}
return result;
}
template< class T >
int ReModelBase< T >::GetDataCount() const
{
return m_dataPool.Size();
}
template< class T >
void ReModelBase< T >::ClearData()
{
//T* data = NULL;
//while( NULL != ( data = m_dataPool.Pop() ) )
//{
// // Here we cannot call RecycleData anymore, since the data
// // has been popped off the data pool.
// m_recyclePool.Push( data );
//}
T* data = NULL;
while( NULL != ( data = m_dataPool.Back() ) )
{
RecycleData( data );
//m_dataPool.Pop();
}
}
template< class T >
void ReModelBase< T >::DestroyData()
{
// Do not directly call Destroy on both pools because
// we might need to log the whole exact process.
ClearData();
CollectGarbage();
}
template< class T >
void ReModelBase< T >::CollectGarbage()
{
m_recyclePool.Destroy();
}
}
#endif // _RE_MODEL_BASE_H_
| true |
b5e06a7175ded405d3d407b21dcbae6e1198ccdf | C++ | luckyxuanyeah/Algorithm_Practice | /PAT/code/fourth/4.1/4.1 6 A1055(1)(25) -3score/4.1 6 A1055(25)/4.1 6 A1055(25).cpp | GB18030 | 1,541 | 2.640625 | 3 | [] | no_license | // 4.1 6 A1055(25).cpp : ̨Ӧóڵ㡣
//
#include "stdafx.h"
#include <stdio.h>
#include "string.h"
#include <algorithm>
using namespace std;
const int maxn = 100010;
struct person{
char name[9];
int age, netWorth;
}per[maxn];
struct query{
int num, age1, age2;
}que[maxn];
bool cmp1(person a, person b)
{
return a.age > b.age;
}
bool cmp2(person a, person b)
{
if (a.netWorth != b.netWorth) return a.netWorth > b.netWorth;
else if (a.age != b.age) return a.age < b.age;
else if (a.name != b.name) return strcmp(a.name, b.name) < 0;
}
bool judge(person a,int p,int q)
{
return (a.age >= p && a.age <= q);
}
int main()
{
int n, k;
scanf("%d%d", &n, &k);
for (int i = 0; i < n; i++)
scanf("%s%d%d", per[i].name, &per[i].age, &per[i].netWorth);
sort(per, per + n, cmp1);
for (int i = 0; i < k; i++)
scanf("%d%d%d", &que[i].num, &que[i].age1, &que[i].age2);
for (int i = 0; i < k;i++){
int m = 0, min = 0, max = 0;
for (int j = 0; j < n; j++){
if (judge(per[j], que[i].age1, que[i].age2) == true){
min = j;
break;
}
}
for (int j = min; j < n;j++){
if (judge(per[j], que[i].age1, que[i].age2) == true)
m++;
}
max = min + m;
sort(per + min, per + max, cmp2);
if (m == 0){
printf("Case #%d:\n", i + 1);
printf("None\n");
}
else
{
printf("Case #%d:\n", i + 1);
if (m < que[i].num)
que[i].num = m;
for (int j = 0; j < que[i].num; j++)
printf("%s %d %d\n", per[j + min].name, per[j + min].age, per[j + min].netWorth);
}
}
return 0;
} | true |
1f2d8942bf252afcc7c242e70ad1082ca1c3bc87 | C++ | zhangzhizhongz3/CppPrimer | /ch15/ex15.27/main.cpp | UTF-8 | 262 | 2.578125 | 3 | [
"CC0-1.0"
] | permissive | //!
//! Exercise 15.27:
//! Redefine your Bulk_quote class to inherit its constructors.
//!
#include "Quote.h"
#include "Disc_quote.h"
#include "Bulk_quote.h"
#include "Limit_quote.h"
using namespace std;
int main()
{
Bulk_quote bq("sss", 20.0, 2, 0.3);
}
| true |
7c409d18f2912f331245c9ac3cc02c69ed0774b5 | C++ | ddonix/sfjs2 | /12107/12107.cpp | UTF-8 | 5,350 | 3.28125 | 3 | [] | no_license | /* uva 12107: 题意:改动数字谜语中的某几位,使得谜语有唯一解。要求改动的位数最小。如果有多个改动
* 输出结果谜语字典序最小的那个。
* 分析:本题分为两个问题,第一是判断谜语是否有唯一解。第二是在原谜语基础上进行最少改
* 动成为有唯一解的新谜语。判断是否有唯一解,思路是枚举谜语左边所有*取值,看看
* 与谜语右边匹配的可能有多少。最大计算量为pow(10,4)*4=40000。
* 第二个问题可以枚举所有改动。可选改动的数量:谜语最多8位,可以改动0-8位,每位
* 有10个可改选项,所有改动有:
* C(8,0)*pow(10,0)+C(8,1)*pow(10,1)+C(8,2)*pow(10,2)...+C(8,8)*pow(10,8)
* =很大的数。每个改动判断是否唯一解,还要进行40000次运算.
* 思路:1.ida。这是最直接的思路,直觉判断会超时。
* 2.先根据当前谜语,得到所有等式,然后根据等式形式,反向推导唯一解谜语。推导
* 方法是固定固定某几位*,看看结果是否为唯一。这道题就变成了集合查找问题。这种思
* 路是错误的:如果改动不是固定*,而是把一个数字变成另一个数字,或者变成一
* 个*。可能会导致错误答案,因为对转移做了限制。如8 ** 8*应当改为6 ** 8*
* 3.枚举所有的谜语,打表有唯一解谜语,然后看看当前谜语距离有唯一解谜语
* 最近的是哪个。计算量太大,不可取。
* 老老实实ida吧,想想有什么剪枝策略是正路。
*/
#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
using namespace std;
char t[10][10][10][10][5];//乘法表
const unsigned char bits[8] = { 0x1, 0x2, 0x4, 0x8,
0x10, 0x20, 0x40, 0x80};
struct Puzzle
{
char pu[9];
int s;
Puzzle newp(int pos, char c) const
{
Puzzle np;
strcpy(np.pu, pu);
np.pu[pos] = c;
np.getsolve();
return np;
}
bool operator<(const Puzzle & b) const
{
if (!pu[0])
return false;
if (!b.pu[0])
return true;
if (strlen(pu) != strlen(b.pu))
return false;
if (('0' == pu[0] && '0' != b.pu[0]) || ('0' != pu[0] && '0' == b.pu[0]))
return false;
if (('0' == pu[2] && '0' != b.pu[2]) || ('0' != pu[2] && '0' == b.pu[2]))
return false;
for(int i = 0; pu[i]; i++)
{
if (b.pu[i] == pu[i])
continue;
if ('*' == pu[i])
return true;
else if ('*' == b.pu[i])
return false;
else
return pu[i] < b.pu[i];
}
return false;
}
void print() const
{
if ('0' != pu[0])
cout<<pu[0];
cout<<pu[1]<<' ';
if ('0' != pu[2])
cout<<pu[2];
cout<<pu[3]<<' '<<pu+4<<endl;
}
char minb(int i) const
{
if (0 == i || 2 == i || 4 == i)
return '1';
else if (1 == i || 3 == i)
return ('0' == pu[i-1]) ? '1' : '0';
else
return '0';
}
void getsolve()
{
s = 0;
int ab[4][2];
for(int i = 0; i < 4; i++)
{
ab[i][0] = (pu[i] == '*') ? ((i == 0 || i == 2) ? 1: 0) : pu[i]-'0';
ab[i][1] = (pu[i] == '*') ? 9 : pu[i]-'0';
}
for(int a = ab[0][0]; a <= ab[0][1]; a++)
for(int b = ab[1][0]; b <= ab[1][1]; b++)
for(int c = ab[2][0]; c <= ab[2][1]; c++)
for(int d = ab[3][0]; d <= ab[3][1]; d++)
{
int j = 0;
for(; pu[4+j] && t[a][b][c][d][j]; j++)
{
if (!(t[a][b][c][d][j] == pu[4+j]
|| '*' == pu[4+j]))
break;
}
if (!pu[4+j] && !t[a][b][c][d][j])
{
s++;
if (s > 1)
return;
}
}
}
};
Puzzle be;
Puzzle ans;
void initialize()
{
for(int a = 0; a <= 9; a++)
for(int b = 0; b <= 9; b++)
for(int c = 0; c <= 9; c++)
for(int d = 0; d <= 9; d++)
sprintf(t[a][b][c][d],"%d",(a*10+b)*(c*10+d));
}
int dd;
bool ida(int d, unsigned char vis, const Puzzle & p)
{
if (d == dd)
{
if (p.s == 1 && p < ans)
ans = p;
return p.s == 1;
}
else
{
if (ans < p)
return false;
for(int i = 0; p.pu[i]; i++) //数字变*,变小
{
if (vis & bits[i] || ((0==i||2==i) && '0'==p.pu[i]) || '*' == p.pu[i])
continue;
if (ida(d+1, vis | bits[i], p.newp(i, '*')))
return true;
for(char j = p.minb(i); j < p.pu[i]; j++)
if (ida(d+1, vis | bits[i], p.newp(i, j)))
return true;
}
bool r = false;
//递归过程不能保证按字典排序,递归成功后要继续枚举所有解
for(int i = strlen(p.pu)-1; i >= 0; i--)//数字变大,*变数字
{
if (vis & bits[i] || ((0 == i || 4 == i) && '0' == p.pu[i]))
continue;
for(char j = p.minb(i); j <= '9'; j++)
if (ida(d+1, vis | bits[i], p.newp(i, j)))
r = true;
}
return r;
}
}
int main()
{
int ka = 0;
string s;
initialize();
while(getline(cin, s) && s[0] != '0')
{
string::size_type pos0 = s.find(' ');
string::size_type pos1 = s.find(' ', pos0+1);
be.pu[0] = (pos0 < 2) ? '0' : s[0];
be.pu[1] = (pos0 < 2) ? s[0] : s[1];
be.pu[2] = (pos1-pos0 <= 2) ? '0' : s[pos0+1];
be.pu[3] = (pos1-pos0 <= 2) ? s[pos0+1] : s[pos0+2];
strcpy(be.pu+4, s.c_str()+pos1+1);
be.getsolve();
ans.pu[0] = 0;
for(dd = 0; dd <= 6; dd++)
{
if (ida(0, 0, be))
break;
}
cout<<"Case "<<++ka<<": ";
ans.print();
}
}
| true |
6d47417cbb6c9ea6a6df3777e21c576aaefee379 | C++ | TESLA-Self-Driving-Car/Lane-Change-Simulation | /header/vec2D.h | UTF-8 | 8,322 | 3.453125 | 3 | [] | no_license | //
// vec2D.hpp
// CarGame
//
// Created by HJKBD on 8/20/16.
// Copyright © 2016 HJKBD. All rights reserved.
//
#ifndef vec2D_h
#define vec2D_h
#include <cfloat>
#include <climits>
#include <tuple>
#include "globals.h"
#include <iostream>
using std::ostream;
/*The Vector2d class is an object consisting of simply an x and
y value. Certain operators are overloaded to make it easier
for vector math to be performed.*/
#define PI 3.14159265
template<class T>
class Vector2d {
public:
/*The x and y values are public to give easier access for
outside funtions. Accessors and mutators are not really
necessary*/
T x;
T y;
//Constructor assigns the inputs to x and y.
Vector2d(): x(T(0)), y(T(0)) {}
Vector2d(const T& vx, const T& vy): x(vx), y(vy) {}
Vector2d(const Vector2d& v):x(v[0]), y(v[1]){}
T& operator[](int i) { return (i == 0)?x:y; }
T operator[](int i) const { return (i== 0)?x:y;}
/*The following operators simply return Vector2ds that
have operations performed on the relative (x, y) values*/
Vector2d& operator+=(const Vector2d& v) { x += v.x; y += v.y; return *this; }
Vector2d& operator-=(const Vector2d& v) { x -= v.x; y -= v.y; return *this; }
Vector2d& operator*=(const Vector2d& v) { x *= v.x; y *= v.y; return *this; }
Vector2d& operator/=(const Vector2d& v) { x /= v.x; y /= v.y; return *this; }
//Check if the Vectors have the same values (uses pairwise comparison of `std::tuple` on the x,y values of L and R.
friend bool operator==(const Vector2d& L, const Vector2d& R) { return std::tie(L.x, L.y) == std::tie(R.x, R.y); }
friend bool operator!=(const Vector2d& L, const Vector2d& R) { return !(L == R); }
//Check if the Vectors have the same values (uses pairwise comparison of `std::tuple` on the x,y values of L and R.
friend bool operator< (const Vector2d& L, const Vector2d& R) { return std::tie(L.x, L.y) < std::tie(R.x, R.y); }
friend bool operator>=(const Vector2d& L, const Vector2d& R) { return !(L < R); }
friend bool operator> (const Vector2d& L, const Vector2d& R) { return R < L ; }
friend bool operator<=(const Vector2d& L, const Vector2d& R) { return !(R < L); }
//Negate both the x and y values.
Vector2d operator-() const { return Vector2d(-x, -y); }
//Apply scalar operations.
Vector2d& operator*=(const T& s) { x *= s; y *= s; return *this; }
Vector2d& operator/=(const T& s) { x /= s; y /= s; return *this; }
//utility functions below for analaysis
//roate
void rotate(float angle_degrees);
//return roated vector
Vector2d<T> rotated(float angle_degrees);
//Product functions
T dot(const Vector2d<T>&, const Vector2d<T>&);
T cross(const Vector2d<T>&, const Vector2d<T>&);
//Returns the length of the vector from the origin.
T Length(const Vector2d<T>& v);
//set length of the vector
T Length() { return sqrt((this->x * this->x) + (this->y * this->y));}
//get distance between objects
T get_distance(const Vector2d<T>& other) {
return sqrt(pow((x - other[0]),2) + pow((y - other[1]),2));}
//nomalized vector
void normalized();
Vector2d<T> normalized(const Vector2d<T>& v);
//Return a vector perpendicular to the left.
Vector2d<T> perpendicular() { return Vector2d<T>(y, -x);}
//Return true if two line segments intersect.
bool Intersect(const Vector2d<T>&, const Vector2d<T>&, const Vector2d<T>&, const Vector2d<T>&);
//Return the point where two lines intersect.
Vector2d<T> get_Intersect(const Vector2d<T>&, const Vector2d<T>&, const Vector2d<T>&, const Vector2d<T>&);
//return the angle
float get_angle() {
if (this->Length() == 0) return 0;
float angle = atan2(y, x);
return angle/PI*180;
;
}
//return the angle between two vectors
float get_angle_between(const Vector2d<T>&);
// get the opposite direction vector
Vector2d<T> get_reflection() {
return Vector2d(-x, -y);
}
//projection
T project(const Vector2d<T>& point, const Vector2d<T>& vector);
// projection
std::pair<T,T> projectPoints(const std::vector<Vector2d<T>>& points, const Vector2d<T>& vec);
friend ostream& operator<<(std::ostream& os, const Vector2d<T>& v)
{
os << "("<<v[0] << ", " << v[1] << ")";
return os;
}
};
template<class T>
Vector2d<T> operator+(const Vector2d<T>& L, const Vector2d<T>& R) {
return Vector2d<T>(L) += R; }
template<class T>
Vector2d<T> operator-(const Vector2d<T>& L, const Vector2d<T>& R) {
return Vector2d<T>(L)-= R; }
template<class T>
Vector2d<T> operator*(const Vector2d<T>& L, const Vector2d<T>& R) {
return Vector2d<T>(L)*= R; }
template<class T>
Vector2d<T> operator/(const Vector2d<T>& L, const Vector2d<T>& R) {
return Vector2d<T>(L)/= R; }
template<class T>
Vector2d<T> operator*(const T& s, const Vector2d<T>& v)
{ return Vector2d<T>(v) *= s; }
template<class T>
Vector2d<T> operator*(const Vector2d<T>& v, const T& s)
{ return Vector2d<T>(v) *= s; }
template<class T>
Vector2d<T> operator/(const T& s, const Vector2d<T>& v) {
return Vector2d<T>(v) /= s;
}
template<class T>
Vector2d<T> operator/(const Vector2d<T>& v, const T& s) {
return Vector2d<T>(v) /= s;
}
template<class T>
T dot(const Vector2d<T>& a, const Vector2d<T>& b){
return ((a.x * b.x) + (a.y * b.y));}
template<class T>
T cross(const Vector2d<T>& a, const Vector2d<T>& b){
return ((a.x * b.y) - (a.y * b.x));
}
template<class T>
T Length(const Vector2d<T>& v) { return sqrt((v.x * v.x) + (v.y * v.y));}
template<class T> Vector2d<T> normalized(const Vector2d<T>& v){
T magnitude = Length(v);
return Vector2d<T>(v.x / magnitude, v.y / magnitude);
}
template<class T> void Vector2d<T>::normalized(){
T magnitude = this->Length();
if (magnitude != 0) {
x /= magnitude;
y /= magnitude;
}else{
x = 0;
y = 0;
}
}
template<class T>
bool Vector2d<T>::Intersect(const Vector2d<T>&aa, const Vector2d<T>&ab, const Vector2d<T>&ba, const Vector2d<T>&bb){
Vector2d<T> p = aa;
Vector2d<T> r = ab - aa;
Vector2d<T> q = ba;
Vector2d<T> s = bb - ba;
float t = CrossProduct((q - p), s) / CrossProduct(r, s);
float u = CrossProduct((q - p), r) / CrossProduct(r, s);
return (0.0 <= t && t <= 1.0) &&
(0.0 <= u && u <= 1.0);
}
template<class T>
Vector2d<T> Vector2d<T>::get_Intersect(const Vector2d<T>&aa, const Vector2d<T>&ab, const Vector2d<T>&ba, const Vector2d<T>&bb){
T pX = (aa.x*ab.y - aa.y*ab.x)*(ba.x - bb.x) - (ba.x*bb.y - ba.y*bb.x)*(aa.x - ab.x);
T pY = (aa.x*ab.y - aa.y*ab.x)*(ba.y - bb.y) -(ba.x*bb.y - ba.y*bb.x)*(aa.y - ab.y);
T denominator = (aa.x - ab.x)*(ba.y - bb.y) -
(aa.y - ab.y)*(ba.x - bb.x);
return Vector2d<T>(pX / denominator, pY / denominator);
}
template<class T>
void Vector2d<T>::rotate(float angle_degrees){
T radians = angle_degrees/180*PI;
T co = cos(radians);
T sn = sin(radians);
T xx = x*co - y*sn;
T yy = x*sn + y*co;
x = xx;
y = yy;
}
template<class T>
Vector2d<T> Vector2d<T>::rotated(float angle_degrees){
float radians = angle_degrees/180*PI;
float co = cos(radians);
float sn = sin(radians);
T xx = x*co - y*sn;
T yy = x*sn + y*co;
return Vector2d(xx, yy);
}
template<class T>
float Vector2d<T>::get_angle_between(const Vector2d<T>& other)
{
T cross = x*other[1] - y*other[0];
T dot = x*other[0] + y*other[1];
return atan2(cross, dot)/PI*180;
}
template<class T>
T project(const Vector2d<T>& point, const Vector2d<T>& vector)
{ return dot(point,vector) / dot(vector, vector); }
template<class T>
std::pair<T,T> projectPoints(const std::vector<Vector2d<T>>& points, const Vector2d<T>& vec)
{
std::vector<T> values;
for (const auto& point: points) {
T value = project(point, vec);
values.push_back(value);
}
auto ele = std::minmax_element(values.begin(), values.end());
// std::cout<<*ele.first<<std::endl;
// std::pair<T,T> result = make_pair(*ele.first, *ele.second);
std::pair<T,T> result(*ele.first, *ele.second);//(points[0], points[1]);
return result;
//return ele;
}
#endif /* vec2D_hpp */
| true |
4e43f448df0e4834967b80abb4dd3a1a304665c9 | C++ | hamdanjaveed/Learning-CPP | /Input/Input.cpp | UTF-8 | 1,087 | 4.1875 | 4 | [] | no_license | // ask for the user's name, and then generate a framed greeting
#include <iostream>
#include <string>
// say that we're using the std namespace
using namespace std;
int main() {
// ask for the person's name
cout << "Please enter your name: ";
// read the name
// a variable to hold the user's name
string name;
// read the name
cin >> name;
// build the message
const string greeting = "Hello, " + name + "!";
// the number of blank spaces around the greeting (both vert and horz)
const int pad = 1;
// the number of rows and columns to write
const int rows = pad * 2 + 3;
const string::size_type columns = greeting.size() + pad * 2 + 2;
// write a line to separate output
cout << endl;
// write the output
for (int r = 0; r < rows; r++) {
string::size_type c = 0;
while (c < columns) {
if (r == pad + 1 && c == pad + 1) {
cout << greeting;
c += greeting.size();
} else {
if (r == 0 || r == rows - 1 || c == 0 || c == columns - 1) {
cout << "*";
} else {
cout << " ";
}
c++;
}
}
cout << endl;
}
return 0;
}
| true |
37d7b76e08273d2690a44da3a4cb720a1306adf2 | C++ | goncaloacteixeira/feup-aeda | /aeda1920_fp03/Tests/grafo.h | UTF-8 | 6,697 | 3.578125 | 4 | [] | no_license | #include <iostream>
#include <vector>
#include <string>
using namespace std;
/**
* Versao da classe generica Grafo usando a classe vector
*/
template <class N, class A> class Aresta;
template <class N, class A>
class No {
public:
N info;
vector< Aresta<N,A> > arestas;
No(N inf) {
info = inf;
}
};
template <class N, class A>
class Aresta {
public:
A valor;
No<N,A> *destino;
Aresta(No<N,A> *dest, A val) {
valor = val;
destino = dest;
}
};
template <class N, class A>
class Grafo {
vector< No<N,A> *> nos;
public:
Grafo();
~Grafo();
Grafo & inserirNo(const N &dados);
Grafo & inserirAresta(const N &inicio, const N &fim, const A &val);
Grafo & eliminarAresta(const N &inicio, const N &fim);
A & valorAresta(const N &inicio, const N &fim);
int numArestas(void) const;
int numNos(void) const;
void imprimir(std::ostream &os) const;
};
template<class N, class A>
Grafo<N, A>::Grafo() {
this->nos = {};
}
template<class N, class A>
Grafo<N, A>::~Grafo() {
}
template <class N, class A>
std::ostream & operator<<(std::ostream &out, const Grafo<N,A> &g){
g.imprimir(out);
}
// excecao NoRepetido
template <class N>
class NoRepetido
{
public:
N info;
NoRepetido(N inf) { info=inf; }
};
template <class N>
std::ostream & operator<<(std::ostream &out, const NoRepetido<N> &no)
{ out << "No repetido: " << no.info; return out; }
// excecao NoInexistente
template <class N>
class NoInexistente {
public:
N info;
NoInexistente(N inf) {
info = inf;
}
};
template <class N>
std::ostream & operator<<(std::ostream &out, const NoInexistente<N> &ni)
{ out << "No inexistente: " << ni.info; return out; }
// excecao ArestaRepetida
template <class N>
class ArestaRepetida {
public:
N inicio;
N destino;
ArestaRepetida(N inicio, N destino) {
this->inicio = inicio;
this->destino = destino;
}
};
template <class N>
std::ostream & operator<<(std::ostream &out, const ArestaRepetida<N> &ni)
{ out << "Aresta repetida: " << ni.inicio << " , " << ni.destino; return out; }
// excecao ArestaInexistente
template <class N>
class ArestaInexistente {
public:
N inicio;
N destino;
ArestaInexistente(N inicio, N destino) {
this->inicio = inicio;
this->destino = destino;
}
};
template <class N>
std::ostream & operator<<(std::ostream &out, const ArestaInexistente<N> &ni)
{ out << "Aresta inexistente: " << ni.inicio << " , " << ni.destino; return out; }
template<class N, class A>
int Grafo<N, A>::numNos(void) const {
return nos.size();
}
template<class N, class A>
int Grafo<N, A>::numArestas(void) const {
int count = 0;
if (this->numNos() == 0)
return count;
for (int i = 0; i < numNos(); i++)
{
count += nos[i]->arestas.size();
}
return count;
}
template<class N, class A>
Grafo<N, A> &Grafo<N, A>::inserirNo(const N &dados) {
if (this->numNos() != 0) {
for (int i = 0; i < this->numNos(); i++) {
if (nos[i]->info == dados) {
throw NoRepetido<N>(dados);
}
}
}
nos.push_back(new No<N, A>(dados));
return *this;
}
template<class N, class A>
Grafo<N, A> &Grafo<N, A>::inserirAresta(const N &inicio, const N &fim, const A &val) {
if (this->numNos() == 0)
throw NoInexistente<N>(inicio);
bool inicioExiste = false;
for (int i = 0; i < this->numNos(); i++){
if (nos[i]->info == inicio)
inicioExiste = true;
}
for (int i = 0; i < this->numNos(); i++)
{
if (nos[i]->info == inicio){
if (nos[i]->arestas.size() != 0) {
for (int j = 0; j < nos[i]->arestas.size(); j++)
{
if (nos[i]->arestas[j].destino->info == fim)
{
throw ArestaRepetida<N>(inicio, fim);
}
}
}
nos[i]->arestas.push_back(Aresta<N,A>(new No<N,A>(fim), val));
return *this;
}
}
if (inicioExiste)
throw NoInexistente<N>(fim);
throw NoInexistente<N>(inicio);
}
template<class N, class A>
A &Grafo<N, A>::valorAresta(const N &inicio, const N &fim) {
if (this->numArestas() == 0)
throw ArestaInexistente<N>(inicio, fim);
bool flag = false;
bool inicioExiste = false;
for (int i = 0; i < this->numNos(); i++){
if (nos[i]->info == inicio)
inicioExiste = true;
}
for (int i = 0; i < this->numNos(); i++)
{
if (nos[i]->info == inicio)
{
flag = true;
if (nos[i]->arestas.size() != 0)
{
for (int j = 0; j < nos[i]->arestas.size(); j++)
{
if (nos[i]->arestas[j].destino->info == fim)
return nos[i]->arestas[j].valor;
}
}
}
}
if (flag)
throw ArestaInexistente<N>(inicio, fim);
if (inicioExiste)
throw NoInexistente<N>(fim);
throw NoInexistente<N>(inicio);
}
template<class N, class A>
Grafo<N,A> &Grafo<N, A>::eliminarAresta(const N &inicio, const N &fim) {
if (this->numArestas() == 0)
throw ArestaInexistente<N>(inicio, fim);
bool inicioExiste = false;
bool fimExiste = false;
int i = 0;
for (i; i < this->numNos(); i++){
if (nos[i]->info == inicio) {
inicioExiste = true;
break;
}
}
for (int k = 0; k < this->numNos(); k++){
if (nos[k]->info == fim) {
fimExiste = true;
break;
}
}
if (inicioExiste && fimExiste)
{
if (nos[i]->arestas.size() == 0)
throw ArestaInexistente<N>(inicio, fim);
for (int j = 0; j < nos[i]->arestas.size(); j++)
{
if (nos[i]->arestas[j].destino->info == fim)
{
nos[i]->arestas.erase(nos[i]->arestas.begin() + j);
return *this;
}
}
throw ArestaInexistente<N>(inicio, fim);
}
if (!inicioExiste)
throw NoInexistente<N>(inicio);
throw NoInexistente<N>(fim);
}
template<class N, class A>
void Grafo<N, A>::imprimir(std::ostream &os) const {
if (this->numNos() != 0)
{
for (int i = 0; i < this->numNos(); i++){
os << "( " << nos[i]->info;
if (nos[i]->arestas.size() != 0)
{
for (int j = 0; j < nos[i]->arestas.size(); j++){
os << " [" << nos[i]->arestas[j].destino->info << " " << nos[i]->arestas[j].valor << "]";
}
}
os << " )";
}
}
}
| true |
50a0e5bcd025820ed391ffff9d954b17813a4416 | C++ | per1234/arduino-nemeus-lib | /examples/LoRa_02_send_frame_OTAA/LoRa_02_send_frame_OTAA.ino | UTF-8 | 3,959 | 2.703125 | 3 | [
"Apache-2.0"
] | permissive | /* Basic example for LoRaWAN OTAA
*
* Uses Nemeus Library
* Offers the possibility to change the app UID and the app KEY
* In main loop,sends a frame using LoRaWAN.
*
*/
#include <NemeusLib.h>
#include <Wire.h>
/* Define APPUID and APPKEY, change value here if needed */
#define APPUID "70B3D53260000100"
//#define APPKEY "000102030405060708090A0B0C0D0E0F" //Uncomment if you want to change the APPKEY
#define MAXPAYLOADSIZE 512
/* Define a counter variable */
uint16_t frameCounter = 0;
uint8_t ret;
char pattern[4] = { 'C', 'A', 'F', 'E' };
/* Reception callback for RF frames */
void onReceive(const char *string);
/* Reception callback for Downlink frames */
void onReceiveDownlink(uint8_t port , boolean more, const char * hexaPayload, int rssi, int snr);
void setup()
{
/* serial monitor */
SerialUSB.begin(115200);
#ifdef CONSOLE_CHECK
while(!SerialUSB)
{
; /*SerialUSB not ready */
}
SerialUSB.println(">>Console Ready");
#endif
SerialUSB.println(">>Sketch: Sending frame using LoRaWAN OTAA ");
delay(1000);
/* Reset the modem */
if ( nemeusLib.resetModem() != NEMEUS_SUCCESS)
{
SerialUSB.print("Nemeus device is not responding!");
while(1)
{
}
}
/* Init nemeus library */
if(nemeusLib.init() != NEMEUS_SUCCESS)
{
SerialUSB.print("Nemeus device is not responding!");
while(1)
{
}
}
/* Register a callback for reception */
nemeusLib.register_at_response_callback(&onReceive);
/* Register a callback for downlink frames */
nemeusLib.loraWan()->register_downlink_callback(&onReceiveDownlink);
nemeusLib.setVerbose(true);
/* Enable verbose traces */
ret = nemeusLib.setVerbose(true);
/* Turn off LoRaWAN if not */
ret = nemeusLib.loraWan()->OFF();
/* Read personnal parameters */
DevPerso_t *devPerso = nemeusLib.loraWan()->readDevPerso();
/* Compare with values defined */
if (strcmp(devPerso->appUID, (char*)APPUID) == 0)
{
SerialUSB.println("No changement for the APPUID");
}
else
{
SerialUSB.println("Changing APPUID...");
ret = nemeusLib.loraWan()->setAppUID((char*)APPUID);
}
#ifdef APPKEY
SerialUSB.println("Changing the APPKEY...");
ret = nemeusLib.loraWan()->setAppKey((char*)APPKEY);
#endif
/* Turn ON Radio */
ret = nemeusLib.loraWan()->ON('A', true);
if(ret == NEMEUS_SUCCESS)
{
SerialUSB.println("LoRaWAN ON - Class A - OTAA!!!");
}
else
{
SerialUSB.println("LoRaWAN ON OTAA failure!");
while(1)
{
}
}
/* Read ABP perso */
DevPerso_t *abpPerso = nemeusLib.loraWan()->readAbpPerso();
}
void loop()
{
/* Get Maximum payload */
int maxPayloadSize = nemeusLib.loraWan()->getMaximumPayloadSize();
static char buffer[MAXPAYLOADSIZE];
for (int i = 0; i < maxPayloadSize; i++)
{
buffer[i] = pattern[i % 4];
}
buffer[maxPayloadSize] = 0;
/* Send a frame (BINARY mode, Repetition = 1, mac Port = 2, ACK, Encrypted) */
ret = nemeusLib.loraWan()->sendFrame(0, 1, 2, buffer, 1, 1);
nemeusLib.pollDevice(5000);
nemeusLib.printTraces();
}
/* ---------------- Functions ---------------- */
void onReceive(const char *string)
{
SerialUSB.print("mm002 >> ");
SerialUSB.println(string);
}
/*
* If piggyback setting is disabled and device class is A, the server will be polled automatically to receive more downlink frames.
* A downlink frame unsolicited response is always sent after a Tx to indicate the end of Rx windows.
*/
void onReceiveDownlink(uint8_t port , boolean more, const char * hexaPayload, int rssi, int snr)
{
SerialUSB.println("Downlink frame received");
SerialUSB.print("Port:");
SerialUSB.println(port);
SerialUSB.print("Pending frames:");
if(more == 1)
{
SerialUSB.println("False");
}
else
{
SerialUSB.println("True");
}
SerialUSB.print("Payload:");
SerialUSB.println(hexaPayload);
SerialUSB.print("RSSI:");
SerialUSB.println(rssi);
SerialUSB.print("SNR:");
SerialUSB.println(snr);
}
| true |
b97c0d455f388f29bd89d423b9dd6d08c3cafe8b | C++ | neptune46/design-pattern-cpp | /facade/Facade.cpp | UTF-8 | 1,053 | 2.578125 | 3 | [] | no_license | //This source code was generated using Premium Visual Studio Design Patterns add-in
//You can find the source code and binaries at http://VSDesignPatterns.codeplex.com
////Provide a unified interface to a set of interfaces in a subsystem. Facade defines
//a higher-level interface that makes the subsystem easier to use.
#include "stdafx.h"
#include "facade.h"
namespace facade
{
SubsystemA* Facade::a = new SubsystemA();
SubsystemB* Facade::b = new SubsystemB();
void FacadeClient::Test()
{
Facade::Operation1();
Facade::Operation2();
}
std::string SubsystemA::A1()
{
return "SubsystemA, Method A1\n";
}
std::string SubsystemA::A2()
{
return "SubsystemA, Method A2\n";
}
std::string SubsystemB::B1()
{
return "SubsystemB, Method B1\n";
}
std::string SubsystemB::B2()
{
return "SubsystemB, Method B2\n";
}
void Facade::Operation1()
{
std::cout << "Operation 1\n" << a->A1() << b->B1() << std::endl;
}
void Facade::Operation2()
{
std::cout << "Operation 2\n" << b->B2() << a->A2() << std::endl;
}
} | true |
98b6efa2dc7baf01a4f1b7425f548d4ad5cb15f4 | C++ | toskov/CodiCamp | /MyGame/SpaceGame/SpaceGame/Thing.cpp | UTF-8 | 3,774 | 2.640625 | 3 | [] | no_license | #include "Thing.h"
Thing::Thing()
{
}
Thing::Thing(CIndieLib *mI, IND_Surface *thingsPicture, int type, int x, int y, int life, int angle, vector<Frame*> frms)
{
// random speed and direction (rand() % 2 - 1)
//srand(time(NULL));
*velosityX = rand() % 100;
*velosityY = rand() % 100;
this->thingPictures = thingsPicture;
this->frames = frms;
*posX = x;
*posY = y;
*health = life;
*this->type = type;
thing->setSurface(thingsPicture);
mI->_entity2dManager->add(thing);
int radius = 0;
string typ = "";
switch (type){
case HEALTH:
typ = "health";
radius = 20;
break;
case ASTEROID:
typ = "asteroid";
radius = 40;
thing->setScale(0.7, 0.7);
break;
case ROCK:
typ = "rock";
radius = 20;
break;
case DIAMOND:
typ = "diamond";
radius = 20;
break;
case UFO:
typ = "ufo";
radius = 15;
break;
}
name = typ;
// Search first picture for type;
frameCount = 0; // clear number of frames
int width, height,offsetX,offsetY;
for (int i = 0; i < frms.size(); i++)
{
if (typ == frms.at(i)->name)
{
frameCount++;
width = frms.at(i)->width;
height = frms.at(i)->height;
offsetX = frms.at(i)->offsetX;
offsetY = frms.at(i)->offsetY;
// break;
currentFrame = i;// last frame
}
}
//srand(time(NULL)); // random generfated possition
currentFrame = rand() % (frameCount-1);
// Entity adding
thing->setPosition(x, y, 1);
//health (1) = 360 1180 50 50
//thing->setRegion(360, 1180, 50, 50);
thing->setRegion(offsetX, offsetY, width, height); // shows first picture from sprite
// Empty object for colisions!
mI->_entity2dManager->add(border);
border->setSurface(collisionSurface);
//border->setPosition(x,y,COLLISIONS);
border->setBoundingCircle("thing", x + width /2, y + height / 2, radius);
// prepare positions for explosion
*collisionsX = border->getPosX();//x + width / 2;
*collisionsY = border->getPosY();//y + height / 2;
relativeX = width / 2;
relativeY = height / 2;
}
IND_Entity2d* Thing::getColisionBorder()
{
return border;
}
int Thing::getHealth(void)
{
return *health;
}
int Thing::getType()
{
return *type;
}
int Thing::getCollisionPositionX()
{
return *posX+relativeX;
}
int Thing::getCollisionPositionY()
{
return *posY+relativeY;
}
void Thing::animationUpdate()
{
// get current frame from sprite
int width, height, offsetX, offsetY;
currentFrame++;
if (currentFrame > frameCount) currentFrame = 1;
for (int i = 0; i < frames.size(); i++)
{
if ((name == frames.at(i)->name) && (frames.at(i)->frameNumber == currentFrame))
{
width = frames.at(i)->width;
height = frames.at(i)->height;
offsetX = frames.at(i)->offsetX;
offsetY = frames.at(i)->offsetY;
break;
}
}
thing->setRegion(offsetX, offsetY, width, height); // shows region
}
//Used for moving objects
void Thing::setVelosity(int vx, int vy)
{
*velosityX = vx;
*velosityY = vy;
}
//Update moving objects
void Thing::Update(double *delta)
{
*posX = *posX + *velosityX*(*delta);
*posY = *posY + *velosityY*(*delta);
thing->setPosition(*posX,*posY, 2);
*collisionsX = border->getPosX() + *velosityX*(*delta);
*collisionsY = border->getPosY() + *velosityY*(*delta);
border->setPosition(*collisionsX, *collisionsY, ENEMY);
if ((*posX > WINDOW_WIDTH) || (*posX <1)) *velosityX = -*velosityX;
if ((*posY > WINDOW_HEIGHT) || (*posY <1)) *velosityY = -*velosityY;
}
void Thing::destroy(CIndieLib *mI)
{
delete health;
delete type;
delete posX;
delete posY;
border->deleteBoundingAreas("thing");
mI->_entity2dManager->remove(thing);
mI->_entity2dManager->remove(border);
mI->_surfaceManager->remove(collisionSurface);
}
Thing::~Thing()
{
delete velosityX;
delete velosityY;
delete health;
delete posX;
delete posY;
delete type;
} | true |
fab1d7524668c130ea33bbb765bd9d8f8b783635 | C++ | benbancroft/2DEngine | /Common/tiles/tilesystem.cpp | UTF-8 | 8,368 | 2.59375 | 3 | [
"MIT"
] | permissive | #include "tiles/tilesystem.h"
namespace Core {
TileSystem::TileSystem(Level* level, TileGenerator* generator, std::string tilesheetUrl, int tileSize, int chunkSize){
this->level = level;
this->generator = generator;
this->tileSize = tileSize;
this->chunkSize = chunkSize;
this->tilesheetUrl = tilesheetUrl;
generator->SetLevel(level);
generator->SetTileSystem(this);
//if level has bounds check to see if boundx,y mod chunksize is zero
//attach generator...
}
void TileSystem::Render(Core::Render *render){
for (const auto& kv : this->tileChunks) {
//kv.second->Render(kv.first, render);
}
}
void TileSystem::Loaded(Engine* engine){
if (generator != NULL) {
generator->RegisterBlocks(engine);
generator->Loaded(engine);
}
}
int toBlockComponent(double comp, double tileSize, bool up = false){
if (up)
return (int)ceil(comp/tileSize);
else
return (int)floor(comp/tileSize);
}
bool scanForEdgeCollision(double collisionX, double collisionY, double aabbWidth, double aabbHeight, TileSystem* tileSystem, bool farSide, bool flipAxis = false){
if (flipAxis){
std::swap(collisionX, collisionY);
std::swap(aabbWidth, aabbHeight);
}
if (farSide){
collisionY += aabbHeight;
}
int yBlock = toBlockComponent(collisionY, tileSystem->tileSize);
int startX = toBlockComponent(collisionX, tileSystem->tileSize);
int endX = toBlockComponent((collisionX+aabbWidth), tileSystem->tileSize);
int dir = farSide ? 0 : 1;
for (int xBlock = startX; xBlock <= endX; xBlock++) {
int blockId = 0;
if (flipAxis){
blockId = tileSystem->GetBlock(Maths::Vector2<int>(yBlock-dir, xBlock));
}else{
blockId = tileSystem->GetBlock(Maths::Vector2<int>(xBlock, yBlock-dir));
}
if (blockId != 0 && tileSystem->GetBlockById(blockId)->isSolid) {
return true;
}
}
return false;
}
CollisionSide TileSystem::ResolveCollision(double currentX, double currentY, double *newX, double *newY, double aabbWidth, double aabbHeight, bool canSlide){
double deltaY = *newY - currentY;
double deltaX = *newX - currentX;
double angle = atan2(deltaY, deltaX);
CollisionSide collisionState = CollisionSide::None;
bool isTouching = false;
double xFactor = 1;
double yFactor = 1;
double collisionX = currentX;
double collisionY = currentY;
int xDir = 0;
if (deltaY == 0 || deltaX == 0) {
yFactor = 0;
xFactor = 0;
}else{
yFactor = tan(angle);
if (yFactor != 0)
xFactor = 1 / tan(angle);
else
xFactor = 0;
}
yFactor=deltaY;
xFactor=deltaX;
if (deltaX > 0) {
xDir = 1;
}else if(deltaX < 0) {
xDir = -1;
}else{
xDir = 0;
}
int yDir = 0;
if (deltaY > 0) {
yDir = 1;
}else if (deltaY < 0) {
yDir = -1;
}else{
yDir = 0;
}
while (xDir != 0 && yDir != 0) {
double xDist = 0;
double yDist = 0;
if (yDir < 0) {
yDist = std::fabs(collisionY - (double)(toBlockComponent(collisionY, this->tileSize)*this->tileSize));
}else{
yDist = std::fabs(collisionY+aabbHeight - (toBlockComponent(collisionY+aabbHeight, this->tileSize, true)*this->tileSize));
}
//Check for touching on Y side that we are traveling in.
if (yDist == 0){
isTouching = scanForEdgeCollision(collisionX, collisionY, aabbWidth, aabbHeight, this, yDir > 0, false);
collisionState = yDir > 0 ? CollisionSide::Bottom : CollisionSide::Top;
}
if (xDir < 0) {
xDist = std::fabs(collisionX - (toBlockComponent(collisionX, this->tileSize)*this->tileSize));
}else{
xDist = std::fabs(collisionX+aabbWidth - (toBlockComponent(collisionX+aabbWidth, this->tileSize, true)*this->tileSize));
}
//Check for touching on Y side that we are traveling in.
if (isTouching == false && xDist == 0){
isTouching = scanForEdgeCollision(collisionX, collisionY,aabbWidth, aabbHeight, this, xDir > 0, true);
collisionState = xDir > 0 ? CollisionSide::Right : CollisionSide::Left;
}
if (!isTouching && ((yDist <= xDist && yDist != 0) || (xDist == 0)) && yDist < std::fabs(collisionY - *newY)) {
double tXdist = (yDist*yDir)/yFactor*xFactor;
bool wasCollision = scanForEdgeCollision(collisionX+tXdist, collisionY+yDist*yDir,aabbWidth, aabbHeight, this, yDir > 0, false);
if (wasCollision){
collisionState = yDir > 0 ? CollisionSide::Bottom : CollisionSide::Top;
}
collisionY += yDist*yDir;
collisionX += tXdist;
}else if (!isTouching && xDist != 0 && xDist < yDist && xDist < std::fabs(collisionX - *newX)) {
double tYdist = (xDist*xDir)/xFactor*yFactor;
bool wasCollision = scanForEdgeCollision(collisionX+xDist*xDir, collisionY+tYdist,aabbWidth, aabbHeight, this, xDir > 0, true);
if (wasCollision){
collisionState = xDir > 0 ? CollisionSide::Right : CollisionSide::Left;
}
collisionX += xDist*xDir;
collisionY += tYdist;
}else{
if (isTouching){
//Do nothing
}else{
collisionState = CollisionSide::None;
collisionX = *newX;
collisionY = *newY;
}
break;
}
if (collisionState != CollisionSide::None) {
break;
}
}
if (collisionState != CollisionSide::None || isTouching) {
if (canSlide){
double slideX = collisionX;
double slideY = collisionY;
switch(collisionState){
case Top:
case Bottom:
slideX = *newX;
break;
case Left:
case Right:
slideY = *newY;
break;
}
ResolveCollision(collisionX, collisionY, &slideX, &slideY, aabbWidth, aabbHeight, false);
collisionX = slideX;
collisionY = slideY;
}
*newX = collisionX;
*newY = collisionY;
}
return collisionState;
}
void TileSystem::Tick(Engine* engine){
if (generator != NULL) {
generator->Tick(engine);
}
}
Block* TileSystem::GetBlockById(int blockId){
auto it = blocks.find(blockId);
if (it != blocks.end()) {
return it->second;
}else
return NULL;
}
TileChunk* TileSystem::GetChunk(Maths::Vector2<int> chunkPosition, bool create){
auto chunkIter = tileChunks.find(chunkPosition);
TileChunk* chunk = NULL;
if (chunkIter != tileChunks.end()) chunk = chunkIter->second;
else if (create) {
chunk = new TileChunk(this, chunkPosition);
this->tileChunks[chunkPosition] = chunk;
}
return chunk;
}
void TileSystem::SetBlock(Maths::Vector2<int> position, int blockId){
auto chunkPosition = position.Clone()/chunkSize;
auto chunk = GetChunk(chunkPosition);
chunk->SetBlock(position%chunkSize, blockId);
}
int TileSystem::GetBlock(Maths::Vector2<int> position){
auto chunkPosition = position.Clone()/chunkSize;
auto chunk = GetChunk(chunkPosition, false);
if (chunk != NULL) {
return chunk->GetBlock(position%chunkSize);
}else{
return 0;
}
}
void TileSystem::RegisterBlockType(int blockId, Block* block){
blocks[blockId] = block;
}
void TileSystem::CreateTile(int depth, Maths::Vector2<int> position, Maths::Vector2<int> tile, bool createChunk){
auto chunkPosition = Maths::Vector2<int>(position.GetX(), position.GetY())/chunkSize;
TileChunk* chunk = GetChunk(chunkPosition, createChunk);
if (chunk != NULL) {
chunk->CreateTile(depth,position%chunkSize,tile);
}
}
void TileSystem::CreateTiles(){
for (const auto& kv : tileChunks) {
TileChunk* chunk = kv.second;
if (chunk->NeedsUpdate()) chunk->CreateTiles();
}
}
void TileSystem::CommitTiles(){
for (const auto& kv : tileChunks) {
TileChunk* chunk = kv.second;
chunk->CommitTiles();
}
}
}
| true |
346803912440fc25a4982128c14131702aeffb85 | C++ | xiekch/leetcode | /Single_Number.cpp | UTF-8 | 672 | 3.703125 | 4 | [
"MIT"
] | permissive | #include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
// Given a non-empty array of integers, every element appears twice except for
// one.
// Find that single one.
class Solution {
public:
int singleNumber(vector<int> &nums) {
sort(nums.begin(), nums.end());
int i;
for (i = 0; i < nums.size() - 1;) {
if (nums[i] == nums[i + 1]) {
i += 2;
} else
break;
}
return nums[i];
}
};
int main(int argc, char const *argv[]) {
vector<int> test = {4, 1, 2, 1, 2};
Solution sol;
cout << sol.singleNumber(test) << endl;
return 0;
}
| true |
55beb0d59a3c9d2f178498cad54a7c6d6d209257 | C++ | fromradio/ProjectEuler | /src/51-100/spiral_prime_58.cpp | UTF-8 | 756 | 2.765625 | 3 | [] | no_license | #include "prime.h"
#include <iostream>
#include <climits>
constexpr long limit = 1e9;
int main(int argc, char *argv[])
{
std::cout<<LONG_MAX<<std::endl;
auto primes = primeList(limit);
long side = 3;
long f = 3;
long ps = 0;
long n =1;
double ratio;
while (true)
{
if(f>(*primes.rbegin()))
{
std::cout<<"out of range "<<ratio<<std::endl;
break;
}
if(primes.find(f)!=primes.end())
ps += 1;
f += (side-1);
if(primes.find(f)!=primes.end())
ps += 1;
f += (side-1);
if(primes.find(f)!=primes.end())
ps += 1;
f += (side-1);
if(primes.find(f)!=primes.end())
ps += 1;
n += 4;
ratio = static_cast<double>(ps)/n;
if(ratio<0.1)
{
std::cout<<side<<std::endl;
break;
}
side += 2;
f += (side-1);
}
} | true |
22f43fefa89d984b5d1954928ec5cdc30c3435a5 | C++ | VicSch/Prata_S_Cpp_2011 | /Chapter_08/Exercises/Exerc_07.cpp | UTF-8 | 808 | 3.515625 | 4 | [] | no_license | #include <iostream>
using namespace std;
template <class T>
T sumArray(T* arr, int n); // template #1
template <class T>
T sumArray(T* arr[], int n); // template #2
struct debts {char name[20]; double amount;};
int main() {
int things[6] = {21, 15, 34, 9, 155, 6};
cout << sumArray(things, 6) << endl; // template #1
cout << endl;
debts mr[3] {
{"Uma", 2400.5},
{"Shaned", 3200.8},
{"Ann", 1200.2}
};
double* ptd[3];
for (int i = 0; i < 3; ++i)
ptd[i] = &mr[i].amount;
cout << sumArray(ptd, 3) << endl; // template #2
cin.get();
}
template <class T>
T sumArray(T* arr, int n) {
T sum = 0;
for (int i = 0; i < n; ++i)
sum += arr[i];
return sum;
}
template <class T>
T sumArray(T* arr[], int n) {
T sum = 0;
for (int i = 0; i < n; ++i)
sum += *arr[i];
return sum;
} | true |
c044796253ec1f2da02e2c4c139a9cd94ba26328 | C++ | Czyzmanski/simple-http-server | /main.cpp | UTF-8 | 15,967 | 2.703125 | 3 | [] | no_license | #include <cstdio>
#include <cstdlib>
#include <unistd.h>
#include <sys/stat.h>
#include <netinet/in.h>
#include <regex>
#include <fstream>
#include <iostream>
using requests_t = std::deque<std::string>;
using correlated_resources_t = std::map<const std::string, const std::string>;
using response_map_t = std::map<const std::string, std::string>;
const std::string DEFAULT_PORT = "8080";
const unsigned BUFFER_SIZE = 1024;
void create_urls_for_correlated_resources(
const std::string &filename,
correlated_resources_t &correlated_resources
) {
std::string prot = "http://";
std::string colon = ":";
std::ifstream file(filename);
if (!file.is_open()) {
std::cerr << "Unable to open a file: " << strerror(errno) << std::endl;
exit(EXIT_FAILURE);
}
for (std::string line; std::getline(file, line);) {
char delim = '\t';
std::istringstream iss(line);
std::string resrc, server, port;
std::getline(iss, resrc, delim);
std::getline(iss, server, delim);
std::getline(iss, port, delim);
std::string url = prot + server + colon + port + resrc;
correlated_resources.insert({resrc, url});
}
file.close();
}
void process_start_line_handle_target_file(
const std::string &target_path,
const std::string &directory,
std::ifstream &file,
response_map_t &response_map
) {
char *target_act_path = realpath(target_path.c_str(), nullptr);
char *directory_act_path = realpath(directory.c_str(), nullptr);
if (target_act_path != nullptr && directory_act_path != nullptr) {
// Check if directory_act_path is a prefix of target_act_path.
if (strlen(directory_act_path) < strlen(target_act_path) &&
std::string(target_act_path).rfind(directory_act_path, 0) == 0) {
std::string message_body(std::istreambuf_iterator<char>(file), {});
response_map.insert({"status-code", "200"});
response_map.insert({"reason-phrase", "OK"});
response_map.insert({"message-body", message_body});
response_map.insert(
{"content-length", std::to_string(message_body.length())}
);
response_map.insert({"content-type", "application/octet-stream"});
}
else {
response_map.insert({"status-code", "404"});
response_map.insert({"reason-phrase", "Not Found"});
}
}
else {
response_map.insert({"status-code", "500"});
response_map.insert({"reason-phrase", "Internal Server Error"});
}
free(directory_act_path);
free(target_act_path);
}
// Return first pos in request after start line.
size_t process_start_line(
const std::string &request,
const std::string &start_line_pattern,
const std::string &directory,
const correlated_resources_t &correlated_resources,
response_map_t &response_map
) {
std::smatch match;
std::regex start_line_regex(start_line_pattern);
std::regex_search(request, match, start_line_regex);
std::string method, target, version;
std::stringstream start_line_stream(match[0]);
start_line_stream >> method >> target >> version;
if (method != "GET" && method != "HEAD") {
response_map.insert({"status-code", "501"});
response_map.insert({"reason-phrase", "Not Implemented"});
}
else {
std::string target_path = directory == "/" ? target : directory + target;
struct stat sb;
std::ifstream file(target_path, std::ios::binary);
if (stat(target_path.c_str(), &sb) >= 0 &&
S_ISREG(sb.st_mode) != 0 && file.is_open()) {
process_start_line_handle_target_file(
target_path,
directory,
file,
response_map
);
file.close();
}
else {
auto resrc_it = correlated_resources.find(target);
if (resrc_it == correlated_resources.end()) {
response_map.insert({"status-code", "404"});
response_map.insert({"reason-phrase", "Not Found"});
}
else {
response_map.insert({"status-code", "302"});
response_map.insert({"reason-phrase", "Found"});
response_map.insert({"location", resrc_it->second});
}
}
}
if (method == "HEAD") {
response_map.erase("message-body");
}
response_map.insert({"content-length", "0"});
return match[0].length();
}
void process_header_field_lines(
const std::string &request,
const std::string &header_field_pattern,
response_map_t &response_map
) {
std::regex header_field_regex(header_field_pattern);
bool bad_format = false;
bool content_length_occurred = false;
std::sregex_iterator regex_it = std::sregex_iterator(
request.begin(),
request.end(),
header_field_regex
);
for (; regex_it != std::sregex_iterator(); regex_it++) {
std::smatch match = *regex_it;
std::string field_name, field_value;
std::stringstream line_stream(match.str());
line_stream >> field_name >> field_value;
for (size_t i = 0; i < field_name.length(); i++) {
field_name[i] = std::tolower(field_name[i]);
}
if (field_value != "") {
field_name.pop_back(); // Remove colon.
}
else {
size_t colon_pos = field_name.find(':');
field_value = field_name.substr(colon_pos + 1);
field_name = field_name.substr(0, colon_pos);
}
if (field_name == "connection") {
if (response_map.find(field_name) != response_map.end()) {
bad_format = true;
}
else {
response_map.insert({field_name, field_value});
}
}
else if (field_name == "content-length") {
if (content_length_occurred || field_value != "0") {
bad_format = true;
}
else {
content_length_occurred = true;
}
}
}
if (response_map["status-code"] == "501") {
response_map.insert({"connection", "close"});
}
else {
response_map.insert({"connection", "keep-alive"});
}
if (bad_format) {
response_map["status-code"] = "400";
response_map["reason-phrase"] = "Bad Request";
response_map["connection"] = "close";
response_map.erase("message-body");
response_map["content-length"] = "0";
response_map.erase("content-type");
}
}
response_map_t prepare_response_map(
const std::string &request,
const std::string &directory,
const correlated_resources_t &correlated_resources
) {
std::cout << "Request:" << std::endl << request;
std::smatch match;
std::string start_line_pattern(
R"(^[^ ]+ /[^ ]* HTTP/1.1\r\n)"
);
std::string header_field_pattern(R"([^ ]+: *[^ ]+ *\r\n)");
std::string ending_line_pattern(R"(\r\n$)");
std::regex request_regex(
start_line_pattern + "(" + header_field_pattern + ")*" + ending_line_pattern
);
response_map_t response_map;
response_map.insert({"http-version", "HTTP/1.1"});
if (!std::regex_match(request, match, request_regex)) {
response_map.insert({"status-code", "400"});
response_map.insert({"connection", "close"});
response_map.insert({"content-length", "0"});
}
else {
size_t start = process_start_line(
request,
start_line_pattern,
directory,
correlated_resources,
response_map
);
process_header_field_lines(
request.substr(start),
header_field_pattern,
response_map
);
}
return response_map;
}
const std::string prepare_response(response_map_t &response_map) {
std::string status_line =
response_map["http-version"] + " " + response_map["status-code"] + " " +
response_map["reason-phrase"] + "\r\n";
std::string connection_line =
"Connection: " + response_map["connection"] + "\r\n";
std::string content_type_line;
std::string content_length_line =
"Content-length: " + response_map["content-length"] + "\r\n";
std::string location_line;
std::string message_body = response_map["message-body"];
if (response_map.find("content-type") != response_map.end()) {
content_type_line = "Content-type: " + response_map["content-type"] + "\r\n";
}
if (response_map.find("location") != response_map.end()) {
content_type_line = "Location: " + response_map["location"] + "\r\n";
}
std::string response;
response += status_line;
response += connection_line;
response += content_type_line;
response += content_length_line;
response += location_line;
response += "\r\n";
std::cout << "Response (only status line and headers):" << std::endl << response;
response += message_body;
return response;
}
void send_response(int client_sock, const std::string &response) {
ssize_t sent;
size_t start = 0;
size_t to_send = response.length();
const char *buffer = response.c_str();
do {
sent = send(client_sock, buffer + start, to_send, MSG_NOSIGNAL);
if (sent < 0) {
std::cerr << "Writing to client socket failed: " << std::strerror(errno)
<< std::endl << std::endl;
break;
}
start += sent;
to_send -= sent;
} while (to_send > 0);
}
void handle_client(
int client_sock,
const std::string &directory,
const correlated_resources_t &correlated_resources
) {
size_t start = 0;
char buffer[BUFFER_SIZE];
// Number of bytes read from the buffer.
ssize_t bytes_read;
// If true, then new buffer read deals with a new request, false otherwise.
bool new_request = true;
std::string request;
// Last four characters read to determine when current request ends.
std::string last_four_chars;
do {
if (start == 0) {
bytes_read = read(client_sock, buffer, sizeof(char) * BUFFER_SIZE);
if (bytes_read < 0) {
std::cerr << "Error when reading from a client: "
<< std::strerror(errno) << std::endl << std::endl;
break;
}
else if (bytes_read == 0) {
// Client disconnected.
break;
}
}
if (new_request) {
new_request = false;
}
size_t i;
for (i = start; i < (size_t) bytes_read && !new_request; i++) {
request += buffer[i];
if (last_four_chars.length() == 4) {
last_four_chars = last_four_chars.substr(1);
}
last_four_chars += buffer[i];
// Check if the current request ended.
if (last_four_chars == "\r\n\r\n") {
new_request = true;
}
}
if (new_request) {
// Handle current request first before dealing with the next request.
response_map_t response_map = prepare_response_map(
request,
directory,
correlated_resources
);
const std::string response = prepare_response(response_map);
send_response(client_sock, response);
if (response_map["connection"] == "close") {
// Close connection with the client.
break;
}
// Prepare for a new request.
request.clear();
last_four_chars.clear();
}
start = i % bytes_read;
} while (bytes_read > 0);
std::cout << "Closing connection with a client" << std::endl;
if (close(client_sock) < 0) {
std::cerr << "Closing client socket failed: " << strerror(errno) << std::endl;
exit(EXIT_FAILURE);
}
}
void validate_command_line_arguments(
const std::string &directory,
const std::string &filename,
const std::string &port_str
) {
struct stat sb;
if (stat(directory.c_str(), &sb) < 0 || S_ISDIR(sb.st_mode) == 0) {
std::cerr << "Not a regular directory: " << std::strerror(errno) << std::endl;
exit(EXIT_FAILURE);
}
if (stat(filename.c_str(), &sb) < 0 || S_ISREG(sb.st_mode) == 0) {
std::cerr << "Not a regular file: " << std::strerror(errno) << std::endl;
exit(EXIT_FAILURE);
}
std::smatch match;
// https://stackoverflow.com/questions/12968093/regex-to-validate-port-number
std::regex port_regex(
R"(^[0-9]{1,4}|[1-5][0-9]{4}|6[0-4][0-9]{3}|)"
R"(65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5]$)"
);
if (!std::regex_match(port_str, match, port_regex)) {
std::cerr << "Not a valid port: " << std::endl;
exit(EXIT_FAILURE);
}
}
void handle_clients(
int sock,
const std::string &directory,
const correlated_resources_t &correlated_resources
) {
for (;;) {
struct sockaddr_in client_address;
socklen_t client_address_len = sizeof(client_address);
std::cout << "Waiting for a client..." << std::endl;
int client_sock = accept(
sock, (struct sockaddr *) &client_address, &client_address_len
);
if (client_sock < 0) {
std::cerr << "Accepting connection from a client failed: "
<< std::strerror(errno) << std::endl;
if (errno == ECONNABORTED) {
continue;
}
else {
exit(EXIT_FAILURE);
}
}
std::cout << "Accepted connection from a client" << std::endl;
handle_client(client_sock, directory, correlated_resources);
}
}
int create_and_prepare_socket_for_accepting_clients(unsigned port_num) {
int sock = socket(PF_INET, SOCK_STREAM, 0);
if (sock < 0) {
std::cerr << "Socket creation failed: " << std::strerror(errno) << std::endl;
exit(EXIT_FAILURE);
}
struct sockaddr_in address;
address.sin_family = AF_INET;
address.sin_addr.s_addr = htonl(INADDR_ANY);
address.sin_port = htons(port_num);
if (bind(sock, (struct sockaddr *) &address, sizeof(address)) < 0) {
std::cerr << "Socket binding failed: " << std::strerror(errno) << std::endl;
exit(EXIT_FAILURE);
}
if (listen(sock, SOMAXCONN) < 0) {
std::cerr << "Socket listening failed: " << std::strerror(errno) << std::endl;
exit(EXIT_FAILURE);
}
return sock;
}
int main(int argc, char *argv[]) {
if (argc != 3 && argc != 4) {
std::cerr << "Invalid number of arguments, usage:" << std::endl
<< "<path-to-executable> <directory> <filename> [<port>]"
<< std::endl;
exit(EXIT_FAILURE);
}
std::cout << "Starting server..." << std::endl;
std::string directory = argv[1];
if (directory[directory.length() - 1] == '/' && directory.length() > 1) {
directory.pop_back();
}
std::string filename = argv[2];
std::string port_str = argc == 4 ? std::string(argv[3]) : DEFAULT_PORT;
validate_command_line_arguments(directory, filename, port_str);
const unsigned port_num = stoi(port_str);
correlated_resources_t correlated_resources;
create_urls_for_correlated_resources(filename, correlated_resources);
int sock = create_and_prepare_socket_for_accepting_clients(port_num);
handle_clients(sock, directory, correlated_resources);
return 0;
}
| true |
c3b6c9d9bb59f895b58b1f43c1625cd527141b1c | C++ | j-a-h-i-r/Online-Judge-Solutions | /LightOj/1009 - Back to underworld.cpp | UTF-8 | 1,365 | 2.515625 | 3 | [] | no_license | #include<cstdio>
#include<vector>
#include<queue>
#include<cstring>
using namespace std;
queue<int> q;
int bfs( vector<int> a[], int s) {
int vis[20005], f[2];
f[0]=0; f[1]=0;
memset(vis, -1, sizeof(vis));
f[0]++;
vis[s] = 0;
while(!q.empty()){
int n = q.front(); q.pop();
//printf("n=%d s=%d\n", n, a[n].size());
for(int i=0; i<a[n].size(); i++) {
printf("n = %d ", n);
if(vis[a[n][i]]== -1 ){
q.push(a[n][i]);
vis[a[n][i]] = 1 - vis[n];
f[vis[a[n][i]]]++;
printf("%d ", a[n][i]);
}
}
}
if(f[0]<f[1]) return f[1];
else return f[0];
}
int main()
{
freopen("in.txt", "r", stdin);
int t,n,x,y, c=0;
vector <int> v[20005];
scanf("%d", &t);
while(t--) {
scanf("%d", &n);
scanf("%d%d", &x, &y);
v[x].push_back(y);
v[y].push_back(x);
q.push(x);
q.push(y);
int src = x;
n--;
while(n--) {
scanf("%d%d", &x, &y);
v[x].push_back(y);
v[y].push_back(x);
q.push(x);
q.push(y);
}
int ans = bfs(v, src);
printf("Case %d: %d\n",++c, ans);
}
}
| true |
fb5fbfa1f3fcce98328141055322a5e8d8a6de44 | C++ | egnuez/interpreter | /chapter07/parser.hpp | UTF-8 | 2,827 | 3.546875 | 4 | [] | no_license | /**
* Grammar:
* expr : term ((PLUS | MINUS) term ) *
* term : factor ((MUL | DIV) factor ) *
* factor: INTEGER | LPAREN expr RPAREN
*
*/
#include <string>
#include <cctype>
#include <stdexcept>
#include <iostream>
#include <sstream>
namespace lsbasi {
struct VisitorPrint {
virtual std::stringstream visit(class Num *ast, int deep) = 0;
virtual std::stringstream visit(class BinOp *ast, int deep) = 0;
};
struct VisitorInterpreter {
virtual int visit(class Num *ast) = 0;
virtual int visit(class BinOp *ast) = 0;
};
struct AST {
virtual std::stringstream handler(VisitorPrint * v, int deep) = 0;
virtual int handler(VisitorInterpreter * v) = 0;
};
struct Num: public AST {
Token * token;
int value;
Num(Token * token):token(token){
value = std::stoi(token->value);
}
std::stringstream handler(VisitorPrint * v, int deep){
return v->visit(this, deep);
}
int handler(VisitorInterpreter * v){
return v->visit(this);
}
};
struct BinOp: public AST {
AST * left;
Token * token;
std::string op;
AST * right;
BinOp(Token * token, AST * left, AST * right): token(token), left(left), right(right), op(token->value){}
std::stringstream handler(VisitorPrint * v, int deep){
return v->visit(this, deep);
}
int handler(VisitorInterpreter * v){
return v->visit(this);
}
};
class Parser {
Token * current_token;
Lexer lexer;
int error () {
throw std::runtime_error("Invalid Syntax");
}
void eat (Token::TokenType type){
if (current_token->type == type)
current_token = lexer.get_next_token();
else
error();
}
AST * factor(){
AST * ast;
switch(current_token->type){
case Token::_INTEGER:
ast = new Num(current_token);
eat(Token::_INTEGER);
break;
case Token::_LPAREN:
eat(Token::_LPAREN);
ast = expr();
eat(Token::_RPAREN);
break;
default:
error();
}
return ast;
}
AST * term(){
AST * ast = factor();
while((current_token->type == Token::_MUL) || (current_token->type == Token::_DIV)){
Token * tk;
tk = current_token;
if (current_token->type == Token::_MUL)
eat(Token::_MUL);
if (current_token->type == Token::_DIV)
eat(Token::_DIV);
ast = new BinOp(tk, ast, factor());
}
return ast;
}
public:
Parser(lsbasi::Lexer& lexer): lexer(lexer) {
current_token = this->lexer.get_next_token();
}
AST * expr(){
AST * ast = term();
while((current_token->type == Token::_PLUS) || (current_token->type == Token::_MINUS)){
Token * tk;
tk = current_token;
if (current_token->type == Token::_PLUS)
eat(Token::_PLUS);
if (current_token->type == Token::_MINUS)
eat(Token::_MINUS);
ast = new BinOp(tk, ast, term());
}
return ast;
}
};
}; | true |
8db7eb10729236d5ae35a1ceaaab3136d42ddba2 | C++ | oikkoikk/ALOHA | /important_problems/BFS.cpp | UTF-8 | 898 | 3.375 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <queue>
using namespace std;
const int MAX = 10000;
vector<int> graph[MAX+1];
queue<int> q;
bool visited[MAX+1];
void BFS(int start) //start = 처음 시작할 정점
{
q.push(start);
visited[start] = true; //큐에 넣고 방문 표시
while(!q.empty()) //큐가 비어있지 않을 때(연결된 정점이 있을 때)
{
int curr = q.front(); //큐 맨 앞의 요소 = curr
q.pop(); //방문하였으니 pop
cout << curr << ' ';
for(int i=0; i<graph[curr].size(); i++) //현재 정점에 연결된 정점 개수만큼
{
if(!visited[graph[curr][i]]) //방문하지 않았으면
{
q.push(graph[curr][i]); //큐에 push
visited[graph[curr][i]] = true; //그 정점을 방문했다고 표시(매우 중요)
}
}
}
} | true |
6dd0992d4121db32bf65bd5634b86a975b6c3992 | C++ | Yunhao0799/Metodologia-de-la-Programacion-UGR | /Practica 2/Ejercicio 3/src/utilidades 2018-03-27 15_30_24.cpp | UTF-8 | 880 | 3.265625 | 3 | [] | no_license | #include "utilidades.h"
#include<iostream>
using namespace std;
void obtenerMayorSecuenciaMonotonaCreciente( int array[], int util_array, int salida[], int &util_salida){
util_salida = 0;
int maximo = 0;
int pos, valor;
int i;
for ( i = 0; i < util_array; i++){
valor = ascendentesDesdei(array, util_array, i);
if(valor > maximo){
maximo = valor;
pos = i;
}
}
util_salida = maximo;
for( i = 0; i < util_salida; i++ ){
salida[i] = array[i + pos];
}
}
//funcion que comprueba cantidad de numeros ascendentes desde una posicion
int ascendentesDesdei (int array[], int tam, int posicion){
int i = posicion;
int contador = 0;
while ( i < (tam - 1) && array[i] < array[i + 1] )
contador++;
return contador;
}
void imprimirArray (int array[], int tam)
{
int i;
for( i = 0; i < tam; i++)
cout << array[i] << " ";
}
| true |
08b0a55c68a39aa2576293aa475ea10416d46672 | C++ | FranciscoThiesen/cses_solutions | /queries/1739.cpp | UTF-8 | 1,824 | 2.828125 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
template <typename T> struct BIT2D
{
vector<vector<T>> table;
int n, m;
T id;
BIT2D(int _n, int _m, T _id) : n(_n + 1), m(_m + 1), id(_id)
{
table.assign(n, vector<T>(m));
}
// 0-indexed!
inline void modify(int i, int j, T delta)
{
++i, ++j;
int x = i;
while (x < n)
{
int y = j;
while (y < m)
{
table[x][y] += delta;
y |= (y + 1);
}
x |= (x + 1);
}
}
inline T get(int i, int j)
{
T v = id;
int x = i + 1;
while (x > 0)
{
int y = j + 1;
while (y > 0)
{
v += table[x][y];
y = (y & (y + 1)) - 1;
}
x = (x & (x + 1)) - 1;
}
return v;
}
inline T get(int y1, int x1, int y2, int x2)
{
return get(y2, x2) - get(y1 - 1, x2) - get(y2, x1 - 1) + get(y1 - 1, x1 - 1);
}
};
int main()
{
ios::sync_with_stdio(false); cin.tie(nullptr);
int n, q;
cin >> n >> q;
auto B = BIT2D<int>(n + 1, n + 1, 0);
vector< string > mat(n);
for(int i = 0; i < n; ++i)
{
cin >> mat[i];
for(int j = 0; j < n; ++j)
{
if(mat[i][j] == '*') B.modify(i, j, 1);
}
}
for(int i = 0; i < q; ++i)
{
int t;
cin >> t;
if(t == 1)
{
int x, y;
cin >> x >> y;
--x; --y;
if(mat[x][y] == '.')
{
mat[x][y] = '*';
B.modify(x, y, 1);
}
else
{
mat[x][y] = '.';
B.modify(x, y, -1);
}
}
else
{
int y1, x1, y2, x2;
cin >> y1 >> x1 >> y2 >> x2;
--y1; --x1; --y2; --x2;
cout << B.get(y1, x1, y2, x2) << '\n';
}
}
return 0;
} | true |
0ad24fbd7ee317cfd6482a351e264e5eb43bb253 | C++ | mParticle/mparticle-apple-sdk | /mParticle-Apple-SDK/Utils/MPBracket.h | UTF-8 | 774 | 2.71875 | 3 | [
"Apache-2.0"
] | permissive | #ifndef __mParticle__Bracket__
#define __mParticle__Bracket__
#include <cstdint>
#include <memory>
using namespace std;
namespace mParticle {
class Bracket final {
public:
int64_t mpId = 0;
short low = 0;
short high = 100;
bool shouldForward();
Bracket(const long mpId, const short low, const short high) :
mpId(mpId), low(low), high(high)
{}
inline bool operator==(const Bracket &bracket) const {
return mpId == bracket.mpId &&
low == bracket.low &&
high == bracket.high;
}
inline bool operator!=(const Bracket &bracket) const {
return !(*this == bracket);
}
};
}
#endif
| true |
aaff44cca00abf00ba9bbe9957bef7e546e10f02 | C++ | malzantot/uva_solutions | /uva537.cpp | UTF-8 | 1,958 | 3.25 | 3 | [] | no_license | /**
Author: Moustafa Alzantot (malzantot@ucla.edu)
All rights reserved.
**/
#include <string>
#include <iostream>
#include <iomanip>
using std::cin;
using std::cout;
using std::endl;
using std::string;
using std::setprecision;
float ReadValue(string statement, int pos, char unit) {
int field_end = statement.find(unit, pos);
float scalar = 1.0f;
char last_digit_or_scalar = statement[field_end-1];
if (last_digit_or_scalar >= '0' and last_digit_or_scalar <= '9') {
} else {
field_end--;
if (last_digit_or_scalar == 'm') {
scalar *= 0.001f;
} else if (last_digit_or_scalar == 'M') {
scalar *= 1000000.0f;
} else if (last_digit_or_scalar == 'k') {
scalar *= 1000.0f;
}
}
string str_value = statement.substr(pos+2, field_end-pos-2);
return scalar * std::stof(str_value);
}
int main() {
int n;
cin >> n;
cin.get();
for (int idx = 1; idx <= n; idx++) {
string statement;
getline(cin, statement);
std::cout << "Problem #" << idx << std::endl;
float i, u, p;
int current_pos = statement.find("I=");
int volt_pos = statement.find("U=");
int power_pos = statement.find("P=");
bool has_current = (current_pos != string::npos);
bool has_volt = (volt_pos != string::npos);
bool has_power = (power_pos != string::npos);
if (has_current) {
i = ReadValue(statement, current_pos, 'A');
}
if (has_volt) {
u = ReadValue(statement, volt_pos, 'V');
}
if (has_power) {
p = ReadValue(statement, power_pos, 'W');
}
float ans = 0.0f;
std::cout << std::fixed;
std::cout << std::setprecision(2);
if (!has_current) {
ans = p / u;
std::cout << "I="<< ans <<'A'<< std::endl;
}
if (!has_volt) {
ans = p/i;
std::cout << "U=" << ans <<'V' << std::endl;
}
if (!has_power) {
ans = i *u;
std::cout << "P=" << ans <<'W' << std::endl;
}
std::cout << std::endl;
}
return 0;
}
| true |
7c9d2ba2578fb7f689d864418a8361c07bb2cf96 | C++ | gbrlas/AVSP | /CodeJamCrawler/dataset/08_2562_75.cpp | SHIFT_JIS | 2,915 | 2.703125 | 3 | [] | no_license | #include <iostream>
#include <cstdio>
#include <math.h>
using namespace std;
double sR;
double f, R, t, r, g;
double M_PI = acos(-1.0);
double lx;
double integral(double x)
{
return 0.5*sR*(x*sqrt(1-x*x/(sR*sR)) + sR*asin(x/sR));
}
double area(int x, int y)
{
double Lx, Ly, Rx, Ry;
Lx = r + x*(g+2*r) +f;
Ly = r + y*(g+2*r) +f;
Rx = r + x*(g+2*r) +g -f;
Ry = r + y*(g+2*r) +g -f;
if( Lx*Lx+Ly*Ly > sR*sR)
return 0.0;
if(Rx < Lx)
return 0.0;
if( Rx*Rx+Ry*Ry < sR*sR)
return (Rx-Lx)*(Ry-Ly);
double by=sqrt(sR*sR-Rx*Rx),
ay=sqrt(sR*sR-Lx*Lx);
if(Rx > sR)
by = Ly-1000.0;
if(Ry > sR)
ay = Ry - 1000.0;
double ret;
double ax, bx;
if(by < Ly)
bx=sqrt(sR*sR - Ly*Ly);
else
bx = Rx;
ret = integral(bx);
if(ay < Ry)
ax = Lx;
else
{
ax = sqrt(sR*sR -Ry*Ry);
}
ret = ret - integral(ax);
ret = ret - (bx-ax)*Ly; // ̂
ret = ret + (ax-Lx)*(Ry-Ly);
return ret;
}
int main()
{
int n;
cin >> n;
for(int i=0; i<n; i++)
{
cin >> f >> R >> t >> r >> g;
sR=R-t-f;
double innerRate= (sR*sR)/(R*R);
int cnt=0;
double quote=0.0;
int c=(sR-r)/((2*r)+g);
lx = r + (2*r + g)*c;
double sumOfArea=0.0;
for(int x=0; x<=c; x++)
{
for(int y=0; y<=c; y++)
{
sumOfArea+=area(x, y);
}
}
double ans = 4.0*sumOfArea/(sR*sR*M_PI);
printf("Case #%d: %.7lf\n", i+1, 1.0-ans*innerRate);
/*
for(x =g + r; x<sR; x+= 2*r+g)
{
double width = g-2*f;
if(width>0.0)
{
double tmp=integral(x-f) - integral(x-g+f);
tmp -= lx*width;
if(tmp>0.0)
quote+=tmp;
}
cnt++;
}
int cnt2=(sR-r)/((2*r)+g);
if(cnt!= cnt2)
cerr << "hoge" <<endl;
// assert(lx==x-g);
double ly=sqrt(sR*sR- (lx+f)*(lx+f));
if(ly>lx+f)
quote += integral(ly) - integral(lx+f) - (ly-lx-f)*(lx+f); //
if(g-2*f > 0.0)
quote += (g-2*f)*(g-2*f)* (cnt*cnt);//
double ans = 4.0*quote/(sR*sR*M_PI);
if(ans>1.0)
ans=1.0;
printf("Case #%d: %.7lf\n", i+1, 1.0-ans*innerRate);
*/
// printf("Case #%d: %.7lf\n", i+1, 1.0-ans*innerRate);
/*
double a = (g-2*f);
if(a<0.0)
a =0.0;
double ans = (a*a) / ((g+2*r)*(g+2*r));
printf("Case #%d: %.7lf\n", i+1, 1.0-ans*innerRate);
*/
}
return 0;
}
| true |
9f90375444f9091ebaaccb985f9a9124111600c9 | C++ | mikecancilla/ProgrammingProblems | /ProgrammingProblems/src/StringFromDictionary.cpp | UTF-8 | 2,113 | 3.953125 | 4 | [] | no_license | /*
This problem was asked by Microsoft.
Given a dictionary of words and a string made up of those words(no spaces), return the original sentence in a list.If there is more than one possible reconstruction, return any of them.
If there is no possible reconstruction, then return null.
For example, given the set of words 'quick', 'brown', 'the', 'fox', and the string "thequickbrownfox", you should return['the', 'quick', 'brown', 'fox'].
Given the set of words 'bed', 'bath', 'bedbath', 'and', 'beyond', and the string "bedbathandbeyond", return either['bed', 'bath', 'and', 'beyond] or ['bedbath', 'and', 'beyond'].
*/
#include <iostream>
#include <vector>
#include <string>
/*
std::vector<std::string> FindStrings(char *inputString, std::vector<std::string>& dictionary)
{
std::vector<std::string> retVector;
for (std::string word : dictionary)
{
if (char* ptr = std::strstr(inputString, word.c_str()))
{
retVector.push_back(word);
for(unsigned int i = 0; i < word.length(); i++)
ptr[i] = ' ';
}
}
return retVector;
};
*/
std::vector<std::string> FindStrings(char* inputString, std::vector<std::string>& dictionary)
{
std::vector<std::string> retVector;
unsigned int stringLength = std::strlen(inputString);
for (unsigned int i = 0; i < stringLength; i++)
{
bool found = false;
for (unsigned int j = 0; j < dictionary.size() && !found; j++)
{
std::string word = dictionary[j];
if (0 == std::strncmp(inputString + i, word.c_str(), word.length()))
{
retVector.push_back(word);
i += word.length() - 1;
found = true;
}
}
}
return retVector;
}
void DoStringFromDictionary()
{
char inputString[64] = "thequickbrownfox";
std::vector<std::string> dictionary = {"quick", "brown", "the", "fox"};
std::vector<std::string> returnStrings;
returnStrings = FindStrings(inputString, dictionary);
} | true |
d6d549f70046d19cd8c974704dc8faf4ed18fed2 | C++ | lylythechosenone/g | /DataStream.h | UTF-8 | 1,791 | 3.171875 | 3 | [] | no_license | #ifndef G_DATASTREAM_H
#define G_DATASTREAM_H
#include <memory>
template<typename T>
class DataStreamBase
{
public:
virtual ~DataStreamBase() = default;
virtual T get() = 0;
virtual bool done() = 0;
virtual bool doneNow() = 0;
};
template<typename T>
class DataStream
{
public:
explicit DataStream(DataStreamBase<T> *_class)
{
this->callbacks = _class;
}
explicit DataStream(std::unique_ptr<DataStreamBase<T>> _class): callbacks{std::move(_class)} {}
T get()
{
if (callbacks.index() == 0)
{
auto callbacksValue = std::get<0>(callbacks);
return callbacksValue->get();
} else
{
auto callbacksValue = std::get<1>(std::move(callbacks));
return callbacksValue->get();
}
}
bool done()
{
if (callbacks.index() == 0)
{
auto callbacksValue = std::get<0>(callbacks);
return callbacksValue->done();
} else
{
auto callbacksValue = std::get<1>(std::move(callbacks));
return callbacksValue->done();
}
}
bool doneNow()
{
if (callbacks.index() == 0)
{
auto callbacksValue = std::get<0>(callbacks);
return callbacksValue->doneNow();
} else
{
auto callbacksValue = std::get<1>(std::move(callbacks));
return callbacksValue->doneNow();
}
}
DataStream *operator>>(T &dest)
{
dest = get();
return this;
}
private:
std::variant<DataStreamBase<T> *, std::unique_ptr<DataStreamBase<T>>> callbacks;
};
template<typename T>
T &operator<<(T &dest, DataStream<T> &src)
{
dest = src.get();
return dest;
}
#endif //G_DATASTREAM_H
| true |
08265b37bc56bb69f22f471674ccec4460a0e3fc | C++ | hikachi/ZMPO-lab3 | /ZMPO lab2/CMenuCommand.cpp | UTF-8 | 394 | 2.71875 | 3 | [] | no_license | #include "pch.h"
#include "CMenuCommand.h"
#include "CCommand.h"
using namespace std;
CMenuCommand::CMenuCommand(string s_name,string s_comm,CCommand* commandPointer)
{
pointer = commandPointer;
name = s_name;
command = s_comm;
}
CMenuCommand::~CMenuCommand()
{
}
void CMenuCommand::run()
{
if (pointer) {
pointer->runCommand();
}
else
{
cout << "Pusta komenda" << endl;
}
}
| true |
4b8b86c0289a0c9791d04e167e90d5dbb7e4529e | C++ | pastaread/TanksBattle | /Classes/GameScene.cpp | UTF-8 | 8,152 | 2.609375 | 3 | [
"MIT"
] | permissive | //
// GameScene.cpp
// Tanks
//
#include "GameScene.h"
Scene* GameScene::createScene()
{
// 'scene' is an autorelease object
auto scene = Scene::create();
// 'layer' is an autorelease object
auto layer = GameScene::create();
// add layer as a child to scene
scene->addChild(layer);
// return the scene
return scene;
}
// on "init" you need to initialize your instance
bool GameScene::init()
{
//////////////////////////////
// 1. super init first
if ( !Layer::init() )
{
return false;
}
_VisibleSize = Director::getInstance()->getVisibleSize();
_Origin = Director::getInstance()->getVisibleOrigin();
/////////////////////////////
// 2. add a menu item with "X" image, which is clicked to quit the program
// you may modify it.
// add a "close" icon to exit the progress. it's an autorelease object
auto pauseItem = MenuItemImage::create("buttonPause.png",
"buttonPause.png",
CC_CALLBACK_1(GameScene::PauseGame, this));
pauseItem->setPosition(Vec2(_Origin.x + _VisibleSize.width - pauseItem->getContentSize().width/2 ,
_Origin.y + pauseItem->getContentSize().height/2));
// create menu, it's an autorelease object
auto menu = Menu::create(pauseItem, NULL);
menu->setPosition(Vec2::ZERO);
this->addChild(menu, 1);
InitDefaults();
CreateObjects();
setAccelerometerEnabled(true);
// New begin
setTouchEnabled(true);
// New end
schedule(schedule_selector(GameScene::update), 0.0167);
return true;
}
void GameScene::InitDefaults()
{
_GameIsPaused = false;
}
void GameScene::setTouchEnabled(bool enabled)
{
if (enabled)
{
_touchListener = EventListenerTouchOneByOne::create();
_touchListener->retain();
_touchListener->onTouchBegan = CC_CALLBACK_2(GameScene::onTouchBegan, this);
_touchListener->onTouchEnded = CC_CALLBACK_2(GameScene::onTouchEnded, this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(_touchListener, this);
}
else if (!enabled)
{
_eventDispatcher->removeEventListener(_touchListener);
_touchListener->release();
_touchListener = nullptr;
}
}
void GameScene::CreateObjects()
{
// New begin
auto backg = Sprite::create("Ground.png");
backg->setPosition(_VisibleSize.width * 0.5f, _VisibleSize.height * 0.5f);
backg->setScale(_VisibleSize.width / 1242.0f, _VisibleSize.height / 2208.0f);
this->addChild(backg, Z_ORDER_GROUND);
GameObject rock1(3, Vec2(_VisibleSize.width * 0.18f, _VisibleSize.height * 0.82f));
this->addChild(rock1._Spr, Z_ORDER_ROCK);
_Rocks.push_back(rock1);
GameObject rock2(3, Vec2(_VisibleSize.width * 0.48f, _VisibleSize.height * 0.12f));
this->addChild(rock2._Spr, Z_ORDER_ROCK);
_Rocks.push_back(rock2);
GameObject rock3(3, Vec2(_VisibleSize.width * 0.68f, _VisibleSize.height * 0.52f));
this->addChild(rock3._Spr, Z_ORDER_ROCK);
_Rocks.push_back(rock3);
GameObject rock4(3, Vec2(_VisibleSize.width * 0.38f, _VisibleSize.height * 0.42f));
this->addChild(rock4._Spr, Z_ORDER_ROCK);
_Rocks.push_back(rock4);
// New end
_MainPlayer = new Player(1, Vec2(_VisibleSize.width * 0.12f, _VisibleSize.height * 0.12f));
this->addChild(_MainPlayer->_Spr, Z_ORDER_PLAYER);
}
void GameScene::onAcceleration(Acceleration *acc, Event *unused_event) // Acceleration (Device rotation)
{
if(_GameIsPaused == true ) return;
float acceleration = 2.0f; // acceleration
float maxVelocity = 2; // Max speed
_PlayerVelocity.x = acc->x * acceleration;
_PlayerVelocity.y = acc->y * acceleration;
if (_PlayerVelocity.x > maxVelocity)
{
_PlayerVelocity.x = maxVelocity;
}
else if (_PlayerVelocity.x < -maxVelocity)
{
_PlayerVelocity.x = -maxVelocity;
}
if (_PlayerVelocity.y > maxVelocity)
{
_PlayerVelocity.y = maxVelocity;
}
else if (_PlayerVelocity.y < -maxVelocity)
{
_PlayerVelocity.y = -maxVelocity;
}
}
void GameScene::updatePosition() // Update player position
{
Vec2 pos = _MainPlayer->GetObjectPos();
pos.x += _PlayerVelocity.x;
pos.y += _PlayerVelocity.y;
float imageWidthHalved = 48.0f;
float imageHeightHalved = 48.0f;
float leftBorderLimit = imageWidthHalved;
float rightBorderLimit = _VisibleSize.width - imageWidthHalved;
float topBorderLimit = imageHeightHalved;
float bottomBorderLimit = _VisibleSize.height - imageHeightHalved;
// If out of border, stop player
if (pos.x < leftBorderLimit)
{
pos.x = leftBorderLimit;
_PlayerVelocity.x = 0;
}
else if (pos.x > rightBorderLimit)
{
pos.x = rightBorderLimit;
_PlayerVelocity.x = 0;
}
if (pos.y < topBorderLimit)
{
pos.y = topBorderLimit;
_PlayerVelocity.y = 0;
}
else if (pos.y > bottomBorderLimit)
{
pos.y = bottomBorderLimit;
_PlayerVelocity.y = 0;
}
// Check rock collision
std::vector <GameObject>::iterator itRock;
for (itRock = _Rocks.begin(); itRock != _Rocks.end(); itRock++)
{
if (fabsf(pos.x - itRock->GetObjectPos().x) < 80.0f &&
fabsf(pos.y - itRock->GetObjectPos().y) < 74.0f)
_PlayerVelocity.x = 0;
if (fabsf(pos.x - itRock->GetObjectPos().x) < 74.0f &&
fabsf(pos.y - itRock->GetObjectPos().y) < 80.0f)
_PlayerVelocity.y = 0;
}
// CCLOG("x = %f y = %f", _PlayerVelocity.x, _PlayerVelocity.y);
_MainPlayer->SetObjectDir(_PlayerVelocity);
_MainPlayer->UpdatePosition();
for (int i = 0; i < _BulletsPlayer.size(); i++)
{
_BulletsPlayer[i].UpdatePosition();
}
}
// New begin
bool GameScene::onTouchBegan(Touch *pTouch, Event *pEvent)
{
Bullet bullet(4,
Vec2(_MainPlayer->GetObjectPos().x, _MainPlayer->GetObjectPos().y),
_MainPlayer->GetBulletDir());
this->addChild(bullet._Spr, Z_ORDER_BULLET);
_BulletsPlayer.push_back(bullet);
return true;
}
void GameScene::onTouchEnded(Touch *pTouch, Event *pEvent)
{
}
// New end
void GameScene::update(float deltaT) // Method called every 0.0167 second
{
if (_GameIsPaused == false)
{
updatePosition();
}
}
void GameScene::PauseGame(Ref* pSender)
{
if (_GameIsPaused == true) return;
_GameIsPaused = true;
auto bResume = MenuItemImage::create("buttonResume.png", "buttonResume.png",
CC_CALLBACK_1(GameScene::ResumeGame, this));
bResume->setScale(0.32f);
auto bMenu = MenuItemImage::create("buttonMainMenu.png", "buttonMainMenu.png",
CC_CALLBACK_1(GameScene::MainMenu, this));
bMenu->setScale(0.32f);
auto bRestart = MenuItemImage::create("buttonRestart.png", "buttonRestart.png",
CC_CALLBACK_1(GameScene::RestartGame, this));
bRestart->setScale(0.32f);
_PauseMenu = Menu::create(bResume, bMenu, bRestart, NULL);
_PauseMenu->alignItemsHorizontallyWithPadding(_VisibleSize.width / 15.0f);
_PauseMenu->setPosition(_VisibleSize.width * 0.5f, _VisibleSize.height * 0.5f);
this->addChild(_PauseMenu, Z_ORDER_MENU);
}
void GameScene::ResumeGame(Ref* pSender)
{
_GameIsPaused = false;
_PauseMenu->removeFromParentAndCleanup(true);
}
void GameScene::RestartGame(Ref* pSender)
{
this->removeAllChildrenWithCleanup(true);
Director::getInstance()->popScene();
auto scene = GameScene::createScene();
Director::getInstance()->pushScene(scene);
}
void GameScene::MainMenu(Ref* pSender)
{
Director::getInstance()->popScene();
}
| true |
0d3397251d04dcf240b4f5cb720a4773923d8533 | C++ | minersail/The-Unfortunate-Adventure-of-Joe | /Character.h | UTF-8 | 652 | 2.890625 | 3 | [] | no_license | #pragma once
#include "stdafx.h"
#include "Entity.h"
class Character : public Entity
{
public:
Character(float initX, float initY, std::string textureID, std::string name);
~Character();
// In order for this to work, the spritesheet provided for characters should be 4x4:
// Vertically the walk animation should progress and the four columns should be
// North, East, South, West
virtual void Walk(Direction dir);
// Since characters will be moving from chunk to chunk, this will update the
// EntityLists as they move from chunk to chunk
virtual void UpdateChunk();
protected:
int charW;
int charH;
int speed;
}; | true |