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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
e75f0c167758213015f5271088dce3727b3b0c81 | C++ | tomcruse/algorithm | /1777순열복원.cpp | UHC | 958 | 2.75 | 3 | [] | no_license | #include<cstdio>
#include<algorithm>
#include<vector>
using namespace std;
int n, seg[400010], arr[100100];
int update(int pos, int val, int node, int l, int r) {
if (pos<l || pos>r) return seg[node];
if (l == r) return seg[node] = val;
int mid = (l + r) >> 1;
return seg[node] = update(pos, val, node * 2, l, mid) + update(pos, val, node * 2 + 1, mid + 1, r);
}
int query(int val, int node, int l, int r) {
if (l == r) return l;
int mid = (l + r) >> 1;
//
if (seg[node * 2 + 1] >= val) query(val, node * 2 + 1, mid + 1, r);
else query(val - seg[node * 2 + 1], node * 2, l, mid);
}
int main() {
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
update(i, 1, 1, 0, n - 1);
}
vector<int> vt(n + 1, 0);
for (int i = n - 1; i >= 0; i--) {
int k = query(arr[i] + 1, 1, 0, n - 1);
update(k, 0, 1, 0, n - 1);
vt[k + 1] = i + 1;
}
for (int i = 1; i <= n; i++) printf("%d ", vt[i]);
return 0;
} | true |
06a280b83f040c044ae300822ff0bde9dc4ef72b | C++ | PlasticPack/SPAAAACE | /SPAAAACE/SPAAAACE/GameLogicComponent.h | UTF-8 | 1,033 | 2.875 | 3 | [] | no_license | /*****************************
Créé par Charles Murphy
Component servant à la gestion de la
logique du jeu : les points de vie, le
carburant, le moteur
******************************/
#pragma once
#include "Component.h"
#include <vector>
#include <memory>
class GameLogicComponent :
public Component
{
public:
GameLogicComponent(luabridge::LuaRef& componentTable);
virtual ~GameLogicComponent();
unsigned int getCurrentLife() { return m_life; }
unsigned int getMaxLife() const { return m_maxLife; }
unsigned int getMaxFuel() const { return m_maxFuel; }
unsigned int getCurrentFuel() { return m_fuel; }
unsigned int getEnginePower() const { return m_enginePower; }
void setLife(unsigned int l) { if (l <= m_maxLife )m_life = l; }
void setFuel(unsigned int l) { if (l <= m_maxFuel && m_fuel + l > 0) m_fuel = l; }
void setEnginePower(unsigned int l) { if (l >= 0) m_enginePower = l; }
protected:
unsigned int m_life;
unsigned int m_maxLife;
unsigned int m_fuel;
unsigned int m_maxFuel;
unsigned int m_enginePower;
};
| true |
fbfcabde14b1b561e7c2e2439e25b2b5507e40da | C++ | jzweig/snow-gl | /shapes/Renderable.h | UTF-8 | 253 | 2.765625 | 3 | [] | no_license | #ifndef RENDERABLE_H
#define RENDERABLE_H
/**
A renderable shape/object/some-dimensional figure.
*/
class Renderable
{
public:
Renderable();
//! Renders this shape.
virtual void render() = 0;
};
#endif // RENDERABLE_H
| true |
12c6a897fd8c4e07bee75026e66b7cd2dd72cea0 | C++ | TopologicalAnalysisArsuagaLab/Minicircles | /bigvalence.cpp | UTF-8 | 14,071 | 2.9375 | 3 | [] | no_license |
//============================================================================
// Name : bigvalence.cpp
// Author : Kenneth Edward Hinson
// Version :
// Copyright : Copyrights by Owner
// Description : C++, Ansi-style
//============================================================================
#include<iostream>
#include<fstream>
#include<math.h>
#include<time.h>
#include<stdio.h>
#include<stdlib.h>
using namespace std;
const long ntrials=1000;
const float pi=3.14159265358979324;
const int digits=20;
const int Height=7;
const int Width=7;
//structure definitions
struct point {
float x;
float y;
float z;
};
struct vertex {
struct point pt;
struct vertex * prev;
struct vertex * next;
};
struct segment {
struct point start;
struct point end;
};
struct chain {
int linknumber;
int ncircles; // number of minicircles in the chain
chain * linkedto;
};
struct circle {
point center;
point normalvector;
chain * link;
float dists[44]; //added for valence computation -- to store distances to 44 nearest neighbors
};
int operator==(point p1, point p2) // to use == for equality of vectors
{
if(p1.x==p2.x && p1.y==p2.y && p1.z==p2.z)
return 1;
else
return 0;
}
float randdouble() //random number generator - random float between 0 and 1
{
int digit;
int k;
double numb=0;
for(k=0;k<digits;k++)
{
digit=rand()%10;
numb=numb*0.1+digit;
}
return numb*0.1;
}
float distanc(point pt1, point pt2)
{
return sqrt(pow(pt1.x-pt2.x,2)+pow(pt1.y-pt2.y,2)+pow(pt1.z-pt2.z,2));
}
struct point randomunitvector(float tilting, float azimuthal)
{
point vector;
float theta;
vector.z=(2*randdouble()-1)*cos(tilting*pi/180);
theta=(2*randdouble()-1)*(0.5-azimuthal/180)*pi;
vector.x=sqrt(1-pow(vector.z,2))*cos(theta);
vector.y=sqrt(1-pow(vector.z,2))*sin(theta);
return vector;
}
int linked(circle * circle1, circle * circle2, float radius, int nbr)
{
float plane1a, plane1b, plane1c, plane1d;
float plane2a, plane2b, plane2c, plane2d;
float plane3a, plane3b, plane3c, plane3d;
point intersect;
if((circle1->center).x==(circle2->center).x)
{
plane2a=(circle1->center).x - (circle2->center).x;
plane2b=(circle1->center).y - (circle2->center).y;
plane2c=(circle1->center).z - (circle2->center).z; //should be 0
plane2d=plane2a*0.5*((circle1->center).x+(circle2->center).x)+plane2b*0.5*((circle1->center).y+(circle2->center).y)+plane2c*0.5*((circle1->center).z+(circle2->center).z);
if((circle1->normalvector).x == 0)
{
plane3a=(circle1->normalvector).x;
plane3b=(circle1->normalvector).y;
plane3c=(circle1->normalvector).z;
plane3d=(circle1->normalvector).x*(circle1->center).x+(circle1->normalvector).y*(circle1->center).y+(circle1->normalvector).z*(circle1->center).z;
plane1a=(circle2->normalvector).x;
plane1b=(circle2->normalvector).y;
plane1c=(circle2->normalvector).z;
plane1d=(circle2->normalvector).x*(circle2->center).x+(circle2->normalvector).y*(circle2->center).y+(circle2->normalvector).z*(circle2->center).z;
}
else
{
plane1a=(circle1->normalvector).x;
plane1b=(circle1->normalvector).y;
plane1c=(circle1->normalvector).z;
plane1d=(circle1->normalvector).x*(circle1->center).x+(circle1->normalvector).y*(circle1->center).y+(circle1->normalvector).z*(circle1->center).z;
plane3a=(circle2->normalvector).x;
plane3b=(circle2->normalvector).y;
plane3c=(circle2->normalvector).z;
plane3d=(circle2->normalvector).x*(circle2->center).x+(circle2->normalvector).y*(circle2->center).y+(circle2->normalvector).z*(circle2->center).z;
}
}
else
{
plane1a=(circle1->center).x - (circle2->center).x;
plane1b=(circle1->center).y - (circle2->center).y;
plane1c=(circle1->center).z - (circle2->center).z; //should be 0
plane1d=plane1a*0.5*((circle1->center).x+(circle2->center).x)+plane1b*0.5*((circle1->center).y+(circle2->center).y)+plane1c*0.5*((circle1->center).z+(circle2->center).z);
if(plane1a*(circle1->normalvector).y == plane1b*(circle1->normalvector).x)
{
plane3a=(circle1->normalvector).x;
plane3b=(circle1->normalvector).y;
plane3c=(circle1->normalvector).z;
plane3d=(circle1->normalvector).x*(circle1->center).x+(circle1->normalvector).y*(circle1->center).y+(circle1->normalvector).z*(circle1->center).z;
plane2a=(circle2->normalvector).x;
plane2b=(circle2->normalvector).y;
plane2c=(circle2->normalvector).z;
plane2d=(circle2->normalvector).x*(circle2->center).x+(circle2->normalvector).y*(circle2->center).y+(circle2->normalvector).z*(circle2->center).z;
}
else
{
plane2a=(circle1->normalvector).x;
plane2b=(circle1->normalvector).y;
plane2c=(circle1->normalvector).z;
plane2d=(circle1->normalvector).x*(circle1->center).x+(circle1->normalvector).y*(circle1->center).y+(circle1->normalvector).z*(circle1->center).z;
plane3a=(circle2->normalvector).x;
plane3b=(circle2->normalvector).y;
plane3c=(circle2->normalvector).z;
plane3d=(circle2->normalvector).x*(circle2->center).x+(circle2->normalvector).y*(circle2->center).y+(circle2->normalvector).z*(circle2->center).z;
}
}
intersect.z=((plane1a*plane2b-plane1b*plane2a)*(plane1a*plane3d-plane1d*plane3a)-(plane1a*plane3b-plane1b*plane3a)*(plane1a*plane2d-plane1d*plane2a))/((plane1a*plane2b-plane1b*plane2a)*(plane1a*plane3c-plane1c*plane3a)-(plane1a*plane3b-plane1b*plane3a)*(plane1a*plane2c-plane1c*plane2a));
intersect.y=(plane1a*plane2d-plane2a*plane1d-(plane1a*plane2c-plane1c*plane2a)*intersect.z)/(plane1a*plane2b-plane1b*plane2a);
intersect.x=(plane1d-plane1c*intersect.z-plane1b*intersect.y)/plane1a;
circle1->dists[nbr]=distanc(intersect,circle1->center);
if(distanc(intersect,circle1->center)<radius && distanc(intersect,circle2->center)<radius)
return 1;
else
{
return 0;
}
}
int minlinknum(circle * circle1)
{
chain * currentchain;
currentchain=circle1->link;
while(currentchain->linknumber != (currentchain->linkedto)->linknumber)
{
currentchain=currentchain->linkedto;
}
return currentchain->linknumber;
}
struct chain * minlinkedchain(chain * currentchain)
{
chain * findmin;
findmin=currentchain;
while(findmin->linknumber != (findmin->linkedto)->linknumber)
{
findmin=findmin->linkedto;
}
return findmin;
}
int comparelinks(circle * circlesarray[Width][Height], int currentrow, int currentcol, int comparerow, int comparecol, float circleradius, int linkcount, int nbrindex)
{
if(linked(circlesarray[currentcol][currentrow],circlesarray[comparecol][comparerow],circleradius,nbrindex)==1)
{
if(minlinknum(circlesarray[currentcol][currentrow]) != minlinknum(circlesarray[comparecol][comparerow]))
{
if(((circlesarray[currentcol][currentrow])->link)->linknumber == 0) //i.e. unlinked
{
circlesarray[currentcol][currentrow]->link = circlesarray[comparecol][comparerow]->link;
(minlinkedchain(circlesarray[comparecol][comparerow]->link))->ncircles++;
}
else if(((circlesarray[comparecol][comparerow])->link)->linknumber == 0)
{
circlesarray[comparecol][comparerow]->link = circlesarray[currentcol][currentrow]->link;
(minlinkedchain(circlesarray[comparecol][comparerow]->link))->ncircles++;
}
else
{
if(minlinknum(circlesarray[comparecol][comparerow]) < minlinknum(circlesarray[currentcol][currentrow]))
{
(minlinkedchain(circlesarray[comparecol][comparerow]->link))->ncircles = (minlinkedchain(circlesarray[comparecol][comparerow]->link))->ncircles + (minlinkedchain(circlesarray[currentcol][currentrow]->link))->ncircles;
(minlinkedchain(circlesarray[currentcol][currentrow]->link))->linkedto = minlinkedchain(circlesarray[comparecol][comparerow]->link);
}
else
{
(minlinkedchain(circlesarray[currentcol][currentrow]->link))->ncircles = (minlinkedchain(circlesarray[comparecol][comparerow]->link))->ncircles + (minlinkedchain(circlesarray[currentcol][currentrow]->link))->ncircles;
(minlinkedchain(circlesarray[comparecol][comparerow]->link))->linkedto = minlinkedchain(circlesarray[currentcol][currentrow]->link);
}
}
}
else if((circlesarray[currentcol][currentrow]->link)->linknumber == 0)
{
chain * newlink;
newlink = new chain;
newlink->linknumber=linkcount;
newlink->ncircles = (circlesarray[currentcol][currentrow]->link)->ncircles + (circlesarray[comparecol][comparerow]->link)->ncircles;
newlink->linkedto=newlink;
circlesarray[currentcol][currentrow]->link = newlink;
circlesarray[comparecol][comparerow]->link = newlink;
linkcount++;
}
}
return linkcount;
}
int main()
{
circle * minicircles[Width][Height];
float radius; //radius of circles
float tiltrestrict=0;
float azirestrict=0;
int linky; //label for links
int perc;
chain * unlinked;
//char qw;
srand(time(0));
unlinked=new chain;
unlinked->linknumber=0;
unlinked->ncircles=1;
unlinked->linkedto=unlinked;
cout<<"Enter amount of tilting restriction (in degrees, 0 to 90): ";
cin>>tiltrestrict;
while(tiltrestrict<0 || tiltrestrict>90)
{
cout<<"Error -- This entry must be between 0 and 90. Please try again: ";
cin>>tiltrestrict;
}
cout<<"Enter amount of azimuthal restriction (in degrees, 0 to 90): ";
cin>>azirestrict;
while(azirestrict<0 || azirestrict>90)
{
cout<<"Error -- This entry must be between 0 and 90. Please try again: ";
cin>>azirestrict;
}
int valencecounts[44][500];
for(int initval=0;initval<44;initval++)
{
for(int initrange=0;initrange<500;initrange++)
valencecounts[initval][initrange]=0;
}
ofstream fsavec("valencedata001.txt",ios::out);
for(int trial=0;trial<ntrials;trial++)
{
// first=1;
linky=1;
perc=0;
for(int row=0;row<Height;row++)
{
for(int col=0;col<Width;col++)
{
minicircles[col][row]=new circle;
(minicircles[col][row]->center).x=(float)col;
(minicircles[col][row]->center).y=(float)row;
(minicircles[col][row]->center).z=0;
minicircles[col][row]->normalvector=randomunitvector(tiltrestrict,azirestrict);
minicircles[col][row]->link=unlinked;
}
}
radius=0.5;
while(radius<0.51) //only going through one time to get distances
{
linky=comparelinks(minicircles, 3,3, 4,3, radius, linky, 0);
linky=comparelinks(minicircles, 3,3, 4,4, radius, linky, 1);
linky=comparelinks(minicircles, 3,3, 3,4, radius, linky, 2);
linky=comparelinks(minicircles, 3,3, 2,4, radius, linky, 3);
linky=comparelinks(minicircles, 3,3, 2,3, radius, linky, 4);
linky=comparelinks(minicircles, 3,3, 2,2, radius, linky, 5);
linky=comparelinks(minicircles, 3,3, 3,2, radius, linky, 6);
linky=comparelinks(minicircles, 3,3, 4,2, radius, linky, 7);
linky=comparelinks(minicircles, 3,3, 5,3, radius, linky, 8);
linky=comparelinks(minicircles, 3,3, 5,4, radius, linky, 9);
linky=comparelinks(minicircles, 3,3, 5,5, radius, linky, 10);
linky=comparelinks(minicircles, 3,3, 4,5, radius, linky, 11);
linky=comparelinks(minicircles, 3,3, 3,5, radius, linky, 12);
linky=comparelinks(minicircles, 3,3, 2,5, radius, linky, 13);
linky=comparelinks(minicircles, 3,3, 1,5, radius, linky, 14);
linky=comparelinks(minicircles, 3,3, 1,4, radius, linky, 15);
linky=comparelinks(minicircles, 3,3, 1,3, radius, linky, 16);
linky=comparelinks(minicircles, 3,3, 1,2, radius, linky, 17);
linky=comparelinks(minicircles, 3,3, 1,1, radius, linky, 18);
linky=comparelinks(minicircles, 3,3, 2,1, radius, linky, 19);
linky=comparelinks(minicircles, 3,3, 3,1, radius, linky, 20);
linky=comparelinks(minicircles, 3,3, 4,1, radius, linky, 21);
linky=comparelinks(minicircles, 3,3, 5,1, radius, linky, 22);
linky=comparelinks(minicircles, 3,3, 5,2, radius, linky, 23);
linky=comparelinks(minicircles, 3,3, 6,3, radius, linky, 24);
linky=comparelinks(minicircles, 3,3, 6,4, radius, linky, 25);
linky=comparelinks(minicircles, 3,3, 6,5, radius, linky, 26);
linky=comparelinks(minicircles, 3,3, 5,6, radius, linky, 27);
linky=comparelinks(minicircles, 3,3, 4,6, radius, linky, 28);
linky=comparelinks(minicircles, 3,3, 3,6, radius, linky, 29);
linky=comparelinks(minicircles, 3,3, 2,6, radius, linky, 30);
linky=comparelinks(minicircles, 3,3, 1,6, radius, linky, 31);
linky=comparelinks(minicircles, 3,3, 0,5, radius, linky, 32);
linky=comparelinks(minicircles, 3,3, 0,4, radius, linky, 33);
linky=comparelinks(minicircles, 3,3, 0,3, radius, linky, 34);
linky=comparelinks(minicircles, 3,3, 0,2, radius, linky, 35);
linky=comparelinks(minicircles, 3,3, 0,1, radius, linky, 36);
linky=comparelinks(minicircles, 3,3, 1,0, radius, linky, 37);
linky=comparelinks(minicircles, 3,3, 2,0, radius, linky, 38);
linky=comparelinks(minicircles, 3,3, 3,0, radius, linky, 39);
linky=comparelinks(minicircles, 3,3, 4,0, radius, linky, 40);
linky=comparelinks(minicircles, 3,3, 5,0, radius, linky, 41);
linky=comparelinks(minicircles, 3,3, 6,1, radius, linky, 42);
linky=comparelinks(minicircles, 3,3, 6,2, radius, linky, 43);
float density[44]; // for sorting density values
float temp;
int sorted=1; // to track number of items sorted so far
for(int item=0;item<44;item++)
{
if(minicircles[3][3]->dists[item]>0) //testing for nans
density[item]=pow(minicircles[3][3]->dists[item],2);
else
density[item]=pow(10,20); //to get rid of nans
}
while(sorted<44)
{
int sort=0;
while(sort<sorted)
{
if(density[sorted-sort]<density[sorted-1-sort])
{
temp=density[sorted-sort];
density[sorted-sort]=density[sorted-1-sort];
density[sorted-1-sort]=temp;
sort++;
}
else
sort=sorted;
}
sorted++;
}
for(int val=0;val<44;val++)
{
for(int range=0;range<500;range++)
{
if(density[val]<=0.25+(float)range/100)
valencecounts[val][range]++;
}
}
cout<<trial<<endl;
radius+=0.1;
}
}
for(int outrange=0;outrange<500;outrange++)
{
for(int outdist=0;outdist<44;outdist++)
{
if(outdist==43)
fsavec<<valencecounts[outdist][outrange];
else
fsavec<<valencecounts[outdist][outrange]<<'\t';
}
fsavec<<endl;
}
fsavec.close();
return 0;
}
| true |
d9b827272f0b53153523cc3bb7fbdca55e9fc706 | C++ | georgyangelov/fireflies | /Arduino/SerialProtocol.hpp | UTF-8 | 1,553 | 2.96875 | 3 | [] | no_license | #define SERIAL_PACKET_BUFFER_SIZE 2048
#define min(a, b) ((a) < (b) ? (a) : (b))
struct Packet {
byte type;
uint16 length;
byte data[SERIAL_PACKET_BUFFER_SIZE];
};
class SerialProtocol {
bool reading = false,
packetReady = false;
Packet packet;
uint16 lengthLeftToRead = 0;
const byte BEGIN_MARKER = 0xff,
ACK = 0x4b;
public:
void setup() {
Serial.begin(250000);
Serial.setTimeout(500);
while (!Serial);
}
void reset() {
reading = false;
packetReady = false;
}
void loop() {
if (!reading && Serial.available() >= sizeof(BEGIN_MARKER) + sizeof(packet.type) + sizeof(packet.length)) {
// Read control byte and header
if (Serial.read() != BEGIN_MARKER) {
return;
}
packet.type = Serial.read();
Serial.readBytes((byte*)&packet.length, sizeof(uint16_t));
reading = true;
lengthLeftToRead = packet.length;
if (packet.length > SERIAL_PACKET_BUFFER_SIZE) {
return;
}
} else if (reading && Serial.available()) {
// Read data
lengthLeftToRead -= Serial.readBytes(packet.data + packet.length - lengthLeftToRead, min(Serial.available(), lengthLeftToRead));
if (lengthLeftToRead == 0) {
reading = false;
packetReady = true;
}
}
}
bool hasPacketReady() {
return packetReady;
}
const Packet& getPacket() {
packetReady = false;
return packet;
}
void ackPacket() {
if (Serial.availableForWrite() >= sizeof(ACK)) {
// Writing without checking first may block the operation if there is noone to receive the data
Serial.write(ACK);
}
}
}; | true |
7f4a7862bc767ee1cf4444d5d6fb605062d3dfe1 | C++ | dwykat/practice | /week20201019-20201025/20201024/2-method1.cpp | UTF-8 | 1,979 | 3.453125 | 3 | [] | no_license | /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
int carry = 0;
ListNode* head = new ListNode(0);
ListNode* cur = head;
bool is_first = true;
// 先按位计算,再用尾插法建表
while(l1 != nullptr && l2 != nullptr){
int left = l1->val;
int right = l2->val;
int sum = left + right + carry;
if(sum >= 10){
sum -= 10;
carry = 1;
}else{
carry = 0;
}
if(is_first){
cur->val = sum;
is_first = false;
}else{
ListNode* tmp = new ListNode(0);
tmp->val = sum;
cur->next = tmp;
cur = tmp;
}
l1 = l1->next;
l2 = l2->next;
}
// 计算剩余位的值
ListNode* left;
bool skip = false;
if(l1 != nullptr)
left = l1;
else if(l2 != nullptr)
left = l2;
else{
skip = true;
}
while(!skip && left!=nullptr){
int sum = left->val + carry;
if(sum >= 10){
sum -= 10;
carry = 1;
}else{
carry = 0;
}
ListNode* tmp = new ListNode(0);
tmp->val = sum;
cur->next = tmp;
cur = tmp;
left = left->next;
}
if(carry != 0){
ListNode* tmp = new ListNode(1);
cur->next = tmp;
cur = tmp;
}
cur->next = nullptr;
return head;
}
};
| true |
a0c5cd35c58ef214fd1fd9b9b39342217c7d3598 | C++ | danceinthedark/BUPT-Projects | /Algorithm/第4章作业/main.cpp | GB18030 | 15,697 | 2.875 | 3 | [] | no_license | #include <iostream>
#include <sstream>
#include <fstream>
#include <cstring>
#include <cstdlib>
#include <vector>
#include <climits>
#include <cmath>
#include <queue>
#include <map>
#include <algorithm>
#define MAXSIZE 10000
#define Pi 3.141592657
typedef struct station
{
long long enodedId;
double longitude, latitude;
int index;
} Station;
typedef struct node
{
struct node *left, *right;
int weight;
char ch;
} Node, *pNode;
typedef struct edge
{
int u, v;
double cost;
bool operator < (const struct edge &m)const {
return cost < m.cost;
}
} Edge, *pEdge;
using namespace std;
const double R = 6378137.0; //뾶mΪλ
Station stations[MAXSIZE];
int dp[MAXSIZE][MAXSIZE];
int opr[MAXSIZE][MAXSIZE];
double weight[MAXSIZE][MAXSIZE];
int father[MAXSIZE];
double distance(const Station &u, const Station &v)
{
double radLat1 = u.latitude * Pi / 180.0;
double radLat2 = v.latitude * Pi / 180.0;
double radLon1 = u.longitude * Pi / 180.0;
double radLon2 = v.longitude * Pi / 180.0;
return R * acos(cos(radLat1) * cos(radLat2) * cos(radLon1 - radLon2)
+ sin(radLat1) * sin(radLat2));
}
double Weight(int i, int k, int j)
{
return weight[i][k] + weight[i][j] + weight[k][j];
}
double MinWeightTriangulation(const int &n)
{
memset(dp, 0, sizeof(dp));
memset(opr, 0, sizeof(opr));
for (int i = 0; i < n; i++)
for (int j = i; j < n; j++)
weight[j][i] = weight[i][j] = distance(stations[i], stations[j]);
for (int r = 2; r <= n; r++)
for (int i = 1; i <= n-r+1; i++)
{
int j = i + r - 1;
dp[i][j] = dp[i + 1][j] + Weight(i - 1, i, j);
opr[i][j] = i;
for (int k = i+1; k < j; k++)
{
int u = dp[i][k] + dp[k + 1][j] + Weight(i - 1, k, j);
if (u < dp[i][j])
{
dp[i][j] = u;
opr[i][j] = k;
}
}
}
double len = 0;
for (int i = 0; i < n-1; i++)
{
len += weight[i][i+1];
}
len += weight[n-1][0];
return (len + dp[1][n-1]) / 2;
}
void TraceBack(int i, int j)
{
if (i == j)
return;
TraceBack(i, opr[i][j]);
TraceBack(opr[i][j] + 1, j);
cout << "ʷֶ㣺V" << i-1 << ",V" << j << ",V" << opr[i][j] << endl;
}
struct cmp{
bool operator()(pNode node1, pNode node2){
return node1->weight > node2->weight;
}
};
pNode HuffmanTree(int incidence[])
{
priority_queue<pNode, vector<pNode>, cmp > heap;
for (int i = 0; i <= 26; i++)
{
pNode haffman = new Node;
haffman->left = NULL;
haffman->right = NULL;
haffman->weight = incidence[i];
if (i == 0)
haffman->ch = '#';
else
haffman->ch = i - 1 + 'a';
heap.push(haffman);
}
while (heap.size() != 1)
{
pNode node1 = heap.top();
heap.pop();
pNode node2 = heap.top();
heap.pop();
pNode haffman = new Node;
haffman->left = node1;
haffman->right = node2;
haffman->weight = node1->weight + node2->weight;
heap.push(haffman);
}
return heap.top();
}
int printHuffman(pNode node, string str, int incidence[])
{
if (node->left == NULL && node->right == NULL)
{
cout << node->ch << ": " << str << endl;
int result = incidence[(node->ch == '#') ? 0 : (node->ch - 'a' + 1)] * str.length();
delete node;
return result;
}
int result1 = 0, result2 = 0;
if (node->left)
result1 = printHuffman(node->left, str + '0', incidence);
if (node->right)
result2 = printHuffman(node->right, str + '1', incidence);
delete node;
return result1 + result2;
}
void Dijkstra(double dist[], double map[][42], bool known[], int seq, int path[], int scale)
{
dist[seq] = 0;
known[seq] = true;
while (1) {
for (int i = 0; i < scale; i++)
if (!known[i] && map[seq][i] > 0 && dist[seq] + map[seq][i] < dist[i]) {
dist[i] = dist[seq] + map[seq][i];
path[i] = seq;
}
seq = -1;
double min = INT_MAX;
for (int i = 0; i < scale; i++)
if (!known[i] && min > dist[i])
{
min = dist[i];
seq = i;
}
if (seq == -1)
break;
known[seq] = true;
}
}
void Traverse(int path[], int city, int origin, map<int, int> &seq)
{
if (city == origin)
{
cout << seq.find(city)->second;
return;
}
Traverse(path, path[city], origin, seq);
cout << " -> " << seq.find(city)->second ;
}
int find(int x)
{
if (x != father[x])
father[x] = find(father[x]);
return father[x];
}
void unite(int x, int y)
{
x = find(x);
y = find(y);
if (x != y)
father[x] = y;
}
bool same(int x, int y)
{
return find(x) == find(y);
}
double Kruskal(vector<Edge> &edges, bool map[][42])
{
sort(edges.begin(), edges.end());
double res = 0;
int n = edges.size();
for (int i = 0; i < n; i++) {
Edge e = edges[i];
if (!same(e.u, e.v)) {
map[e.u][e.v] = map[e.v][e.u] = true;
unite(e.u, e.v);
res += e.cost;
}
}
return res;
}
int main(int argc, char const *argv[])
{
int choose = 0;
while (choose != 5)
{
cout << "ѡ²" << endl;
cout << "1 ̰ķʷ" << endl;
cout << "2 " << endl;
cout << "3 Դ·" << endl;
cout << "4 С" << endl;
cout << "5 ˳" << endl;
while (cin >> choose, !(choose >= 1 && choose <= 5))
{
cout << "벻Ϸ" << endl;
cin.clear();
cin.sync();
}
cout << "-----------------------------------------------------------------" << endl;
switch (choose)
{
case 1:
{
ifstream in1("3-1.21վ.txt", ios_base::in);
ifstream in2("3-2.29վ.txt", ios_base::in);
if (!in1.is_open() || !in2.is_open())
{
cout << "Error opening file..." << endl;
exit(1);
}
int n = 0;
while (in1 >> stations[n].enodedId >> stations[n].longitude
>> stations[n].latitude >> stations[n].index)
n++;
cout << "21վεʷֵΪ " << MinWeightTriangulation(n) << endl;
cout << "ʷֽṹΪ" << endl;
TraceBack(1, n - 1);
n = 0;
while (in2 >> stations[n].enodedId >> stations[n].longitude
>> stations[n].latitude >> stations[n].index)
n++;
cout << endl << "29վεʷֵΪ " << MinWeightTriangulation(n) << endl;
cout << "ʷֽṹΪ" << endl;
TraceBack(1, n - 1);
in1.close();
in2.close();
cout << "-----------------------------------------------------------------" << endl;
break;
}
case 2:
{
ifstream in("2.ı.txt", ios_base::in);
if (!in.is_open())
{
cout << "Error opening file..." << endl;
exit(1);
}
char ch;
int incidence[MAXSIZE] = {0};
while (in >> ch)
{
if (ch == '#')
incidence[0]++;
else
{
ch = tolower(ch);
incidence[ch - 'a' + 1]++;
}
}
pNode Tree = HuffmanTree(incidence);
cout << "£" << endl;
int HuffmanCode = printHuffman(Tree, string(), incidence);
int OrdinaryCode = 0;
for (int i = 0; i <= 26; i++)
OrdinaryCode += incidence[i] * 5;
cout << "ù룬ıҪĴ洢: " << HuffmanCode << endl;
cout << "ö룬ıҪĴ洢: " << OrdinaryCode << endl;
in.close();
cout << "-----------------------------------------------------------------" << endl;
break;
}
case 3:
{
ifstream in1("1-1.22վͼڽӾ-v1.txt", ios_base::in);
ifstream in2("1-1.42վͼڽӾ-v1.txt", ios_base::in);
if (!in1.is_open() || !in2.is_open())
{
cout << "Error opening file..." << endl;
exit(1);
}
map<int, int> mark, seq;
int enodedID, i = 0;
double num;
bool known[42];
double map[42][42];
double dist[42];
int path[42];
string line;
getline(in1, line);
istringstream iss(line);
while (iss >> enodedID) {
mark.insert(make_pair(enodedID, i));
seq.insert(make_pair(i++, enodedID));
}
for (int i = 0; i < 22; i++) {
dist[i] = INT_MAX;
for (int j = 0; j <= 22; j++) {
in1 >> num;
if (j != 0)
map[i][j - 1] = num;
}
}
memset(known, 0, sizeof(known));
Dijkstra(dist, map, known, mark.find(567443)->second, path, 22);
cout << "22վɵͼ: " << endl;
cout << "567443ĵԴ·" << endl;
for (int i = 0; i < 22; i++)
{
cout << "567443->" << seq.find(i)->second << ": " << dist[i] << endl;
}
cout << "56744333109·" << endl;
Traverse(path, mark.find(33109)->second, mark.find(567443)->second, seq);
cout << endl;
mark.clear();
seq.clear();
getline(in2, line);
iss.clear();
iss.str(line);
i = 0;
while (iss >> enodedID) {
mark.insert(make_pair(enodedID, i));
seq.insert(make_pair(i++, enodedID));
}
for (int i = 0; i < 42; i++) {
dist[i] = INT_MAX;
for (int j = 0; j <= 42; j++) {
in2 >> num;
if (j != 0)
map[i][j - 1] = num;
}
}
memset(known, 0, sizeof(known));
Dijkstra(dist, map, known, mark.find(565845)->second, path, 42);
cout << "42վɵͼ " << endl;
cout << "565845ĵԴ·" << endl;
for (int i = 0; i < 42; i++)
{
cout << "565845->" << seq.find(i)->second << ": " << dist[i] << endl;
}
cout << "565845565667·" << endl;
Traverse(path, mark.find(565667)->second, mark.find(565845)->second, seq);
cout << endl;
in1.close();
in2.close();
cout << "-----------------------------------------------------------------" << endl;
break;
}
case 4:
{
ifstream in1("1-1.22վͼڽӾ-v1.txt", ios_base::in);
ifstream in2("1-1.42վͼڽӾ-v1.txt", ios_base::in);
if (!in1.is_open() || !in2.is_open())
{
cout << "Error opening file..." << endl;
exit(1);
}
map<int, int> mark, seq;
int enodedID, i = 0;
double num;
bool map[42][42] = {0};
vector<Edge> edges;
string line;
getline(in1, line);
istringstream iss(line);
while (iss >> enodedID) {
mark.insert(make_pair(enodedID, i));
seq.insert(make_pair(i++, enodedID));
}
for (int i = 0; i < 22; i++) {
father[i] = i;
for (int j = 0; j <= 22; j++) {
in1 >> num;
if (j != 0 && num > 0) {
Edge temp;
temp.u = i;
temp.v = j - 1;
temp.cost = num;
edges.push_back(temp);
}
}
}
double res = Kruskal(edges, map);
cout << "22վɵͼСΪ " << res << endl;
cout << "ӵıУ" << endl;
for (int i = 0; i < 22; i++)
for (int j = i + 1; j < 22; j++)
if (map[i][j])
cout << i + 1 << "--" << j + 1 << '\t';
cout << endl;
mark.clear();
seq.clear();
edges.clear();
memset(map, 0, sizeof(map));
i = 0;
getline(in2, line);
iss.str(line);
while (iss >> enodedID) {
mark.insert(make_pair(enodedID, i));
seq.insert(make_pair(i++, enodedID));
}
for (int i = 0; i < 42; i++) {
father[i] = i;
for (int j = 0; j <= 42; j++) {
in2 >> num;
if (j != 0 && num > 0) {
Edge temp;
temp.u = i;
temp.v = j - 1;
temp.cost = num;
edges.push_back(temp);
}
}
}
res = Kruskal(edges, map);
cout << "42վɵͼСΪ " << res << endl;
cout << "ӵıУ" << endl;
for (int i = 0; i < 42; i++)
for (int j = i + 1; j < 42; j++)
if (map[i][j])
cout << i + 1 << "--" << j + 1<< '\t';
cout << endl;
in1.close();
in2.close();
cout << "-----------------------------------------------------------------" << endl;
break;
}
default:
break;
}
}
return 0;
}
| true |
6d5912d39b4c3e4c5668dd61081e45404bec7e3e | C++ | DelyanaR/OOP_20_21 | /Subscribers and Publishers/Repository.hpp | UTF-8 | 885 | 3.0625 | 3 | [] | no_license | #pragma once
#include "Averager.hpp"
#include "MovingAverager.hpp"
#include "PeriodicSampler.hpp"
#include <vector>
// Repository is the single place where Subscribers will
// be stored. A Repository has ownership of the Subscribers
// stored inside it.
// The only way to access the available Subscribers in the
// repository is via the Subscriber's unique id.
// id's are guaranteed to be unique
class Repository {
public:
// add registers a new Subscriber in the Repository
void add(Subscriber*);
Repository()=default;
virtual ~Repository() = default;
Repository& operator=(const Repository& rhs);
Repository(const Repository& rhs);
//get returns a Subscriber in the Repository if a
// Subscriber with the given id exists.
// Returns nullptr otherwise
Subscriber* get(std::string id);
private:
std::vector<Subscriber*> subscribers;
};
| true |
87553fbe56567bd43d529db42af1422ae7c204ae | C++ | StefanoBelli/mallocx | /mallocx_based_allocator.cpp | UTF-8 | 1,153 | 3.203125 | 3 | [] | no_license | #include <cstdint>
#include <new>
#include <string>
#include <vector>
#include <mallocx.h>
void* operator new(std::size_t count) {
void* ptr = mallocx(count);
if(ptr == nullptr)
throw std::bad_alloc();
return ptr;
}
void operator delete(void* oldptr) {
freex(oldptr);
}
void operator delete[](void* oldptr) {
operator delete(oldptr);
}
void* operator new[](std::size_t count) {
return operator new(count);
}
template<typename __Type>
struct Allocatorx {
public:
using value_type = __Type;
using size_type = std::size_t;
using difference_type = std::ptrdiff_t;
using pointer = __Type*; //deprecated
Allocatorx() = default;
~Allocatorx() = default;
pointer allocate(std::size_t alloc_size) {
return static_cast<pointer>(operator new[](alloc_size));
}
void deallocate(void* ptr, [[maybe_unused]] std::size_t size) {
operator delete[](ptr);
}
};
template <typename T>
using vectorx = std::vector<T, Allocatorx<T>>;
using stringx = std::basic_string<char, std::char_traits<char>, Allocatorx<char>>;
| true |
39a69e8c7ee9d19a9f0ebf89a894ca24ffc5059c | C++ | danilaferents/maestroofprogramming | /2018/graph/summdistances.cpp | UTF-8 | 2,995 | 3.15625 | 3 | [] | no_license |
#include<climits>
using namespace std;
#include <iostream>
#include <vector>
#include <algorithm>
#include <map>
/** Interface */
inline int readChar();
template <class T = int> inline T readInt();
template <class T> inline void writeInt( T x, char end = 0 );
inline void writeChar( int x );
inline void writeWord( const char *s );
/** Read */
static const int buf_size = 4096;
inline int getChar() {
static char buf[buf_size];
static int len = 0, pos = 0;
if (pos == len)
pos = 0, len = fread(buf, 1, buf_size, stdin);
if (pos == len)
return -1;
return buf[pos++];
}
inline int readChar() {
int c = getChar();
while (c <= 32)
c = getChar();
return c;
}
template <class T>
inline T readInt() {
int s = 1, c = readChar();
T x = 0;
if (c == '-')
s = -1, c = getChar();
while ('0' <= c && c <= '9')
x = x * 10 + c - '0', c = getChar();
return s == 1 ? x : -x;
}
/** Write */
static int write_pos = 0;
static char write_buf[buf_size];
inline void writeChar( int x ) {
if (write_pos == buf_size)
fwrite(write_buf, 1, buf_size, stdout), write_pos = 0;
write_buf[write_pos++] = x;
}
template <class T>
inline void writeInt( T x, char end ) {
if (x < 0)
writeChar('-'), x = -x;
char s[24];
int n = 0;
while (x || !n)
s[n++] = '0' + x % 10, x /= 10;
while (n--)
writeChar(s[n]);
if (end)
writeChar(end);
}
inline void writeWord( const char *s ) {
while (*s)
writeChar(*s++);
}
struct Flusher {
~Flusher() {
if (write_pos)
fwrite(write_buf, 1, write_pos, stdout), write_pos = 0;
}
} flusher;
struct Fraction {
int num, den;
};
struct cmp
{
bool operator() (const Fraction &first,const Fraction &sec)
{
if(sec.den==0) return true;
long long Y = (long long) first.num * (long long)sec.den - (long long) sec.num * (long long)first.den;
return (Y > 0) ? true : false;
}
};
// Get max of the two fractions
bool maxFraction(const Fraction &first,const Fraction &sec)
{
if(sec.den==0) return true;
long long Y = (long long) first.num * (long long)sec.den - (long long) sec.num * (long long)first.den;
return (Y > 0) ? true : false;
}
int main()
{
int numbertops=0,numberribs;
numbertops=readInt();
numberribs=readInt();
int array[numbertops][numbertops];
int first,second;
for (int k=0; k<numbertops; ++k)
for (int i=0; i<numbertops; ++i)
{
if(k == i) array[k][i]=0;
else array[k][i]=INT_MAX;
}
for(int i=0;i<numberribs;i++)
{
first=readInt();
second=readInt();
if (first!=second)
{
array[first-1][second-1]=1;
array[second-1][first-1]=1;
}
}
for (int k=0; k<numbertops; ++k)
for (int i=0; i<numbertops; ++i)
for (int j=0; j<numbertops; ++j)
if (array[i][k] < INT_MAX && array[k][j] < INT_MAX)
array[i][j] = min (array[i][j], array[i][k] + array[k][j]);
long long summ=0;
for (int k=0; k<numbertops; ++k)
for (int i=0; i<numbertops; ++i)
{
if(array[k][i] != INT_MAX) summ+=array[k][i];
// cout<<array[k][i]<<" ";
}
cout<<summ/2;
} | true |
d228966bfbd7b80a452552b870b98f5c5122c4d5 | C++ | quinnc/adventofcode2018 | /day7/parser.cpp | UTF-8 | 5,356 | 3.1875 | 3 | [
"MIT"
] | permissive |
#include <cstdio>
#include <iostream>
#include <map>
#include <list>
#include "parser.h"
using namespace std;
#if 0
list<char>::iterator Parser::InsertTask (char task, list<char>::iterator startPos)
{
// as long as the letters more, move to next
// insert before the first letter you find that is higher
if (startPos == opOrder.end())
{
cout << " weird, sent in the end iterator " << endl;
opOrder.push_back(task);
//return opOrder.end()--;
list<char>::iterator newpos;
FindTask(task, opOrder.begin(), newpos);
return newpos;
}
else
{
// cout << " starting looking for insert point at letter " << *startPos << endl;
}
for (auto curr = startPos; curr != opOrder.end(); curr++)
{
//cout << __LINE__ << ": curr=" << *curr << " new task=" << task << endl;
if (*curr > task)
{
// cout << "inserting --- " << task << " --- BEFORE === " << *curr << " ===" << endl;
return opOrder.emplace(curr, task);
}
else
{
// cout << " searching... (curr= " << *curr << " < new= " << task << " ) " << endl;
}
}
cout << "didn't find a better place so put '" << task << "' at the end of the ops" << endl;
opOrder.push_back(task);
return opOrder.end()--;
}
void Parser::FindTask (char task, list<char>::iterator start, list<char>::iterator & pos)
{
for (auto curr = start; curr != opOrder.end(); curr++)
{
if (*curr == task)
{
// cout << " found task " << task << endl;
pos = curr;
return;
}
}
//cout << " > didn't find " << task << " between " << *start << " and the end" << endl;
pos = opOrder.end();
}
#endif
#if 0
void Parser::Process(const std::string & curr_line)
{
char doFirst, doAfter;
bool ok = false;
//cout << __LINE__ << endl;
ok = ParseLine(curr_line, doFirst, doAfter);
if (!ok)
{
cout << "Failed to parse line::: " << curr_line << endl;
return;
}
//cout << __LINE__ << endl;
if (this->opOrder.size() == 0)
{
this->opOrder.push_back(doFirst);
this->opOrder.push_back(doAfter);
// cout << " list was empty, added " << doFirst << " then " << doAfter << endl;
PrintResults();
return;
}
//cout << __LINE__ << endl;
// find the 'dofirst' item
list<char>::iterator firstPos;
FindTask(doFirst, opOrder.begin(), firstPos);
//cout << __LINE__ << endl;
// if don't find it
if (firstPos == opOrder.end())
{
cout << " first task wasn't found in the list, inserting from the beginning... " << doFirst << endl;
firstPos = InsertTask(doFirst, opOrder.begin());
}
// find the 'doAfter' item
list<char>::iterator afterPos;
FindTask (doAfter, firstPos, afterPos);
//cout << __LINE__ << endl;
// already after the before task
if (afterPos != opOrder.end())
{
//cout << __LINE__ << endl;
PrintResults();
// cout << " task " << doAfter << " is already after is already after before " << doFirst << " ... done " << endl;
return;
}
//cout << __LINE__ << " about to erase " << doAfter << " from the list" << endl;
// cout << " Before ERaSE task=" << doAfter << endl;
// PrintResults();
// if it is before, erase
opOrder.remove(doAfter);
// cout << " After ERASE task=" << doAfter << endl;
// PrintResults();
//PrintResults();
// if it is before or not at all, insert after
auto firstInsertPoint = firstPos;
// cout << " first task= " << doFirst << ", but at firstPos=" << *firstPos << endl;
firstInsertPoint++;
InsertTask (doAfter, firstInsertPoint);
// cout << " Task to be completed first = " << doFirst << ", task to do after = " << doAfter << endl;
PrintResults();
}
#endif
void Parser::Process (const string& line)
{
char before, after;
bool parsed;
parsed = ParseLine (line, before, after);
if (!parsed)
{
cout << "ERROR: unable to parse line [" << line << "]" << endl;
return;
}
UpdateNoBefore(before, after);
UpdateQueues(before, after);
}
list<char>::iterator FindInList (char id, list<char>& listToSearch)
{
return std::find (listToSeach.begin(), listToSearch.end(), id);
}
void Parser::UpdateNoBefore (char currBefore, char currAfter)
{
// if currAfter is in the NoBefores list, then remove
noBefores.erase(currAfter);
// if currBefore is not in EvenSeen, add to NoBefores
if (FindInList(currBefore, everSeen) == everSeen.end())
{
InsertIntoList(currBefore, noBefores);
InsertIntoList(currBefore, everSeen);
}
// add CurrBefore and CurrAfter no EvenSeen
InsertInfoList(currAfter, everSeen);
}
void Parser::UpdateQueues (char currBefore, char currAfter)
{
// insert currAfter to currBefore's queuek
auto currBeforeQueue = queueMap[currBefore];
InsertIntoList(currAfter, currBeforeQueue);
}
void Parser::PrintResults()
{
cout << "Order of operations:: ";
// ???
for (const auto& curr : opOrder)
{
cout << curr;
}
cout << endl;
}
bool Parser::ParseLine (const std::string& line, char & beforeTask, char& afterTask)
{
// Step F must be finished before step E can begin.
//cout << " PARSING::: " << line << endl;
if (line[4] != ' ' || line[6] != ' ')
return false;
int stepIdx = line.find("step ");
if (stepIdx == string::npos)
return false;
beforeTask = line[5];
afterTask = line[stepIdx+5];
if (line[stepIdx+6] != ' ')
return false;
cout << " " << beforeTask << " BEFORE " << afterTask << endl;
return true;
}
| true |
90c9aa2f76f2bdc4d1a5b55611565b2025749b3e | C++ | t-mochizuki/cpp-study | /AtCoder/typical90/018 - Statue of Chokudai/main.cpp | UTF-8 | 1,183 | 2.625 | 3 | [
"MIT"
] | permissive | // g++ -std=c++14 -DDEV=1 main.cpp
#include <stdio.h>
#include <cassert>
#include <iostream>
#include <fstream>
#include <vector>
#include <cmath>
using std::cin;
using std::cout;
using std::endl;
using std::terminate;
using std::vector;
#define rep(i, a, n) for (int i = (a); i < (n); ++i)
#define bit(n, k) ((n >> k) & 1)
class Problem {
private:
const double pi = std::acos(-1.0);
double T, L, X, Y;
int Q;
vector<double> E;
public:
Problem() {
cin >> T >> L >> X >> Y >> Q;
E.resize(Q);
rep(i, 0, Q) cin >> E[i];
}
void solve() {
rep(i, 0, Q) {
double theta = 2.0 * pi * (E[i] / T);
double y = L/2.0 - (L/2.0) * cos(theta);
assert(y >= 0);
double x = sqrt(X*X + (Y-(-(L/2.0)*sin(theta)))*(Y-(-(L/2.0)*sin(theta))));
assert(x >= 0);
printf("%.8f\n", 180 * atan2(y, x) / pi);
}
}
};
int main() {
#ifdef DEV
std::ifstream in("input");
cin.rdbuf(in.rdbuf());
int t; cin >> t;
for (int x = 1; x <= t; ++x) {
Problem p;
p.solve();
}
#else
Problem p;
p.solve();
#endif
return 0;
}
| true |
36daa31d5386262041a898fd6cd561e41a7e35df | C++ | akadjoker/mob2d | /libMob2D/src/SpriteManager.cpp | UTF-8 | 3,139 | 2.578125 | 3 | [] | no_license | #include "SpriteManager.h"
namespace Mob2D {
SpriteManager*
SpriteManager::m_pInstance = NULL;
void SpriteManager::Init()
{
// string error = "ERROR";
pSprite error_spr(new Sprite());
sprites.insert(std::pair<string, pSprite>("ERROR", error_spr)); // Create the error sprite.
error_color_array[0] = 1.0;
error_color_array[1] = 17/255;
error_color_array[2] = 231/255;
}
void SpriteManager::Deinit()
{
// Clear the map and multimap
nodes.clear();
sprites.clear();
}
void SpriteManager::AddResource(string file)
{
pSprite sprite(new Sprite(file));
if(sprite->GetName() != "ERROR")
{
if(sprites.find(sprite->GetName()) == sprites.end())
{
sprites.insert(std::pair<string, pSprite>(sprite->GetName(), sprite));
}
else
{
sprites.insert(std::pair<string, pSprite>(sprite->GetName(), sprite));
Mob2DLog::Instance()->PushString("Sprite data overwritten.\n");
}
}
else
Mob2DLog::Instance()->PushString("Sprite load failed. Tried to overwrite default error resource.\n");
}
M2DNode SpriteManager::AddNode(string handle)
{
if(sprites.find(handle) != sprites.end())
{
M2DNode node(new mob2d_node(sprites[handle]));
nodes.insert(std::pair<string, M2DNode>(handle, node));
return node;
}
else
{
M2DNode node(new mob2d_node(sprites["ERROR"]));
Mob2DLog::Instance()->PushString("Mob2DNode set to error and left unmapped.\n");
return node;
}
}
void SpriteManager::MapNode(M2DNode node, string key)
{
// Ain't I clever?
if(sprites.find(key) == sprites.end())
Mob2DLog::Instance()->PushString("ERROR! Could not map node to a nonexistant key.\n");
else
nodes.insert(std::pair<string, M2DNode>(key, node));
}
void SpriteManager::DeleteSprite(string sprite_name)
{
// Delete the Sprite resource stored and reset all existing nodes pointing to it to the error sprite
if(sprites.find(sprite_name) != sprites.end())
{
// all nodes now point to the error sprite and the sprite gets deallocated automatically by Boost.
std::pair<Mob2DNodeIter, Mob2DNodeIter> range_pair = nodes.equal_range(sprite_name);
for(Mob2DNodeIter i = range_pair.first; i != range_pair.second; i++)
{
// reassign the node's internal pointer.
(*i).second->ReassignToSprite(sprites["ERROR"]);
(*i).second->SetAnimation("ERROR");
}
nodes.erase(sprite_name);
sprites.erase(sprite_name);
}
else
Mob2DLog::Instance()->PushString("Sprite resource not found. Can not delete.\n");
}
void SpriteManager::ClearNodes(string handle)
{
if(nodes.find(handle) != nodes.end())
{
std::pair<Mob2DNodeIter, Mob2DNodeIter> range_pair = nodes.equal_range(handle);
for(Mob2DNodeIter i = range_pair.first; i != range_pair.second; i++)
{
// reassign the node's internal pointer.
(*i).second->ReassignToSprite(sprites["ERROR"]);
(*i).second->SetAnimation("ERROR");
}
nodes.erase(handle);
}
}
pSprite SpriteManager::GetSprite(string sprite_name)
{
if(sprites.find(sprite_name) != sprites.end())
return sprites[sprite_name];
else
return sprites["ERROR"];
}
} // namespace
| true |
3ae6fd13b9153ec321cd3ce9291f86620ea84e2b | C++ | kartavya96/Competitive | /SPOJ/Phidias.cpp | UTF-8 | 718 | 2.5625 | 3 | [] | no_license | #include <iostream>
#include <cstring>
using namespace std;
int T,W,H,N,w,h,best[620][620];
int main() {
cin >> T;
while (T--) {
memset(best,0x3f,sizeof(best));
cin >> W >> H >> N;
while (N--)
{
cin >> w >> h;
best[w][h]=0;
}
for (int i=0; i<=W; i++)
{
for (int j=0; j<=H; j++)
{
best[i][j] = min( best[i][j], i*j );
for (int k=1; k<i; k++)
best[i][j] = min( best[i][j], best[k][j] + best[i-k][j] );
for (int k=1; k<j; k++)
best[i][j] = min( best[i][j], best[i][k] + best[i][j-k] );
cout<<best[i][j]<<" ";
}
cout<<endl;
}
cout << best[W][H] << endl;
}
return 0;
} | true |
8f6d27c42e832ac350938b05540d837e5c5f868c | C++ | solaresjuan98/EDD-ejemplos | /ListaDoble/listadoble.cpp | UTF-8 | 2,418 | 3.265625 | 3 | [] | no_license | #include "listadoble.h"
ListaDoble::ListaDoble()
{
this->head=NULL;
}
ListaDoble::~ListaDoble(){
Nodo* aux=this->head;
Nodo* tmp;
while(aux!=NULL){
tmp=aux->getDerecha();
delete aux;
aux=tmp;
}
}
void ListaDoble::insertarOrdenado(Nodo *nuevo){
if(this->head==NULL){
this->head=nuevo;
}else{
int valorcabeza=this->head->getVal();
int valornuevo=nuevo->getVal();
if(valornuevo<=valorcabeza){
nuevo->setDerecha(this->head);
this->head->setIzquierda(nuevo);
this->head=nuevo;
}else{
Nodo* aux=this->head;
while(aux!=NULL){
if(aux->getIzquierda()!=NULL){
if(valornuevo>aux->getIzquierda()->getVal()&&valornuevo<=aux->getVal()){
Nodo *izq=aux->getIzquierda();
Nodo *der=aux;
izq->setDerecha(nuevo);
nuevo->setIzquierda(izq);
nuevo->setDerecha(der);
der->setIzquierda(nuevo);
break;
}
}
if(aux->getDerecha()==NULL){
aux->setDerecha(nuevo);
nuevo->setIzquierda(aux);
break;
}
aux=aux->getDerecha();
}
}
}
}
string ListaDoble::generar(){
ostringstream cadena;
cadena<<"digraph G {"<<endl<<"node[shape=\"record\"];"<<endl;
cadena<<"rankdir=LR;"<<endl;
cadena<<generar(this->head)<<endl;
cadena<<"}"<<endl;
return cadena.str();
}
string ListaDoble::generar(Nodo* aux){
ostringstream cadena;
if(aux!=NULL){
cadena<<"nodo"<<&(*aux)<<"[label=\""<<aux->getVal()<<"\"];"<<endl;
Nodo* siguiente=aux->getDerecha();
//Creacion de nodos
cadena<< (siguiente==NULL?"":generar(siguiente));
//Union de nodos
if(siguiente!=NULL){
cadena<<"nodo"<<&(*siguiente)<<"->nodo"<<&(*aux)<<";"<<endl;
cadena<<"nodo"<<&(*aux)<<"->nodo"<<&(*siguiente)<<";"<<endl;
}
}
return cadena.str();
}
void ListaDoble::imprimir(){
Nodo* aux=this->head;
while(aux!=NULL){
cout<<"Elemento : "<<aux->getVal()<<endl;
aux=aux->getDerecha();
}
cout<<"------------------------------"<<endl;
}
| true |
31171a60c93cf4acf86dc3b93b7adb58494ee55d | C++ | ReemTarek/GraduationProjectfinal | /bicycle (1).cpp | UTF-8 | 1,493 | 2.640625 | 3 | [] | no_license | #include "bicycle.h"
#include <QDebug>
#include<QTransform>
Bicycle::Bicycle()
{
}
QPair<QPointF, qreal> Bicycle::run(QPair<QPointF, qreal>curConfig, qreal velocity, qreal wheelsAngle)
{
QPointF pos = curConfig.first;
qreal rotation = curConfig.second;
qreal theta = qDegreesToRadians(rotation);
qreal dx = velocity * qCos(theta);
qreal dy = velocity * qSin(theta);
qreal phi = qDegreesToRadians(wheelsAngle);
qreal dtheta = velocity / wheelBase * qTan(phi);
qreal x = pos.x() + dx * dt * 1000;
qreal y = pos.y() + dy * dt * 1000;
theta += dtheta * dt;
theta = qRadiansToDegrees(theta);
return {{x,y}, theta};
}
QPair<qreal, qreal> Bicycle::run(QPair<QPointF, qreal> curConfig, QPair<QPointF, qreal> nxtConfig)
{
qreal xDot = (nxtConfig.first.x() - curConfig.first.x()) / (1000 * dt);
qreal yDot = (nxtConfig.first.y() - curConfig.first.y()) / (1000 * dt);
qreal v = hypot(xDot, yDot);
qreal nxtTheta = qDegreesToRadians(nxtConfig.second);
qreal thetaDot = (nxtTheta - qDegreesToRadians(curConfig.second)) / dt;
qreal phi = qAtan2(wheelBase * thetaDot, v);
qreal wheelsAngle = qRadiansToDegrees(phi);
/* if (wheelsAngle > 35) {
qDebug() << wheelsAngle << endl << "not steerable" << endl;
}
*/
return {v, wheelsAngle};
}
int Bicycle::getPhiMax() const
{
return phiMax;
}
qreal Bicycle::getLength() const
{
return length;
}
qreal Bicycle::getWidth() const
{
return width;
}
| true |
3d16380a87ebe663c7b35bc2ac41d85833420795 | C++ | hernandez232/FP_Tareas_00075919 | /x_y.cpp | UTF-8 | 799 | 3.140625 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main(){
int n=0, cx=1, cy=1, l=1, x [50], y [50];
cout << "Ingrese la magnitud de la lista: "; cin >> n;
cout << endl;
cout << "Ingrese los numeros de la lista X:" << endl;
for (int i=0; i<n; i++){
cout << "X" << cx << ": ";
cin >> x[i];
cx++;
}
cout << endl;
cout << "Ingrese los numeros de la lista Y:" << endl;
for (int i=0; i<n; i++){
cout << "Y" << cy << ": ";
cin >> y[i];
cy++;
}
cout << endl;
cout << "Los elementos X y Y de la lista son: " << endl;
for (int i=0; i<n; i++){
cout << x[i] << " ";
}
cout << endl;
cout << endl;
for (int i=0; i<n; i++){
cout << y[i] << " ";
}
return 0;
} | true |
03ca29a63cde1da1ac758624f9fe75fd63f08f8e | C++ | MelisaLuciano/SistemasDistribuidos | /16/SocketDatagrama.h | UTF-8 | 1,070 | 2.640625 | 3 | [] | no_license | #ifndef SOCKETDATAGRAMA_H_
#define SOCKETDATAGRAMA_H_
#include "PaqueteDatagrama.h"
#include <sys/socket.h>
#include <sys/time.h>
#include <netinet/in.h>
class SocketDatagrama {
public:
SocketDatagrama(int); // puerto local no se podrá cambiar para el proceso. Si
// es cero, lo asigna el sistema operativo
~SocketDatagrama();
// Recibe un paquete tipo datagrama proveniente de este socket
int recibe(PaqueteDatagrama& p);
// Recibe un paquete tipo datagrama proveniente de este socket
int recibeTimeOut(PaqueteDatagrama& p);
// Envía un paquete tipo datagrama desde este socket
int envia(PaqueteDatagrama& p);
void setTimeOut(time_t segundos, suseconds_t microsegundos);
void setTimeOut(timeval RTT);
void unsetTimeOut();
void setBroadcast();
private:
struct sockaddr_in direccionLocal;
struct sockaddr_in direccionForanea;
int s; // ID socket
struct timeval timer;
bool timeOut;
static long double RTO;
static long double srtt;
static long double rttvar;
static long double delta;
};
#endif
| true |
7b0a5be41242c5aa75a76fb24eba02bd90b800a7 | C++ | gexchai/Papouja | /src/GUI.hpp | UTF-8 | 1,583 | 2.703125 | 3 | [] | no_license | #ifndef GUI_HPP
#define GUI_HPP
#include "Resourcemanager.hpp"
#include "Settings.hpp"
#include <SFML/Graphics.hpp>
#include <cstddef>
#include <string>
class MenuPoint
{
public:
MenuPoint();
~MenuPoint();
void SetText(const std::string& text, unsigned int size);
void SetFont(const sf::Font& font);
void SetPosition(const sf::Vector2f& position);
void Activate(bool activate);
bool IsActivated();
void Select();
void Deselect();
sf::FloatRect GetRect();
void Draw(sf::RenderWindow& window);
private:
sf::Text myText;
bool isActive;
};
class Gui
{
public:
enum GuiStatus
{
DISABLED,
FADEIN,
ENABLED,
FADEOUT
};
public:
Gui(sf::RenderWindow& window, Settings& settings, Resourcemanager* resourcemanager);
virtual ~Gui();
void LoadResources();
void ActivateMenupoint(std::size_t number, bool activate);
void SetMenupointText(std::size_t number, const std::string& text);
void CheckEvents(const sf::Event& event);
void Render();
void FadeIn();
void FadeOut();
GuiStatus GetGuiStatus();
bool IsEnabled();
std::size_t GetMenuPosition();
protected:
sf::RenderWindow& myWindow;
Settings& mySettings;
Resourcemanager* myResourcemanager;
private:
std::size_t myMenuPosition;
sf::Clock myClock;
MenuPoint myMenuPoints[5];
Gui::GuiStatus myGuiStatus;
protected:
virtual void Slot1() = 0;
virtual void Slot2() = 0;
virtual void Slot3() = 0;
virtual void Slot4() = 0;
virtual void Slot5() = 0; // Back/Quit
};
#endif // GUI_HPP
| true |
f0ce4dd0408dc782df26a154e35e6d397e41dec3 | C++ | 7ZONE/TheObjOfCpp | /ConsoleApplication5/ConsoleApplication5/TheStudentSystem.cpp | GB18030 | 9,332 | 3.046875 | 3 | [] | no_license | #include<stdio.h>
#include<math.h>
#include <conio.h>
#include <process.h>
#define n 2//ѧУĿ
#define m 1//ĿĿ
#define w 1//ŮĿĿ
#define null 0
typedef struct
{
int itemnum; //Ŀ
int top; //ȡεĿ
int range[5]; //
int mark[5]; //
}itemnode; //Ŀ
typedef struct
{
int schoolnum; //ѧУ
int score; //ѧУܷ
int mscore; //ܷ
int wscore; //Ůܷ
itemnode c[m + w]; //Ŀ
}headnode;//ͷ
headnode h[n];//һͷ
void inputinformation() //Ϣϵͳ
{
int i, j, k, s;
for (i = 0;i<n;i++)
{
h[i].score = 0;
h[i].mscore = 0;
h[i].wscore = 0;
}
for (i = 0;i<n;i++)
{
printf("*****ѧУ:");
scanf_s("%d", &h[i].schoolnum);
for (j = 0;j<m + w;j++)
{ //ʼͷ //ͷϢ
printf("*****Ŀ:");
scanf_s("%d", &h[i].c[j].itemnum);
printf("*****ȡǰ3orǰ5:");
scanf_s("%d", &h[i].c[j].top);
printf("*****üΣ");
scanf_s("%d", &k); //ĿϢ
for (s = 0;s<5;s++)
h[i].c[j].range[s] = 0, h[i].c[j].mark[s] = 0; //ʼͷ
for (s = 0;s<k;s++)
{
printf("*****:");
scanf_s("%d", &h[i].c[j].range[s]); //Ϣ
if (h[i].c[j].top == 3)
switch (h[i].c[j].range[s])
{
case 0: h[i].c[j].mark[s] = 0;
break;
case 1: h[i].c[j].mark[s] = 5;
break;
case 2: h[i].c[j].mark[s] = 3;
break;
case 3: h[i].c[j].mark[s] = 2;
break;
}
else
switch (h[i].c[j].range[s])
{
case 0: h[i].c[j].mark[s] = 0;
break;
case 1: h[i].c[j].mark[s] = 7;
break;
case 2: h[i].c[j].mark[s] = 5;
break;
case 3: h[i].c[j].mark[s] = 3;
break;
case 4: h[i].c[j].mark[s] = 2;
break;
case 5: h[i].c[j].mark[s] = 1;
break;
}
h[i].score = h[i].score + h[i].c[j].mark[s];
//ȡǰȡǰֱǷ
if (j <= m - 1)
h[i].mscore = h[i].mscore + h[i].c[j].mark[s];
//Ŀǵӷȥ
else
h[i].wscore = h[i].wscore + h[i].c[j].mark[s];
//ŮĿǵŮĿȥ
}
printf("\n");
}
}
}
void output() //
{
int choice, i, j, k;
int remember[n];
int sign;
do
{
printf("*******************1.ѧУ.*******************\n");
printf("*******************2.ѧУܷ.*******************\n");
printf("*******************3.ܷ.*******************\n");
printf("*******************4.Ůܷ.*******************\n");
printf("\n\n******************* ѡ*************************\n\n:");
scanf_s("%d", &choice);
switch (choice)
{
case 1: //˳
for (i = 0;i < n;i++)
{
printf("\n\n*****ѧУ:%d\n", h[i].schoolnum);
printf("*****ѧУܷ:%d\n", h[i].score);
printf("*****ܷ:%d\n", h[i].mscore);
printf("*****Ůܷ: %d\n\n\n", h[i].wscore);
}
break;
case 2:// ðøסͷ±
for (i = 0;i < n;i++)
remember[i] = i;
for (i = 0;i < n;i++)
{
for (j = i + 1;j < n;j++)
if (h[remember[i]].score < h[j].score)
k = remember[i];
remember[i] = remember[j], remember[j] = k;
}
for (i = 0;i < n;i++)
{
printf("\n\n*****ѧУţ%d\n", h[remember[i]].schoolnum); printf("*****ѧУܷ:%d\n", h[remember[i]].score);
printf("*****ܷ:%d\n", h[remember[i]].mscore);
printf("*****Ůܷ: %d\n\n\n", h[remember[i]].wscore);
//±˳
} //ѧУܷ
break;
case 3:
for (i = 0;i < n;i++)
remember[i] = i;
for (i = 0;i < n;i++)
{
for (j = i + 1;j < n;j++)
if (h[remember[i]].mscore < h[j].mscore)
k = remember[i];remember[i] = remember[j];remember[j] = k;
}
for (i = 0;i < n;i++)
{
printf("\n\n*****ѧУ:%d\n", h[remember[i]].schoolnum); printf("*****ѧУܷ:%d\n", h[remember[i]].score);
printf("*****ܷ:%d\n", h[remember[i]].mscore);
printf("*****Ůܷ: %d\n\n\n", h[remember[i]].wscore);
} //ܷ break;
case 4:
for (i = 0;i < n;i++)
remember[i] = i;
for (i = 0;i < n;i++)
{
for (j = i + 1;j < n;j++)
if (h[remember[i]].wscore < h[j].wscore)
k = remember[i];
remember[i] = remember[j];remember[j] = k;
}
for (i = 0;i < n;i++)
{
printf("\n\n*****ѧУ:%d\n", h[remember[i]].schoolnum); printf("*****ѧУܷ:%d\n", h[remember[i]].score);
printf("*****ܷ:%d\n", h[remember[i]].mscore);
printf("*****Ůܷ: %d\n\n\n", h[remember[i]].wscore);
}
break; //Ůܷ
}
printf("ѡ 2 ,0 \n");
scanf_s("%d", &sign);
}while (sign == 2); //ѭִ
exit(0);
}
void Inquiry() //ѯ
{
int choice;
int i, j, k, s;
printf("\n*****1:ѧУŲѯ\n");
printf("\n*****2:ĿŲѯ\n");
printf("\n\n*****ѡѯʽ:"); // ṩֲѯʽ
scanf_s("%d",&choice);
switch (choice)
{
case 1:
do
{
printf("ҪѯѧУ:");
scanf_s("%d", &i);
if (i>n)
printf("ѧУûвμӴ˴˶!\n\n\n"); else
{
printf("ҪѯĿ:");
scanf_s("%d", &j);
if (j>m + w || j == 0)
printf("˴˶ûĿ\n\n\n");
//ѧУųΧ
else
{
printf("Ŀȡǰ %d,ѧУijɼ:\n", h[0].c[j - 1].top);
for (k = 0;k<5;k++)
if (h[i - 1].c[j - 1].range[k] != 0)
printf(":%d\n", h[i - 1].c[j - 1].range[k]); //ҪѯѧУĿijɼ
}
}
printf("ѡ 2 , 0 \n");
scanf_s("%d", &s);
printf("\n\n\n");
} while (s == 2); //ѭִ break;
case 2:
do
{
printf("ҪѯĿ:");
scanf_s("%d", &s);
if (s>m + w || s == 0)
printf("˴˶Ŀ.\n\n\n");
//ĿųΧ
else
{
printf("Ŀȡǰ %d,ȡεѧУ\n", h[0].c[s - 1].top);
for (i = 0; i<n;i++)
for (j = 0;j<5;j++)
if (h[i].c[s - 1].range[j] != 0)
printf("ѧУ:%d,:%d\n", h[i].schoolnum,
h[i].c[s - 1].range[j]);
} //ĿȡѧУijɼ
printf("\n\n\n 2, 0\n");
scanf_s("%d", &i);
printf("\n\n\n");
} while (i == 2);
break;
}
}
void writedata() //ݴ洢ļ
{
FILE *report;
errno_t err;
int i;
if ((err = fopen_s(&report,"sportsdata.txt", "w")) !=0)
{
printf("ܴļ\n");
exit(1);
}
for (i = 0;i<n;i++)
fwrite(&h[i], sizeof(headnode), 1, report);
fclose(report);
} //ͷд
void readdata() //ļݵĺ
{
FILE *report;
errno_t err;
int i, j, k, s;
if ((err = fopen_s(&report, "sportsdata.txt", "r")) != 0)
{
printf("file can not be opened\n");
exit(1);
}
for (i = 0;i<n;i++)
{
printf("******ѧУ:");
fread(&k, sizeof(int), 1, report);
printf("%d\n", k);
printf("******ѧУܷ:");
fread(&k, sizeof(int), 1, report);
printf("%d\n", k);
printf("******ܷ:");
fread(&k, sizeof(int), 1, report);
printf("%d\n", k);
printf("******Ůܷ:");
fread(&k, sizeof(int), 1, report);
printf("%d\n", k);
printf("\n\n\n");
_getch();
for (j = 0;j<m + w;j++)
{
printf("******Ŀ:");
fread(&k, sizeof(int), 1, report);
printf("%d\n", k);
printf("******ȡ:");
fread(&k, sizeof(int), 1, report);
printf("%d\n", k);
for (s = 0;s<5;s++)
{
fread(&k, sizeof(int), 1, report);
if (k != 0)
printf("******:"),
printf("%d\n", k);
}
for (s = 0;s<5;s++)
{
fread(&k, sizeof(int), 1, report);
if (k != 0) printf("******:"),
printf("%d\n", k);
}
}
printf("\n\n\n");
getchar();
}
fclose(report); //رļ
} //նһݾһݵķʽʾ
void main()
{
int choice;
printf("======================ӭʹ======================\n"); printf("\n\n*****************˶ͳϵͳ********************\n");
printf("\n\n********************1.Ϣ*************************\n");
printf("********************2.Ϣ*************************\n");
printf("********************3.ѯϢ*************************\n");
printf("********************4.Ϣ*************************\n");
printf("********************5.˳ϵͳ*************************\n\n\n");
printf("================================================\n\n");
printf("********ѡҪʵֲı:\n\n");
scanf_s("%d", &choice);
switch (choice)
{
case 1:
inputinformation();
writedata();
readdata();
main();
case 2:
output();
main();
case 3:
Inquiry();
main();
case 4:
readdata();
main();
case 5:
exit(0);
default:
exit(0);
}
} | true |
e938b1b04f8c99224e8008a062a1a222f19ef2c9 | C++ | tigoe/BallDropGame | /ESP-to-ATTiny-TelnetClient/ESPSerialToTelnetClient/ESPSerialToTelnetClient.ino | UTF-8 | 3,657 | 3.234375 | 3 | [] | no_license | /*
This sketch makes a telnet client on port 8080 to a server
It echoes any serial bytes to the server, and any server bytes
to the serial port. This is a modified version of the EspWiFiTelnetClient
note: the header file "settings.h" is not included in this repository.
Add a new tab in Arduino, call it "settings.h", and Include the following variables:
char ssid[] = "ssid"; // your network SSID
char password[] = "password"; // your network password
char host[] = "192.168.0.2"; // the IP address of the device running the server
You need to run a telnet server on port 8080 of the host to talk to this
sketch.
created 26 Jun 2015
modified 29 Oct 2015
by Tom Igoe
*/
#include <ESP8266WiFi.h>
#include "settings.h"
WiFiClient socket; // variable for the socket connection
const int port = 8080; // port for the socket connection
// set the pin numbers for the indicator LEDS:
const int leftPin = 13;
const int rightPin = 12;
const int upPin = 14;
const int downPin = 16;
const int connectedPin = 15;
void setup() {
Serial.begin(9600);
Serial.setTimeout(10);
socket.setTimeout(10);
pinMode(leftPin, OUTPUT);
pinMode(rightPin, OUTPUT);
pinMode(upPin, OUTPUT);
pinMode(downPin, OUTPUT);
pinMode(connectedPin, OUTPUT);
WiFi.begin(ssid, password);
Serial.print("Connecting to "); // connect to access point
Serial.println(ssid);
// wait for connection to network access point:
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
// when connected to access point, acknowledge it:
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP()); // print device's IP address
}
void loop() {
// Read the reply from server and print them to serial port:
while (socket.available()) {
Serial.print("Got something");
String input = socket.readString();
Serial.print(input);
}
// Read the reply from serial port and print them to server:
while (Serial.available()) {
char input = Serial.read();
// turn on the LEDs depending on what comes in the serial:
switch (input) {
case 'l': // left
digitalWrite(leftPin, HIGH);
socket.print(input);
break;
case 'r': // right
socket.print(input);
digitalWrite(rightPin, HIGH);
break;
case 'u': // up
socket.print(input);
digitalWrite(upPin, HIGH);
break;
case 'd': // down
socket.print(input);
digitalWrite(downPin, HIGH);
break;
case '1': // button pushed
if (socket.connected()) { // if the socket's connected, disconnect
socket.print('x'); // by sending an x
} else { // if the socket's not connected,
login(); // login to the server
}
break;
}
}
// if there's no serial input, turn the LEDs off:
digitalWrite(leftPin, LOW);
digitalWrite(rightPin, LOW);
digitalWrite(upPin, LOW);
digitalWrite(downPin, LOW);
// set the connected LED based on the state of the connection:
digitalWrite(connectedPin, socket.connected());
}
boolean login() {
socket.connect(host, port); // attempt to connect
while (!socket.connected()) { // While not connected, try again
delay(1000);
if (socket.connected()) { // if you connected,
socket.println("hello"); // say hello to the server
} else {
// if not connected, try again:
Serial.println("connection failed, trying again");
socket.connect(host, port);
}
}
}
| true |
23fb7ea95552a74b5ba401bd028ed6316fb49f20 | C++ | kuqadk3/CTF-and-Learning | /YUBITSEC 2017/Cryptography/175 - Simple Encryption/decode.cpp | UTF-8 | 341 | 2.609375 | 3 | [] | no_license | #include <iostream>
#include <iomanip>
#include <numeric>
#include <vector>
#include <algorithm>
#include <fstream>
using namespace std;
int main(){
std::fstream myfile("encrypted.txt", std::ios_base::in);
int number;
while(myfile >> number){
cout << (char)(number^62);
}
cout << endl;
system("pause");
return 0;
} | true |
892165ef8557b7f59348400ee6fbfbfe3fe71d70 | C++ | SebastianMateo/CursoGlobant | /MathLib/MathLib/Matrix.cpp | UTF-8 | 1,070 | 3.265625 | 3 | [] | no_license | #include "Matrix.h"
template <unsigned int N>
Matrix<N>::Matrix(std::array<double, N*N> values) : mMatrix(values) { }
template <unsigned int N>
Matrix<N>::Matrix() { }
//Addition
template <unsigned int N>
Matrix<N>& Matrix<N>::operator+=(const Matrix<N>& rhs)
{
for (int i = 0; i < N * N; i++)
this->mMatrix[i] += rhs.mMatrix[i];
return *this;
}
//Substraction
template <unsigned int N>
Matrix<N>& Matrix<N>::operator-=(const Matrix<N>& rhs)
{
for (int i = 0; i < N * N; i++)
this->mMatrix[i] -= rhs.mMatrix[i];
return *this;
}
//Product
template <unsigned int N>
Matrix<N>& Matrix<N>::operator*=(const Matrix<N>& rhs)
{
Matrix<N> result;
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
result.get(i, j) = 0;
for (int k = 0; k < N; k++)
{
result.get(i,j) += this->get(i,k) * rhs.get(k,j);
}
}
}
*this = result;
return *this;
}
// explicit instantiations
template class Matrix<3>;
template class Matrix<4>; | true |
17496b520a154a1719e93915b0478cda5472ebe7 | C++ | SaulZhang/Algorithm-Templates | /1-PAT专题训练/收拾残局/1058.cpp | UTF-8 | 887 | 2.78125 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
#include <string>
#include <sstream>
#include <vector>
using namespace std;
string A,B,token;
vector<int> An,Bn,res;
int main()
{
cin>>A>>B;
stringstream ssA(A),ssB(B);
while(getline(ssA,token,'.')){
An.push_back(stoi(token));
}
while(getline(ssB,token,'.')){
Bn.push_back(stoi(token));
}
int c=0,cur=0;//10^7 17 29
res.resize(3);
for(int i=2;i>=0;i--){
if(i==2){
cur = (An[i]+Bn[i]+c)%29;
c = (An[i]+Bn[i]+c)/29;
}
else if(i==1){
cur = (An[i]+Bn[i]+c)%17;
c = (An[i]+Bn[i]+c)/17;
}
else{
cur = (An[i]+Bn[i]+c);
}
res[i]=cur;
}
for(int i=0;i<res.size();i++){
cout<<res[i];
if(i!=res.size()-1)
cout<<".";
}
cout<<endl;
return 0;
}
| true |
b0271a6fec4e93a698cc4208d9b3590b4275d957 | C++ | jpieper/rpicar | /holster/include/error.h | UTF-8 | 538 | 3.015625 | 3 | [] | no_license | /*
* @author Carl Saldanha <cjds92@gmail.com>
* @brief An error handler
*/
#ifndef HOLSTER_INCLUDE_ERROR
#define HOLSTER_INCLUDE_ERROR
#include <optional>
#include <string>
class Error
{
public:
explicit Error(const std::string& error):
error_(error)
{}
const char* throw_error() const throw()
{
return error_.c_str();
}
private:
std::string error_;
};
const std::optional<Error> make_error(const std::string& error_str)
{
return std::make_optional<Error>(error_str);
}
#endif // HOLSTER_INCLUDE_ERROR
| true |
c7be338f737a05addd108778daa479209afba781 | C++ | btroxell/CS30000 | /One_Operand_Instr.h | UTF-8 | 815 | 2.796875 | 3 | [] | no_license | #ifndef _ONE_OPERAND_INSTR_H_
#define _ONE_OPERAND_INSTR_H_
#include "Instruction.h"
#include "Operand.h"
/*
4/24/18 Brandon Troxell:
TODO: Need to create a copy constructor for instructions so that when the
HashTable getInstruction() returns an instruction, we can copy it and initialize
an operand to be able to pass to a Source_Line object
*/
class One_Operand_Instr : public Instruction
{
public:
One_Operand_Instr(void);
One_Operand_Instr(std::string m, std::string hex, std::string form);
One_Operand_Instr(std::string m, std::string hex, std::string form, Operand *op);
~One_Operand_Instr(void);
Operand *get_operand();
void set_operand(Operand *op);
// Operand should be its own class so it can have the register or operand name and location
Operand * operand_;
};
#endif // !_ONE_OPERAND_INSTR_H_
| true |
e60d9363a2a426e6e5a12b809a7c44e4d284a3c3 | C++ | DiogoMCampos/osmParsePOI | /src/Parser.cpp | UTF-8 | 4,046 | 2.78125 | 3 | [] | no_license | #include "Parser.hpp"
using namespace std;
bool Parser::openFiles() {
if (!openOSMFile() || !openPOIFile() || !isValidOSMFile())
return false;
return true;
}
void Parser::closeFiles() {
osmFile.close();
destFile.close();
}
bool Parser::openOSMFile() {
string filename;
do {
if (osmFile.fail()) {
osmFile.clear();
cout << "Invalid filename. Please enter again: ";
}
else {
cout << "Enter the OSM file name (including extension) or \"exit\" to cancel: ";
}
cin >> filename;
if (cin.eof() || filename == "exit") {
return false;
}
osmFile.open(filename.c_str());
} while (osmFile.fail());
return true;
}
bool Parser::openPOIFile() {
destFile.open("poi.txt");
if (destFile.fail())
return false;
return true;
}
bool Parser::isValidOSMFile() {
string line;
getline(osmFile, line);
if (line.substr(0, 2) != "<?" || line.substr(line.length() - 2, 2) != "?>")
return false;
getline(osmFile, line);
if (line.substr(0, 4) != "<osm" || line[line.length() - 1] != '>')
return false;
getline(osmFile, line);
if (line.substr(1, 7) != "<bounds" || line[line.length() - 1] != '>')
return false;
return true;
}
void Parser::store() {
if (poiList.size() == 0)
return;
destFile << poiList[0].getNodeID() << ";" << poiList[0].getType() << ";;" << poiList[0].getName() << ";;" << poiList[0].getLat() << ";" << poiList[0].getLon();
for (size_t i = 1; i < poiList.size(); ++i) {
destFile << "\n" << poiList[i].getNodeID() << ";" << poiList[i].getType() << ";;" << poiList[i].getName() << ";;" << poiList[i].getLat() << ";" << poiList[i].getLon();
}
}
bool Parser::readNodes() {
string nodeLine;
while (getline(osmFile, nodeLine)) {
string nodeInfo;
for (size_t i = 0; i < nodeLine.length(); ++i) {
if (nodeLine[i] != ' ' || nodeInfo.length() != 0) {
nodeInfo += nodeLine[i];
}
}
if (nodeInfo.substr(0, 5) != "<node") {
break;
}
if (nodeInfo.substr(0, 5) == "<node" && nodeInfo[nodeInfo.length() - 2] == '/') {
continue;
}
int firstDelim = nodeInfo.find('"');
int idLength = nodeInfo.find('"', firstDelim + 1) - firstDelim - 1;
string idString = nodeInfo.substr(firstDelim + 1, idLength);
int beginLat = nodeInfo.find("lat=") + 4;
int endLat = nodeInfo.find('"', beginLat + 4) - beginLat - 1;
string latitude = nodeInfo.substr(beginLat + 1, endLat);
int beginLon = nodeInfo.find("lon=") + 4;
int endLon = nodeInfo.find('"', beginLon + 4) - beginLon - 1;
string longitude = nodeInfo.substr(beginLon + 1, endLon);
getPOI(idString, latitude, longitude);
}
return true;
}
void Parser::getPOI(string nodeID, string lat, string lon) {
string line;
getNextTag(line);
while (line[0] != '/') {
getline(osmFile, line, ' '); // k="..."
// check if it's an amenity
if (line == "k=\"amenity\"") {
string type;
getline(osmFile, line, '\"'); // garbage
getline(osmFile, type, '\"');
getline(osmFile, line); // garbage
if (type == "atm")
getName(nodeID, type, "k=\"operator\"", lat, lon);
else if (type == "restaurant")
getName(nodeID, type, "k=\"name\"", lat, lon);
else if (type == "pharmacy")
getName(nodeID, type, "k=\"name\"", lat, lon);
else if (type == "hospital")
getName(nodeID, type, "k=\"name\"", lat, lon);
else if (type == "fuel")
getName(nodeID, type, "k=\"brand\"", lat, lon);
else {
getNextTag(line);
}
}
else {
getline(osmFile, line);
getNextTag(line);
}
}
}
void Parser::getName(string nodeID, string type, string key, string lat, string lon) {
string line;
string name = "";
getNextTag(line);
while (line[0] != '/') {
getline(osmFile, line, ' '); // k="..."
// check if it's the corresponding key
if (line == key) {
getline(osmFile, line, '\"'); // garbage
getline(osmFile, name, '\"');
}
getNextTag(line);
}
POI temp(nodeID, type, name, lat, lon);
poiList.push_back(temp);
}
void Parser::getNextTag(string &line) {
getline(osmFile, line, '<'); // discards whitespaces
getline(osmFile, line, ' '); // gets tag
}
| true |
66f458de37e397ad913d944c512c5d7b992dc2b0 | C++ | hyejinhong/Algorithm-study | /Problem Solving/SWEA 5357 터널 속의 기차.cpp | UHC | 706 | 3.046875 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
int t; // test case
cin >> t;
for (int test = 1; test <= t; test++) {
int N, H;
cin >> N >> H;
int a[100001];
int o[100001];
for (int i = 0; i<N; i++)
cin >> a[i];
for (int i = 0; i<N; i++)
cin >> o[i];
int count = 0;
int result = 0;
if (o[0] == 0) { //
o[0] = 1;
result++;
}
if (o[N-1] == 0) { //
o[N - 1] = 1;
result++;
}
for (int i = 0; i<N; i++) {
if (o[i] == 1) {
count = 0;
}
else if (o[i] == 0) {
count += a[i];
}
if (count >= H) {
o[i] = 1;
count = 0;
result++;
}
}
cout << "#" << test << " " << result << endl;
}
}
| true |
eae6ee860bd641fb52a8b2a475fbdb919b077b96 | C++ | sharonsitu/Quadris-CS246-F2016 | /Jblock.cc | UTF-8 | 5,462 | 3.015625 | 3 | [] | no_license | #include "Include/Jblock.h"
#include <iostream>
#include <vector>
using namespace std;
/* JBLOCK METHODS */
//Jblock cstr
JBlock::JBlock(char type, int number,Board* myboard):Block(type,number,myboard){
cellArray[0] = Cell(3,0,'J',number);
cellArray[1] = Cell(4,0,'J',number);
cellArray[2] = Cell(4,1,'J',number);
cellArray[3] = Cell(4,2,'J',number);
}
//Clockwise
void JBlock::Clockwise(){
int r0 = cellArray[0].getPosition('r');
int c0 = cellArray[0].getPosition('c');
if(direction == north){
if(r0 - 1 >= 0 &&
bd->getType(r0 - 1, c0) == 32 &&
bd->getType(r0 - 1, c0 + 1) == 32){
cellArray[0].setPosition('r',r0-1);
cellArray[0].setPosition('c',c0+1);
cellArray[1].setPosition('r',r0-1);
cellArray[1].setPosition('c',c0);
cellArray[2].setPosition('r',r0);
cellArray[2].setPosition('c',c0);
cellArray[3].setPosition('r',r0+1);
cellArray[3].setPosition('c',c0);
direction = east;
}
}else if(direction == east){
if(c0 + 1 < 11 &&
bd->getType(r0 + 1, c0) == 32 &&
bd->getType(r0 + 1, c0+1) == 32 &&
bd->getType(r0 + 2, c0+1) == 32){
cellArray[0].setPosition('r',r0+2);
cellArray[0].setPosition('c',c0+1);
cellArray[1].setPosition('r',r0+1);
cellArray[1].setPosition('c',c0+1);
cellArray[2].setPosition('r',r0+1);
cellArray[2].setPosition('c',c0);
cellArray[3].setPosition('r',r0+1);
cellArray[3].setPosition('c',c0-1);
direction = south;
}
}else if(direction == south){
if(r0 - 2 >= 0 &&
bd->getType(r0, c0-2) == 32 &&
bd->getType(r0, c0-1) == 32 &&
bd->getType(r0-2,c0-1) == 32){
cellArray[0].setPosition('r',r0);
cellArray[0].setPosition('c',c0-2);
cellArray[1].setPosition('r',r0);
cellArray[1].setPosition('c',c0-1);
cellArray[2].setPosition('r',r0-1);
cellArray[2].setPosition('c',c0-1);
cellArray[3].setPosition('r',r0-2);
cellArray[3].setPosition('c',c0-1);
direction = west;
}
}else if(direction == west){
if(c0 + 2 < 11 &&
bd->getType(r0-1, c0) == 32 &&
bd->getType(r0, c0+2) == 32){
cellArray[0].setPosition('r',r0-1);
cellArray[0].setPosition('c',c0);
cellArray[1].setPosition('r',r0);
cellArray[1].setPosition('c',c0);
cellArray[2].setPosition('r',r0);
cellArray[2].setPosition('c',c0+1);
cellArray[3].setPosition('r',r0);
cellArray[3].setPosition('c',c0+2);
direction = north;
}
}
}
//CounterClockWise
void JBlock::CounterClockWise(){
int r0 = cellArray[0].getPosition('r');
int c0 = cellArray[0].getPosition('c');
if(direction == north){
if(r0 - 1 >= 0 &&
bd->getType(r0- 1,c0+1) == 32 &&
bd->getType(r0,c0+1) == 32){
cellArray[0].setPosition('r',r0+1);
cellArray[0].setPosition('c',c0);
cellArray[1].setPosition('r',r0+1);
cellArray[1].setPosition('c',c0+1);
cellArray[2].setPosition('r',r0);
cellArray[2].setPosition('c',c0+1);
cellArray[3].setPosition('r',r0-1);
cellArray[3].setPosition('c',c0+1);
direction = west;
}
}else if(direction == east){
if(c0 + 1 < 11 &&
bd->getType(r0 + 2, c0) == 32 &&
bd->getType(r0 + 2, c0 + 1) == 32){
cellArray[0].setPosition('r',r0+1);
cellArray[0].setPosition('c',c0-1);
cellArray[1].setPosition('r',r0+2);
cellArray[1].setPosition('c',c0-1);
cellArray[2].setPosition('r',r0+2);
cellArray[2].setPosition('c',c0);
cellArray[3].setPosition('r',r0+2);
cellArray[3].setPosition('c',c0+1);
direction = north;
}
}else if(direction == south){
if(r0 - 2 >= 0 &&
bd->getType(r0-2, c0-2) == 32 &&
bd->getType(r0-2, c0-1) == 32 &&
bd->getType(r0, c0-2) == 32){
cellArray[0].setPosition('r',r0-2);
cellArray[0].setPosition('c',c0-1);
cellArray[1].setPosition('r',r0-2);
cellArray[1].setPosition('c',c0-2);
cellArray[2].setPosition('r',r0-1);
cellArray[2].setPosition('c',c0-2);
cellArray[3].setPosition('r',r0);
cellArray[3].setPosition('c',c0-2);
direction = east;
}
}else if(direction == west){
if(c0 + 2 < 11 &&
bd->getType(r0-1, c0) == 32 &&
bd->getType(r0-1, c0+2) == 32 &&
bd->getType(r0, c0+2) == 32){
cellArray[0].setPosition('r',r0);
cellArray[0].setPosition('c',c0+2);
cellArray[1].setPosition('r',r0-1);
cellArray[1].setPosition('c',c0+2);
cellArray[2].setPosition('r',r0-1);
cellArray[2].setPosition('c',c0+1);
cellArray[3].setPosition('r',r0-1);
cellArray[3].setPosition('c',c0);
direction = south;
}
}
}
//getShape
string JBlock::getShape(){
return "J\nJJJ";
}
| true |
975edc8bef2bff9be2665df2b55e2efaa220e4d6 | C++ | shashankch/DataStructures-Algorithms | /balancedparanthesestack.cpp | UTF-8 | 690 | 3.625 | 4 | [] | no_license |
#include <iostream>
#include <stack>
#include <cstring>
using namespace std;
int main()
{
char str[100];
cin >> str;
stack<char> stk;
for (int i = 0; str[i] != '\0'; i++)
{
if (str[i] == '(')
{
stk.push(str[i]);
}
else if (str[i] == ')')
{
if (stk.empty() || stk.top() != '(')
{
cout << "not balanced";
break;
}
else
{
stk.pop();
}
}
}
if (stk.empty())
{
cout << "bracket are balanced";
}
else
{
cout << "not balanced";
}
return 0;
}
| true |
8285a97bd65e9314b02463f43db8a322bf4e5f72 | C++ | sean-dougherty/cuda-edu | /dev/tests/guard/main.cpp | UTF-8 | 6,401 | 2.515625 | 3 | [] | no_license | #define EDU_CUDA_ERR_THROW
#include <eduguard.h>
using namespace std;
using namespace edu;
using namespace edu::guard;
#define expect_fail(stmt) try {stmt; cerr << __FILE__ << ":" << __LINE__ << ": Expected failure" << endl; abort();} catch(...){}
//---
//--- 1D Arrays
//---
void test_array() {
const int N = 20;
float x[N];
array1_guard_t<float, N> gx;
assert(sizeof(x) == sizeof(gx));
for(int i = 0; i < N; i++) {
x[i] = i;
gx[i] = i;
}
for(int i = 0; i < N; i++) {
assert(x[i] == gx[i]);
}
for(int i = 0; i < N; i++) {
x[i] *= 2;
gx[i] *= 2;
}
for(int i = 0; i < N; i++) {
assert(x[i] == gx[i]);
}
for(int i = 0; i < N; i++) {
x[i] *= 10;
}
memcpy(gx, x, sizeof(gx));
for(int i = 0; i < N; i++) {
assert(x[i] == gx[i]);
}
for(int i = 0; i < N; i++) {
assert( *(gx + i) == *(x + i) );
}
expect_fail(gx[-1]);
expect_fail(gx[N]);
expect_fail(gx - 1);
expect_fail(gx + N);
}
//---
//--- 2D Arrays
//---
void test_array2() {
const int M = 30;
const int N = 20;
float x[M][N];
array2_guard_t<float, M, N> gx;
assert(sizeof(x) == sizeof(gx));
#define __foreach(stmt) \
for(int i = 0; i < M; i++) { \
for(int j = 0; j < N; j++) { \
stmt; \
} \
}
#define __cmp() __foreach(assert(x[i][j] == gx[i][j]));
__foreach(x[i][j] = 1 + i*j; gx[i][j] = 1 + i*j);
__cmp();
__foreach(x[i][j] *= 2; gx[i][j] *= 2);
__cmp();
__foreach(x[i][j] /= 3);
__foreach(gx[i][j] = x[i][j]);
__cmp();
__foreach(gx[i][j] /= 3);
__foreach(x[i][j] = gx[i][j]);
__cmp();
__foreach(gx[i][j] += 100);
memcpy(x, gx, sizeof(gx));
__cmp();
#undef __foreach
#undef __cmp
expect_fail(gx[-1]);
expect_fail(gx[M]);
expect_fail(gx[0][-1]);
expect_fail(gx[0][N]);
}
//---
//--- 3D Arrays
//---
void test_array3() {
const int M = 30;
const int N = 20;
const int O = 10;
float x[M][N][O];
array3_guard_t<float, M, N, O> gx;
assert(sizeof(x) == sizeof(gx));
#define __foreach(stmt) \
for(int i = 0; i < M; i++) { \
for(int j = 0; j < N; j++) { \
for(int k = 0; k < O; k++) { \
stmt; \
} \
} \
}
#define __cmp() __foreach(assert(x[i][j][k] == gx[i][j][k]));
__foreach(x[i][j][k] = 1 + i*j*k; gx[i][j][k] = 1 + i*j*k);
__cmp();
__foreach(x[i][j][k] *= 2; gx[i][j][k] *= 2);
__cmp();
__foreach(x[i][j][k] /= 3);
__foreach(gx[i][j][k] = x[i][j][k]);
__cmp();
__foreach(gx[i][j][k] /= 3);
__foreach(x[i][j][k] = gx[i][j][k]);
__cmp();
__foreach(gx[i][j][k] += 100);
memcpy(x, gx, sizeof(gx));
__cmp();
#undef __foreach
#undef __cmp
expect_fail(gx[-1]);
expect_fail(gx[M]);
expect_fail(gx[0][-1]);
expect_fail(gx[0][N]);
expect_fail(gx[0][0][-1]);
expect_fail(gx[0][0][N]);
}
//---
//--- Pointers
//---
void test_ptr() {
const size_t N = 100;
ptr_guard_t<float> gp = (float*)mem::alloc(mem::MemorySpace_Host, N * sizeof(float));
float *p = new float[100];
expect_fail(gp[-1] = 0);
expect_fail(gp[N] = 0);
#define __foreach(stmt) for(size_t i = 0; i < N; i++) {stmt;}
#define __cmp() __foreach(assert(p[i] == gp[i]));
__foreach(p[i] = i+1; gp[i] = i+1);
__cmp();
float *tp = p;
ptr_guard_t<float> tgp = gp;
expect_fail(tgp[N] = 0);
expect_fail(tgp[-1] = 0);
__foreach(assert(*tp++ == *tgp++));
tgp = gp + N - 1;
expect_fail(*++tgp);
tp = p - 1;
tgp = gp - 1;
__foreach(assert(*++tp == *++tgp));
tp = p;
tgp = gp;
tp = p + 2;
tgp = tgp + 2;
assert(*tp == *tgp);
tp += 2;
tgp += 2;
assert(*tp == *tgp);
tp -= 2;
tgp -= 2;
assert(*tp == *tgp);
expect_fail(*(gp + N));
expect_fail(*(gp - 1));
#undef __foreach
#undef __cmp
}
void __malloc(void ** p, unsigned len) {
*p = mem::alloc(mem::MemorySpace_Host, len);
}
void test_cudaMalloc() {
const unsigned N = 10;
ptr_guard_t<float> p;
__malloc((void**)&p, sizeof(float)*N);
assert(p.buf.addr == p.ptr);
assert(p.buf.space == mem::MemorySpace_Host);
for(size_t i = 0; i < N; i++)
p[i] = i;
assert(p.buf.space == mem::MemorySpace_Host);
expect_fail(p[-1]);
expect_fail(p[N]);
}
void test_write_callback() {
clear_write_callback();
clear_write_callback();
function<void()> noop = [](){};
set_write_callback(noop);
clear_write_callback();
set_write_callback(noop);
clear_write_callback();
clear_write_callback();
set_write_callback(noop);
expect_fail(set_write_callback(noop));
clear_write_callback();
{
int ncallback = 0;
function<void()> inc = [&ncallback]() {ncallback++;};
set_write_callback(inc);
const unsigned N = 10;
array1_guard_t<unsigned, N> x;
for(unsigned i = 0; i < N; i++) {
x[i] = i;
}
assert(ncallback == N);
ncallback = 0;
for(unsigned i = 0; i < N; i++) {
assert(x[i] == i);
}
assert(ncallback == 0);
clear_write_callback();
}
{
int ncallback = 0;
function<void()> inc = [&ncallback]() {ncallback++;};
set_write_callback(inc);
const unsigned N = 10;
ptr_guard_t<unsigned> x = (unsigned *)mem::alloc(mem::MemorySpace_Host, N * sizeof(unsigned));
for(unsigned i = 0; i < N; i++) {
x[i] = i;
}
assert(ncallback == N);
ncallback = 0;
for(unsigned i = 0; i < N; i++) {
assert(x[i] == i);
}
assert(ncallback == 0);
clear_write_callback();
mem::dealloc(mem::MemorySpace_Host, x);
}
}
int main(int argc, const char **argv) {
test_array();
test_array2();
test_array3();
test_ptr();
test_cudaMalloc();
test_write_callback();
cout << "--- Passed guard tests ---" << endl;
return 0;
}
| true |
7ac62770690d1485f04a68d1d4c00ba85dc9f8f5 | C++ | naoki-cpp/LittleWars | /LittleWars/include/Task.h | SHIFT_JIS | 537 | 2.609375 | 3 | [] | no_license | #pragma once
class Task
{
public:
virtual ~Task()
{}
//
virtual void Initialize(){} //͎ĂȂĂ
//㏈
virtual void Finalize() {} //I͎ĂȂĂ
//t[Ăяo
virtual void Update() = 0; //XV͕KpŎ
//`揈
virtual void Draw()const = 0; //`揈͕KpŎ
protected:
Task(){};
private:
Task(Task&);//Öٕϊ̋֎~
};
| true |
99e0524ebd68e4cf5fb29a32ce4d6e5cfd472467 | C++ | lovms/code_snippets | /leetcode_solutions/curated_top_100/list/20201213_19_Remove_Nth_Node_From_End_of_List_20201201.cpp | UTF-8 | 3,960 | 3.3125 | 3 | [
"MIT"
] | permissive | //Given the head of a linked list, remove the nth node from the end of the list and return its head.
//
//Follow up: Could you do this in one pass?
//
//
//
//Example 1:
//
//
//Input: head = [1,2,3,4,5], n = 2
//Output: [1,2,3,5]
//Example 2:
//
//Input: head = [1], n = 1
//Output: []
//Example 3:
//
//Input: head = [1,2], n = 1
//Output: [1]
//
//
//Constraints:
//
//The number of nodes in the list is sz.
//1 <= sz <= 30
//0 <= Node.val <= 100
//1 <= n <= sz
//通过次数289,367提交次数713,169
//
//来源:力扣(LeetCode)
//链接:https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list
//著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
// 思路:
// 常用的List数据结构中的trick,一次遍历找到距离末尾距离n的节点,
// 使用双指针,先固定好它们之间的距离,然后同时往后迭代,直到第二个
// 指针达到了nullptr。
// 题目中给了很多限定,包括距离一定小于list的长度 ,所以很多边界条件
// 都不需要处理了,否则边界条件才是这类问题最大的难点,稍有不慎,就会访问
// 空指针,从而出core
#include <iostream>
#include <vector>
using std::vector;
/**
* Definition for singly-linked list.*/
struct ListNode {
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
/**/
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* previous = head;
ListNode* p1 = head->next;
ListNode* p2 = head->next;
while (n-- > 0) {
p2 = p2->next;
}
while (p2 != nullptr) {
previous = p1;
p1 = p1->next;
p2 = p2->next;
}
// delete p1
previous->next = p1->next;
delete p1;
return head;
}
};
/*
* 这是AC的版本,head就是第一个List节点的指针
* 而不像上面的那个版本,head是头,head->next才是真正的第一个节点
*
* 所以在处理删除第一个节点上,需要注意,是不是删除了head节点,
*
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* previous = head;
ListNode* p1 = head;
ListNode* p2 = head;
while (n-- > 0) {
p2 = p2->next;
}
while (p2 != nullptr) {
previous = p1;
p1 = p1->next;
p2 = p2->next;
}
// delete p1
if (p1 == head) { //要删除头节点了,所以赶紧转移
head = p1->next;
} else {
previous->next = p1->next;
}
delete p1;
return head;
}
};
*/
class List {
public:
List() : head(new ListNode(0)) {}
void buildListFromVec(vector<int>& input) {
for (int i = input.size()-1; i>=0; --i) {
ListNode* nd = new ListNode(input[i]);
nd->next = head->next;
head->next = nd;
head->val++;
}
}
static void printList(List& l) {
ListNode* p = l.head->next;
while (p!=nullptr) {
std::cout << p->val << " ";
p = p->next;
}
std::cout << std::endl;
}
void destroyList() {
ListNode* p = head;
ListNode* q = p->next;
while (p!=nullptr) {
delete p;
p = q;
q = q->next;
}
}
public:
ListNode* head;
};
int main() {
// case 1:
//vector<int> nums = {1,2,3,4,5};
//int n = 2;
// case 2:
//vector<int> nums = {1};
//int n = 1;
// case 3:
vector<int> nums = {1,2};
int n = 1;
List l;
l.buildListFromVec(nums);
List::printList(l);
Solution s;
s.removeNthFromEnd(l.head, n);
ListNode* p = l.head->next;
while (p!=nullptr) {
std::cout << p->val << " ";
p = p->next;
}
std::cout << std::endl;
return 0;
}
| true |
45c5de297f67cc2a44e54a93f25a7b99946b2a8f | C++ | YASHGUPTA410/Algorithm | /linearSearch.cpp | UTF-8 | 894 | 3.984375 | 4 | [
"MIT"
] | permissive | //implementing linear search in an unsorted array
//It is an example of subtractive recursive/iterative algorithm
//as after every iteration size of an array decreases by 1
#include<iostream>
#include<stdlib.h>
using namespace std;
//time complexity O(n)
//searches recursively
int linearSearch(int a[], int low, int high, int key){
if (high<low){return -1;}
if(a[low]==key){return low;}
return linearSearch(a,low+1,high,key);
}
int main(){
int key,size;
// int a[]={1,2,3,4,7,5,6,10,0,-1};
// int size=sizeof(a)/sizeof(a[0]);
cout<<"Enter the size of an array ";
cin>>size;
cout<<"\nEnter the array elements :";
int a[size];
for(int i=0;i<size;i++){cin>>a[i];}
cout<<"\nEnter the element to be searched : ";
cin>>key;
int result=linearSearch(a,0,9,key);
if(result==-1){cout<<"No such element";}
else cout<<"Position of "<<key<<" is "<<result+1;
return 0;
}
| true |
b2bc0ae038048a2bbc7071f6f924c252d8b7a1fc | C++ | Manthan-R-Sheth/CodingHub | /gfg/Leaves.cpp | UTF-8 | 681 | 3.671875 | 4 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
struct treenode
{
int data;
struct treenode* left;
struct treenode* right;
};
struct treenode* newNode(int data)
{
struct treenode* node=(struct treenode*)malloc(sizeof(struct treenode));
node->left=NULL;
node->right=NULL;
node->data=data;
return node;
}
void leaves(struct treenode* root)
{
if(root->left==NULL && root->right==NULL)
{
cout<<root->data<<endl;
}
else
{
leaves(root->right);
leaves(root->left);
}
}
int main()
{
struct treenode* root=newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
leaves(root);
}
| true |
5e6687579a8cd6871538d27301bfccdd37d19771 | C++ | profeIMA/PID-UdG | /installation/Linux/sources/DrawFilledTriangle.h | UTF-8 | 1,871 | 3.453125 | 3 | [] | no_license | #ifndef DRAWFILLEDTRIANGLE_H
#define DRAWFILLEDTRIANGLE_H
#include "Drawable.h"
#include "RGBColor.h"
#include "Figures.h"
/** @brief Implementation of Drawable interface.
* This class is capable of storing the information of a filled triangle and represent it on a Window drawing the figure.
*/
#ifdef _WIN32
class DLL_EXPORT DrawFilledTriangle : public Drawable
#else
class DrawFilledTriangle : public Drawable
#endif
{
public:
/** Destructor of the class
*/
~DrawFilledTriangle() {};
/** One of the parametric constructors of the class.
* @param x1 X coordinate of the first point.
* @param y1 Y coordinate of the first point.
* @param x2 X coordinate of the second point.
* @param y2 Y coordinate of the second point.
* @param x3 X coordinate of the third point.
* @param y3 Y coordinate of the third point.
* @param color Color used to draw the triangle.
*/
DrawFilledTriangle(float x1, float y1, float x2, float y2, float x3, float y3, RGBColor color);
/** One of the parametric constructors of the class.
* @param p1 coordinates of the first point.
* @param p2 coordinates of the second point.
* @param p3 coordinates of the third point.
* @param color Color used to draw the triangle.
*/
DrawFilledTriangle(Point2D p1, Point2D p2, Point2D p3, RGBColor color);
/** Draws a filled triangle on the Window @p w.
* @param w Target Window to draw.
*/
void draw(Window & w);
protected:
/** Initializes the class.
* @param p1 coordinates of the first point.
* @param p2 coordinates of the second point.
* @param p3 coordinates of the third point.
* @param color Color used to draw the triangle.
*/
void init(Point2D p1, Point2D p2, Point2D p3, RGBColor color);
figures::Triangle triangle; /**< Figure containing all the information needed to draw the triangle.*/
RGBColor color; /**< Color of the triangle. */
};
#endif
| true |
2a9a616d20e8adb16c587adeeb0c9cc65886fb32 | C++ | lriki/Volkoff | /Sources/Object/Valfirle.h | SHIFT_JIS | 8,363 | 2.546875 | 3 | [] | no_license | //=============================================================================
/*!
@addtogroup
@file Valfirle.h
@brief @t@[wb_
@t@[pAI̒`
@attention -
@note -
@author Hi-ra Mizuno
@date 2012/02/15
@version 1.0.0
@par Copyright
Copyright (c) 2012 Valfirle Developer. All Rights Reserved.
===============================================================================
@par History
- 2012/02/15 Hi-ra Mizuo
-# 쐬
*/
//=============================================================================
//Include Guard
#ifndef __INCLUDE_VALFIRLE_H__
#define __INCLUDE_VALFIRLE_H__
/*! @par include */
#include "./Character.h"
#include "Enemy.h"
/*! @par global */
//Փxpϐ //Easy,Normal,Hard,Valfirle
static const bool scg_bValfirleAttack1Permission[] = {true,true,true,true}; //U1iڂo邩ǂ
static const bool scg_bValfirleAttack2Permission[] = {true,true,true,true}; //U2iڂo邩ǂ
static const bool scg_bValfirleAttack3Permission[] = {true,true,true,true}; //U3iڂo邩ǂ
static const int scg_nValfirleAttackRatio[] = {12,10,9,8}; //UJn䗦B10ł1/10ōUJn
static const int scg_nValfirleAttack2Ratio[] = {30,40,50,60}; //U2iڂs䗦B10ł9/10ōUJn
static const int scg_nValfirleAttack3Ratio[] = {30,40,50,60}; //U3iڂs䗦B10ł9/10ōUJn
static const int scg_nValfirleJumpAttackRatio[] = {4,4,4,4}; //WvUsB10ł1/10ŃWvUJn
static const int scg_nValfirleSquatAttackRatio[] = {4,4,4,4}; //ႪݍUsB10ł1/10łႪݍUJn
static const int scg_nValfirleStandbyRatio[] = {25,25,25,25}; //ώ@sB10ł1/10Ŋώ@Jn
static const int scg_nValfirleGuardRatio[] = {70,60,50,40}; //hsB10ł1/10ŖhJn
static const int scg_nValfirleSquatGuardRatio[] = {100,90,85,80}; //ႪݖhsB10ł1/10ŖhJn
static const int scg_nValfirleSquatRatio[] = {50,50,50,50}; //Ⴊ݂s
static const int scg_nValfirleJumpRatio[] = {30,30,30,30}; //Wvs
static const int scg_nValfirleEscapeRatio[] = {20,20,20,20}; //s
static const int scg_nValfirleLife[] = {1200,1200,1200,1200}; //̗
static const int scg_nValfirleLifePhase2[] = {500,700,750,800}; //iKɓHP
/*! @class Valfirle */
class Valfirle : public Character
{
public:
struct CreateData
{
LVector3 Position;
LVector3 Velocity;
u32 WeaponType;
u32 WeaponLevel; ///< 탌x (1`3)
/// Ô߂̏l
CreateData()
: WeaponType ( WEAPON_NON )
, WeaponLevel ( 1 )
{}
};
protected:
static const int scm_nSearchX = 400; //XWT͈
static const int scm_nSearchY = 100; //YWT͈
static const int scm_nSearchRand = 10; //T͈͌덷
static const int scm_nWalkIntv = 0; //UԊut[
static const int scm_nWalkRange = 50; //U͈
static const int scm_nEscapeRange = 60; //͈
static const int scm_nStandbyRange = 200; //ώ@͈
static const int scm_nStandbyIntv = 60; //ώ@t[
static const int scm_nGuardIntv = 120; //ht[
EnemyAction m_eAction;
bool m_bCreateWeapon;
int m_nAttackDelay; //ݐύUfBC
int m_nRandAttackDelay; //_fBC
int m_nRandAttackRange; //_U͈
int m_nRandSearchRange; //_T͈
int m_nWalkIntvCnt; //U܂ł̗ݐσt[
int m_nWalkRangeCnt; //Uc
bool m_bWalkDir; //U
int m_nEscapeRangeCnt; //c
int m_nStandbyCnt; //ώ@ct[
int m_nGuardCnt; //hct[
int m_nSquatCnt; //Ⴊݎct[
u32 mExp; //|擾łol
int m_nPhase; //{X̒iK
int m_nNum[10]; //XNvggϐ
private:
/// RXgN^͎gpsBcreate() ō쐬邱ƁB
Valfirle();
bool SearchPlayer();
bool SearchAttack1Range();
bool SearchJumpAttackRange();
bool SearchAntiairAttackRange();
void ChangePhase();
public:
/// fXgN^
virtual ~Valfirle();
/// IuWFNg쐬 (Initialize() ͂̒ŌĂBʏAis_entity_ true ɂĂ)
static Valfirle* create( void* args_, bool is_entity_ = true );
static Valfirle* createRandom();
public:
//---------------------------------------------------------------------------
/*! @brief oQb^[ */
//---------------------------------------------------------------------------
const char* getName() const {return m_pszName;}
const CharaState& getCharaState() const {return m_eCharaState;}
const int& getAnimePuttern() const { return m_AnimePuttern; }
const CharaDir& getDirection() const {return m_eDirection;}
virtual ObjectType getObjType() const { return OBJ_ENEMY; }
const int getPhase() const {return this->m_nPhase;}
const int getNum(int nElm_) const {return this->m_nNum[nElm_];}
/// ̕탌x̎擾
virtual u32 getWeaponLevel() const { return mWeaponLevel; }
virtual u32 getExp() const { return mExp; }
//---------------------------------------------------------------------------
/*! @brief oZb^[ */
//---------------------------------------------------------------------------
void setNum(int nElm_,int nNum_) {this->m_nNum[nElm_] = nNum_;}
//---------------------------------------------------------------------------
/*!
@brief Valfirle::Initialize
@param[in] void
@return bool
- true
- false s
@exception none
*/
//---------------------------------------------------------------------------
bool Initialize( const CreateData& data_ );
//---------------------------------------------------------------------------
/*!
@brief Valfirle::Release
I
@param[in] void
@return bool
- true
- false s
@exception none
*/
//---------------------------------------------------------------------------
bool Release();
//---------------------------------------------------------------------------
/*!
@brief Valfirle::Update
t[XV
@param[in] void
@return bool
@exception none
*/
//---------------------------------------------------------------------------
virtual bool Update();
/// t[XV (IuWFNgɉe^鏈)
virtual bool UpdateSelf();
//---------------------------------------------------------------------------
/*!
@brief Valfirle::HandleEvent
Cxg
@param[in] EventType event_ Cxg^Cv
@param[in] void *args_ f[^(KɃLXg)
@return void
@exception none
*/
//---------------------------------------------------------------------------
virtual int HandleEvent(u32 event_,void *args_);
protected:
Character* mTargetCharacter; ///< UΏ
u32 mWeaponLevel; ///< 탌x (Ɏw)
};
//End of Include Guard
#endif
//=============================================================================
// End of File
//=============================================================================
| true |
63e156367aa3c2e36cb487d7f9e68595e0369500 | C++ | muzigef/Play-with-Algorithms | /02-Sorting-Basic/01-Selection-Sort/main.cpp | UTF-8 | 280 | 3.046875 | 3 | [] | no_license | #include <iostream>
#include "selectionSort.h"
using namespace std;
int main() {
int arr[] = { 4, 1, 6, 3, 7, 2, 8 };
selectionSort(arr, 7);
for (int i = 0; i < 7; i++) {
cout << arr[i] << " ";
}
cout << endl;
system("pause");
return 0;
}
| true |
6e26e5852028fc96d559c7332596e5f044246c03 | C++ | marcoStocchi/DSPX_Fast_wavelet_transform_assisted_predictors_of_streaming_time_series | /DSPX_financial_convert.h | UTF-8 | 4,106 | 2.625 | 3 | [
"MIT"
] | permissive | // Copyright (c) <2016> <Marco Stocchi, UNICA>
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#pragma once
namespace convert
{
// time format conversions
template <class char_type>
struct time_format_t
{
typedef std::basic_string<char_type> string_type;
typedef std::basic_istringstream<char_type> istringstream_type;
typedef std::basic_ostringstream<char_type> ostringstream_type;
typedef std::chrono::system_clock::time_point time_point_type;
time_format_t(const time_t& _T, const int& _Dst = -1) : _t(_T)
{
//gmtime_s(&_tm, &_T); // UTC
localtime_s(&_tm, &_T);
_tm.tm_isdst = _Dst;
}
time_format_t(const int& _Year, const int& _Mon, const int& _Day,
const int& _Hour, const int& _Min, const int& _Sec = 0,
const int& _Dst = -1)
{
_tm.tm_sec = _Sec;
_tm.tm_min = _Min;
_tm.tm_hour = _Hour;
_tm.tm_mday = _Day;
_tm.tm_mon = _Mon - 1;
_tm.tm_year = _Year - 1900;
_tm.tm_isdst = _Dst;
_t = std::mktime(&_tm);
}
time_format_t(const string_type& _DaytimeGroup)
{// eg."2016.11.27 09:40"
*this = _DaytimeGroup;
}
void operator = (const string_type& _DaytimeGroup)
{// assign new daytime
istringstream_type iss(_DaytimeGroup);
iss >> _tm.tm_year; _tm.tm_year -= 1900;
iss.ignore(1); iss >> _tm.tm_mon; _tm.tm_mon -= 1;
iss.ignore(1); iss >> _tm.tm_mday;
iss.ignore(1); iss >> _tm.tm_hour;
iss.ignore(1); iss >> _tm.tm_min;
_tm.tm_sec = 0;
_tm.tm_isdst = -1;
_t = std::mktime(&_tm);
}
// query
auto year() const ->int { return 1900 + _tm.tm_year; }
auto month() const ->int { return 1 + _tm.tm_mon; }
auto day() const ->int { return _tm.tm_mday; }
auto hours() const ->int { return _tm.tm_hour; }
auto minutes() const ->int { return _tm.tm_min; }
auto seconds() const ->int { return _tm.tm_sec; }
auto week_day() const ->int { return _tm.tm_wday; /*sunday==0*/ }
// test
bool operator == (const time_format_t& _TS) const { return _t == _TS._t; }
bool operator != (const time_format_t& _TS) const { return _t != _TS._t; }
// conversions
auto to_datetime() const ->string_type
{
ostringstream_type x;
x << std::setfill(x.widen('0'));
x << year() << "."
<< std::setw(2) << month() << "."
<< std::setw(2) << day() << " "
<< std::setw(2) << hours() << ":"
<< std::setw(2) << minutes();
return x.str();
}
auto to_date() const ->string_type
{
ostringstream_type x;
x << std::setfill(x.widen('0'));
x << year() << "."
<< std::setw(2) << month() << "."
<< std::setw(2) << day();
return x.str();
}
auto to_time() const ->string_type
{
ostringstream_type x;
x << std::setfill(x.widen('0'));
x << std::setw(2) << hours() << ":"
<< std::setw(2) << minutes();
return x.str();
}
auto to_unix_time() const ->time_t { return _t; }
auto to_chrono_time_point() const ->time_point_type { return std::chrono::system_clock::from_time_t(_t); }
private:
time_t _t;
tm _tm;
};
typedef time_format_t<char> time_string;
typedef time_format_t<wchar_t> time_wstring;
} | true |
797db952be8191bc8546b208c23e0bb9af5d1cd2 | C++ | CommunicoPublic/iris | /tags/iris-0.1.23/include/net/ClientTCPSocket.hpp | UTF-8 | 2,025 | 2.53125 | 3 | [] | no_license | /*-
* Copyright (c) Iris Dev. team. All rights reserved.
* See http://www.communico.pro/license for details.
*
*/
#ifndef _CLIENT_TCP_SOCKET_HPP__
#define _CLIENT_TCP_SOCKET_HPP__ 1
#include "TCPSocket.hpp"
namespace IRIS
{
/**
@class ClientTCPSocket ClientTCPSocket.hpp <ClientTCPSocket.hpp>
@brief Base client TCP socket class
*/
class ClientTCPSocket:
public TCPSocket
{
public:
/**
@brief Constructor
*/
ClientTCPSocket(const bool bICheckTCPInfo = true);
/**
@brief Get client IP
*/
virtual CCHAR_P GetPath() const;
/**
@brief Get client IP
*/
virtual CCHAR_P GetIP() const;
/**
@brief Get client Port
*/
virtual UINT_32 GetPort() const;
/**
@brief Read from socket
@param vBuffer - destination buffer
@param iBufferSize - max buffer size
@param iReadBytes - number of bytes actually read
@return OK - if success, ERROR - if some error occured, TIMEOUT - if timeout reached
*/
virtual TCPSocket::State Read(void * vBuffer,
const UINT_64 iBufferSize,
UINT_64 & iReadBytes);
/**
@brief Write to socket
@param vBuffer - source buffer
@param iBufferSize - buffer size
@param iWroteBytes - number of written bytes
@return OK - if success, ERROR - if some error occured, TIMEOUT - if timeout reached
*/
virtual TCPSocket::State Write(const void * vBuffer,
const UINT_64 iBufferSize,
UINT_64 & iWroteBytes);
/**
@brief Check socket support SSL/TLS
@return true, it socket supports SSL/TLS
*/
virtual bool IsSSL() const;
/**
@brief A virtual destructor
*/
virtual ~ClientTCPSocket() throw();
protected:
// Does not exist
ClientTCPSocket(const ClientTCPSocket & oRhs);
ClientTCPSocket & operator=(const ClientTCPSocket & oRhs);
/** Check TCP info flag, if applicable */
const bool bCheckTCPInfo;
};
} // namespace IRIS
#endif // _CLIENT_TCP_SOCKET_HPP__
// End.
| true |
e284c44dfa911aca1bba6f7835ae5e1872c2fdf3 | C++ | arjun-krishna/Graph-Coloring | /color.cpp | UTF-8 | 2,864 | 3.453125 | 3 | [] | no_license | /*
* NAME : col.cpp
* AUTHOR : Arjun Krishna
* usage : ./[prog_name] filename N
* "filename" contains data in edge List format
* N is the number of vertices in the Graph represented in "filename"
* NOTE : vertices labeled from 0 to N-1 should be in filename
and it won't be checked in this code.
*/
#include <iostream>
#include <fstream>
#include <cstdio>
#include <cstdlib>
#include <list>
#include <map>
using namespace std;
// GLOBAL VARIABLES
int N; // N -- Number of Vertices --> argv[2]
ifstream edge;
//
class Graph
{
// Parameters
int V; // no. of vertices
list <int> * adj; // adjacency List
map <int,int> * xCol; // A List to note what colors can't be used to color a particular vertex
map <int,int> col; //vertex number to color used map
int colors; // number od colors used
int * deg; //array to store degree
multimap <int,int> deg_ver; // for sorting degree
int* ver_order;
public:
Graph(int V,char* fname) //contructor
{
this->V = V;
adj = new list<int> [V];
xCol = new map<int,int> [V];
deg = (int*) malloc(sizeof(int)*V);
deg_ver.clear();
for(int i = 0;i<V;i++)
deg[i] = 0;
colors = 0;
readGraph(fname);
for(int i=0;i<V;i++)
deg_ver.insert(make_pair(deg[i],i));
ver_order = (int*) malloc(sizeof(int)*V);
}
void addEdge(int a,int b) //Add edge a,b to the Graph
{
adj[a].push_back(b);
adj[b].push_back(a);
}
void readGraph(char* fname)
{
edge.open(fname);
int a,b;
while(edge>>a>>b)
{
addEdge(a,b);
(deg[a])++;
(deg[b])++;
}
edge.close();
}
void rmVertex(int x,int c) //Remove vertex number x which shall be colored with c
{
while(!adj[x].empty())
{
xCol[adj[x].back()].insert(make_pair(c,c));
adj[x].pop_back();
}
col[x] = c;
}
int colMin(int x) // min Color needed to color vertex number x
{
map<int,int>::iterator itr;
if(xCol[x].empty()) return 1;
else
{
int i = 1;
for(itr = xCol[x].begin() ; itr!=xCol[x].end() ; itr++)
{
if((itr->first) != i)
return i;
i++;
}
return i;
}
}
void vertexOrder()
{
multimap<int,int>::reverse_iterator itr;
int i =0;
for(itr = deg_ver.rbegin(); itr != deg_ver.rend() ; itr++)
ver_order[i++] = itr->second;
}
void colorGraph() // coloring algorithm
{
int c;
vertexOrder();
for(int i = 0 ; i<V ; i++)
{
c = colMin(ver_order[i]);
if( c > colors) colors = c;
rmVertex(ver_order[i],c);
}
}
void printColoring() //prints the coloring
{
map<int,int>::iterator itr;
cout << "Colors Used : "<<colors <<endl;
for(itr = col.begin(); itr!= col.end(); itr++)
cout << itr->first << " " <<itr->second<<endl;
}
};
/**MAIN**/
int main(int argc,char* argv[])
{
if(argc!=3) { cerr<<"Usage : ./color fileName N "<<endl;return 0;}
N = atoi(argv[2]);
Graph G(N,argv[1]);
G.colorGraph();
G.printColoring();
return 0;
}
| true |
f9d4f9c2748b328a1af0d946981d88302e77c8b0 | C++ | voltrevo/vortex | /src/vm/Array.cpp | UTF-8 | 10,401 | 3.484375 | 3 | [] | no_license | #include <immer/flex_vector_transient.hpp>
#include "Array.hpp"
#include "LexOrder.hpp"
#include "Object.hpp"
#include "Value.hpp"
namespace Vortex {
void TransientInsert(
immer::flex_vector_transient<Value>& arr,
Uint64 pos,
Value&& val
) {
auto p = arr.persistent().insert(pos, val);
arr = p.transient();
}
bool Array::operator==(const Array& right) const {
if (!isFunctionless() || !right.isFunctionless()) {
throw TypeError("== on arrays that contain functions");
}
if (ArrayTypeOrderUnchecked(*this, right) != 0) {
throw TypeError("== on arrays of different (deep) types");
}
return ArrayValueOrderUnchecked(*this, right) == 0;
}
bool Array::operator<(const Array& right) const {
if (!isFunctionless() || !right.isFunctionless()) {
throw TypeError("< on arrays that contain functions");
}
if (ArrayTypeOrderUnchecked(*this, right) != 0) {
throw TypeError("< on arrays of different (deep) types");
}
return ArrayValueOrderUnchecked(*this, right) < 0;
}
int ArrayTypeOrderUnchecked(const Array& left, const Array& right) {
return lexContainerOrder(left.values, right.values, TypeOrderUnchecked);
}
int ArrayValueOrderUnchecked(const Array& left, const Array& right) {
return lexContainerOrder(left.values, right.values, ValueOrderUnchecked);
}
bool Array::isFunctionless() const {
for (const Value& el: values) {
if (!el.isFunctionless()) {
return false;
}
}
return true;
}
void Array::pushBack(Value&& value) {
values.push_back(std::move(value));
}
void Array::pushFront(Value&& value) {
auto p = values.persistent().push_front(std::move(value));
values = p.transient();
}
void Array::update(Uint64 i, Value&& value) {
values.set(i, std::move(value));
}
Value Array::at(Uint64 i) const {
if (i >= values.size()) {
throw BadIndexError("Attempt to index past the end of an array");
}
return values[i];
}
bool Array::hasIndex(Uint64 i) const {
return i < values.size();
}
void Array::concat(Array&& right) {
values.append(std::move(right.values));
}
void Array::plus(const Array& right) {
auto len = Length();
if (len != right.Length()) {
throw TypeError("Length mismatch in Array + Array");
}
auto rightIter = right.values.begin();
for (auto i = 0ul; i < len; ++i) {
values.update(
i,
[&](Value&& v) {
BinaryOperators::plus(v, *rightIter);
return v;
}
);
++rightIter;
}
}
void Array::minus(const Array& right) {
auto len = Length();
if (len != right.Length()) {
throw TypeError("Length mismatch in Array - Array");
}
auto rightIter = right.values.begin();
for (auto i = 0ul; i < len; ++i) {
values.update(
i,
[&](Value&& v) {
BinaryOperators::minus(v, *rightIter);
return v;
}
);
++rightIter;
}
}
void Array::multiply(const Value& right) {
if (right.type == ARRAY) {
multiplyArray(*right.data.ARRAY);
return;
}
if (right.type == OBJECT) {
multiplyObject(*right.data.OBJECT);
return;
}
if (!isNumeric(right.type)) {
throw TypeError("Attempt to multiply Array by invalid type");
}
auto len = values.size();
for (auto i = 0ul; i < len; i++) {
values.update(
i,
[&](Value&& v) {
BinaryOperators::scalarMultiply(v, right);
return v;
}
);
}
}
void Array::multiplyArray(const Array& right) {
Uint64 innerLength = InnerLength();
if (innerLength != right.Length()) {
throw TypeError("Incompatible dimensions for matrix multiplication");
}
auto rightIter = right.values.begin();
auto rightEnd = right.values.end();
if (rightIter == rightEnd) {
throw TypeError("Can't multiply by empty array");
}
immer::flex_vector_transient<Value> matrix;
if (rightIter->type == ARRAY) {
Uint64 rightInnerLength = right.InnerLength();
Uint64 len = Length();
for (auto i = 0ul; i < len; ++i) {
const Value& v = values[i];
Array& leftRow = *v.data.ARRAY;
immer::flex_vector_transient<Value> row;
for (auto j = 0ul; j < rightInnerLength; ++j) {
Value sum = leftRow.values[0];
BinaryOperators::multiply(sum, Value(right.values[0].data.ARRAY->values[j]));
for (auto inner = 1ul; inner < innerLength; ++inner) {
Value product = leftRow.values[inner];
BinaryOperators::multiply(product, Value(right.values[inner].data.ARRAY->values[j]));
BinaryOperators::plus(sum, std::move(product));
}
row.push_back(std::move(sum));
}
matrix.push_back(Value(new Array{.values = std::move(row)}));
}
values = std::move(matrix);
return;
}
if (rightIter->type == OBJECT) {
Array rightInnerKeys = right.InnerKeys();
Uint64 rightInnerKeyLen = rightInnerKeys.Length();
Uint64 len = Length();
for (auto i = 0ul; i < len; ++i) {
const Value& v = values[i];
Array& leftRow = *v.data.ARRAY;
immer::flex_vector_transient<Value> row;
for (auto j = 0ul; j < rightInnerKeyLen; ++j) {
Value sum = leftRow.values[0];
BinaryOperators::multiply(sum, Value(right.values[0].data.OBJECT->values.values[j]));
for (auto inner = 1ul; inner < innerLength; ++inner) {
Value product = leftRow.values[inner];
BinaryOperators::multiply(
product,
Value(right.values[inner].data.OBJECT->values.values[j])
);
BinaryOperators::plus(sum, std::move(product));
}
row.push_back(std::move(sum));
}
matrix.push_back(Value(new Object{
.keys = rightInnerKeys,
.values = Array{.values = std::move(row)}
}));
}
values = std::move(matrix);
return;
}
throw TypeError("Can't matrix multiply with rhs that lacks inner dimension");
}
void Array::multiplyObject(const Object& right) {
Array innerKeys = InnerKeys();
if (!(innerKeys == right.keys)) {
throw TypeError("Incompatible dimensions for matrix multiplication");
}
auto rightIter = right.values.values.begin();
auto rightEnd = right.values.values.end();
if (rightIter == rightEnd) {
throw TypeError("Can't multiply by empty object");
}
auto innerKeyLen = innerKeys.Length();
immer::flex_vector_transient<Value> matrix;
if (rightIter->type == ARRAY) {
Uint64 rightInnerLength = right.InnerLength();
Uint64 len = Length();
for (auto i = 0ul; i < len; ++i) {
const Value& v = values[i];
Object& leftRow = *v.data.OBJECT;
immer::flex_vector_transient<Value> row;
for (auto j = 0ul; j < rightInnerLength; ++j) {
Value sum = leftRow.values.values[0];
BinaryOperators::multiply(sum, Value(right.values.values[0].data.ARRAY->values[j]));
for (auto inner = 1ul; inner < innerKeyLen; ++inner) {
Value product = leftRow.values.values[inner];
BinaryOperators::multiply(
product,
Value(right.values.values[inner].data.ARRAY->values[j])
);
BinaryOperators::plus(sum, std::move(product));
}
row.push_back(std::move(sum));
}
matrix.push_back(Value(new Array{.values = std::move(row)}));
}
values = std::move(matrix);
return;
}
if (rightIter->type == OBJECT) {
Array rightInnerKeys = right.InnerKeys();
Uint64 rightInnerKeyLen = rightInnerKeys.Length();
Uint64 len = Length();
for (auto i = 0ul; i < len; ++i) {
const Value& v = values[i];
Object& leftRow = *v.data.OBJECT;
immer::flex_vector_transient<Value> row;
for (auto j = 0ul; j < rightInnerKeyLen; ++j) {
Value sum = leftRow.values.values[0];
BinaryOperators::multiply(
sum,
Value(right.values.values[0].data.OBJECT->values.values[j])
);
for (auto inner = 1ul; inner < innerKeyLen; ++inner) {
Value product = leftRow.values.values[inner];
BinaryOperators::multiply(
product,
Value(right.values.values[inner].data.OBJECT->values.values[j])
);
BinaryOperators::plus(sum, std::move(product));
}
row.push_back(std::move(sum));
}
matrix.push_back(Value(new Object{
.keys = rightInnerKeys,
.values = Array{.values = std::move(row)}
}));
}
values = std::move(matrix);
return;
}
throw TypeError("Can't matrix multiply with rhs that lacks inner dimension");
}
Uint64 Array::Length() const { return values.size(); }
Uint64 Array::InnerLength() const {
auto iter = values.begin();
auto end = values.end();
if (iter == end) {
throw TypeError("Assumed inner length of empty array");
}
if (iter->type != ARRAY) {
throw TypeError("Assumed inner length of array with non-array content");
}
Uint64 result = iter->data.ARRAY->Length();
++iter;
for (; iter != end; ++iter) {
if (iter->type != ARRAY) {
throw TypeError("Assumed inner length of array with non-array content");
}
if (iter->data.ARRAY->Length() != result) {
throw TypeError("Inconsistent inner length");
}
}
return result;
}
Array Array::InnerKeys() const {
auto iter = values.begin();
auto end = values.end();
if (iter == end) {
throw TypeError("Assumed inner keys of empty array");
}
if (iter->type != OBJECT) {
throw TypeError("Assumed inner keys of array with non-object content");
}
Array result = iter->data.OBJECT->keys;
++iter;
for (; iter != end; ++iter) {
if (iter->type != OBJECT) {
throw TypeError("Assumed inner keys of array with non-object content");
}
if (!(iter->data.OBJECT->keys == result)) {
throw TypeError("Inconsistent inner keys");
}
}
return result;
}
}
| true |
431b6fe8ea4f60fd919024457fbbde655e25f07a | C++ | alberiolima/Inspire-OpenLung-RCModelFirmware | /INSPIRE/INSPIRE/ARDUINO/MAIN/PRESSURE.ino | UTF-8 | 498 | 2.703125 | 3 | [
"MIT"
] | permissive | #define CmH20_0 207.0 //A0 val @0cmH2O
#define CmH2O_20 528.0 //A0 val @20cmH2O
#define PRESSURE_PIN A0
//Constants
const float deltaCmH2O = 20 / (CmH2O_20 - CmH20_0);
float PressureGet_cmH2O()
{
float Pressure = (float) analogRead(PRESSURE_PIN ) - CmH20_0;
return (deltaCmH2O * Pressure);
}
int PressureGet_raw()
{
return analogRead(PRESSURE_PIN );
}
float PressureRaw2CmH2O(int RawPress)
{
float Pressure = (float) RawPress - CmH20_0;
return (deltaCmH2O * Pressure);
}
| true |
9eed5524fdb68a0555f80452bcdda49950285a01 | C++ | Koldar/pathfinding-utils | /src/main/include/operators.hpp | UTF-8 | 1,297 | 3.25 | 3 | [
"MIT"
] | permissive | #ifndef _PATHFINDING_UTILS_OPERATORS_HEADER__
#define _PATHFINDING_UTILS_OPERATORS_HEADER__
#include <cpp-utils/exceptions.hpp>
#include "types.hpp"
namespace pathfinding {
//TODO remove superseded by std::function. Remember to create a local variable of type std::function if you want to pass a lambda
/**
* @brief Generic template function used to fetch a `cost_t` from the label of an edge
*
* Specialize this for the type you wish to use. Here's an example of specialization:
*
* @code
* namespace pathfinding {
* template <>
* struct GetCost<MyAwesomeType> {
* cost_t operator() (const MyAwesomeType& label) const {
* return label.getCost();
* }
* };
* }
* @endcode
*
* The specialization is required to be put in pathfinding namespace
*
* @tparam E edge label type
*/
template <typename E>
struct GetCost {
cost_t operator ()(const E& label) {
throw cpp_utils::exceptions::NotYetImplementedException{"You need to specialize GetCost with your custom data"};
}
};
template <>
struct GetCost<cost_t> {
cost_t operator ()(const cost_t& label) const {
return label;
}
};
}
#endif | true |
bc63e12cda7de94ab37d88d1cf86e8022b786720 | C++ | wakare/Leviathan | /src/RuntimeAttributeWatcher/InternRuntimeAttribute.h | UTF-8 | 1,720 | 2.953125 | 3 | [
"MIT"
] | permissive | #pragma once
#include "RuntimeAttribute.h"
#include <sstream>
namespace Util
{
template <typename T>
class InternalAttribute : public RuntimeAttribute
{
public:
InternalAttribute(T value);
void SetName(const INTERN_STRING& name);
void SetDesc(const INTERN_STRING& desc);
void SetValue(const INTERN_STRING& value);
INTERN_STRING GetDesc() const;
INTERN_STRING GetName() const;
INTERN_STRING GetValue() const;
private:
T m_value;
INTERN_STRING m_name;
INTERN_STRING m_desc;
};
template<typename T>
inline InternalAttribute<T>::InternalAttribute(T value)
: m_value(value)
, m_desc(INTERN_STRING("Default desc."))
{
}
template <typename T>
void Util::InternalAttribute<T>::SetDesc(const INTERN_STRING& desc)
{
m_desc = desc;
}
template <typename T>
void Util::InternalAttribute<T>::SetName(const INTERN_STRING& name)
{
m_name = name;
}
template<typename T>
inline void InternalAttribute<T>::SetValue(const INTERN_STRING & value)
{
std::stringstream stream(value);
stream >> m_value;
}
template<typename T>
inline INTERN_STRING InternalAttribute<T>::GetDesc() const
{
return m_desc;
}
template <typename T>
INTERN_STRING Util::InternalAttribute<T>::GetName() const
{
return m_name;
}
template<typename T>
inline INTERN_STRING InternalAttribute<T>::GetValue() const
{
// TODO: Use internal defined value-stirng convert interface.
return std::to_string(m_value);
}
// Base internal typedef
typedef InternalAttribute<int> AttributeInt;
typedef InternalAttribute<long> AttributeLong;
typedef InternalAttribute<unsigned> AttributeUInt;
typedef InternalAttribute<float> AttributeFloat;
typedef InternalAttribute<double> AttributeDouble;
} | true |
51948c7f23a9f9e87f77c713ee891895b29c93a6 | C++ | atubo/online-judge | /luogu/P3143.cpp | UTF-8 | 2,257 | 2.828125 | 3 | [] | no_license | // https://www.luogu.org/problem/show?pid=3143
// [USACO16OPEN]钻石收藏家Diamond Collector
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 50010;
int N, K;
int A[MAXN], B[MAXN], C[MAXN], D[MAXN], E[MAXN], F[MAXN];
class BIT {
public:
// Note size needs to be power of 2
BIT(int size): N(size) {
tree = (int*)malloc((size+1) * sizeof(int));
clear();
}
~BIT() {
free(tree);
tree = NULL;
}
void clear() {
memset(tree, 0, (N+1) * sizeof(int));
}
// add v to value at x
void set(int x, int v) {
while(x <= N) {
tree[x] += v;
x += (x & -x);
}
}
// get cumulative sum up to and including x
int get(int x) const {
int res = 0;
while(x) {
res += tree[x];
x -= (x & -x);
}
return res;
}
// get result for [x, y]
int get(int x, int y) const {
return get(y) - (x > 1 ? get(x-1) : 0);
}
// get largest value with cumulative sum less than or equal to x;
// for smallest, pass x-1 and add 1 to result
int getind(int x) {
int idx = 0, mask = N;
while(mask && idx < N) {
int t = idx + mask;
if(x >= tree[t]) {
idx = t;
x -= tree[t];
}
mask >>= 1;
}
return idx;
}
private:
int* tree;
const int N;
};
int main() {
scanf("%d %d", &N, &K);
for (int i = 1; i <= N; i++) {
scanf("%d", &A[i]);
}
sort(A + 1, A + N + 1);
B[1] = A[1];
C[1] = 1;
int M = 0;
for (int p = 2, q = 1; p <= N; p++) {
if (B[q] == A[p]) {
C[q]++;
} else {
q++;
B[q] = A[p];
C[q] = 1;
}
M = q;
}
BIT ft(65536);
for (int i = 1; i <= M; i++) {
ft.set(i, C[i]);
}
for (int i = M; i >= 1; i--) {
int j = upper_bound(B+i, B+M+1, B[i] + K) - B;
D[i] = ft.get(i, j-1);
E[i] = max(E[i+1], D[i]);
F[i] = j;
}
int ret = 0;
for (int i = 1; i <= M; i++) {
ret = max(ret, D[i] + E[F[i]]);
}
printf("%d\n", ret);
return 0;
}
| true |
f5a5e9743cd75766a08d2175e47abcdf417d8f5c | C++ | madhavanrp/InfluenceMaximization | /InfluenceMaximization/GenerateGraphLabels.cpp | UTF-8 | 5,510 | 2.765625 | 3 | [] | no_license | //
// GenerateGraphLabels.cpp
// InfluenceMaximization
//
// Created by Madhavan R.P on 12/15/17.
// Copyright © 2017 Madhavan R.P. All rights reserved.
//
#include "GenerateGraphLabels.hpp"
void GenerateGraphLabels::initializeDataAndGenerate(Graph *graph, float percentage, LabelSetting labelSetting) {
this->graph = graph;
this->setting = labelSetting;
this->percentage = percentage;
this->totalNumberOfNonTargets = 0;
int n = graph->getNumberOfVertices();
this->numberOfTargetsToLabel = round((float)n * percentage);
this->numberOfNonTargetsToLabel = n - this->numberOfTargetsToLabel;
this->labels = vector<NodeLabel>(n);
for (int i=0; i<n; i++) {
this->labels[i] = NodeLabelTarget;
}
generate();
}
GenerateGraphLabels::GenerateGraphLabels(Graph *graph, float percentage, LabelSetting setting) {
initializeDataAndGenerate(graph, percentage, setting);
}
GenerateGraphLabels::GenerateGraphLabels(Graph *graph, float percentage) {
initializeDataAndGenerate(graph, percentage, LabelSettingUniform);
}
void GenerateGraphLabels::doDFSWithLabel(int currentNode, int currentDepth, int depthLimit) {
if(currentDepth>depthLimit) return;
if(this->labels[currentNode]==NodeLabelNonTarget) return;
if(this->totalNumberOfNonTargets>=this->numberOfNonTargetsToLabel) return;
this->labels[currentNode] = NodeLabelNonTarget;
this->totalNumberOfNonTargets++;
float probability = 0.75f;
vector<vector<int>> *adjacencyList = this->graph->getGraph();
for(int neighbour: (*adjacencyList)[currentNode]) {
float randomFloat = static_cast <float> (rand()) / (static_cast <float> (RAND_MAX));
if(randomFloat<=probability && (this->labels[currentNode]==NodeLabelNonTarget)) {
doDFSWithLabel(neighbour, currentDepth+1, depthLimit);
}
}
}
void GenerateGraphLabels::generate() {
int n = this->graph->getNumberOfVertices();
int numberOfTargets = round((float)n * this->percentage);
int numberOfNonTargets = n - numberOfTargets;
string comment;
switch (this->setting) {
case LabelSettingClusters:
comment = "Label Setting Clusters with depth level=" + to_string(2);
generateWithSetting1(numberOfTargets, numberOfNonTargets);
break;
case LabelSettingTIMNonTargets:
comment = "Find Influence Maximization seed set, do diffusion and label as non targets";
generateWithTIMNonTargets(numberOfTargets, numberOfNonTargets);
break;
case LabelSettingUniform:
comment = " Each node is target with probability equal to percentage";
generateUniformRandom();
break;
default:
comment = " Each node is target with probability equal to percentage";
generateUniformRandom();
break;
}
this->graph->setLabels(this->labels, this->percentage);
this->graph->writeLabels(this->setting, comment);
}
void GenerateGraphLabels::generateUniformRandom() {
int n = graph->getNumberOfVertices();
for (int i=0; i<n; i++) {
float randomFloat = static_cast <float> (rand()) / (static_cast <float> (RAND_MAX));
if (randomFloat<=this->percentage) {
this->labels[i] = NodeLabelTarget;
} else {
this->labels[i] = NodeLabelNonTarget;
}
}
}
void GenerateGraphLabels::generateWithSetting1(int numberOfTargets, int numberOfNonTargets) {
int n = graph->getNumberOfVertices();
vector<vector<int>> adjList = *graph->getGraph();
cout << "\n Value of n is " << n << flush;
cout << "\n Number of non targets aimed is " << numberOfNonTargets;
cout << "\n Number of targets aimed is " << numberOfTargets;
int level = 2;
while(this->totalNumberOfNonTargets< this->numberOfNonTargetsToLabel) {
int randomVertex = rand() % n;
if(this->labels[randomVertex]==NodeLabelNonTarget) continue;
doDFSWithLabel(randomVertex, 0, level);
}
int sanityCount = 0;
for(NodeLabel l: this->labels) {
if(l==NodeLabelNonTarget) sanityCount++;
}
cout << "\n Total number of non targets: " << this->totalNumberOfNonTargets;
cout << "\n Sanity count: " << sanityCount;
cout << "\n Value of n: " << n;
}
void GenerateGraphLabels::generateWithTIMNonTargets(int numberOfTargets, int numberOfNonTargets) {
double epsilon = (double)2;
int n = this->graph->getNumberOfVertices();
int R = (8+2 * epsilon) * n * (2 * log(n) + log(2))/(epsilon * epsilon);
// R = 23648871;
Graph *graph = this->graph;
graph->generateRandomRRSets(R, true);
vector<vector<int>>* rrSets = graph->getRandomRRSets();
vector<vector<int>> lookupTable;
TIMCoverage *timCoverage = new TIMCoverage(&lookupTable);
timCoverage->initializeLookupTable(rrSets, n);
timCoverage->initializeDataStructures(R, n);
set<int> seedSet;
double scalingFactor = (double)n/(double)R;
while(timCoverage->getNumberOfRRSetsCovered() * scalingFactor< numberOfNonTargets ) {
pair<int, double> nodeWithInfluence = timCoverage->findMaxInfluentialNodeAndUpdateModel(rrSets);
seedSet.insert(nodeWithInfluence.first);
}
delete timCoverage;
set<int> activatedSet = findActivatedSetAndInfluenceUsingDiffusion(graph, seedSet, NULL).second;
for (int activeNode:activatedSet) {
this->labels[activeNode] = NodeLabelNonTarget;
this->totalNumberOfNonTargets++;
}
}
| true |
bdb48ca6a73b8be33d9454d12dcaf93095dc634d | C++ | Adrian94F/SDiZO_PEA | /SDiZO2d/sdizo-proj2/display.cpp | UTF-8 | 337 | 3.15625 | 3 | [] | no_license | #include "header.h"
void DisplayVec(vector<int> input, int dest)
{
cout << input[dest] << " ";
}
void DisplayEdge(vector<Edge> input)
{
cout << " Src: Dst: Wt:" << endl;
for (int i = 0; i < input.size(); i++)
cout << setw(6) << input[i].source << " " << setw(6) << input[i].dest << " " << setw(6) << input[i].weight << endl;
} | true |
4cd5faffdd1d2c19c6aca4aa259b1f61b5ee7abb | C++ | hassanrwarraich/Cplusplus-small-projects-and-hws | /Lab3Partb_2/src/main.cpp | UTF-8 | 344 | 2.71875 | 3 | [] | no_license | #include <iostream>
#include "MedianHeap.h"
using namespace std;
int main()
{
MedianHeap median;
cout<<median.findMedian()<<endl;
median.insert(1);
median.insert(2);
median.insert(3);
median.insert(4);
median.insert(5);
median.insert(6);
cout<<median.findMedian()<<endl;
return 0;
}
| true |
c5ffa00a304b44ce4c8ac2a4420f1f3e74bcc200 | C++ | haiimz1234/mmCoreAndDevices | /DeviceAdapters/LightSheetManager/LightSheetDeviceManager.h | UTF-8 | 2,380 | 2.546875 | 3 | [
"BSD-3-Clause"
] | permissive | /*
* Project: Light Sheet Device Manager
* License: BSD 3-clause, see license.txt
* Author: Brandon Simpson (brandon@asiimaging.com)
* Copyright (c) 2022, Applied Scientific Instrumentation
*/
#ifndef _LIGHTSHEET_DEVICE_MANAGER_H_
#define _LIGHTSHEET_DEVICE_MANAGER_H_
#include "MMDevice.h"
#include "DeviceBase.h"
#include "LightSheetManager.h"
#include "MicroscopeGeometry.h"
#include <vector>
#include <string>
class LightSheetDeviceManager : public CGenericBase<LightSheetDeviceManager>
{
public:
LightSheetDeviceManager();
~LightSheetDeviceManager();
// Device API
int Initialize();
int Shutdown();
bool Busy();
void GetName(char* name) const;
// Pre-init Property Actions
int OnNumImagingPaths(MM::PropertyBase* pProp, MM::ActionType eAct);
int OnNumIlluminationPaths(MM::PropertyBase* pProp, MM::ActionType eAct);
int OnNumSimultaneousCameras(MM::PropertyBase* pProp, MM::ActionType eAct);
int OnMicroscopeGeometry(MM::PropertyBase* pProp, MM::ActionType eAct);
int OnLightSheetType(MM::PropertyBase* pProp, MM::ActionType eAct);
private:
// Create properties for all properties in the device map.
void CreateDeviceProperties(std::map<std::string, MM::DeviceType> deviceMap);
// Create properties for the imaging camera based on the number of imaging paths and simultaneous cameras on each imaging path.
void CreateCameraProperties();
// Returns true if the string starts with the search term.
bool StringStartsWith(const std::string& str, const std::string& searchTerm) const;
// Returns the device names of all devices of MM::DeviceType loaded in the hardware configuration as strings.
std::vector<std::string> GetLoadedDevicesOfType(const MM::DeviceType deviceType);
// Create multiple properties with the light path prefix.
void CreatePrefixProperties(const std::string& propertyName, const std::string& prefix,
const int numProperties, MM::DeviceType deviceType);
std::map<MM::DeviceType, std::vector<std::string>> devices_;
MicroscopeGeometry geometry_;
bool initialized_;
// pre-init properties
std::string geometryType_; // type of microscope geometry
std::string lightSheetType_; // scanned or static sheet
long numImagingPaths_;
long numIlluminationPaths_;
long numSimultaneousCameras_;
};
#endif // _LIGHTSHEET_DEVICE_MANAGER_H_ | true |
a4dc64867c5ef6a92c8c33b056217967c18d87d4 | C++ | SebastianEd/Laser-Ships | /Laser-Ships/Sound.cpp | UTF-8 | 1,162 | 2.796875 | 3 | [] | no_license | #include "Sound.h"
//Constructor
//
CSound::CSound() {
m_pBMG = nullptr;
m_pSoundEffect = nullptr;
if (Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 2048) < 0) {
std::cerr << "Error: " << Mix_GetError() << std::endl;
}
}//Constructor
void CSound::CleanUp() {
freeMusic();
Mix_CloseAudio();
Mix_Quit();
}
//Destructor
//
CSound::~CSound() {
if (m_pSoundEffect != nullptr) {
Mix_FreeChunk(m_pSoundEffect);
m_pSoundEffect = nullptr;
}
}//Destructor
void CSound::freeMusic() {
if (m_pBMG != nullptr) {
Mix_FreeMusic(m_pBMG);
m_pBMG = nullptr;
}
//You never can be sure enough to free your memory :D
if (m_pSoundEffect != nullptr) {
Mix_FreeChunk(m_pSoundEffect);
m_pSoundEffect = nullptr;
}
}
//playBMG: plays background music
//
void CSound::playBGM(const std::string &filePath) {
//Load Background Music
m_pBMG = Mix_LoadMUS(filePath.c_str());
if (!Mix_PlayingMusic()) {
Mix_PlayMusic(m_pBMG, -1);
}
}//playBGM
//playSoundEffect
//
void CSound::playSoundEffect(const std::string &filePath) {
m_pSoundEffect = Mix_LoadWAV(filePath.c_str());
Mix_PlayChannel(-1, m_pSoundEffect, 0);
}//playSoundEffect
| true |
e6db101b71160f53e7c31f9511aa129b7d906275 | C++ | dacap/handy | /app/cursors.h | UTF-8 | 862 | 2.9375 | 3 | [
"MIT"
] | permissive | // handy text editor
// Copyright (c) 2016 David Capello
//
// This file is released under the terms of the MIT license.
// Read LICENSE.txt for more information.
#pragma once
#include "base.h"
#include <vector>
class Cursors {
public:
Cursors() { }
cursor_ref add(cursor_t p) {
for (cursor_ref i=0; i<m_values.size(); ++i) {
if (m_values[i] == -1) {
m_values[i] = p;
return i;
}
}
m_values.push_back(p);
return m_values.size()-1;
}
void del(cursor_ref ref) {
m_values[ref] = -1;
}
cursor_t get(cursor_ref ref) {
return m_values[ref];
}
void set(cursor_ref ref, cursor_t value) {
m_values[ref] = value;
}
void update_cursors_from(cursor_t from, cursor_t delta) {
for (auto& p : m_values)
if (p >= from)
p += delta;
}
private:
std::vector<cursor_t> m_values;
};
| true |
1d4db13ed53c5fa10656716c4d6fbdad7cab367c | C++ | nikkokun/software-engineering | /HashMap/include/SortedList.h | UTF-8 | 5,313 | 3.765625 | 4 | [] | no_license | //
// Created by Nico Roble on 2019-10-07.
//
#ifndef HASHMAP_SORTEDLIST_H
#define HASHMAP_SORTEDLIST_H
#include <vector>
using namespace std;
class Node {
private:
int data;
Node *next;
public:
int getData() const {
return data;
}
void setData(int data) {
Node::data = data;
}
Node *getNext() const {
return Node::next;
}
void setNext(Node *next) {
Node::next = next;
}
Node(int data) {
Node::data = data;
Node::next = nullptr;
}
};
class SortedList {
private:
Node *head;
Node *tail;
int count;
void add_first(int data) {
Node *new_node = new Node(data);
new_node->setNext(nullptr);
if(SortedList::head == nullptr) {
SortedList::head = new_node;
SortedList::tail = SortedList::head;
}
else {
new_node->setNext(SortedList::head);
SortedList::head = new_node;
}
++SortedList::count;
}
void add_last(int data) {
Node *new_node = new Node(data);
new_node->setNext(nullptr);
if(SortedList::head == nullptr) {
SortedList::tail = new_node;
SortedList::head = SortedList::tail;
}
else {
SortedList::tail->setNext(new_node);
SortedList::tail = new_node;
}
++SortedList::count;
}
public:
Node *getHead() {
return SortedList::head;
}
Node *getTail() {
return SortedList::tail;
}
int getCount() {
return SortedList::count;
}
void insert(int data) {
if(SortedList::head == nullptr) {
add_first(data);
return;
}
if(data < SortedList::head->getData()) {
add_first(data);
return;
}
if(data > SortedList::tail->getData()) {
add_last(data);
return;
}
Node *current = SortedList::head;
Node *next = current->getNext();
while(next != nullptr) {
if(next->getData() >= data) {
// insert
Node *new_node = new Node(data);
new_node->setNext(next);
current->setNext(new_node);
break;
}
// move
current = current->getNext();
next = next->getNext();
}
++SortedList::count;
}
void remove_first() {
if(SortedList::head == nullptr) {
throw "The List is empty!\n";
}
Node *temp = SortedList::head;
if(SortedList::head->getNext() == nullptr) {
SortedList::head = nullptr;
SortedList::tail = SortedList::head;
}
else {
SortedList::head = SortedList::head->getNext();
}
int tmp_data = temp->getData();
delete temp;
--SortedList::count;
cout << "Deleted " + to_string(tmp_data) + " \n";
}
void remove_last() {
if(SortedList::head == nullptr) {
throw "The list is empty!\n";
}
if(SortedList::head == SortedList::tail) {
SortedList::remove_first();
}
Node *current = SortedList::head;
Node *previous = nullptr;
while(current != SortedList::tail) {
previous = current;
current = current->getNext();
}
SortedList::tail = previous;
previous->setNext(nullptr);
int current_data = current->getData();
delete current;
--SortedList::count;
cout << "Deleted " + to_string(current_data) + " \n";
}
void remove(int data) {
if(SortedList::head->getData() == data) {
return SortedList::remove_first();
}
if(SortedList::tail->getData() == data) {
return SortedList::remove_last();
}
Node *current = SortedList::head->getNext();
Node *previous = SortedList::head;
while(current != SortedList::tail) {
if(current->getData() == data) {
previous->setNext(current->getNext());
int current_data = current->getData();
delete current;
--SortedList::count;
cout << "Deleted " + to_string(current_data) + " \n";
return;
}
else {
previous = current;
current = current->getNext();
}
}
cout << "Element does not exist in list\n";
}
int search(int data) {
if(SortedList::head ==nullptr && SortedList::tail ==nullptr) {
return -1;
}
if(SortedList::head->getData() == data) {
return 1;
}
if(SortedList::tail->getData() == data) {
return 1;
}
Node *current = SortedList::head;
int step_count = 1;
//search
while(current != SortedList::tail) {
++step_count;
if(current->getData() == data) {
return step_count;
}
else {
current = current->getNext();
}
}
//no matches
return -1;
}
vector<int> to_vector() {
vector<int> result;
Node *current = SortedList::head;
while(current != nullptr) {
result.push_back(current->getData());
current = current->getNext();
}
return result;
}
void print() {
Node *current = SortedList::head;
cout << "Printing list:\n";
if(SortedList::count < 1) {
cout << "The list is empty!\n";
return;
}
while(current !=nullptr) {
cout << to_string(current->getData()) + ", ";
current = current->getNext();
}
cout << "\n";
}
~SortedList() {
Node *current = SortedList::head;
while(current !=nullptr) {
Node *next = current->getNext();
Node *tmp = current;
delete tmp;
current = next;
}
}
};
#endif //HASHMAP_SORTEDLIST_H
| true |
af1928d1063323ff0d64b076dbaa93905dc51110 | C++ | zeroplusone/AlgorithmPractice | /Leetcode/246. Strobogrammatic Number.cpp | UTF-8 | 535 | 3.15625 | 3 | [] | no_license | class Solution {
public:
bool isStrobogrammatic(string num) {
unordered_map<char, char> m;
m['0']='0';
m['1']='1';
m['6']='9';
m['9']='6';
m['8']='8';
int n=num.length();
for(int i=0;i<n/2;++i) {
if(m[num[i]]!=num[n-i-1]) {
return false;
}
}
if(n%2==1) {
if(num[n/2]!='0'&&num[n/2]!='1'&&num[n/2]!='8') {
return false;
}
}
return true;
}
};
| true |
f9949c5f6db7cd5a714e7eb72091a90f4970e432 | C++ | surya3997/HackerRank | /Data Structures/Trees/Tree: Height of a Binary Tree/Tree: Height of a Binary Tree.cpp | UTF-8 | 384 | 3.625 | 4 | [] | no_license |
/*The tree node has data, left child and right child
struct node
{
int data;
node* left;
node* right;
};
*/
int height(node * root)
{
int num1,num2;
if(root==NULL)
return -1;
else{
num1=height(root->left);
num2=height(root->right);
if(num1>num2)
return num1+1;
else
return num2+1;
}
}
| true |
66aaa31db430e091426c57964f8667242ce8499d | C++ | Sine-mora/CPP_Exercises | /CourseC++/src/Structs/Structs.cpp | UTF-8 | 1,248 | 2.953125 | 3 | [] | no_license | #include "Structs.h"
Camera::Camera(int nFront, int nRear) : m_nFront{nFront}, m_nRear{nRear}
{
}
std::ostream& operator<<(std::ostream& out, const Camera& obj)
{
out << "\nCamera Rear: " << obj.m_nRear << "\nCamera Front: " << obj.m_nFront << "\n";
return out;
}
Phone::Phone(const std::string& strName,
int nRAM,
int nROM,
const std::string& strProcessor,
const Camera& camera)
: m_strName{strName}, m_nRAM{nRAM}, m_nROM{nROM}, m_strProcessor{strProcessor},
m_cCamera{camera}
{
}
void Phone::RunExercise()
{
std::cout << "\nPhone's RunExercise\n";
}
std::ostream& operator<<(std::ostream& out, const Phone& obj)
{
out << "\nPhone's name: " << obj.m_strName << "\nRAM: " << obj.m_nRAM
<< "\nROM: " << obj.m_nROM << "\nProcessor: " << obj.m_strProcessor
<< "\nCameran Diaz: " << obj.m_cCamera;
return out;
}
void Student::PrintData()
{
std::cout << "\n Student's name: " << m_strFullname << "\n Student's Id: " << m_nID
<< "\n Student's marks: " << m_nMarks << "\n";
}
void Student::RunExercise()
{
std::cout << "\nStudent's RunExercise:\n";
}
Student::Student() : m_strFullname{"Petko Petkov"}, m_nID{34}, m_nMarks{100}
{
}
| true |
6a12ddfbd1239ba9bd20775b2dc2f0ab195788f7 | C++ | alifainur/mtech | /mqtt_relay_String.ino | UTF-8 | 2,418 | 2.546875 | 3 | [] | no_license | #include <WiFi.h>
#include <PubSubClient.h>
const char* ssid = "yourSSID";
const char* password = "yourPASSWORD";
const char* mqtt_server = "broker.hivemq.com";
WiFiClient espClient;
PubSubClient client(espClient);
void setup_wifi(){
delay(10); // Start connecting to WiFi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED){
// Status for connecting to WiFi
digitalWrite(2, !digitalRead(2));
delay(500);
Serial.print(".");
}
randomSeed(micros());
Serial.println("");
Serial.println("WiFi connected");
// Status connected to WiFi
digitalWrite(2, HIGH);
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void callback(char* topic, byte* payload, unsigned int length){
if (String((char*)payload) == "hidup"){ // tukar kepada string
digitalWrite(18, HIGH); // ON relay 1
}
if ((char)payload[0] == '1'){ // guna char
digitalWrite(18, LOW); // OFF relay 1
}
/*if ((char)payload[0] == '2'){
digitalWrite(19, HIGH); // ON relay 2
}
if ((char)payload[0] == '3'){
digitalWrite(19, LOW); // OFF relay 2
}
if ((char)payload[0] == '4'){
digitalWrite(23, HIGH); // ON relay 3
}
if ((char)payload[0] == '5'){
digitalWrite(23, LOW); // OFF relay 3
}*/
}
void reconnect(){
digitalWrite(2,LOW);
while (!client.connected()){
Serial.print("Attempting MQTT connection...");
String clientId = "ESP32Client-";
clientId += String(random(0xffff), HEX);
if (client.connect(clientId.c_str())){
Serial.println("connected");
digitalWrite(2, HIGH);
// Once connected, publish an announcement...
client.publish("mtech/out/iot", "Connected to ESp32");
//... resubscribe
client.subscribe("mtech/in/iot");
}else{
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 1 seconds");
digitalWrite(2, !digitalRead(2));
delay(1000);
}
}
}
void setup() {
Serial.begin(115200);
pinMode(2, OUTPUT);
pinMode(18,OUTPUT);
pinMode(19,OUTPUT);
pinMode(23,OUTPUT);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}
void loop() {
if (!client.connected()){
reconnect();
}
client.loop();
}
| true |
f03853ffe8f6972808c73a4cecc133c29384cd1b | C++ | romualdo97/opengl_studies | /022_framebuffers/code_vs_v16_2019/001_framebuffers/Box.h | UTF-8 | 10,711 | 3.03125 | 3 | [] | no_license | #pragma once
#include <glad\glad.h>
// index drawing data for draw a cube
unsigned int const BACK_OFFSET = 4;
unsigned int const LEFT_OFFSET = 8;
unsigned int const RIGHT_OFFSET = 12;
unsigned int const TOP_OFFSET = 16;
unsigned int const BOTTOM_OFFSET = 20;
// Struct used for drawwing boxes
struct Box
{
public:
Box()
{
// generate VAO for store status of subsequent "vertex attribute" calls and element array buffer configs
glGenVertexArrays(1, &VAO);
glBindVertexArray(VAO); // bind VAO
// generate VBO for allocate memory in GPU
unsigned int VBO;
glGenBuffers(1, &VBO);
// bind VBO with GL_ARRAY_BUFFER target
glBindBuffer(GL_ARRAY_BUFFER, VBO);
// copy data from CPU to GPU
// use the currently bounded buffer to GL_ARRAY_BUFFER as container
glBufferData(GL_ARRAY_BUFFER, sizeof(vertex_data), vertex_data, GL_STATIC_DRAW);
// tell OpenGL how it should interpret the vertex data(per
// vertex attribute) using glVertexAttribPointer:
// glVertexAttribPointer(index = [vertex attrib location remember the layout (location = n) keyword in vertex shader],
// size = [is vec2 = 2, vec3 = 3, etc..],
// type = [GL_FLOAT, GL_BOOL, etc..],
// normalize = [opengl should normalize the given data?],
// stride = [distance in bytes between each "position" ternas in VBO],
// start = [whare is the start index of "position"?];
// indicate which part of vertex data are vertex positions
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 11 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0); // enable the vertex attribute at location 0
// indicate which part of vertex data are vertex colors
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 11 * sizeof(float), (void*)(3 * sizeof(float)));
glEnableVertexAttribArray(1); // enable the vertex attribute at location 1
// indicate which part of vertex data are texture coordinates
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 11 * sizeof(float), (void*)(6 * sizeof(float)));
glEnableVertexAttribArray(2); // enable the vertex attribute at location 2
// indicate which part of vertex data are model normals
glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, 11 * sizeof(float), (void*)(8 * sizeof(float)));
glEnableVertexAttribArray(3); // enable the vertex attribute at location 2
std::cout << "\n\nGL_ARRAY_BUFFER:\n";
std::cout << "sizeof(float): " << sizeof(float) << " bytes" << std::endl;
std::cout << "Num of indices at GL_ARRAY_BUFFER: " << sizeof(vertex_data) / sizeof(float) << std::endl;
std::cout << "Size reserved for GL_ARRAY_BUFFER: " << sizeof(vertex_data) << " bytes" << std::endl;
// generate EBO
unsigned int EBO;
glGenBuffers(1, &EBO);
// bind EBO to GL_ELEMENT_ARRAY_BUFFER
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
// pass EBO data from CPU to GPU
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(index_drawing_data), index_drawing_data, GL_STATIC_DRAW);
std::cout << "\n\nGL_ELEMENT_ARRAY_BUFFER:\n";
std::cout << "sizeof(unsigned int): " << sizeof(unsigned int) << " bytes" << std::endl;
std::cout << "Num of indices at GL_ELEMENT_ARRAY_BUFFER: " << sizeof(index_drawing_data) / sizeof(unsigned int) << std::endl;
std::cout << "Size reserved for GL_ELEMENT_ARRAY_BUFFER: " << sizeof(index_drawing_data) << " bytes" << std::endl;
std::cout << "\n\nTOTAL BYTES SENT TO GPU: " << sizeof(index_drawing_data) + sizeof(vertex_data) << " bytes" << std::endl;
}
void draw()
{
// define the winding order
#ifdef USE_CUBE_CULLING
glFrontFace(GL_CW); // defines "winding order" for specify which triangle side is considered the "front" face
glEnable(GL_CULL_FACE); // enable the face culling
glCullFace(GL_BACK); // cull back faces
#else
glEnable(GL_DEPTH_TEST);
#endif // USE_CUBE_CULLING
// read more at: https://people.eecs.ku.edu/~jrmiller/Courses/672/InClass/3DModeling/glDrawElements.html
// glDrawArrays(GL_TRIANGLES, 0, 3); // draw triangle
const int VERTICES_PER_TRIANGLE = 3;
const int NUM_OF_TRIANGLES = 12;
GLenum mode = GL_TRIANGLES; // Specifies what kind of primitives to render.
GLsizei count = VERTICES_PER_TRIANGLE * NUM_OF_TRIANGLES; // Specifies the number of elements to be rendered.
GLenum type = GL_UNSIGNED_INT; // Specifies the type of the values in indices.Must be one of GL_UNSIGNED_BYTE, GL_UNSIGNED_SHORT, or GL_UNSIGNED_INT.
GLvoid* indices = nullptr; // Specifies a pointer to the location where the indices are stored
// Passing nullptr as the final parameter to glDrawElements tells the vertex fetch processor to use the currently bound element buffer object when extracting per - vertex data for vertex shader executions.
glDrawElements(mode, count, type, indices); // draw a quad
}
void setPosition(glm::vec3 position)
{
model = glm::translate(model, position);
}
void setRotationY(float radians)
{
model = glm::rotate(model, radians, glm::vec3(0.0f, 1.0f, 0.0f));
}
// Initialized using default memeber initilization to solve warning https://docs.microsoft.com/en-us/cpp/code-quality/c26495?view=msvc-160
unsigned int VAO{};
unsigned int VBO{};
unsigned int EBO{};
// Related to model matrix
glm::mat4 model;
// Data for sending to GPU
const float vertex_data[11 * 4 * 6] = {
// FRONT (Z-POSITIVE)
// positions (in NDC) // colors // texture coordinates // face normal
-0.5f, 0.5f, 0.5f, /*left-top*/ 0.0f, 0.0f, 1.0f, /*blue*/ 0.0, 1.0, 0.0f, 0.0f, 1.0f,
0.5f, 0.5f, 0.5f, /*right-top*/ 0.0f, 0.0f, 1.0f, /*blue*/ 1.0, 1.0, 0.0f, 0.0f, 1.0f,
-0.5f, -0.5f, 0.5f, /*left-bttm*/ 0.0f, 0.0f, 1.0f, /*blue*/ 0.0, 0.0, 0.0f, 0.0f, 1.0f,
0.5f, -0.5f, 0.5f, /*right-bttm*/ 0.0f, 0.0f, 1.0f, /*blue*/ 1.0, 0.0, 0.0f, 0.0f, 1.0f,
// BACK (Z-NEGATIVE)
// positions (in NDC) // colors // texture coordinates // face normal
-0.5f, 0.5f, -0.5f, /*left-top*/ 0.0f, 0.0f, 0.5f, /*blue*/ 0.0, 1.0, 0.0f, 0.0f, -1.0f,
0.5f, 0.5f, -0.5f, /*right-top*/ 0.0f, 0.0f, 0.5f, /*blue*/ 1.0, 1.0, 0.0f, 0.0f, -1.0f,
-0.5f, -0.5f, -0.5f,/*left-bttm*/ 0.0f, 0.0f, 0.5f, /*blue*/ 0.0, 0.0, 0.0f, 0.0f, -1.0f,
0.5f, -0.5f, -0.5f, /*right-bttm*/ 0.0f, 0.0f, 0.5f, /*blue*/ 1.0, 0.0, 0.0f, 0.0f, -1.0f,
// LEFT (X-NEGATIVE)
// positions (in NDC) // colors // texture coordinates // face normal
-0.5f, 0.5f, -0.5f, /*left-top*/ 0.5f, 0.0f, 0.0f, /*red*/ 0.0, 1.0, -1.0f, 0.0f, 0.0f,
-0.5f, 0.5f, 0.5f, /*right-top*/ 0.5f, 0.0f, 0.0f, /*red*/ 1.0, 1.0, -1.0f, 0.0f, 0.0f,
-0.5f, -0.5f, -0.5f, /*left-bttm*/ 0.5f, 0.0f, 0.0f, /*red*/ 0.0, 0.0, -1.0f, 0.0f, 0.0f,
-0.5f, -0.5f, 0.5f, /*right-bttm*/ 0.5f, 0.0f, 0.0f, /*red*/ 1.0, 0.0, -1.0f, 0.0f, 0.0f,
// RIGHT (X-POSITIVE)
// positions (in NDC) // colors // texture coordinates // face normal
0.5f, 0.5f, -0.5f, /*left-top*/ 1.0f, 0.0f, 0.0f, /*red*/ 0.0, 1.0, 1.0f, 0.0f, 0.0f,
0.5f, 0.5f, 0.5f, /*right-top*/ 1.0f, 0.0f, 0.0f, /*red*/ 1.0, 1.0, 1.0f, 0.0f, 0.0f,
0.5f, -0.5f, -0.5f, /*left-bttm*/ 1.0f, 0.0f, 0.0f, /*red*/ 0.0, 0.0, 1.0f, 0.0f, 0.0f,
0.5f, -0.5f, 0.5f, /*right-bttm*/ 1.0f, 0.0f, 0.0f, /*red*/ 1.0, 0.0, 1.0f, 0.0f, 0.0f,
// TOP (Y-POSITIVE)
// positions (in NDC) // colors // texture coordinates // face normal
-0.5f, 0.5f, -0.5f, /*left-top*/ 0.0f, 1.0f, 0.0f, /*green*/ 0.0, 1.0, 0.0f, 1.0f, 0.0f,
0.5f, 0.5f, -0.5f, /*right-top*/ 0.0f, 1.0f, 0.0f, /*green*/ 1.0, 1.0, 0.0f, 1.0f, 0.0f,
-0.5f, 0.5f, 0.5f, /*left-bttm*/ 0.0f, 1.0f, 0.0f, /*green*/ 0.0, 0.0, 0.0f, 1.0f, 0.0f,
0.5f, 0.5f, 0.5f, /*right-bttm*/ 0.0f, 1.0f, 0.0f, /*green*/ 1.0, 0.0, 0.0f, 1.0f, 0.0f,
// BOTTOM (Y-NEGATIVE)
// positions (in NDC) // colors // texture coordinates // face normal
-0.5f, -0.5f, -0.5f,/*left-top*/ 0.0f, 0.5f, 0.0F, /*green*/ 0.0, 1.0, 0.0f, -1.0f, 0.0f,
-0.5f, -0.5f, 0.5f, /*right-top*/ 0.0f, 0.5f, 0.0f, /*green*/ 1.0, 1.0, 0.0f, -1.0f, 0.0f,
0.5f, -0.5f, -0.5f, /*left-bttm*/ 0.0f, 0.5f, 0.0f, /*green*/ 0.0, 0.0, 0.0f, -1.0f, 0.0f,
0.5f, -0.5f, 0.5f, /*right-bttm*/ 0.0f, 0.5f, 0.0f, /*green*/ 1.0, 0.0, 0.0f, -1.0f, 0.0f,
};
const unsigned int index_drawing_data[3 * 2 * 6] = {
#ifdef USE_CUBE_CULLING
// FRONT (Z-POSITIVE) specified in "clock wise" "winding order"
0, 1, 2, /*first triangle*/
1, 3, 2, /*second triangle*/
// BACK (Z-NEGATIVE) specified in "counter-clock wise" "winding order"
0 + BACK_OFFSET, 2 + BACK_OFFSET, 1 + BACK_OFFSET, /*first triangle*/
1 + BACK_OFFSET, 2 + BACK_OFFSET, 3 + BACK_OFFSET, /*second triangle*/
// LEFT (X-NEGATIVE) specified in "clock wise" "winding order"
0 + LEFT_OFFSET, 1 + LEFT_OFFSET, 2 + LEFT_OFFSET, /*first triangle*/
1 + LEFT_OFFSET, 3 + LEFT_OFFSET, 2 + LEFT_OFFSET, /*second triangle*/
// LEFT (X-NEGATIVE) specified in "counter-clock wise" "winding order"
0 + RIGHT_OFFSET, 2 + RIGHT_OFFSET, 1 + RIGHT_OFFSET, /*first triangle*/
1 + RIGHT_OFFSET, 2 + RIGHT_OFFSET, 3 + RIGHT_OFFSET, /*second triangle*/
// TOP (Y-POSITIVE) specified in "counter-clock wise" "winding order"
0 + TOP_OFFSET, 1 + TOP_OFFSET, 2 + TOP_OFFSET, /*first triangle*/
1 + TOP_OFFSET, 3 + TOP_OFFSET, 2 + TOP_OFFSET, /*second triangle*/
// TOP (Y-POSITIVE) specified in "counter-clock wise" "winding order"
0 + BOTTOM_OFFSET, 1 + BOTTOM_OFFSET, 2 + BOTTOM_OFFSET, /*first triangle*/
1 + BOTTOM_OFFSET, 3 + BOTTOM_OFFSET, 2 + BOTTOM_OFFSET, /*second triangle*/
#else
// FRONT (Z-POSITIVE) specified in "clock wise" "winding order"
0, 1, 2, /*first triangle*/
1, 3, 2, /*second triangle*/
// BACK (Z-NEGATIVE) specified in "clock wise" "winding order"
1 + BACK_OFFSET, 2 + BACK_OFFSET, 0 + BACK_OFFSET, /*first triangle*/
3 + BACK_OFFSET, 2 + BACK_OFFSET, 1 + BACK_OFFSET, /*second triangle*/
// LEFT (X-NEGATIVE) specified in "clock wise" "winding order"
0 + LEFT_OFFSET, 1 + LEFT_OFFSET, 2 + LEFT_OFFSET, /*first triangle*/
1 + LEFT_OFFSET, 3 + LEFT_OFFSET, 2 + LEFT_OFFSET, /*second triangle*/
// LEFT (X-NEGATIVE) specified in "clock wise" "winding order"
1 + RIGHT_OFFSET, 2 + RIGHT_OFFSET, 0 + RIGHT_OFFSET, /*first triangle*/
3 + RIGHT_OFFSET, 2 + RIGHT_OFFSET, 1 + RIGHT_OFFSET, /*second triangle*/
// TOP (Y-POSITIVE) specified in "clock wise" "winding order"
2 + TOP_OFFSET, 1 + TOP_OFFSET, 0 + TOP_OFFSET, /*first triangle*/
2 + TOP_OFFSET, 3 + TOP_OFFSET, 1 + TOP_OFFSET, /*second triangle*/
// TOP (Y-POSITIVE) specified in "clock wise" "winding order"
2 + BOTTOM_OFFSET, 1 + BOTTOM_OFFSET, 0 + BOTTOM_OFFSET, /*first triangle*/
2 + BOTTOM_OFFSET, 3 + BOTTOM_OFFSET, 1 + BOTTOM_OFFSET, /*second triangle*/
#endif
};
};
| true |
a9be01928a880d3e62fcd17978c1e0b68006e970 | C++ | SquarePants1991/EZGLKit | /Classes/utils/ELFileUtil.cpp | UTF-8 | 2,318 | 2.671875 | 3 | [] | no_license | //
// Created by wangyang on 16/11/24.
//
#include "ELFileUtil.h"
#include "ELAssets.h"
#include <fstream>
#include <regex>
std::string ELFileUtil::stringContentOfFile(const char *filePath) {
std::ifstream fileStream(filePath);
std::string fileContent;
std::string line;
if (fileStream.is_open()) {
fileStream.seekg(0, std::ios::end);
long fileSize = fileStream.tellg();
fileStream.seekg(0, std::ios::beg);
char *content = new char[fileSize + 1];
fileStream.read(content,fileSize);
content[fileSize] = '\0';
return std::string(content);
}
fileStream.close();
return "";
}
std::string ELFileUtil::stringContentOfShader(const char *filePath) {
std::string fileContent = stringContentOfFile(filePath);
std::regex includeRegex("#include[[:space:]]?\\<(([[:alpha:]]|_|\\.)+)\\>");
auto resultBegin = std::sregex_iterator(fileContent.begin(), fileContent.end(),includeRegex);
auto resultEnd = std::sregex_iterator();
std::vector<std::string> includeStatements;
std::vector<std::string> includeFilePaths;
for (std::sregex_iterator i = resultBegin; i != resultEnd; ++i) {
std::smatch match = *i;
std::string includeStatement = match.str();
std::string includeFileName = match.str(1);
std::string includeFilePath = ELAssets::shared()->findFile(includeFileName);
includeStatements.push_back(includeStatement);
includeFilePaths.push_back(includeFilePath);
}
for (int j = 0; j < includeFilePaths.size(); ++j) {
std::string includeFilePath = includeFilePaths.at(j);
std::string includeStatement = includeStatements.at(j);
if (includeFilePath.compare("") != 0) {
std::string replaceShaderContent = stringContentOfShader(includeFilePath.c_str());
std::size_t found = fileContent.rfind(includeStatement);
if (found != std::string::npos) {
fileContent = fileContent.replace(found,includeStatement.size(),replaceShaderContent);
} else {
printf("ReplaceStatement [%s] not exists!!!",includeStatement.c_str());
}
} else {
printf("Shader File [%s] not exists!!!",includeFilePath.c_str());
}
}
return fileContent;
} | true |
ed6ddd28aa0d84ea49b5891bdcb9760924beadf7 | C++ | bladykast/MotionCar206 | /receiver-car-code.ino | UTF-8 | 3,051 | 2.890625 | 3 | [] | no_license | #include <nRF24L01.h>
#include <printf.h>
#include <RF24.h>
#include <RF24_config.h>
//Mert Arduino and Tech YouTube Channel -- https://goo.gl/ivcZhW
//Add the necessary libraries
//You can find all the necessary library links in the video description
#include <SPI.h> //SPI library for communicate with the nRF24L01+
#include "RF24.h" //The main library of the nRF24L01+
//Define enable pins of the Motors
const int enbA = 8;
const int enbB = 4;
//Define control pins of the Motors
//If the motors rotate in the opposite direction, you can change the positions of the following pin numbers
const int IN1 = 7; //Right Motor (-)
const int IN2 = 6; //Right Motor (+)
const int IN3 = 3; //Left Motor (+)
const int IN4 = 2; //Right Motor (-)
//Define variable for the motors speeds
//I have defined a variable for each of the two motors
//This way you can synchronize the rotation speed difference between the two motors
int RightSpd = 150;
int LeftSpd = 150;
//Define packet for the direction (X axis and Y axis)
int data[2];
//Define object from RF24 library - 9 and 10 are a digital pin numbers to which signals CE and CSN are connected
RF24 radio(9,10);
//Create a pipe addresses for the communicate
const byte thisSlaveAddress[5] = {'R','x','A','A','A'};
void setup(){
//Define the motor pins as OUTPUT
pinMode(enbA, OUTPUT);
pinMode(enbB, OUTPUT);
digitalWrite(enbA, HIGH);
digitalWrite(enbB,HIGH);
pinMode(IN1, OUTPUT);
pinMode(IN2, OUTPUT);
pinMode(IN3, OUTPUT);
pinMode(IN4, OUTPUT);
Serial.begin(9600);
Serial.print("I work!");
radio.begin(); //Start the nRF24 communicate
radio.setDataRate( RF24_250KBPS );
radio.openReadingPipe(1, thisSlaveAddress); //Sets the address of the transmitter to which the program will receive data.
radio.startListening();
Serial.print("I got this far!");
}
void loop(){
if (radio.available()){
radio.read(data, sizeof(data));
Serial.print(data[0]);
Serial.print(" ");
Serial.print(data[1]);
Serial.println("");
if(data[0] > 380){
//forward
digitalWrite(IN1, HIGH);
digitalWrite(IN2, LOW);
digitalWrite(IN3, HIGH);
digitalWrite(IN4, LOW);
}
if(data[0] < 310){
//backward
digitalWrite(IN1, LOW);
digitalWrite(IN2, HIGH);
digitalWrite(IN3, LOW);
digitalWrite(IN4, HIGH);
}
if(data[1] > 180){
//left
digitalWrite(IN1, HIGH);
digitalWrite(IN2, LOW);
digitalWrite(IN3, LOW);
digitalWrite(IN4, HIGH);
}
if(data[1] < 110){
//right
digitalWrite(IN1, LOW);
digitalWrite(IN2, HIGH);
digitalWrite(IN3, HIGH);
digitalWrite(IN4, LOW);
}
if(data[0] > 330 && data[0] < 360 && data[1] > 130 && data[1] < 160){
//stop car
//analogWrite(enbA, 0);
//analogWrite(enbB, 0);
}
}
}
| true |
b861cae3924923c277156734e5e29f7d6305c1ed | C++ | tamwaiban/nextgame | /tests/Core/TestStaticVector.cpp | UTF-8 | 1,871 | 2.59375 | 3 | [
"BSD-3-Clause",
"MIT"
] | permissive | #include "stf.h"
#include "Core/Defer.h"
#include "Core/StaticVector.h"
STF_SUITE_NAME("Core.StaticVector")
/*
_ _
| | | |
| |_ ___ __| | ___
| __/ _ \ / _` |/ _ \
| || (_) | (_| | (_) |
\__\___/ \__,_|\___/
#define CHECK_VECTOR(v, len, cap, data) \
do { \
STF_ASSERT(v.Length() == len); \
STF_ASSERT(v.Capacity() == cap); \
STF_ASSERT(v.Data() data); \
} while (0)
#define CHECK_VECTOR_CONTENTS(v, ...) \
STF_ASSERT(v.Sub() == Slice<const int>({__VA_ARGS__}))
STF_TEST("StaticVector::Init()") {
StaticVector<int, 4> v;
v.Init();
CHECK_VECTOR(v, 0, 4, == v.m_static);
v.Free();
}
STF_TEST("StaticVector::Append(const T&)") {
StaticVector<int, 4> v = StaticVector<int, 4>().Init();
DEFER { v.Free(); };
CHECK_VECTOR(v, 0, 4, == v.m_static);
v.Append(1);
CHECK_VECTOR(v, 1, 4, == v.m_static);
CHECK_VECTOR_CONTENTS(v, 1);
v.Append(2);
v.Append(3);
v.Append(4);
CHECK_VECTOR(v, 4, 4, == v.m_static);
CHECK_VECTOR_CONTENTS(v, 1, 2, 3, 4);
v.Append(5);
STF_ASSERT(v.Length() == 5);
STF_ASSERT(v.Capacity() >= 5);
STF_ASSERT(v.Data() == v.m_dynamic.m_data);
CHECK_VECTOR_CONTENTS(v, 1, 2, 3, 4, 5);
v.Append(6);
v.Append(7);
v.Append(8);
STF_ASSERT(v.Length() == 8);
STF_ASSERT(v.Capacity() >= 8);
STF_ASSERT(v.Data() == v.m_dynamic.m_data);
CHECK_VECTOR_CONTENTS(v, 1, 2, 3, 4, 5, 6, 7, 8);
}
STF_TEST("StaticVector::Append(const T&)") {
StaticVector<int, 4> v = StaticVector<int, 4>().Init();
DEFER { v.Free(); };
v.Append(1);
v.Append(2);
CHECK_VECTOR_CONTENTS(v, 1, 2);
v.QuickRemove(1);
CHECK_VECTOR_CONTENTS(v, 1);
v.Append(2);
v.Append(3);
v.Append(4);
v.Append(5);
v.Append(6);
CHECK_VECTOR_CONTENTS(v, 1, 2, 3, 4, 5, 6);
v.QuickRemove(0);
v.QuickRemove(0);
STF_ASSERT(v.Data() == v.m_static);
CHECK_VECTOR_CONTENTS(v, 5, 2, 3, 4);
}
*/
| true |
b8059630973fe9718de00283c216f101ae1a35cc | C++ | 0GU/Rain-cloud-friends | /Project1/Project1/ObjTurtle.h | SHIFT_JIS | 1,334 | 2.515625 | 3 | [] | no_license | #pragma once
//gpwb_[
#include "GameL\SceneObjManager.h"
//gpl[Xy[X
using namespace GameL;
//IuWFNgFT
class CObjTurtle : public CObj
{
public:
CObjTurtle(float x, float y);
~CObjTurtle() {};
void Init(); //CjVCY
void Action(); //ANV
void Draw(); //h[
float GetVx() { return m_vx; };
float GetPY() { return m_py; };
private:
float m_px; //ʒu
float m_py;
float m_vx; //ړxNg
float m_vy;
float m_posture; //p
int m_ani_time; //Aj[Vt[Ԋu
int m_ani_frame; //`t[
float m_speed_power; //Xs[hp[
float m_ani_max_time; //Aj[VԊuől
//blockƂ̏ՓˏԊmFp
bool m_hit_up;
bool m_hit_down;
bool m_hit_left;
bool m_hit_right;
//lj
float pos_init; //̈ʒuLp
bool m_move; //ړ̌p
bool stay_flag;
int m_hp;
//eW
bool m_damege_flag;//etO@trueŒ~
float m_transparent;//Xɓɕωϐ
bool m_escaoe_flag;//ItO@trueŃIuWFNgj
//łblock̎ނmFp
int m_block_type;
bool m_swanp;
}; | true |
4134716603882a6ec82902f81706f0760f1b011e | C++ | jinay1991/spleeter | /spleeter/inference_engine/null_inference_engine.h | UTF-8 | 1,260 | 2.59375 | 3 | [
"MIT",
"CC-BY-3.0"
] | permissive | ///
/// @file
/// @copyright Copyright (c) 2020. MIT License
///
#ifndef SPLEETER_INFERENCE_ENGINE_NULL_INFERENCE_ENGINE_H
#define SPLEETER_INFERENCE_ENGINE_NULL_INFERENCE_ENGINE_H
#include "spleeter/datatypes/inference_engine.h"
#include "spleeter/inference_engine/i_inference_engine.h"
namespace spleeter
{
/// @brief Null Inference Engine class
class NullInferenceEngine final : public IInferenceEngine
{
public:
/// @brief Constructor
/// @param params[in] Inference Engine Parameters such as model input/output node names
explicit NullInferenceEngine(const InferenceEngineParameters& params);
/// @brief Initialise Null Inference Engine
void Init() override;
/// @brief Execute Inference with Null Inference Engine
/// @param waveform [in] - Waveform to be split
void Execute(const Waveform& waveform) override;
/// @brief Release Null Inference Engine
void Shutdown() override;
/// @brief Provide results in terms of Matrix
/// @return List of waveforms (split waveforms)
Waveforms GetResults() const override;
private:
/// @brief Output Tensors saved as Waveforms
const Waveforms results_;
};
} // namespace spleeter
#endif /// SPLEETER_INFERENCE_ENGINE_NULL_INFERENCE_ENGINE_H
| true |
f1ad3444dcf178ce243576ed8294605abae82c00 | C++ | anigmo97/4 | /IPV/PARTE 1/include/GameCharacters.h | ISO-8859-10 | 4,076 | 2.53125 | 3 | [] | no_license | //FICHERO MODIFICADO-E1
/*/////////////////////////////////////////////////////////////////////////////////////
// @file GameCharacters.h
// Every different kind of character is loaded using this header
//
Prefix: GCHARS_
@author Ramon Molla
@version 2011-08
*/
#ifndef GAME_CHARACTERS
#define GAME_CHARACTERS
#include <UGKCharactersFactory.h>
using namespace UGK;
/**
* It defines the types of characters already in the game
* @param enum GCHARS_CharacterType: which lists all the types of characters that can happen in a game
*/
typedef enum {
CHARS_BACKGROUND = UGK_MAX_RESERVED_CHARS,
CHARS_BONUS, ///<For improving player strenght
CHARS_BONUS_MNGR, ///<For improving player strenght
CHARS_BOOMETER,
CHARS_BRICK, ///<Pieces that make a bunker
CHARS_BUNKER, ///<A collection of bricks together in order to defend the player
CHARS_CIRCLESHIP, ///<Alien space ships that turns once and once again in clircles on the screen
CHARS_GAME, ///<The game itself
CHARS_GUI_GADGET, ///<Temporal character type. This must be done in a pool for the GUI in UGK
CHARS_LASER, ///<Additional shooting left or right device for the player
CHARS_NAVY, ///<Holds all the supplyships and all types of ships
CHARS_PLAYER, ///<The player
CHARS_REACTOR, ///<Extra power engines and shooters for the player. Obtained after the corresponding bonus has been won
CHARS_SHIP, ///<Alien normal space ships
CHARS_SHOOT, ///<Shoots to be thrown to the enemies
CHARS_SHOOT_MNGR, ///<Shoots manager
// AADIDO PARTE ENTREGA1
CHARS_SUPPORT, ///Helps the player reciving damage
CHARS_SUPPLYSHIP, ///<Super ship of the alien troops
CHARS_WEAPON, ///<Not available by the moment
CHARS_MAX_CHARTYPE ///<Only for character types management. No object exist in the game for this type
} GCHARS_CharacterType;
/**
* @enum CHARS_CHARACTER_STATE
* It defines the types of states of an existing character in the game
*/
typedef enum {
CHARS_UNBORN=0, ///For management purpouses only
CHARS_BORN, ///The character is just born but it is not still operative (living)
CHARS_LIVING, ///Everything this character may do while it is alive
CHARS_DYING, ///The character has been touched so many times that its life has gone negative. So it has to burst before being died. Starts an explosion and dies
CHARS_DEAD, ///The character is no operative. Reached after dying
CHARS_MAXSTATE ///For management purpouses only
} CHARS_CHARACTER_STATE; ///Generic character possible states that can be any character by default
/**
* Defines the kinds of transitions from one character in the game existing
* @param enum CHARS_CHARACTER_TRANSITIONS: which lists the types of transitions from one character
*/
typedef enum {
CHARS_DEFAULT=0, ///For management purpouses only
CHARS_BORNING, ///The character is just borning. Passing from UNBORN to BORN states
CHARS_GETTING_ALIVE, ///Passing from BORN to LIVING states
CHARS_BURST, ///The character has been touched so many times that its life has gone negative. So it has to burst. Passing from LIVING to DYING states
CHARS_DIE, ///The character is no operative. Reached after dying
CHARS_MAXTRANSITION ///For management purpouses only
} CHARS_CHARACTER_TRANSITIONS; ///Generic character possible states that can be any character by default
//Sensitive string tags
//See UGKCharacter.h for information about their meanings
extern UGKS_String CHARS_Tags[CHARS_MAX_CHARTYPE];
///Transitions names
extern UGKS_String CHARS_Transitions[CHARS_MAXTRANSITION];
//Collision table that allows a character to collide with another one
extern bool CHARS_COLLISION_TABLE[CHARS_MAX_CHARTYPE][CHARS_MAX_CHARTYPE];
inline UGKS_String CHARS_Token2Lexeme(unsigned int Token)
{
if (Token >= UGK_MAX_RESERVED_CHARS) return CHARS_Tags[Token - UGK_MAX_RESERVED_CHARS]; else return CHARS_Tags[UGK_CHARACTER_UNKNOWN];
}
void InitCollisionTable();
#endif
| true |
81ce1557df4d264ff2ebee8ac62ef56433bc3f90 | C++ | NickGorev/made_2019_cpp | /02/allocator.cpp | UTF-8 | 548 | 3.21875 | 3 | [] | no_license | #include "allocator.h"
LinearAllocator::LinearAllocator(size_t maxSize) {
storage = (char*) malloc(maxSize);
storageEnd = storage;
if (storage != nullptr) {
storageEnd += maxSize;
}
head = storage;
}
LinearAllocator::~LinearAllocator() {
free(storage);
}
char* LinearAllocator::alloc(size_t size) {
if(head + size <= storageEnd) {
char* retValue = head;
head += size;
return retValue;
} else {
return nullptr;
}
}
void LinearAllocator::reset() {
head = storage;
}
| true |
3c485ac63be5ba7b52e976a264a8ff029edd4e01 | C++ | miha-pavel/arduino | /Lesson2-Photosensitive Resistorr/photosensitive/photo_res_2.ino | UTF-8 | 614 | 3.015625 | 3 | [] | no_license | int sensePin = 2; // Пин к которому подключен фоторезистор
int ledPin = 12; // Пин к которому подключен светодиод
void setup() {
pinMode(ledPin, OUTPUT); // назначаем пин ledPin выходом
}
void loop() {
int val = analogRead(sensePin); // Считываем значение с фоторезистора
if(val < 800) digitalWrite(ledPin, HIGH); //включаем светодиод если значение меньше 800
else digitalWrite(ledPin, LOW); // если нет то выключаем светодиод
}
| true |
1e7c7bc7a4277577b2c90c1a041d21408ba14ca9 | C++ | beierjy/InterviewCodes | /8_6_66_StringPathInMatrix.h | UTF-8 | 2,155 | 4 | 4 | [] | no_license | /*
请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。
路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,
向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则该路径不能再进入该格子。
例如 a b c e s f c s a d e e 矩阵中包含一条字符串"bcced"的路径,但是矩阵中不包含"abcb"路径,
因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入该格子。
*/
#include <iostream>
#include <cstring>
using namespace std;
bool hasPathCore(char* matrix,int rows,int cols,int row,int col,char* str,int &PathLength,bool* visited);
bool hasPath(char* matrix,int rows,int cols,char* str){
if(matrix == NULL || rows < 1 || cols < 1 || str == NULL)
return false;
bool *visited = new bool[rows * cols];
memset(visited,0,rows * cols);
int PathLength = 0;
for(int row = 0;row < rows;++row)
{
for(int col = 0;col < cols;++ col)
{
if(hasPathCore(matrix,rows,cols,row,col,str,PathLength,visited))
return true;
}
}
delete visited;
return false;
}
bool hasPathCore(char* matrix,int rows,int cols,int row,int col,char* str,int &PathLength,bool* visited){
if(str[PathLength] == '\0')
return true;
bool hasPath = false;
if(row >= 0 && row < rows && col >= 0 && col < cols && matrix[row * cols + col] == str[PathLength] && !visited[row * cols + col])
{
++PathLength;
visited[row * cols + col] = true;
hasPath = hasPathCore(matrix,rows,cols,row+1,col,str,PathLength,visited) ||
hasPathCore(matrix,rows,cols,row - 1,col,str,PathLength,visited) ||
hasPathCore(matrix,rows,cols,row,col - 1,str,PathLength,visited) ||
hasPathCore(matrix,rows,cols,row,col + 1,str,PathLength,visited);
if(!hasPath)
{
--PathLength;
visited[row * cols + col] = false;
}
}
return hasPath;
}
void Test(){
char matrix[12] = {'a','b','c','e','s','f','c','s','a','d','e','e'};
char* str = "abcd";
bool c = hasPath(matrix,3,4,str);
cout<<c<<endl;
}
| true |
b7d6f0170bd78c1d9c415989572a48d4e35370d0 | C++ | skylersaleh/ArgonEngine | /common/ArgonEngine/ArgonInit.h | UTF-8 | 761 | 2.609375 | 3 | [
"MIT"
] | permissive | //Generated by the Argon Build System
/**
* @brief This file contains the declaration for the initialization functions of the engine.
* @file ArgonInit.h
* @author Skyler Saleh
**/
#ifndef ARGON_INIT_H
#define ARGON_INIT_H
namespace Argon{
/// Initialize the engine and HAL.
void initialize_engine(std::string organization_name, std::string app_name);
/// Termintate the engine, closing the program.
void terminate_engine();
/// Poll for events, this updates all hardware and HAL values, and should be called frequently.
/// Returns true if the window is still open.
bool poll_events();
void set_manual_redraw(void (*draw)());
/// Swaps the rendered buffers to make them visible to the user.
void swap_buffers();
}
#endif
| true |
0a53b38c90171f198c81446903247e766de99037 | C++ | zurczi/OOP-Project | /po-projekt/kasa.cpp | WINDOWS-1250 | 3,527 | 3.078125 | 3 | [] | no_license | #include <string>
#include <iostream>
#include "pracownik.hpp"
#include "student.hpp"
#include "programista.hpp"
#include "konto.hpp"
#include <vector>
#include <fstream>
#include "czlowiek.hpp"
using namespace std;
template <class Temp>
class Kasa {
private:
vector <Temp*> konta;
public:
void sumujsaldo(){
int i;
float lacznesaldo;
for (i=0;i<konta.size();i++){
lacznesaldo+=konta[i]->getsaldo();
}
cout <<"\n Saldo kasy wynosi:" <<lacznesaldo;
};
//dodaj konto
void dodaj_konto(Temp* nowekonto){
konta.push_back(nowekonto);
}
//usun konto
void usun_konto(int nrprac){
int i;
for (i=0;i!=konta.size();i++){
if(nrprac==konta[i]->getpracownik()->getnr()){
if(konta[i]->getsaldo()<0)
cout<<"Nie mona usun konta o ujemnym saldzie!";
else {
konta.erase(konta.begin()+i);
cout<<"Usunieto konto o podanym nr";
break;}
}
}
if (i==konta.size()){
cout<<"Nie znaleziono konta o podanym nr";
}
}
void edytuj_konto(int nrprac,float zmiana){
int i;
for (i=0;i<konta.size();i++){
if(nrprac==(konta[i]->getpracownik()->getnr()))
{
*konta[i]+=zmiana;
break;
}
}
if (i==konta.size()){
cout<<"Nie znaleziono konta o podanym nr";
}
}
void stankont(){//wyswietlania
int i;
for (i=0;i<konta.size();i++){
cout<<"\n";
cout<<konta[i]->getpracownik()->getnr()<<". "<<konta[i]->getpracownik()->getimie()<<" "<<konta[i]->getpracownik()->getnazwisko();
cout<<" stan konta="<<konta[i]->getsaldo();
}}
void przelew(int komu,int odkogo,float ile){
try{
int i,komui=-1,odkogoi=-1;
for(i=0;i!=konta.size();i++){
if (komu==konta[i]->getpracownik()->getnr())
komui=i;
if(odkogo==konta[i]->getpracownik()->getnr())
odkogoi=i;
}
if (odkogoi==-1 || komui==-1)
cout<<"Nie znaleziono pracownika";
else {
if ((konta[komui]->getpracownik()->getpozyczka()==0 )||( konta[odkogoi]->getpracownik()->getpozyczka()==0)) {
cout<<"\nStudent nie ma pozwolenia na wykonywanie przelewow\n";}
else{
if((konta[odkogoi]->getsaldo())>ile){
*konta[komui]+=ile;
*konta[odkogoi]-=ile;
cout<<"Wykonano przelew\n";
}
else {
cout<<"\nNie mozna od tej osoby pozyczyc\n";
}
}}
throw 10;}
catch (int i){
if(i==10){
}
}
}
void odczyt(){
ifstream plik;
string imie,nazwisko,typ;
float saldo;
int nr;
try {
plik.open("dane.txt");
if (plik.good()) {
while(!plik.eof()){
plik >>typ>>imie >> nazwisko>>nr>>saldo;
if(plik.eof()) break;
if(typ=="programista"){
int pozyczka1=1;
programista *nowyprogramista = new programista(imie,nazwisko,nr,pozyczka1);
konto *nowekonto = new konto(nowyprogramista,saldo);
dodaj_konto(nowekonto);
}
else if(typ=="student"){
int pozyczka1=0;
student *nowystudent = new student(imie,nazwisko,nr,pozyczka1);
konto *nowekonto = new konto(nowystudent,saldo);
dodaj_konto(nowekonto);
}
}}}
catch(...){
cout<<"Nie udao si otworzy pliku";
}
plik.close();
}
void zapis(){
int i;
ofstream plik;
plik.open("dane.txt");
for(i=0;i<konta.size();i++) {
konta[i]->sprawdztyp(plik);
}
}
};
| true |
e60d8ab3a029c49ee8038ee62c2e7aa352d60e0c | C++ | stories2/OpenCV | /OpenCV/OpenCV/makefile.cpp | UHC | 3,190 | 2.71875 | 3 | [] | no_license | #include "highgui.h"
#include "cv.h"
#define pic_width 15000
#define pic_height 500
#define limit 10
struct database
{
float data[limit];
struct database *link;
};
void load(database *,char *, int *, int *);
void draw_img(IplImage *, database *, int, int);
float get_y(int, float);
float get_x(int, float);
void output(IplImage *);
void release(IplImage *);
int main()
{
int height = 0, width = 0;
IplImage *target = cvCreateImage(cvSize(pic_width,pic_height),IPL_DEPTH_8U,3);
struct database *db = new database;
load(db, "output.txt", &width, &height);
draw_img(target, db, width, height);
output(target);
release(target);
printf("debug\n");
return 0;
}
void release(IplImage *target)
{
cvSaveImage("output.jpg", target);
cvDestroyAllWindows();
cvReleaseImage(&target);
}
void output(IplImage *target)
{
cvNamedWindow("result");
cvShowImage("result", target);
cvWaitKey(0);
}
void draw_img(IplImage *target, database *db, int width, int height)
{
int threshold = 500, line_width = 2;
db = db->link;
cvLine(target, cvPoint(0, get_y(height, threshold)), cvPoint(get_x(width, pic_width), get_y(height, threshold)), cvScalar(50, 150, 250), line_width);
while (db->link)
{
int x, y;
x = get_x(width, db->data[3]);//īƮ
y = get_y(height, db->data[0]);//
//1 : з¼
//cvSet2D(target,y , x, cvScalar(255,0,0));
cvLine(target, cvPoint(x, y), cvPoint(get_x(width, db->link->data[3]), get_y(height, db->link->data[0])), cvScalar(255, 0, 0), line_width);
cvLine(target, cvPoint(x, get_y(height, db->data[1])), cvPoint(get_x(width, db->link->data[3]), get_y(height, db->link->data[1])), cvScalar(100, 100, 100), line_width);
//cvLine(target, cvPoint(get_x(width, db->link->data[3]), get_y(height, db->link->data[1])), cvPoint(get_x(width, db->data[3]), get_y(height, db->data[1])), cvScalar(0, 0, 0), 1);
if (db->data[6])
{
cvLine(target, cvPoint(x, 0), cvPoint(x, pic_height), cvScalar(0, 255, 0), line_width);
}
if (db->data[7])
{
cvLine(target, cvPoint(x, 0), cvPoint(x, pic_height), cvScalar(0, 0, 255), line_width);
}
if (db->data[8])
{
cvLine(target, cvPoint(x, 0), cvPoint(x, pic_height), cvScalar(223, 78, 204), line_width);
}
if (db->data[9])
{
cvLine(target, cvPoint(x, 0), cvPoint(x, pic_height), cvScalar(106, 226, 186), line_width);
}
db = db->link;
}
printf("test");
}
float get_x(int width, float target)
{
return (float)pic_width / width * target;
}
float get_y(int height, float target)
{
return pic_height - ((float)pic_height / height * target);
}
void load(database *target, char *path, int *width, int *height)
{
freopen(path, "r", stdin);
int i;
bool running = true;
database *node = NULL, *temp = target;
while (running)
{
node = new database;
for (i = 0; i < limit; i += 1)
{
scanf("%f", &node->data[i]);
if (i == 0 && node->data[i] == -1)
{
running = false;
break;
}
}
if ((int)node->data[0] > *height)
{
*height = (int)node->data[0];
}
if ((int)node->data[1] > *height)
{
*height = (int)node->data[1];
}
*width = *width + 1;
node->link = NULL;
temp->link = node;
temp = node;
}
} | true |
ee4681a7f710394a5bf14889ed9c4693db5d6b9d | C++ | schemp98/Cpp_Certification_Course | /Exercise/CA3/deitel_cpp10_sourcecode/deitel_cpp10_sourcecode/ch04/Fig04_10/ClassAverage.cpp | UTF-8 | 1,956 | 3.28125 | 3 | [] | no_license | // Fig. 4.10: ClassAverage.cpp
// Solving the class-average problem using counter-controlled iteration.
#include <iostream>
using namespace std;
int main() {
// initialization phase
int total{0}; // initialize sum of grades entered by the user
unsigned int gradeCounter{1}; // initialize grade # to be entered next
// processing phase uses counter-controlled iteration
while (gradeCounter <= 10) { // loop 10 times
cout << "Enter grade: "; // prompt
int grade;
cin >> grade; // input next grade
total = total + grade; // add grade to total
gradeCounter = gradeCounter + 1; // increment counter by 1
}
// termination phase
int average{total / 10}; // int division yields int result
// display total and average of grades
cout << "\nTotal of all 10 grades is " << total;
cout << "\nClass average is " << average << endl;
}
/**************************************************************************
* (C) Copyright 1992-2017 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
*************************************************************************/
| true |
bc79f2caed04005b2260570c5965ded0dc8874be | C++ | Farmak09/Group-Movement | /Solution/Motor2D/Squad.h | UTF-8 | 544 | 2.515625 | 3 | [] | no_license | #ifndef SQUAD
#define SQUAD
#include "p2List.h"
#include "p2DynArray.h"
#include "Entity.h"
class Squad
{
public:
Squad();
Squad(p2List<Entity*> &squadMembers);
~Squad();
bool Update(float dt);
void StartMovement(iPoint placeClicked);
void GenerateNewPaths();
bool CreateMainPath();
void CreateSecondaryPaths();
bool SelectNewLeader();
void CopyPathData(Entity* entity);
public:
p2List<Entity*> squadMembers;
Entity* squadLeader;
bool isMoving = false;
iPoint destination;
p2DynArray<iPoint> leaderPath;
};
#endif // SQUAD
| true |
4f384dc6882cee5c7a977b646f7c45982e987ca6 | C++ | vadshos/oopHome-Work-2 | /Avia/Avia/Date.h | UTF-8 | 1,772 | 3.765625 | 4 | [] | no_license | #pragma once
#include <iostream>
#include <string>
class Date {
public:
Date(int d = 0, int m = 0, int y = 0) {
setDate(d, m, y);
}
Date(const Date& date) {
setDate(date.day, date.month, date.year);
}
int getDay() const {
return day;
}
int getMonth() const {
return month;
}
int getYear() const {
return year;
}
void setDay(int day) {
this->day = day;
}
void setMonth(int month) {
this->month = month;
}
void setYear(int year) {
this->year = year;
}
void setDate(int day, int month, int year) {
if (isValidDate(day, month, year)) {
setDay(day);
setMonth(month);
setYear(year);
}
else {
throw std::string("Not valid date");
}
}
void print() const {
std::cout << day << '/'
<< month << '/'
<< year << std::endl;
}
static bool isValidDate(int day, int month, int year) {
// Здесь необходимо описать процедуру проверки даты на корректность
return true;
}
static bool isLeapYear(int year) {
// Здесь необходимо проверить является ли год високосным
return false;
}
static int dayInMonth(int month) {
// Здесь определить количество дней в месяце
return 0;
}
friend std::ostream& operator<<(std::ostream& os, const Date& obj) {
os << obj.day << '/'
<< obj.month << '/'
<< obj.year;
return os;
}
private:
int day;
int month;
int year;
}; | true |
f31cfe11758b66b59f5f02ab7b6c541bd9884f24 | C++ | aoyandong/algorithms | /algorithms/search_recursion/word_ladder.cpp | UTF-8 | 2,647 | 3.1875 | 3 | [] | no_license | class Solution {
public:
/**
* @param start, a string
* @param end, a string
* @param dict, a set of string
* @return an integer
*/
/* int ladderLength(string start, string end, unordered_set<string> &dict) {
// write your code here
// 1-way BFS, much slower than 2-way BFS
unordered_map<string,bool> map;
queue<string> Q;
int length=0;
if (start==end) return 1;
int len = start.length(), n;
string cur,tmp;
Q.push(start);
map[start] = true;
while (!Q.empty()){
length++;
n = Q.size();
for (int k=0; k<n; k++){
cur = Q.front();
Q.pop();
for (int i=0; i<len; i++){
tmp = cur;
for (int j=0; j<26; j++){
tmp[i] = 'a'+j;
if (tmp==end) return length+1;
if (dict.find(tmp)!=dict.end() && map.find(tmp)==map.end()){
Q.push(tmp);
map[tmp] = true;
}
}
}
}
}
return 0;
}*/
int ladderLength(string start, string end, unordered_set<string> &dict) {
// 2-way BFS
unordered_set<string> set1;
unordered_set<string> set2;
int level=2;
if (start==end) return 1;
bool flag;
set1.insert(start);
set2.insert(end);
while (!set1.empty() && !set2.empty()){
if (set1.size()<=set2.size()) flag=helper(set1,set2,dict);
else flag=helper(set2,set1,dict);
if (flag) return level;
else level++;
}
return 0;
}
private:
bool helper(unordered_set<string> &set1, unordered_set<string> &set2, unordered_set<string> &dict){
unordered_set<string> set_t;
char tmp;
for (auto i=set1.begin();i!=set1.end();i++){
string cur = *i;
for (int i=0; i<cur.length(); i++){
tmp = cur[i];
for (int j=0; j<26; j++){
cur[i] = 'a'+j;
if (set2.find(cur)!=set2.end()) return true;
if (dict.find(cur)!=dict.end()){
set_t.insert(cur);
dict.erase(cur);
}
}
cur[i] = tmp;
}
}
swap(set1,set_t);
return false;
}
}; | true |
08d5c435b384492c10424b9d13e0be6a2e0d14e3 | C++ | AnabaenaQing/Source-Code_ShaderX_GPU-Pro_GPU-Zen | /GPU Pro5/06_Compute/Object-order Ray Tracing for Fully Dynamic Scenes/beMath/header/beMath/beSphereDef.h | UTF-8 | 4,966 | 3.046875 | 3 | [
"MIT",
"BSD-3-Clause"
] | permissive | /*****************************************************/
/* breeze Engine Math Module (c) Tobias Zirr 2011 */
/*****************************************************/
#pragma once
#ifndef BE_MATH_SPHERE_DEF
#define BE_MATH_SPHERE_DEF
#include "beMath.h"
#include "beSphereFwd.h"
#include "beTuple.h"
#include "beVectorDef.h"
namespace beMath
{
/// Sphere class.
template <class Component, size_t Dimension>
class sphere : private tuple<sphere<Component, Dimension>, Component, Dimension + 1>
{
private:
typedef class tuple<sphere<Component, Dimension>, Component, Dimension + 1> base_type;
public:
/// Component type.
typedef Component component_type;
/// Size type.
typedef typename base_type::size_type size_type;
/// Element count.
static const size_type dimension = Dimension;
/// Compatible scalar type.
typedef component_type compatible_type;
/// Position type.
typedef vector<component_type, dimension> position_type;
/// Radius type.
typedef component_type radius_type;
/// Compatible scalar type.
typedef component_type compatible_type;
/// Tuple type.
typedef base_type tuple_type;
position_type center;
radius_type radius;
/// Creates a default-initialized sphere.
LEAN_INLINE sphere()
: center(),
radius() { }
/// Creates an uninitialized sphere.
LEAN_INLINE sphere(uninitialized_t)
: center(uninitialized) { }
/// Initializes all sphere elements from the given tuple.
template <class TupleClass>
LEAN_INLINE explicit sphere(const class tuple<TupleClass, component_type, dimension + 1> &right)
: center(right),
radius(right[dimension]) { }
/// Initializes all sphere elements from the given sphere position & radius value.
template <class TupleClass>
LEAN_INLINE sphere(const class tuple<TupleClass, component_type, dimension> &position, const radius_type &radius)
: center(position),
radius(radius) { }
/// Initializes all sphere elements from the given sphere position & point on sphere.
template <class TupleClass1, class TupleClass2>
LEAN_INLINE sphere(const class tuple<TupleClass1, component_type, dimension> &position,
const class tuple<TupleClass2, component_type, dimension> &point)
: center(position),
radius( dist(position, point) ) { }
/// Scales this sphere by the given value.
LEAN_INLINE sphere& operator *=(const compatible_type &right)
{
radius *= right;
return *this;
}
/// Scales this sphere dividing by the given value.
LEAN_INLINE sphere& operator /=(const compatible_type &right)
{
radius /= right;
return *this;
}
/// Accesses the n-th component.
LEAN_INLINE component_type& element(size_type n) { return data()[n]; }
/// Accesses the n-th component.
LEAN_INLINE const component_type& element(size_type n) const { return data()[n]; }
/// Accesses the n-th component.
LEAN_INLINE component_type& operator [](size_type n) { return data()[n]; }
/// Accesses the n-th component.
LEAN_INLINE const component_type& operator [](size_type n) const { return data()[n]; }
/// Gets a raw data pointer.
LEAN_INLINE component_type* data() { return m_position.data(); }
/// Gets a raw data pointer.
LEAN_INLINE const component_type* data() const { return m_position.data(); }
/// Gets a raw data pointer.
LEAN_INLINE const component_type* cdata() const { return m_position.cdata(); }
/// Gets a compatible tuple reference to this sphere object.
LEAN_INLINE tuple_type& tpl() { return static_cast<tuple_type&>(*this); }
/// Gets a compatible tuple reference to this sphere object.
LEAN_INLINE const tuple_type& tpl() const { return static_cast<const tuple_type&>(*this); }
};
/// Scales the given sphere by the given value.
template <class Component, size_t Dimension>
LEAN_INLINE sphere<Component, Dimension> operator *(const typename sphere<Component, Dimension>::compatible_type &left, const sphere<Component, Dimension> &right)
{
return sphere<Component, Dimension>(right.center, left * right.radius);
}
/// Scales the given sphere by the given value.
template <class Component, size_t Dimension>
LEAN_INLINE sphere<Component, Dimension> operator *(const sphere<Component, Dimension> &left, const typename sphere<Component, Dimension>::compatible_type &right)
{
return sphere<Component, Dimension>(left.center, left.radius * right);
}
/// Scales the given sphere dividing by the given value.
template <class Component, size_t Dimension>
LEAN_INLINE sphere<Component, Dimension> operator /(const typename sphere<Component, Dimension>::compatible_type &left, const sphere<Component, Dimension> &right)
{
return sphere<Component, Dimension>(right.center, left / right.radius);
}
/// Scales the given sphere dividing by the given value.
template <class Component, size_t Dimension>
LEAN_INLINE sphere<Component, Dimension> operator /(const sphere<Component, Dimension> &left, const typename sphere<Component, Dimension>::compatible_type &right)
{
return sphere<Component, Dimension>(left.center, left.radius / right);
}
} // namespace
#endif | true |
e2decff9a1c22a4af9aede64a20e54aa1a5a3cbf | C++ | jagolu/Universidad | /2/1_Cuatrimestre/ED/Teoria/Ejercicios_STL/Ejercicio15.cpp | UTF-8 | 1,029 | 2.984375 | 3 | [] | no_license | #include <iostream>
#include <list>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
int main(int argc, char * argv[]){
pair<float, float>a;
a=(make_pair(atof(argv[1]),atof(argv[2])));
list<pair<float, float> >coordenadas;
float
n;
do{
cout<<"Coordenada 1: ";
cin>>n;
if(n!=0){
pair<double, double> a;
a.first=n;
cout<<"Coordenada 2: ";
cin>>n;
a.second=n;
coordenadas.push_back(a);
}
}while(n!=0);
pair<float,int>veces1=make_pair(a.first,0);
pair<float,int>veces2=make_pair(a.second,0);
for(list<pair<float, float> >::iterator i=coordenadas.begin();i!=coordenadas.end();i++){
if(a.first==(*i).first){
veces1.second=veces1.second+1;
}
if(a.first==(*i).second){
veces1.second=veces1.second+1;
}
if(a.second==(*i).first){
veces2.second=veces2.second+1;
}
if(a.second==(*i).second){
veces2.second=veces2.second+1;
}
}
cout<<endl<<veces1.first<<" ----> "<<veces1.second<<" veces"<<endl;
cout<<veces2.first<<" ----> "<<veces2.second<<" veces"<<endl;
}
| true |
829f2bfdc7fa261bbd727be2cd490a559a8876a8 | C++ | tochiton/Data-Structures | /CS Lab practice/Lab1/cs163_list.cpp | UTF-8 | 3,616 | 3.46875 | 3 | [] | no_license | #include "cs163_list.h"
using namespace std;
//Sum all of the data together in a LLL
int list::sum_total()
{
//FIRST do this iteratively here. Then recursively
//COMMENT out the iterative version when rewriting
//the solution recursively
//To solve this recursively write another
//function: int sum_total(node * head);
//and call it from this function
/*
if(!head)
return 0;
int sum_total;
node * current = head;
while (current)
{
sum_total= sum_total + current -> data;
current = current ->next;
}
*/
return sum_total(head);
}
//Now implement the function recursively!
int list::sum_total(node * head)
{
if(!head)
return 0;
return head->data + sum_total(head -> next);
/*
int result=0;
if(!head)
return result;
result = sum_total(head -> next);
result = result + head -> data;
return result;
*/
}
// *************************************************
//Remove the last node in a LLL. Return false if the
//list is empty and nothing is removed
bool list::remove_last()
{
//Write your code here
//FIRST do this iteratively here. Then recursively
//COMMENT out the iterative version when rewriting
return remove_last(head, tail);
}
//Now implement the function recursively!
bool list::remove_last(node * & head, node * & tail)
{
if(!head)
return 0;
if(head ->next == tail)
{
node * temp = tail;
tail = head;
delete temp;
temp = NULL;
tail -> next = NULL;
return 1;
}
remove_last(head -> next, tail);
}
// ************************************************
//Remove all nodes in a LLL. Remove false if there is
//nothing to remove
bool list::remove_all()
{
//Remove all nodes in a LLL
//FIRST do this iteratively here. Then recursively
//COMMENT out the iterative version when rewriting
}
//Now implement the function recursively!
bool list::remove_all(node * & head)
{
}
// ************************************************
//Return true if the requested item (sent in as an argument)
//is in the list, otherwise return false
bool list::find_item(int item_to_find)
{
//Write your code here
return find_item(head, item_to_find);
}
//Now implement the function recursively!
bool list::find_item(node * head, int item_to_find)
{
if(!head)
return 0;
if(head ->data == item_to_find)
return true;
return find_item(head -> next, item_to_find);
}
// ************************************************
//Make a complete copy of a LLL
bool list::copy(list & from)
{
//Write your code here
}
//Now implement the function recursively
bool list::copy(node * & dest_head, node * & dest_tail, node * source)
{
//if(!source)
// return 0;
}
bool list:: find_last2nd_node(node * head, node * & temp_copy)
{
if(head -> next == tail)
{
temp_copy = head;
return 1;
}
find_last2nd_node(head -> next, temp_copy);
}
bool list::swap_2nd_last()
{
return swap_2nd_last(head, tail);
}
bool list::swap_2nd_last(node * head, node * & tail)
{
node * temp_last2nd = NULL;
find_last2nd_node(head, temp_last2nd); // gets the 2nd last node from the list
node * temp_2ndnode = head -> next; // gets the second node from the list
tail -> next = temp_2ndnode -> next;
head -> next = tail;
temp_last2nd -> next = temp_2ndnode;
temp_2ndnode -> next = NULL;
tail = temp_2ndnode;
}
| true |
986472e68fd9895c75335ee9944cfc3596d84092 | C++ | HakeT2Lab/CS246-2020 | /Labs/Lab10/lab10B.cpp | UTF-8 | 1,164 | 3.234375 | 3 | [] | no_license | #include <iostream>
#include <string>
#include "Vector.h"
#include "Node.h"
#include "HashTable.h"
using ulong = unsigned long;
bool TwoSum(ds::Vector<ulong>& data, ulong target){
// std::cout<<"is working";
ulong sum=0;
ulong sumtwo;
int c=0;
if(data.Length() != 0){
if(target < 1000){
for(int i = 0; i< data.Length(); i++){
sum = sum + data[c];
if(i == data.Length()-1){
if(sumtwo == sum){
sumtwo = sum;
sum = 0;
}
}
sumtwo = sum;
i=0;
c++;
}
}
if(c== data.Length()-1){
if(){
return true;
}else{
return false;
}
}
}else if(target >= 1000 || data.Length() <= 1){
return false;
}else{
return false;
}
return false;
}
int main()
{
ds::Vector<ulong> Data;
ulong target= 4;
double array[] = {1,2,2,1,4,3};
//Problem I came across: Above numbers give a sum of 5(1 + 2 + 2) instead of 3(1 + 2)
std::cout<<"\n"<<Data.Length()<<"\n";
for(int i = 0; i< 6; i++){
Data.Insert(array[i]);
}
TwoSum(Data, target);
return 0;
}
| true |
f5378e2c08dc68fda3e3ce6447a06b3d9f8f518f | C++ | Seventeen-29/124_PA1 | /randmst.cpp | UTF-8 | 5,833 | 3.234375 | 3 | [] | no_license | /**
*Programming Assignemnt 1, Source Code
*Chris Zhu, Rakesh Nori
**/
#include <algorithm>
#include <iostream>
#include <fstream>
#include <iomanip>
#include <vector>
#include <string>
#include <cmath>
#include <climits>
#include <time.h>
#include <chrono>
using namespace std;
const double scalar = 1.8; //k(n) = scalar * (expected edge weight)
const int non_opt_threshold = 128; //optimize using k(n) if numVertices > threshold
double dist(vector<double> pt1, vector<double> pt2){
double sum = 0;
for (int i = 0; i < pt1.size(); ++i){
double delta = (pt1[i] - pt2[i]);
sum += delta * delta;
}
return sqrt(sum);
}
vector<double> randPoint(int numDimensions){
vector<double> pt;
for (int i = 0; i < numDimensions; i++){
pt.push_back((double) rand()/RAND_MAX);
}
return pt;
}
int getBoxCoord(vector<double> pt, double weight_threshold, int numDimensions){
int grid_size = ceil (1 / weight_threshold);
int index_accumulator = 0;
for(int j = 0; j < numDimensions; j++){ //iterate across currPoint to get box index
index_accumulator += (int) ((floor (pt[j] / weight_threshold)) * pow(grid_size, j));
}
return index_accumulator;
}
vector<int> getNearbyBoxes(int currBox, int gridSize, int numDimensions){
int max = ((int) pow(gridSize, numDimensions));
vector<int> temp;
temp.push_back(0);
for(int i = 0; i < numDimensions; i++){
vector<int> curr;
for(int elt : temp){
curr.push_back(elt);
curr.push_back(elt + (int) pow(gridSize, i));
curr.push_back(elt - (int) pow(gridSize, i));
}
temp = curr;
}
vector<int> output;
for(int elt : temp){
if(elt + currBox < max && elt + currBox >= 0){
output.push_back(elt + currBox);
}
}
return output;
}
double prims(int numVertices, int numDimensions, int suppressOutput){
if (numDimensions <= 0){
throw invalid_argument("error: prims_nonzero dim must be > 0");
}
vector<vector<double>> graphVertices;
vector<bool> visited(numVertices, false);
vector<double> distances(numVertices, numDimensions * 1.0);
distances[0] = 0.0; //pick starting vertex to be index 0
double totalEdgeWeight = 0;
double weight_threshold = sqrt(numDimensions); //worst case distance bound, unused for n = 0, 2, 3, 4
if(numDimensions == 2 && numVertices > non_opt_threshold){
weight_threshold = scalar * 0.7 * pow(numVertices, -0.5);
}
else if(numDimensions == 3 && numVertices > non_opt_threshold){
weight_threshold = scalar * pow(numVertices, -0.37);
}
else if(numDimensions == 4 && numVertices > non_opt_threshold){
weight_threshold = scalar * pow(numVertices, -0.29) + pow(numVertices, -1.7);
}
if(suppressOutput > 0){
cout << "Using weight_threshold k(N) = " << weight_threshold << endl;
}
int grid_size = ceil (1 / weight_threshold);
vector<vector<int>> boxes(pow(grid_size, numDimensions));
for (int i = 0; i < numVertices; ++i){
vector<double> currPoint = randPoint(numDimensions);
graphVertices.push_back(currPoint); //generate the graph
int currIndex = getBoxCoord(currPoint, weight_threshold, numDimensions);
boxes[currIndex].push_back(i);
}
for (int i = 0; i < numVertices; ++i){
int minIndex = -1;
double minDist = INT_MAX;
//find minimal distance vertex that is not yet visited, get index
for(int k = 0; k < numVertices; ++k){
if (!visited[k] && (distances[k] < minDist)){
minIndex = k;
minDist = distances[k];
}
}
totalEdgeWeight += distances[minIndex];
visited[minIndex] = true;
for (int nearbyBox : getNearbyBoxes(getBoxCoord(graphVertices[minIndex],
weight_threshold, numDimensions), grid_size, numDimensions)){
for (int nearbyVertexIndex : boxes[nearbyBox]){
if (!visited[nearbyVertexIndex]){
double currDist = dist(graphVertices[nearbyVertexIndex], graphVertices[minIndex]);
if (currDist < distances[nearbyVertexIndex]){
distances[nearbyVertexIndex] = currDist;
}
}
}
}
if (suppressOutput > 1 && i % 700 == 0){
printf ("%2.2f%%\n", 100 * ((double) i) / numVertices);
}
}
return totalEdgeWeight;
}
double primsZero(int numVertices, int suppressOutput){
vector<bool> visited(numVertices, false);
vector<double> distances(numVertices, 10.0);
distances[0] = 0.0; //pick starting vertex to be index 0
double totalEdgeWeight = 0;
for (int i = 0; i < numVertices; ++i){
int minIndex = -1;
double minDist = 1000.0;
//find minimal distance vertex that is not yet visited, get index
for(int k = 0; k < numVertices; ++k){
if (!visited[k] && (distances[k] < minDist)){
minIndex = k;
minDist = distances[k];
}
}
totalEdgeWeight += distances[minIndex];
visited[minIndex] = true;
for(int k = 0; k < numVertices; ++k){
if(!visited[k]){
double currDist = (double) rand()/RAND_MAX;
if(currDist < distances[k]){
distances[k] = currDist;
}
}
}
if (suppressOutput > 1 && i % 700 == 0){
printf ("%2.2f%%\n", 100 * ((double) i) / numVertices);
}
}
return totalEdgeWeight;
}
int main(int argc, char *argv[]){
srand((unsigned)time(NULL));
int flag = stoi(argv[1]);
int n = stoi(argv[2]);
int numTrials = stoi(argv[3]);
int numDimensions = stoi(argv[4]);
auto start = chrono::high_resolution_clock::now();
double results = 0.0;
for (int i = 0; i < numTrials; i++)
{
double currResult = 0;
if(numDimensions == 0){
currResult = primsZero(n, flag);
}
else{
currResult = prims(n, numDimensions, flag);
}
results += currResult;
}
results = results / numTrials;
auto stop = chrono::high_resolution_clock::now();
auto duration = chrono::duration_cast<chrono::milliseconds>(stop - start);
if(flag > 0){
cout << "N = " << n << ". Dim = " << numDimensions << ". AVG MST weight: " << results << " [" <<
duration.count() << " ms]" << endl;
}
else{
cout << results << " " << n << " " << numTrials << " " << numDimensions << endl;
}
} | true |
05ca7141c1c1a4225f99de101797702c33a77a21 | C++ | AndrijaS37N/chess-game | /chess-game/Knight.cpp | UTF-8 | 506 | 3.21875 | 3 | [] | no_license | #include "Knight.h"
bool Knight::areSquaresLegal(int srcRow, int srcCol, int destRow, int destCol, ChessPiece* boardMove[8][8])
{
// destination square is unoccupied or occupied by opposite color
if ((srcCol == destCol + 1) || (srcCol == destCol - 1))
{
if ((srcRow == destRow + 2) || (srcRow == destRow - 2))
return true;
}
if ((srcCol == destCol + 2) || (srcCol == destCol - 2))
{
if ((srcRow == destRow + 1) || (srcRow == destRow - 1))
return true;
}
return false;
}
| true |
98eaee83b2d7b00911abaddf8355f349c350f1f9 | C++ | enterpriseih/SkipList | /test.cc | UTF-8 | 5,263 | 3.390625 | 3 | [] | no_license | #include "skiplist.h"
#include <cassert>
#include <chrono>
#include <cstdio>
#include <iostream>
#define Log(fmt, ...) fprintf(stderr, fmt, __VA_ARGS__)
// return random = [min, max]
int random_range(int min, int max) { return random() % (max - min + 1) + min; }
void Test(const int max_size) {
int* nums = new int[max_size];
for (int i = 0; i < max_size; ++i) {
nums[i] = i;
}
for (int i = 0; i < max_size - 1; ++i) {
int random_index = random_range(i + 1, max_size - 1);
int temp = nums[random_index];
nums[random_index] = nums[i];
nums[i] = temp;
}
SkipList<int> sl;
auto t1 = std::chrono::steady_clock::now();
// random insert
for (int i = 0; i < max_size; ++i) {
sl.Insert(nums[i]);
}
auto t2 = std::chrono::steady_clock::now();
// random query by index
for (int i = 0; i < max_size; ++i) {
int x = sl[random() % max_size];
(void)x;
}
auto t3 = std::chrono::steady_clock::now();
// random query by data
for (int i = 0; i < max_size; ++i) {
SkipList<int>::Iterator it = sl.Find(nums[i]);
}
auto t4 = std::chrono::steady_clock::now();
// random query index of data
for (int i = 0; i < max_size; ++i) {
int index = sl.IndexOf(nums[i]);
(void)index;
}
auto t5 = std::chrono::steady_clock::now();
// random delete
for (int i = 0; i < max_size; ++i) {
sl.Erase(sl.Find(nums[i]));
}
auto t6 = std::chrono::steady_clock::now();
assert(sl.Size() == 0);
Log("%d elements random insert,timespan=%ldms\n", max_size,
std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1).count());
Log("%d elements random query by index,timespan=%ldms\n", max_size,
std::chrono::duration_cast<std::chrono::milliseconds>(t3 - t2).count());
Log("%d elements random query by data,timespan=%ldms\n", max_size,
std::chrono::duration_cast<std::chrono::milliseconds>(t4 - t3).count());
Log("%d elements random query index of data,timespan=%ldms\n", max_size,
std::chrono::duration_cast<std::chrono::milliseconds>(t5 - t4).count());
Log("%d elements random delete,timespan=%ldms\n", max_size,
std::chrono::duration_cast<std::chrono::milliseconds>(t6 - t5).count());
Log("%s\n",
"------------------------------------------------------------------");
delete[] nums;
}
void Usage() {
class Foo {
public:
Foo() {} // requires default constructor
Foo(const Foo& other) { num_ = other.num_; } // requires copy constructor
~Foo() {}
Foo(int num) : num_(num) {}
int get_num() const { return num_; }
bool operator<(const Foo& other) const { // requires less operator
return num_ < other.num_;
}
private:
int num_;
};
struct Compare {
bool operator()(const Foo& foo, const Foo& other) const {
return foo.get_num() < other.get_num();
}
};
SkipList<Foo> sl; // use operator< to compare
SkipList<Foo, Compare> sl0; // optional use Compare Object
assert(sl.Empty());
// Insert O(logn)
Foo foo(1);
sl.Insert(foo); // copy constructor
sl.Insert(Foo(2)); // move copy constructor if exist
sl.Insert(Foo(6));
sl.Insert(Foo(4));
assert(sl.Size() == 4);
assert(!sl.Empty());
// Query O(logn)
// Query by data, return iterator
auto it = sl.Find(foo);
assert(it->get_num() == 1);
assert((*it).get_num() == 1);
assert((it++)->get_num() == 1);
assert(it->get_num() == 2);
assert(++it == sl.Find(Foo(4)));
it = sl.Find(Foo(10));
assert(it == sl.End());
it = sl.FindFirstGreater(Foo(4));
assert(it->get_num() == 6);
it = sl.FindLastLess(Foo(4));
assert(it->get_num() == 2);
// Query by data, return index
assert(sl.IndexOf(foo) == 0);
assert(sl.IndexOf(Foo(2)) == 1);
// Query by index, return const T&
assert(sl.At(0).get_num() == sl[0].get_num());
// for data range 2->6
for (it = sl.Find(2); it != sl.Find(6); ++it) {
assert(it->get_num() == (*it).get_num());
}
// for data range all
for (it = sl.Begin(); it != sl.End(); ++it) {
assert(it->get_num() == (*it).get_num());
}
// for index range (low efficient, O(nlog))
for (int i = 1; i < 4; ++i) {
assert(sl[i].get_num() == sl.At(i).get_num());
}
// for index range (high efficient, O(n))
auto begin_it = sl.Find(sl[1]);
auto end_it = sl.Find(sl[3]);
for (it = begin_it; it != end_it; ++it) {
assert(it->get_num() == (*it).get_num());
}
// Delete O(logn)
it = sl.Find(foo);
sl.Erase(it);
assert(it->get_num() == 2);
assert(sl.Erase(Foo(6)));
assert(sl.Find(Foo(6)) == sl.End());
assert(sl.Size() == 2);
int deleted = 0;
// Conditional deletion
for (it = sl.Begin(); it != sl.End();) {
if (random() % 2 == 0) {
sl.Erase(it);
++deleted;
} else {
++it;
}
}
assert(sl.Size() == (2 - deleted));
}
int main(int argc, char const* argv[]) {
(void)argc;
(void)argv;
Usage();
Test(10000);
Test(100000);
Test(1000000);
// LeetCode:
// 1206. Design Skiplist
class Skiplist {
public:
Skiplist() {}
bool search(int target) { return sl_.Find(target) != sl_.End(); }
void add(int num) { sl_.Insert(num); }
bool erase(int num) { return sl_.Erase(num); }
private:
SkipList<int> sl_;
};
return 0;
} | true |
4ed3d4eae710b219d3886fbb0be0cf97070f51b7 | C++ | nkher/ctci | /c++/Chapter 17/Question17_7.cpp | UTF-8 | 2,183 | 3.953125 | 4 | [] | no_license | #include <iostream>
#include <string>
#include <vector>
using namespace std;
// declarations
string number_to_str(int number);
string number_to_str_100(int number);
// global variables
vector<string> digits = {"One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"};
vector<string> teens = {"Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
vector<string> tens = {"Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
vector<string> bigs = {"", "Thousand", "Million", "Billion"};
/** The main function used for doing the conversion */
string number_to_str(int number) {
if (number == 0) return "Zero";
if (number < 0) {
return "Negative" + number_to_str(-1 * number);
}
int count = 0;
string str = "";
// main logic starts here
while (number > 0) {
if (number%1000 != 0) {
str = number_to_str_100(number % 1000) + bigs[count] + " " + str;
}
number /= 1000;
count++;
}
return str;
}
/** Helper function that converts the ones, tens and Hundereds place */
string number_to_str_100(int number) {
string str = "";
/** Convert 100s place */
if (number >= 100) {
str += digits[number/100 - 1] + " Hundered ";
number %= 100;
}
/** Convert tens place */
if (number >= 11 && number <= 19) { // if number is a teen
str += teens[number - 11] + " ";
return str;
}
else if(number == 10 || number >= 20) {
str += tens[number/10 - 1] + " ";
number %= 10;
}
/** Converting ones place */
if (number >= 1 && number <= 9) {
str += digits[number - 1] + " ";
}
return str;
}
int main() {
string str;
for (int i=1; i<100; i++) {
str = number_to_str(i);
cout << i << " : " << str << endl;
}
cout << number_to_str(10045) << endl;
cout << number_to_str(98345) << endl;
cout << number_to_str(1000076) << endl;
cout << number_to_str(1000000000) << endl;
cout << endl;
return 0;
}
/*
Commands to run
----------------
g++ -std=c++11 Question17_7.cpp -o Question17_7
./Question17_7
*/
| true |
c46f933332062aed07c5172ccb447a76ee1f08ea | C++ | cwong907/CSCI1300 | /hmwk7/getRating.cpp | UTF-8 | 8,160 | 3.609375 | 4 | [] | no_license | // CSCI 1300 Fall 2019
// Author: Weige Wong
// Recitation: 203 - Soumyajyoti Bhattacharya
// Homework 7 - Problem 3
/*
1. Write a main function that has a username, title, users array, books array, users array size, and books array size
2. Write a function that takes those inputs and checks for the username in the users array
3. If it finds it then keep track of that index and then look for the book title in the books array and if that is found then keep track of that index
4. Return the username's rating of that book by searching through the users array
5. If neither the book nor the title can be found then return -3
Input: userName, title, users, books, userNum, booksNum (string, string, Users, Books, int, int)
Output: rating (int type)
Return: rating (int type)
*/
#include <iostream>
#include <fstream>
#include <string>
#include <stdio.h>
#include <ctype.h>
#include "User.h"
#include "Book.h"
using namespace std;
int split(string temp[], char delimiter, int length, string line)
{
int count = 0;
string word = "";
if(line == "") //checks for a blank sentence
{
return 0;
}
else
{
line = line + delimiter; //adds the delimiter to the end of the sentence so that the code can count the last word
for(int i = 0; i < line.length(); i++) //loops through the sentence
{
if(count >= length) //checks if the sentence is broken up into more chunks than the array size
{
return -1;
}
if(line[i] == delimiter) //checks if the sentence character is equal to the delimited
{
if(word != "") //checks if the word is blank
{
temp[count] = word; //assigns the word to an index in the array
count++; //counts to move to the next array
word = ""; //resets word to a blank string
}
}
else //if a sentence character doesn't equal the delimiter then it adds the character to the string word, as the loop goes through each character it builds the word again until it sees the delimiter
{
word = word + line[i];
}
}
}
return count;
}
int readBooks(string fileName, Book books[], int numBookStored, int booksArrSize)
{
string line = "";
int i = numBookStored;
ifstream in_file(fileName); //open files
if(i >= booksArrSize) //checks if the number of books is already larger than the array size
{
return -2;
}
else if(in_file.is_open()) //checks if the file opened properly
{
while(getline(in_file, line)) //goes line by line through the file
{
if(line != "") //checks if the line is empty
{
if(i == booksArrSize) //i is the counter for the number of lines and this checks if it becomes equal to the size of the array
{
return i;
}
string temp[2]; //declares variables used for the split function
int length = 2;
char delimiter = ',';
split(temp, delimiter, length, line); //calls the split function
books[i].setAuthor(temp[0]);
books[i].setTitle(temp[1]);
i++;
}
}
return i;
}
else //if the file fails to open
{
return -1;
}
}
int readRatings(string fileName, User users[], int numUsersStored, int usersArrSize, int maxCol)
{
int j = numUsersStored;
int counter = 0;
string line = "";
ifstream inFile(fileName); //open file and declares it
if(j >= usersArrSize) //checks if the number of users is equal to or greater than the maximum number of rows
{
return -2;
}
else if(inFile.is_open()) //check if the file opens properly
{
while(getline(inFile, line)) //goes line by line
{
if(line != "") //checks for an empty line
{
string temp[51];
char delimiter = ',';
int length = 51;
counter = split(temp, delimiter, length, line); //calls the split function
users[j].setUsername(temp[0]); //since names will always be the index 0 set the users[] array at whatever index equal to temp at 0
for(int i = 1; i < counter; i++) //the for loop goes through each column and sets it equal to the split array (starting at index 1 and going from there)
{
users[j].setRatingAt((i-1), stoi(temp[i])); //numUsers goes through each row but only gets added to once the line is done (basically each iteration of the while loop)
}
j++;
if(j == usersArrSize) //checks if the array is maxed out
{
return j;
}
}
}
return j;
}
else
{
return -1;
}
}
string convertToLower(string word)
{
string newWord = "";
string a;
for(int i = 0; i < word.length(); i++) //iterates through the word by character
{
a = tolower(word[i]); //sets a to the lowercase letter
newWord += a; //rebuilds the word
}
return newWord;
}
int getRating(string userName, string title, User users[], Book books[], int userNum, int booksNum)
{
int id1 = 0;
int foundUser = 0; // user found
int id2 = 0;
int foundBook = 0;
for(int i = 0; i < userNum; i++) //goes through the entire users array in the Users class
{
if(convertToLower(users[i].getUsername()) == convertToLower(userName)) //calls the convertToLower function while also checking if the username stored in the users array is the same as the username we're looking for
{
id1 = i; //marks what index it's at
foundUser++; //my weird version of a bool
break;
}
}
for(int j = 0; j < booksNum; j++) //loops through the stored books array
{
if(convertToLower(books[j].getTitle()) == convertToLower(title)) //converts titles to lowercase while checking if it matches our search query
{
id2 = j; //marks the index where title was found
foundBook++; //my weird version of a bool
break;
}
}
if(foundUser == 0 || foundBook == 0) // user or book not in the list if the counter increments to 1
{
return -3;
}
else
{
users[id1].setNumRatings(50); //sets the number of ratings
return users[id1].getRatingAt(id2); //gets the user and their rating
}
}
int main()
{
//Test 1
//Input: diane, Watership Down
//Output: 1
string userName = "diane";
string title = "Watership Down";
User users[100];
Book books[50];
int userNum = 100;
int booksNum = 50;
//Test 2
//Input: Cynthia, The Golden Compass
//Output: 4
string userNames = "cynthia";
string titles = "The Golden Compass";
int userNums = 100;
int booksNums = 50;
int numBookStored = 0;
int booksArrSize = 50;
readBooks("books.txt", books, numBookStored, booksArrSize); //populates the books array so we have something to look for
int numUsersStored = 0;
int userArrSize = 100;
int maxCol = 50;
readRatings("ratings.txt", users, numUsersStored, userArrSize, maxCol); //populates the users array so we can look for something in the first place
cout << getRating(userName, title, users, books, userNum, booksNum) << endl;
cout << getRating(userNames, titles, users, books, userNums, booksNums) << endl;
} | true |
f4ecc0a78a6dfc1ae72e2c7f75bf74b8b056c3ef | C++ | dh-wuho/myLeetCode | /C++/216_Combination_Sum_III.cpp | UTF-8 | 712 | 2.84375 | 3 | [] | no_license | class Solution {
public:
vector<vector<int>> combinationSum3(int k, int n) {
vector<vector<int>> res;
vector<int> tmpRes;
search(0, k, n, 1, tmpRes, res);
return res;
}
void search(int depth, int k, int n, int currPos, vector<int>& tmpRes, vector<vector<int>>& res) {
if(n < 0 || depth > k) {
return;
}
if(n == 0 && depth == k) {
res.push_back(tmpRes);
return;
}
for(int i = currPos; i < 10; i++) {
tmpRes.push_back(i);
search(depth + 1, k, n - i, i + 1, tmpRes, res);
tmpRes.pop_back();
}
}
}; | true |
e441f8f94ddcdb16d5ce8ca70e4a68f78739978c | C++ | briantsoi1107/1340-Project | /1340-Project/Action.h | UTF-8 | 651 | 2.578125 | 3 | [] | no_license | #ifndef Action_h
#define Action_h
#include <vector>
#include <string>
using namespace std;
class Action{ //use of class
private:
string itemslist[6]={ "Shuriken","Caltrop","Poison","Medicine","Book of Defensive Skills ","Book of Advanced Ninjutsu" };
public:
vector<int> itemsgot = {0,1,2,3}; //dynamic mememory management
string name;
int maxhp[4] = { 50,100,150,200 }, hp = 50, atk[4] = { 20,30,55,65}, def[4] = { 5,10,20,40 };
void printstatus(int stage);
void attack(int& enemyhp, int enemydef, int stage);
void items(int& enemyhp, int stage);
void gotitem();
void guard(int enemyatk, int stage);
};
#endif | true |
950695636e81d27185cb56de7274e0b5eaa0998b | C++ | C0nstanta/ITEA_CPP_BASE | /Lesson19_XOR_Encr_Decr/main.cpp | UTF-8 | 1,917 | 3.625 | 4 | [] | no_license | //
// main.cpp
// XOR_Encrypt_Decrypt_file
//
// Created by admin on 15.03.2021.
//
#include <iostream>
#include <vector>
#include <fstream>
using namespace std;
void EncryptFunc(const string& in_file_path, string& out_file_path, short& password)
{
ifstream in(in_file_path);
if (in)
{
string line;
vector<char> encrypt_file;
while(getline(in, line))
{
for (char l : line)
{
cout << (char)(l ^ password);
encrypt_file.push_back((char)(l ^ password));
}
}
cout << endl;
in.close();
ofstream out(out_file_path);
for (char e_f : encrypt_file)
{
out << e_f;
}
}
else
{
cout << "Error reading file! Wrong path.";
}
}
void DecryptFunc(const string& de_file_path, short& password)
{
ifstream in(de_file_path);
if (in)
{
string line;
vector<char> decrypt_file;
while(getline(in, line))
{
for (int l : line)
{
cout << (char)(l ^ password);
decrypt_file.push_back((char)(l ^ password));
}
}
cout << endl;
in.close();
}
else
{
cout << "Error reading file! Wrong path.";
}
}
int main(int argc, const char * argv[]) {
string en_file_path;
string de_file_path;
en_file_path = "in.txt";
de_file_path = "out.txt";
cout << "Input file path for encryption: " << endl;
cin >> en_file_path;
cout << "Input encrypt password: " << endl;
short pass = 0;
cin >> pass;
EncryptFunc(en_file_path, de_file_path, pass);
cout << "Input decrypt password: " << endl;
short de_pass = 0;
cin >> de_pass;
DecryptFunc(de_file_path, de_pass);
return 0;
}
| true |
b0ec21cc92554d38df24107938bb876a85e47808 | C++ | RadStr/Music-Keyboard | /Key.h | UTF-8 | 2,073 | 3 | 3 | [
"MIT"
] | permissive | #pragma once
#include <string>
#include "SDL.h"
enum KeyEventType {
KEY_PRESSED = 0,
KEY_RELEASED = 1
};
class TimestampAndID {
public:
// Constructor just copies constructor arguments to properties
TimestampAndID(Uint32 timestamp, size_t ID, KeyEventType keyEventType);
Uint32 timestamp;
size_t ID;
KeyEventType keyEventType;
};
class Button {
public:
// Default Constructor for button
Button();
SDL_Rect rectangle;
// Check if the rectangle representing this button was clicked
bool checkMouseClick(const SDL_MouseButtonEvent &event);
// Resizes the rectangle representing the button
constexpr void resizeButton(int x, int y, int w, int h);
};
class Key : public Button {
public:
// Default constructor for key
Key();
// Initializes the button size by given parameters
Key(int x, int y, int w, int h);
// Points to the audioConvert.buf and tells the first byte to be played in next call of callback function
int startOfCurrAudio;
// Contains the buffer with the audio to be played converted to the format of the keyboards (respectively audioDevice which the keyboards use for playing)
SDL_AudioCVT audioConvert;
// Key ID (indexing from 0 ... left key on keyboard has index 0)
size_t ID;
// == true if it was initialized by the default tone (If the audio buffer wasn't initialized from file)
// == false otherwise
bool isDefaultSound;
// How many times is the key currently pressed (For situations when key is pressed by mouse and also keyboard, or when 1 key is on multiple keys)
int pressCount;
// The key which presses the key
SDL_Keysym keysym;
// Initialize the key variables
constexpr void initKey();
// Initialize the audioConvert.buf with the audio from audio file given in filename. The buffer is in the desiredAudioSpec
// Returns true if the buffer was initialized, false if not
bool setAudioBufferWithFile(char *filename, SDL_AudioSpec *desiredAudioSpec);
// Frees the resources associated with the key
void freeKey();
}; | true |
7adb688c984f8a8ededed77761b4d7509a6f3d53 | C++ | brunosalgado/programacao-avancada | /src/estudo-dirigido/null-flag/PessoaFactory.h | UTF-8 | 594 | 2.578125 | 3 | [
"MIT"
] | permissive | //
// Created by Bruno Salgado on 21/06/2018.
//
#ifndef ESTUDO_DIRIGIDO_PESSOAFACTORY_H
#define ESTUDO_DIRIGIDO_PESSOAFACTORY_H
#include "Pessoa.h"
class PessoaFactory {
private:
Pessoa* _homem;
Pessoa* _mulher;
public:
PessoaFactory();
/**
* @desc retorna um clone de Homem
* @return {Pessoa}
*/
Pessoa* getHomem();
/**
* @desc retorna um clone de Mulher
* @return {Pessoa}
*/
Pessoa* getMulher();
/**
* @desc retorna null
* @return {null}
*/
Pessoa* getCrianca();
};
#endif //ESTUDO_DIRIGIDO_PESSOAFACTORY_H
| true |
1c996c19de91965ceb2840494084e774324c4103 | C++ | MWidlerSchool/mwidlerschool.github.io | /CS16X/Mastermind/main.cpp | UTF-8 | 4,982 | 3 | 3 | [] | no_license | #include "libtcod.hpp"
#include "Sequence.h"
#include "Game.h"
#include <string>
#include <Windows.h>
int moveCursorLeft(int curseLoc)
{
if(curseLoc == 0)
{
return 3;
}
return curseLoc - 1;
}
int moveCursorRight(int curseLoc)
{
if(curseLoc == 3)
{
return 0;
}
return curseLoc + 1;
}
void drawBoard()
{
// draw guess slots
for(int y = 0; y < 10; y += 1)
for(int x = 0; x < 4; x += 1)
{
TCODConsole::root->setCharBackground(2 + (x * 2), (3 * y) + 2, Sequence::getColor(Sequence::DARK_GREY));
}
// draw player guess slots
for(int x = 0; x < 4; x += 1)
{
TCODConsole::root->setCharBackground(2 + (x * 2), 34, Sequence::getColor(Sequence::DARK_GREY));
}
// draw reply slots
for(int i = 0; i < 10; i += 1)
for(int x = 11; x < 13; x += 1)
{
TCODConsole::root->setCharBackground(x, (i * 3) + 2, Sequence::getColor(Sequence::DARK_GREY));
TCODConsole::root->setCharBackground(x, (i * 3) + 3, Sequence::getColor(Sequence::DARK_GREY));
}
std::string instructions{};
instructions += "Mastermind \nimplementation\n2018, Michael Widler\n\n\n";
instructions += "Use the arrow keys to set your input, and Enter or Space to submit your guess.\n\n\n";
instructions += "Press Escape to quit.";
TCODConsole::root->printRect(16, 1, 14, 30, instructions.data());
std::string graphicsString{"Implements libtcod"};
TCODConsole::root->printRect(12, 39, 30, 1, graphicsString.data());
}
void processTurn(Game& game)
{
// draw guess in history
for(int x = 0; x < 4; x += 1)
{
TCODConsole::root->setCharBackground(2 + (x * 2), (3 * game.guessesSoFar) + 2, Sequence::getColor(game.curSeq[x]));
}
// update game
game.processTurn();
// draw guess reply
for(int x = 0; x < 2; x += 1)
{
TCODConsole::root->setCharBackground(11 + x, ((game.guessesSoFar - 1) * 3) + 2, Sequence::getColor(game.lastReply[x]));
TCODConsole::root->setCharBackground(11 + x, ((game.guessesSoFar - 1) * 3) + 3, Sequence::getColor(game.lastReply[x + 2]));
}
}
int main()
{
//TCODConsole::setCustomFont("terminal_large.png",TCOD_FONT_LAYOUT_ASCII_INCOL);
TCODConsole::initRoot(30, 40, "Mastermind", false);
TCODConsole::root->setDefaultBackground(Sequence::getColor(Sequence::LIGHT_GREY));
TCODConsole::root->setDefaultForeground(Sequence::getColor(Sequence::BLACK));
TCODConsole::root->clear();
drawBoard();
TCODConsole::flush();
int curseLoc{0};
Game game{};
// main loop
bool breakF{false};
while ( (!TCODConsole::isWindowClosed()) && (!breakF) )
{
// process key input
TCOD_key_t key;
TCODSystem::checkForEvent(TCOD_EVENT_KEY_PRESS,&key,NULL);
if(game.getGameState() == Game::PLAYING)
{
switch(key.vk)
{
case TCODK_RIGHT : curseLoc = moveCursorRight(curseLoc); break;
case TCODK_LEFT : curseLoc = moveCursorLeft(curseLoc); break;
case TCODK_UP : game.nextColor(curseLoc); break;
case TCODK_DOWN : game.prevColor(curseLoc); break;
case TCODK_ESCAPE : breakF = true; break;
case TCODK_SPACE :
case TCODK_ENTER : processTurn(game);
curseLoc = 0;
break;
default : ;
}
// place the arrow
for(int x = 0; x < 4; x += 1)
{
if(x == curseLoc)
{ // up arrow
if(game.getGameState() == Game::PLAYING)
{
TCODConsole::root->setChar(2 + (x * 2), 35, 24);
}
else
{
TCODConsole::root->setChar(2 + (x * 2), 35, ' ');
}
}
else
{
TCODConsole::root->setChar(2 + (x * 2), 35, ' ');
}
}
// draw player guess slots
for(int x = 0; x < 4; x += 1)
{
TCODConsole::root->setCharBackground(2 + (x * 2), 34, Sequence::getColor(game.curSeq[x]));
}
}
else // game is over
{
switch(key.vk)
{
case TCODK_ESCAPE : breakF = true; break;
case TCODK_SPACE :
case TCODK_ENTER : game = Game{};
curseLoc = 0;
drawBoard();
break;
default : ;
}
}
// draw the state string
TCODConsole::root->printRect(16, 20, 14, 30, game.getGameStateString().data());
TCODConsole::flush();
}
return 0;
}
| true |
b4594faf59857fe2b5667b7b4151741edc6ecbd4 | C++ | yebaoshan/SimpleType | /stack/rw_mutex.inl | UTF-8 | 313 | 3 | 3 | [] | no_license | inline RW_Mutex::RW_Mutex ()
{
pthread_rwlock_init (&lock_, 0);
}
inline bool RW_Mutex::acquire_read ()
{
return !pthread_rwlock_rdlock(&lock_);
}
inline bool RW_Mutex::acquire_write ()
{
return !pthread_rwlock_wrlock(&lock_);
}
inline bool RW_Mutex::release ()
{
return !pthread_rwlock_unlock (&lock_);
}
| true |
29dbe8b62934d2f2fe5fb5ed7401d81b2b6be546 | C++ | shubhamvishu/Codeforces-Solutions | /greedy/chess(3A).cpp | UTF-8 | 2,752 | 3.484375 | 3 | [] | no_license | //http://codeforces.com/problemset/problem/3/A
#include <iostream>
#include<math.h>
using namespace std;
int main() {
int n=2,i=0,k,rd=0,ru=0,ld=0,lu=0,a1,a2,b1,b2;
string s[2];
while(n)
{
cin>>s[i];
i++;
n--;
}
a1=s[0][0];
a2=s[1][0];
b1=s[0][1];
b2=s[1][1];
if(a1<a2)
{ //RIGHT
if(b1>b2)
{
//right down
k=0;rd=0;
while(a1!=a2 && b1!=b2)
{
a1++;
b1--;
rd++;
}
if(a1==a2)
{
int d=b1-b2;
cout<<rd+d<<endl;
while(rd)
{
cout<<"RD"<<endl;rd--;
}
while(d)
{cout<<"D"<<endl;d--;
}
}
else{
int d=a2-a1;
cout<<rd+d<<endl;
while(rd)
{
cout<<"RD"<<endl;rd--;
}
while(d)
{cout<<"R"<<endl;d--;
}
}
}
else if(b1<b2)
{
//right up
k=0;ru=0;
while(a1!=a2 && b1!=b2)
{
a1++;
b1++;
ru++;
}
if(a1==a2)
{
int d=b2-b1;
cout<<ru+d<<endl;
while(ru)
{
cout<<"RU"<<endl;ru--;
}
while(d)
{cout<<"U"<<endl;d--;
}
}
else{
int d=a2-a1;
cout<<ru+d<<endl;
while(ru)
{
cout<<"RU"<<endl;ru--;
}
while(d)
{cout<<"R"<<endl;d--;
}
}
}
else{
//move right
int d=a2-a1;
cout<<d<<endl;
while(d)
{
cout<<"R"<<endl;d--;
}
}
}
//**********right ending*********
else if(a1>a2)
{
//LEFT
if(b1>b2)
{
//left down
k=0;ld=0;
while(a1!=a2 && b1!=b2)
{
a1--;
b1--;
ld++;
}
if(a1==a2)
{
int d=b1-b2;
cout<<ld+d<<endl;
while(ld)
{
cout<<"LD"<<endl;ld--;
}
while(d)
{cout<<"D"<<endl;d--;
}
}
else{
int d=a1-a2;
cout<<ld+d<<endl;
while(ld)
{
cout<<"LD"<<endl;ld--;
}
while(d)
{cout<<"L"<<endl;d--;
}
}
}
else if(b1<b2)
{
//left up
k=0;lu=0;
while(a1!=a2 && b1!=b2)
{
a1--;
b1++;
lu++;
}
if(a1==a2)
{
int d=b2-b1;
cout<<lu+d<<endl;
while(lu)
{
cout<<"LU"<<endl;lu--;
}
while(d)
{cout<<"U"<<endl;d--;
}
}
else{
int d=a1-a2;
cout<<lu+d<<endl;
while(lu)
{
cout<<"LU"<<endl;lu--;
}
while(d)
{cout<<"L"<<endl;d--;
}
}
}
else{
//move left
int d=a1-a2;
cout<<d<<endl;
while(d)
{
cout<<"L"<<endl;d--;
}
}
}
//*************LEFT ENDING********************************
else{
int d=b1-b2;
if(d>0)
{
cout<<d<<endl;
while(d)
{ cout<<"D"<<endl;d--;
}
}
else{
d=abs(d);
cout<<d<<endl;
while(d)
{ cout<<"U"<<endl;d--;
}
}
}
return 0;
}
| true |
b77149c3064c8fe2b2c5bf2a42ea0a732afb7611 | C++ | praveenagrawal/practiceCodes | /CodeChef/HELLO.cpp | UTF-8 | 541 | 2.875 | 3 | [] | no_license | #include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
int T;
cin>>T;
while(T--)
{
int U,N;
float D;
cin>>D>>U>>N;
bool advantage = false;
float newCostIndex = 0;
float newCost = 0;
for(int i =1;i<=N;i++)
{
int M,C;
float R;
cin>>M>>R>>C;
if(newCost==0)
newCost = (C+R*U*M)/M;
if((C+R*U*M)/M <(D*U) && (C+R*U*M)/M<=newCost)
{
advantage = true;
newCost = (C+R*U*M)/M;
newCostIndex = i;
}
}
if(advantage)
cout<<newCostIndex<<endl;
else
cout<<0<<endl;
}
} | true |
befbffe115a7548190912a5c07bcece3abd78241 | C++ | Quadrion/qgfx | /dependencies/qtl/include/qtl/complex.h | UTF-8 | 15,971 | 3.1875 | 3 | [
"MIT"
] | permissive | #ifndef __complex_h_
#define __complex_h_
#include <math.h>
namespace qtl
{
/// <summary>
/// Represents a complex number, a + bi
/// </summary>
/// <typeparam name="Type">
/// Type of complex object
/// </typeparam>
template <typename Type>
class complex
{
public:
/// <summary>
/// Constructs a new complex number
/// </summary>
/// <param name="re">
/// Real component
/// </param>
/// <param name="im">
/// Imaginary component
/// </param>
constexpr complex(const Type& re = Type(), const Type& im = Type());
/// <summary>
/// Copy constructor
/// </summary>
/// <param name="other">
/// Copy from
/// </param>
constexpr complex(const complex& other);
/// <summary>
/// Gets real component of complex number
/// </summary>
/// <returns>
/// Real component
/// </returns>
Type real() const;
/// <summary>
/// Gets imaginary component of complex number
/// </summary>
/// <returns>
/// Imaginary component
/// </returns>
Type imag() const;
/// <summary>
/// Sets real component of complex number
/// </summary>
/// <param name="value">
/// Value to set real component to
/// </param>
void real(Type value);
/// <summary>
/// Sets imaginary component of complex number
/// </summary>
/// <param name="value">
/// Value to set imaginary component to
/// </param>
void imag(Type value);
/// <summary>
/// += on both real and imaginary components by value provided
/// </summary>
/// <param name="other">
/// Value to sum with
/// </param>
/// <returns>
/// Reference to this
/// </returns>
complex& operator+=(const Type& other);
/// <summary>
/// += on both real and imaginary components by the corresponding components in
/// the complex value provided
/// </summary>
/// <param name="other">
/// Value to sum with
/// </param>
/// <returns>
/// Reference to this
/// </returns>
complex& operator+=(const complex<Type>& other);
/// <summary>
/// -= on both real and imaginary components by value provided
/// </summary>
/// <param name="other">
/// Value to subtract with
/// </param>
/// <returns>
/// Reference to this
/// </returns>
complex& operator-=(const Type& other);
/// <summary>
/// -= on both real and imaginary components by the corresponding components in
/// the complex value provided
/// </summary>
/// <param name="other">
/// Value to subtract with
/// </param>
/// <returns>
/// Reference to this
/// </returns>
complex& operator-=(const complex<Type>& other);
/// <summary>
/// *= on both real and imaginary components by value provided
/// </summary>
/// <param name="other">
/// Value to multiply with
/// </param>
/// <returns>
/// Reference to this
/// </returns>
complex& operator*=(const Type& other);
/// <summary>
/// *= on both real and imaginary components by the corresponding components in
/// the complex value provided
/// </summary>
/// <param name="other">
/// Value to multiply with
/// </param>
/// <returns>
/// Reference to this
/// </returns>
complex& operator*=(const complex<Type>& other);
/// <summary>
/// /= on both real and imaginary components by value provided
/// </summary>
/// <param name="other">
/// Value to divide with
/// </param>
/// <returns>
/// Reference to this
/// </returns>
complex& operator/=(const Type& other);
/// <summary>
/// /= on both real and imaginary components by the corresponding components in
/// the complex value provided
/// </summary>
/// <param name="other">
/// Value to divide with
/// </param>
/// <returns>
/// Reference to this
/// </returns>
complex& operator/=(const complex<Type>& other);
private:
Type __re;
Type __im;
};
template <typename Type>
inline constexpr complex<Type>::complex(const Type& re, const Type& im)
: __re(re), __im(im)
{
}
template <typename Type>
inline constexpr complex<Type>::complex(const complex<Type>& other)
: __re(other.__re), __im(other.__im)
{
}
template <typename Type>
inline Type complex<Type>::real() const
{
return __re;
}
template <typename Type>
inline Type complex<Type>::imag() const
{
return __im;
}
template <typename Type>
inline void complex<Type>::real(Type value)
{
__re = value;
}
template <typename Type>
inline void complex<Type>::imag(Type value)
{
__im = value;
}
template <typename Type>
inline complex<Type>& complex<Type>::operator+=(const Type& other)
{
__re += other;
__im += other;
return *this;
}
template <typename Type>
inline complex<Type>& complex<Type>::operator+=(const complex<Type>& other)
{
__re += other.__re;
__im += other.__im;
return *this;
}
template <typename Type>
inline complex<Type>& complex<Type>::operator-=(const Type& other)
{
__re -= other;
__im -= other;
return *this;
}
template <typename Type>
inline complex<Type>& complex<Type>::operator-=(const complex<Type>& other)
{
__re -= other.__re;
__im -= other.__im;
return *this;
}
template <typename Type>
inline complex<Type>& complex<Type>::operator*=(const Type& other)
{
__re *= other;
__im *= other;
return *this;
}
template <typename Type>
inline complex<Type>& complex<Type>::operator*=(const complex<Type>& other)
{
__re *= other.__re;
__im *= other.__im;
return *this;
}
template <typename Type>
inline complex<Type>& complex<Type>::operator/=(const Type& other)
{
__re /= other;
__im /= other;
return *this;
}
template <typename Type>
inline complex<Type>& complex<Type>::operator/=(const complex<Type>& other)
{
__re /= other.__re;
__im /= other.__im;
return *this;
}
/// <summary>
/// Addition operator
/// </summary>
/// <typeparam name="Type">
/// Type of complex number
/// </typeparam>
/// <param name="lhs">
/// Left hand argument
/// </param>
/// <param name="rhs">
/// Right hand argument
/// </param>
/// <returns>
/// Summation
/// </summary>
template <typename Type>
inline complex<Type> operator+(const complex<Type>& lhs, const complex<Type>& rhs)
{
return complex<Type>(lhs.real() + rhs.real(), lhs.imag() + rhs.imag());
}
/// <summary>
/// Subtraction operator
/// </summary>
/// <typeparam name="Type">
/// Type of complex number
/// </typeparam>
/// <param name="lhs">
/// Left hand argument
/// </param>
/// <param name="rhs">
/// Right hand argument
/// </param>
/// <returns>
/// Difference
/// </summary>
template <typename Type>
inline complex<Type> operator-(const complex<Type>& lhs, const complex<Type>& rhs)
{
return complex<Type>(lhs.real() - rhs.real(), lhs.imag() - rhs.imag());
}
/// <summary>
/// Multiplication operator
/// </summary>
/// <typeparam name="Type">
/// Type of complex number
/// </typeparam>
/// <param name="lhs">
/// Left hand argument
/// </param>
/// <param name="rhs">
/// Right hand argument
/// </param>
/// <returns>
/// Product
/// </summary>
template <typename Type>
inline complex<Type> operator*(const complex<Type>& lhs, const complex<Type>& rhs)
{
return complex<Type>(lhs.real() * rhs.real(), lhs.imag() * rhs.imag());
}
/// <summary>
/// Division operator
/// </summary>
/// <typeparam name="Type">
/// Type of complex number
/// </typeparam>
/// <param name="lhs">
/// Left hand argument
/// </param>
/// <param name="rhs">
/// Right hand argument
/// </param>
/// <returns>
/// Quotient
/// </summary>
template <typename Type>
inline complex<Type> operator/(const complex<Type>& lhs, const complex<Type>& rhs)
{
return complex<Type>(lhs.real() / rhs.real(), lhs.imag() / rhs.imag());
}
/// <summary>
/// Equality operator
/// </summary>
/// <typeparam name="Type">
/// Type of complex number
/// </typeparam>
/// <param name="lhs">
/// Left hand argument
/// </param>
/// <param name="rhs">
/// Right hand argument
/// </param>
/// <returns>
/// True if real and imaginary components in lhs and rhs are equivalent to their
/// corresponding component, else false
/// </summary>
template <typename Type>
inline bool operator==(const complex<Type>& lhs, const complex<Type>& rhs)
{
return lhs.real() == rhs.real() && lhs.imag() == rhs.imag();
}
/// <summary>
/// Inequality operator
/// </summary>
/// <typeparam name="Type">
/// Type of complex number
/// </typeparam>
/// <param name="lhs">
/// Left hand argument
/// </param>
/// <param name="rhs">
/// Right hand argument
/// </param>
/// <returns>
/// True if real or imaginary components in lhs and rhs are not equivalent to their
/// corresponding component, else false
/// </summary>
template <typename Type>
inline bool operator!=(const complex<Type>& lhs, const complex<Type>& rhs)
{
return lhs.real() != rhs.real() || lhs.imag() != rhs.imag();
}
/// <summary>
/// Gets real component of the complex value
/// </summary>
/// <typeparam name="Type">
/// Type of value in complex number
/// </typeparam>
/// <param name="c">
/// Complex value
/// </param>
/// <returns>
/// Real component
/// </returns>
template <typename Type>
inline Type real(const complex<Type>& c)
{
return c.real();
}
/// <summary>
/// Gets imaginary component of the complex value
/// </summary>
/// <typeparam name="Type">
/// Type of value in complex number
/// </typeparam>
/// <param name="c">
/// Complex value
/// </param>
/// <returns>
/// Imaginary component
/// </returns>
template <typename Type>
inline Type imag(const complex<Type>& c)
{
return c.imag();
}
/// <summary>
/// Gets the norm of the complex number
/// </summary>
/// <typeparam name="Type">
/// Type of value in complex number
/// </typeparam>
/// <param name="c">
/// Complex value
/// </param>
/// <returns>
/// Norm of complex number
/// </returns>
template <typename Type>
inline Type abs(const complex<Type>& c)
{
return static_cast<Type>(sqrt(static_cast<double>((c.real() * c.real() + c.imag() * c.imag()))));
}
/// <summary>
/// Gets the norm of the complex number
/// </summary>
/// <param name="c">
/// Complex value
/// </param>
/// <returns>
/// Norm of complex number
/// </returns>
template <>
inline float abs(const complex<float>& c)
{
return sqrtf(c.real() * c.real() + c.imag() * c.imag());
}
/// <summary>
/// Gets the norm of the complex number
/// </summary>
/// <param name="c">
/// Complex value
/// </param>
/// <returns>
/// Norm of complex number
/// </returns>
template <>
inline double abs(const complex<double>& c)
{
return sqrt(c.real() * c.real() + c.imag() * c.imag());
}
/// <summary>
/// Gets the norm of the complex number
/// </summary>
/// <param name="c">
/// Complex value
/// </param>
/// <returns>
/// Norm of complex number
/// </returns>
template <>
inline long double abs(const complex<long double>& c)
{
return sqrtl(c.real() * c.real() + c.imag() * c.imag());
}
/// <summary>
/// Gets the phase angle of the complex number
/// </summary>
/// <typeparam name="Type">
/// Type of value in complex number
/// </typeparam>
/// <param name="c">
/// Complex value
/// </param>
/// <returns>
/// Phase angle of complex number
/// </returns>
template <typename Type>
inline Type arg(const complex<Type>& c)
{
return static_cast<Type>(atan2(static_cast<double>(c.imag()), static_cast<double>(c.real())));
}
/// <summary>
/// Gets the phase angle of the complex number
/// </summary>
/// <param name="c">
/// Complex value
/// </param>
/// <returns>
/// Phase angle of complex number
/// </returns>
template <>
inline float arg(const complex<float>& c)
{
return atan2f(c.imag(), c.real());
}
/// <summary>
/// Gets the phase angle of the complex number
/// </summary>
/// <param name="c">
/// Complex value
/// </param>
/// <returns>
/// Phase angle of complex number
/// </returns>
template <>
inline double arg(const complex<double>& c)
{
return atan2(c.imag(), c.real());
}
/// <summary>
/// Gets the phase angle of the complex number
/// </summary>
/// <param name="c">
/// Complex value
/// </param>
/// <returns>
/// Phase angle of complex number
/// </returns>
template <>
inline long double arg(const complex<long double>& c)
{
return atan2l(c.imag(), c.real());
}
/// <summary>
/// Gets the field norm of the complex number
/// </summary>
/// <typeparam name="Type">
/// Type of value in complex number
/// </typeparam>
/// <param name="c">
/// Complex value
/// </param>
/// <returns>
/// Field norm of complex number
/// </returns>
template <typename Type>
inline Type norm(const complex<Type>& c)
{
return c.real() * c.real() + c.imag() * c.imag();
}
/// <summary>
/// Gets the complex conjugate of the complex number
/// </summary>
/// <typeparam name="Type">
/// Type of value in complex number
/// </typeparam>
/// <param name="c">
/// Complex value
/// </param>
/// <returns>
/// Complex conjugate
/// </returns>
template <typename Type>
inline complex<Type> conj(const complex<Type>& c)
{
return complex<Type>(c.real(), -c.imag());
}
/// <summary>
/// Gets the complex number given by the polar values
/// </summary>
/// <typeparam name="Type">
/// Type of value in complex number
/// </typeparam>
/// <param name="mag">
/// Magnitude of polar coordinates
/// </param>
/// <param name="theta">
/// Angle of polar coordinates
/// </param>
/// <returns>
/// Complex number
/// </returns>
template <typename Type>
inline complex<Type> polar(const Type& mag, const Type& theta = Type())
{
return complex<Type>(mag * static_cast<Type>(cos(static_cast<double>(theta))), mag * static_cast<Type>(sin(static_cast<double>(theta))));
}
/// <summary>
/// Gets the complex number given by the polar values
/// </summary>
/// <param name="mag">
/// Magnitude of polar coordinates
/// </param>
/// <param name="theta">
/// Angle of polar coordinates
/// </param>
/// <returns>
/// Complex number
/// </returns>
template <>
inline complex<float> polar(const float& mag, const float& theta)
{
return complex<float>(mag * cosf(theta), mag * sinf(theta));
}
/// <summary>
/// Gets the complex number given by the polar values
/// </summary>
/// <param name="mag">
/// Magnitude of polar coordinates
/// </param>
/// <param name="theta">
/// Angle of polar coordinates
/// </param>
/// <returns>
/// Complex number
/// </returns>
template <>
inline complex<double> polar(const double& mag, const double& theta)
{
return complex<double>(mag * cos(theta), mag * sin(theta));
}
/// <summary>
/// Gets the complex number given by the polar values
/// </summary>
/// <param name="mag">
/// Magnitude of polar coordinates
/// </param>
/// <param name="theta">
/// Angle of polar coordinates
/// </param>
/// <returns>
/// Complex number
/// </returns>
template <>
inline complex<long double> polar(const long double& mag, const long double& theta)
{
return complex<long double>(mag * cosl(theta), mag * sinl(theta));
}
}
#endif | true |
07c31bde45317f9ed1ef405f3adaa5578ceddff7 | C++ | Tourki/Data-structure-projects | / Infix Expression Calculation/main.cpp | UTF-8 | 4,008 | 3.0625 | 3 | [] | no_license | //============================================================================
// Name : A3.cpp
// Author : Hossam Tourki
// Version :
// Copyright : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <iostream>
#include <sstream>
#include <iomanip> // std::setprecision
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
using namespace std;
#include "stack.h"
typedef double NumberDataType ;
NumberDataType string_to_Number(const string &buffer);
void calculate();
Stack<char> operatorStack;
Stack<NumberDataType> numbersStack;
int main(int argc,char*argv[]) {
int i=0,brackets=0;
if(argc>2)
{
cout<<"Invalid Expression";
return 0;
}
else if(argc==1)
{
printf("%.2lf",NumberDataType(0));
return 0;
}
else
{
while(int (strlen(argv[1])) > i)
{
if((argv[1][i]>='0'&&argv[1][i]<='9')||((!(argv[1][i-1]>='0'&&argv[1][i-1]<='9')&& argv[1][i-1]!=')')&&(argv[1][i]=='+'||argv[1][i]=='-')&&(argv[1][i+1]>='0'&&argv[1][i+1]<='9')))
{ // number is anything but numbers (+or-) , 0to9
// if the input is a number or a sign of a number append on a string later to be converted into integer value
string numString ="";//empty string to append to
numString+=argv[1][i];//add the first figure alone in case it was a sign
i++;//to the next figure
while((argv[1][i]>='0'&&argv[1][i]<='9'))
{
//while it is numbers keep appending to the same number
numString+=argv[1][i];
i++;
}
numbersStack.push(string_to_Number(numString));//the number is finished
}
else if((argv[1][i]=='x'||argv[1][i]=='+'||argv[1][i]=='-'||argv[1][i]=='/') && ((argv[1][i-1]>='0'&&argv[1][i-1]<='9')||argv[1][i-1]==')')&&((argv[1][i+1]>='0'&&argv[1][i+1]<='9')||argv[1][i+1]=='('||argv[1][i+1]=='+'||argv[1][i+1]=='-'))
{ // 0to9 or ) operator 0to9 or ( or + or -
if((numbersStack.Counter-(operatorStack.Counter-brackets))!=1)
{
cout<<"Invalid Expression";
return 0;
}
else
{
char poped=0,coming=argv[1][i];
operatorStack.top(poped);
if((coming<=poped || poped=='/') && poped !='(')
calculate();
else
{
operatorStack.push(argv[1][i]);
i++;
}
}
}
else if(argv[1][i]=='(')
{
operatorStack.push(argv[1][i]);
brackets++;
i++;
}
else if(argv[1][i]==')')
{ if(brackets!=0)
{
char oper;
operatorStack.top(oper);
while(oper!='('&&brackets!=0)
{
calculate();
operatorStack.top(oper);
}
operatorStack.pop(oper);
brackets--;
i++;
}
else
{
cout<<"Invalid Expression";
return 0;
}
}
else
{
cout<<"Invalid Expression";
return 0;
}
}
}
if((numbersStack.Counter-operatorStack.Counter)!=1)
{
cout<<"Invalid Expression";
return 0;
}
else
{
while(!operatorStack.isEmpty())
calculate();
NumberDataType output=0;
numbersStack.pop(output);
if(numbersStack.isEmpty())
printf("%.2lf",output);
else
cout<<"Invalid Expression";
}
return 0;
}
NumberDataType string_to_Number(const string &buffer){
NumberDataType number;
stringstream temp;
temp<<buffer;
temp>>number;
return number;
}
void calculate(){
NumberDataType op1,op2;
numbersStack.pop(op2);
numbersStack.pop(op1);
char operator1;
operatorStack.pop(operator1);
if(operator1=='+')
numbersStack.push((op1+op2));
else if(operator1=='-')
numbersStack.push((op1-op2));
else if(operator1=='x')
numbersStack.push((op1*op2));
else if(operator1=='/'){
if(op2==0){
cout<<"Invalid Expression";
exit(1);
}
else
numbersStack.push((op1/op2));
}
else{
numbersStack.push(op1);
numbersStack.push(op2);
operatorStack.push(operator1);
}
}
| true |
0b5796e9f60a5dfaf72d9f80791fca46944273f0 | C++ | Soulwzy/code | /C和指针6.6/C和指针6.6/6.6.cpp | UTF-8 | 536 | 3.328125 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
int Prime_number(int num1, int num2)
{
int n = 0;
char* arr = (char *)malloc((num2 - num1)*sizeof(char));
for (int i = 0; i < (num2 - num1); i++)
{
arr[i] = 1;
}
for (int i = 0; i < (num2 - num1); i++)
{
for (int j = 2; j < i; j++)
{
if (i % j == 0)
{
arr[i] = 0;
continue;
}
}
}
for (int i = 0; i < (num2 - num1); i++)
{
if (arr[i])
{
n++;
//printf("%d\n", i);
}
}
return n;
}
int main()
{
printf("%d\n", Prime_number(5000, 5100));
return 0;
} | true |
b68197afab1f530c0897cafba4789cbfad7767b6 | C++ | tmoritaa/Reflection-Shooter-Test | /Game/Strategy/MovementStrategy/LRMovementStrategy.cpp | UTF-8 | 282 | 2.640625 | 3 | [] | no_license | #include "LRMovementStrategy.h"
LRMovementStrategy::LRMovementStrategy()
: MovementStrategy()
{}
void LRMovementStrategy::Execute(float& velX, float& velY)
{
if (m_movementState < 100)
{
velX = 1;
}
else
{
velX = -1;
}
m_movementState++;
m_movementState %= 200;
}
| true |
0d2d5e59b78a877e05117b28d66db9309652a0e4 | C++ | kajori2000sardar/lab5_141 | /lab5_q3.cpp | UTF-8 | 412 | 3.859375 | 4 | [] | no_license | //include library
#include<iostream>
using namespace std;
//create main
int main()
{
//declaring variables
signed int i;
//ask for value
cout<<"Enter a number: ";
//take input
cin>>i;
//check whether the no. is -ve, +ve, 0 and show output;
if(i>0)
cout<<"Number is positive";
else
if(i<0)
cout<<"Number is negative";
else
cout<<"Number is equal to zero";
//close program
return 0;
}
| true |
9485166d22feeb492a68983b306a34cc5da3677e | C++ | mlwong/CME213-CUDA-Project | /final_project/skeleton_code/gpu_func.h | UTF-8 | 12,642 | 2.921875 | 3 | [] | no_license | #ifndef GPU_FUNC_H_
#define GPU_FUNC_H_
#include <cuda_runtime.h>
#include <helper_cuda.h>
#include <helper_functions.h>
struct event_pair
{
cudaEvent_t start;
cudaEvent_t end;
};
inline void check_launch(const char * kernel_name)
{
cudaThreadSynchronize();
cudaError_t err = cudaGetLastError();
if(err != cudaSuccess)
{
std::cerr << "error in " << kernel_name << " kernel" << std::endl;
std::cerr << "error was: " << cudaGetErrorString(err) << std::endl;
exit(1);
}
}
inline void start_timer(event_pair * p)
{
cudaEventCreate(&p->start);
cudaEventCreate(&p->end);
cudaEventRecord(p->start, 0);
}
inline double stop_timer(event_pair * p)
{
cudaEventRecord(p->end, 0);
cudaEventSynchronize(p->end);
float elapsed_time;
cudaEventElapsedTime(&elapsed_time, p->start, p->end);
cudaEventDestroy(p->start);
cudaEventDestroy(p->end);
return elapsed_time;
}
int useless_gpu_add_one (int t);
/*
* Algorithm 0 of general matrix-matrix multiplication (GEMM)
* GEMM operation is expressed as D = alpha*op(A)*op(B) + beta*C
* One thread is used to calculate one element in matrix D natively
* 1D blocks are used
* natively
*
* Parameters:
* m: Number of rows of op(A) / number of rows of C/D
* n: Number of columns of op(A) / number of rows of op(B)
* l: Number of columns of op(B) / number of columns of C/D
* transpose_A: Whether A should be transposed
* If transpose_A is false, op(A) = A
* Otherwise, op(A) = A^T
* transpose_B: Whether B should be transposed
* If transpose_B is false, op(B) = B
* Otherwise, op(B) = B^T
*/
void gpu_GEMM_0 (const double alpha,
const double beta,
const double* const mat_A,
const double* const mat_B,
const double* const mat_C,
double* mat_D,
const int m,
const int n,
const int l,
const bool transpose_A,
const bool transpose_B);
/*
* Algorithm 1 of general matrix-matrix multiplication (GEMM)
* GEMM operation is expressed as D = alpha*op(A)*op(B) + beta*C
* One thread is used to calculate one element in matrix D
* natively. 2D blocks are used
*
* Parameters:
* m: Number of rows of op(A) / number of rows of C/D
* n: Number of columns of op(A) / number of rows of op(B)
* l: Number of columns of op(B) / number of columns of C/D
* transpose_A: Whether A should be transposed
* If transpose_A is false, op(A) = A
* Otherwise, op(A) = A^T
* transpose_B: Whether B should be transposed
* If transpose_B is false, op(B) = B
* Otherwise, op(B) = B^T
*/
void gpu_GEMM_1 (const double alpha,
const double beta,
const double* const mat_A,
const double* const mat_B,
const double* const mat_C,
double* mat_D,
const int m,
const int n,
const int l,
const bool transpose_A,
const bool transpose_B);
/*
* Algorithm 2 of general matrix-matrix multiplication (GEMM)
* GEMM operation is expressed as D = alpha*op(A)*op(B) + beta*C
* Blocking algorithm and shared memory is used in this algorithm
*
* Parameters:
* m: Number of rows of op(A) / number of rows of C/D
* n: Number of columns of op(A) / number of rows of op(B)
* l: Number of columns of op(B) / number of columns of C/D
* transpose_A: Whether A should be transposed
* If transpose_A is false, op(A) = A
* Otherwise, op(A) = A^T
* transpose_B: Whether B should be transposed
* If transpose_B is false, op(B) = B
* Otherwise, op(B) = B^T
*/
void gpu_GEMM_2 (const double alpha,
const double beta,
const double* const mat_A,
const double* const mat_B,
const double* const mat_C,
double* mat_D,
const int m,
const int n,
const int l,
const bool transpose_A,
const bool transpose_B);
/*
* Algorithm 3 of general matrix-matrix multiplication (GEMM)
* GEMM operation is expressed as D = alpha*op(A)*op(B) + beta*C
* A better blocking algorithm and shared memory is used in this algorithm
*
* Parameters:
* m: Number of rows of op(A) / number of rows of C/D
* n: Number of columns of op(A) / number of rows of op(B)
* l: Number of columns of op(B) / number of columns of C/D
* transpose_A: Whether A should be transposed
* If transpose_A is false, op(A) = A
* Otherwise, op(A) = A^T
* transpose_B: Whether B should be transposed
* If transpose_B is false, op(B) = B
* Otherwise, op(B) = B^T
*/
void gpu_GEMM_3 (const double alpha,
const double beta,
const double* const mat_A,
const double* const mat_B,
const double* const mat_C,
double* mat_D,
const int m,
const int n,
const int l,
const bool transpose_A,
const bool transpose_B);
/*
* Applies the sigmoid function to each element of the matrix
* and returns a new matrix by GPU
* m: number of rows of the matrix
* n: number of columns of the matrix
*/
void gpu_sigmoid (const double* const mat_1,
double* mat_2,
const int m,
const int n);
/*
* Applies the softmax function to each row vector of the matrix
* and returns a new matrix by GPU
* m: number of rows of the matrix
* n: number of columns of the matrix
*/
void gpu_softmax (const double* const mat_1,
double* mat_2,
const int m,
const int n);
/*
* Sum elements of matrix in each column
* m: number of rows of the matrix
* n: number of columns of the matrix
*/
void gpu_sum_col (const double* const mat,
double* row_vec,
const int m,
const int n);
/*
* Elementwise multiplication used to compute dW1
* and return a new matrix by GPU
* mat_da1: input matrix da1
* mat_a1: input matrix a1
* mat_dz1: output matrix dz1
* m: number of rows of the matrices
* n: number of columns of the matrices
*/
void gpu_elementwise_mult (const double* const mat_da1,
const double* const mat_a1,
double* mat_dz1,
const int m,
const int n);
/*
* Elementwise substraction between two matrices by GPU
* C = A - alpha * B
* A new matrix is returned
* mat_A: input matrix A
* mat_B: input matrix B
* mat_C: output matrix C
* m: number of rows of the matrices
* n: number of columns of the matrices
*/
void gpu_elementwise_subtract (const double alpha,
const double* const mat_A,
const double* const mat_B,
double* mat_C,
const int m,
const int n);
/*
* Compute the diff matrix
* and return a new matrix by GPU
* mat_yc: input matrix yc
* mat_y: input matrix y
* mat_diff: output matrix diff
* m: number of rows of the matrices
* n: number of columns of the matrices
*/
void gpu_compute_diff (const double* const mat_yc,
const double* const mat_y,
double* mat_diff,
const int m,
const int n);
/*
* Transpose a matrix and return a new matrix by GPU
* mat_1: input matrix
* mat_2: output matrix
* m: number of rows of the input matrix
* n: number of columns of the input matrix
*/
void gpu_transpose (const double* const mat_1,
double* mat_2,
const int m,
const int n);
/*
* Do the feedforward in GPU entirely
*/
void gpu_accel_feedforward (const double* const mat_X, int X_n_rows, int X_n_cols,
const double* const mat_W1, int W1_n_rows, int W1_n_cols,
const double* const mat_b1, int b1_n_rows, int b1_n_cols,
double* mat_z1, int z1_n_rows, int z1_n_cols,
double* mat_a1, int a1_n_rows, int a1_n_cols,
const double* const mat_W2, int W2_n_rows, int W2_n_cols,
const double* const mat_b2, int b2_n_rows, int b2_n_cols,
double* mat_z2, int z2_n_rows, int z2_n_cols,
double* mat_a2, int a2_n_rows, int a2_n_cols);
/*
* Do the backpropagation in GPU entirely
*/
void gpu_accel_backprop (const double reg,
const double* const mat_diff, const int diff_n_rows, const int diff_n_cols,
const double* const mat_X, const int X_n_rows, const int X_n_cols,
const double* const mat_a1, const int a1_n_rows, const int a1_n_cols,
const double* const mat_W1, const int W1_n_rows, const int W1_n_cols,
const double* const mat_W2, const int W2_n_rows, const int W2_n_cols,
double* mat_dW1, const int dW1_n_rows, const int dW1_n_cols,
double* mat_dW2, const int dW2_n_rows, const int dW2_n_cols,
double* mat_db1, const int db1_n_cols,
double* mat_db2, const int db2_n_cols);
/*
* Do the feedforward and backpropagation in GPU entirely
* Since this function combines both the feedforward and
* backpropagation algorithm, some communication cost over
* the the PCI express is saved such as the cost of transfering
* the data of sub-matrix X, matrices W1 and W2
* the second GEMM algorithm is used
*/
void gpu_accel_feedforward_backprop_1 (const double reg,
const double* const mat_X, int X_n_rows, int X_n_cols,
const double* const mat_y, int y_n_rows, int y_n_cols,
const double* const mat_W1, int W1_n_rows, int W1_n_cols,
const double* const mat_b1, int b1_n_rows, int b1_n_cols,
double* mat_z1, int z1_n_rows, int z1_n_cols,
double* mat_a1, int a1_n_rows, int a1_n_cols,
const double* const mat_W2, int W2_n_rows, int W2_n_cols,
const double* const mat_b2, int b2_n_rows, int b2_n_cols,
double* mat_z2, int z2_n_rows, int z2_n_cols,
double* mat_a2, int a2_n_rows, int a2_n_cols,
double* mat_dW1, const int dW1_n_rows, const int dW1_n_cols,
double* mat_dW2, const int dW2_n_rows, const int dW2_n_cols,
double* mat_db1, const int db1_n_cols,
double* mat_db2, const int db2_n_cols);
/*
* Do the feedforward and backpropagation in GPU entirely
* Compared to gpu_accel_feedforward_backprop_1, this function
* further minimizes the communication cost. Redundant communication
* such as transferring back data of z1, a1, z2 from GPU
* Also, the third GEMM algorithm, which is faster, is used
*/
void gpu_accel_feedforward_backprop_2 (const double reg,
double* mat_X, int X_n_rows, int X_n_cols,
double* mat_y, int y_n_rows, int y_n_cols,
double* mat_W1, int W1_n_rows, int W1_n_cols,
double* mat_b1, int b1_n_rows, int b1_n_cols,
double* mat_W2, int W2_n_rows, int W2_n_cols,
double* mat_b2, int b2_n_rows, int b2_n_cols,
double* mat_a2, int a2_n_rows, int a2_n_cols,
double* mat_dW1, const int dW1_n_rows, const int dW1_n_cols,
double* mat_dW2, const int dW2_n_rows, const int dW2_n_cols,
double* mat_db1, const int db1_n_cols,
double* mat_db2, const int db2_n_cols);
#endif
| true |
33719ee86e1d65814d0765f4de80e528eae6e55b | C++ | andrejlevkovitch/sdl_game | /src/math_2d/include/vertex.hpp | UTF-8 | 407 | 2.875 | 3 | [] | no_license | // vertex.hpp
#pragma once
#include "vector2d.hpp"
#include <ostream>
namespace levi {
class vertex {
public:
vertex();
vertex(float x, float y, float z);
vertex(vector2d v, float z);
vertex operator+(const vertex &rhs) const;
operator levi::vector2d() const;
public:
float x;
float y;
float z;
};
std::ostream &operator<<(std::ostream &out, const vertex &vertex);
}; // namespace levi
| true |
da565472d2d969b118c4de5b1c7960292ab753fc | C++ | psydox/EsenthelEngine | /Engine/H/Math/Shapes/Edge.h | UTF-8 | 28,688 | 3.015625 | 3 | [
"LicenseRef-scancode-other-permissive",
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | /******************************************************************************
Use 'Edge2' to handle 2D edges, Flt type
Use 'Edge' to handle 3D edges, Flt type
Use 'EdgeD2' to handle 2D edges, Dbl type
Use 'EdgeD' to handle 3D edges, Dbl type
/******************************************************************************/
struct Edge2 // Edge 2D
{
Vec2 p[2]; // points
// set
Edge2& set(C Vec2 &p0 , C Vec2 &p1 ) {p[0]=p0 ; p[1]=p1 ; return T;}
Edge2& set(Flt x0, Flt y0, Flt x1, Flt y1) {p[0].set(x0,y0); p[1].set(x1,y1); return T;}
// get
Flt centerX( )C {return Avg(p[0].x, p[1].x);} // center x
Flt centerY( )C {return Avg(p[0].y, p[1].y);} // center y
Vec2 center ( )C {return Vec2(centerX(), centerY());} // center
Vec2 delta ( )C {return p[1]-p[0];} // delta
Vec2 dir ( )C {return !delta() ;} // direction
Vec2 perp ( )C {return Perp (delta());} // perpendicular
Vec2 perpN ( )C {return PerpN(delta());} // perpendicular normalized
Flt length ( )C {return Dist (p[0] , p[1] );} // length
Flt length2( )C {return Dist2(p[0] , p[1] );} // squared length
Vec2 lerp (Flt s)C {return Lerp(p[0] , p[1] , s);} // lerp from p[0] to p[1]
Flt lerpX (Flt s)C {return Lerp(p[0].x, p[1].x, s);} // lerp from p[0].x to p[1].x
Flt lerpY (Flt s)C {return Lerp(p[0].y, p[1].y, s);} // lerp from p[0].y to p[1].y
Str asText()C {return S+"Point0: "+p[0]+", Point1: "+p[1];} // get text description
// operations
Edge2& reverse() {Swap(p[0], p[1]); return T;} // reverse the order of points
// transform
Edge2& operator+=(C Vec2 &v) {p[0]+=v; p[1]+=v; return T;}
Edge2& operator-=(C Vec2 &v) {p[0]-=v; p[1]-=v; return T;}
Edge2& operator*=( Flt f) {p[0]*=f; p[1]*=f; return T;}
Edge2& operator/=( Flt f) {p[0]/=f; p[1]/=f; return T;}
Edge2& operator*=(C Vec2 &v) {p[0]*=v; p[1]*=v; return T;}
Edge2& operator/=(C Vec2 &v) {p[0]/=v; p[1]/=v; return T;}
Edge2& operator*=(C Matrix3 &m) {p[0]*=m; p[1]*=m; return T;}
Edge2& operator*=(C Matrix &m) {p[0]*=m; p[1]*=m; return T;}
friend Edge2 operator+ (C Edge2 &edge, C Vec2 &v) {return Edge2(edge)+=v;}
friend Edge2 operator- (C Edge2 &edge, C Vec2 &v) {return Edge2(edge)-=v;}
friend Edge2 operator* (C Edge2 &edge, Flt f) {return Edge2(edge)*=f;}
friend Edge2 operator/ (C Edge2 &edge, Flt f) {return Edge2(edge)/=f;}
friend Edge2 operator* (C Edge2 &edge, C Vec2 &v) {return Edge2(edge)*=v;}
friend Edge2 operator/ (C Edge2 &edge, C Vec2 &v) {return Edge2(edge)/=v;}
friend Edge2 operator* (C Edge2 &edge, C Matrix3 &m) {return Edge2(edge)*=m;}
friend Edge2 operator* (C Edge2 &edge, C Matrix &m) {return Edge2(edge)*=m;}
// draw
void draw(C Color &color=WHITE )C; // draw
void draw(C Color &color , Flt width )C; // draw with width
void draw(C Color &color0, C Color &color1)C; // draw with per-point color
Edge2() {}
Edge2(C Vec2 &p ) {set(p , p);}
Edge2(C Vec2 &p0, C Vec2 &p1 ) {set(p0, p1);}
Edge2( Flt x0, Flt y0, Flt x1, Flt y1) {set(x0, y0, x1, y1);}
CONVERSION Edge2(C EdgeD2 &edge );
};
/******************************************************************************/
struct EdgeD2 // Edge 2D (double precision)
{
VecD2 p[2]; // points
// set
EdgeD2& set(C VecD2 &p0 , C VecD2 &p1 ) {p[0]=p0 ; p[1]=p1 ; return T;}
EdgeD2& set(Dbl x0, Dbl y0, Dbl x1, Dbl y1) {p[0].set(x0,y0); p[1].set(x1,y1); return T;}
// get
Dbl centerX( )C {return Avg(p[0].x, p[1].x);} // center x
Dbl centerY( )C {return Avg(p[0].y, p[1].y);} // center y
VecD2 center ( )C {return VecD2(centerX(), centerY());} // center
VecD2 delta ( )C {return p[1]-p[0];} // delta
VecD2 dir ( )C {return !delta() ;} // direction
VecD2 perp ( )C {return Perp (delta());} // perpendicular
VecD2 perpN ( )C {return PerpN(delta());} // perpendicular normalized
Dbl length ( )C {return Dist (p[0] , p[1] );} // length
Dbl length2( )C {return Dist2(p[0] , p[1] );} // squared length
VecD2 lerp (Dbl s)C {return Lerp(p[0] , p[1] , s);} // lerp from p[0] to p[1]
Dbl lerpX (Dbl s)C {return Lerp(p[0].x, p[1].x, s);} // lerp from p[0].x to p[1].x
Dbl lerpY (Dbl s)C {return Lerp(p[0].y, p[1].y, s);} // lerp from p[0].y to p[1].y
// draw
void draw(C Color &color=WHITE )C; // draw
void draw(C Color &color , Flt width )C; // draw with width
void draw(C Color &color0, C Color &color1)C; // draw with per-point color
// operations
EdgeD2& reverse() {Swap(p[0], p[1]); return T;} // reverse the order of points
// transform
EdgeD2& operator+=(C VecD2 &v) {p[0]+=v; p[1]+=v; return T;}
EdgeD2& operator-=(C VecD2 &v) {p[0]-=v; p[1]-=v; return T;}
EdgeD2& operator*=( Dbl r) {p[0]*=r; p[1]*=r; return T;}
EdgeD2& operator/=( Dbl r) {p[0]/=r; p[1]/=r; return T;}
EdgeD2& operator*=(C MatrixD &m) {p[0]*=m; p[1]*=m; return T;}
friend EdgeD2 operator+ (C EdgeD2 &edge, C VecD2 &v) {return EdgeD2(edge)+=v;}
friend EdgeD2 operator- (C EdgeD2 &edge, C VecD2 &v) {return EdgeD2(edge)-=v;}
friend EdgeD2 operator* (C EdgeD2 &edge, Dbl r) {return EdgeD2(edge)*=r;}
friend EdgeD2 operator/ (C EdgeD2 &edge, Dbl r) {return EdgeD2(edge)/=r;}
friend EdgeD2 operator* (C EdgeD2 &edge, C MatrixD &m) {return EdgeD2(edge)*=m;}
EdgeD2() {}
EdgeD2(C VecD2 &p ) {set(p , p );}
EdgeD2(C VecD2 &p0, C VecD2 &p1 ) {set(p0, p1);}
EdgeD2( Dbl x0, Dbl y0, Dbl x1, Dbl y1) {set(x0, y0, x1, y1);}
CONVERSION EdgeD2(C Edge2 &edge );
};
/******************************************************************************/
struct Edge // Edge 3D
{
Vec p[2]; // points
// set
Edge& set(C Vec &p0, C Vec &p1 ) {p[0]=p0 ; p[1]=p1 ; return T;}
Edge& set(C Vec2 &p0, C Vec2 &p1, Flt z) {p[0].set(p0 , z); p[1].set(p1 , z); return T;}
Edge& set(C Edge2 &edge , Flt z) {p[0].set(edge.p[0], z); p[1].set(edge.p[1], z); return T;}
// get
Edge2 xy ( )C {return Edge2(p[0].xy , p[1].xy );} // get XY components as Edge2
Edge2 xz ( )C {return Edge2(p[0].xz(), p[1].xz());} // get XZ components as Edge2
Flt centerX( )C {return Avg(p[0].x , p[1].x );} // center x
Flt centerY( )C {return Avg(p[0].y , p[1].y );} // center y
Flt centerZ( )C {return Avg(p[0].z , p[1].z );} // center z
Vec center ( )C {return Vec(centerX(), centerY(), centerZ());} // center
Vec delta ( )C {return p[1]-p[0];} // delta
Vec dir ( )C {return !delta();} // direction
Flt length ( )C {return Dist (p[0] , p[1] );} // length
Flt length2( )C {return Dist2(p[0] , p[1] );} // squared length
Vec lerp (Flt s)C {return Lerp(p[0] , p[1] , s);} // lerp from p[0] to p[1]
Flt lerpX (Flt s)C {return Lerp(p[0].x, p[1].x, s);} // lerp from p[0].x to p[1].x
Flt lerpY (Flt s)C {return Lerp(p[0].y, p[1].y, s);} // lerp from p[0].y to p[1].y
Flt lerpZ (Flt s)C {return Lerp(p[0].z, p[1].z, s);} // lerp from p[0].z to p[1].z
Str asText()C {return S+"Point0: "+p[0]+", Point1: "+p[1];} // get text description
// operations
Edge& reverse() {Swap(p[0], p[1]); return T;} // reverse the order of points
// transform
Edge& operator+=(C Vec &v) {p[0]+=v; p[1]+=v; return T;}
Edge& operator-=(C Vec &v) {p[0]-=v; p[1]-=v; return T;}
Edge& operator*=( Flt f) {p[0]*=f; p[1]*=f; return T;}
Edge& operator/=( Flt f) {p[0]/=f; p[1]/=f; return T;}
Edge& operator*=(C Vec &v) {p[0]*=v; p[1]*=v; return T;}
Edge& operator/=(C Vec &v) {p[0]/=v; p[1]/=v; return T;}
Edge& operator*=(C Matrix3 &m) {p[0]*=m; p[1]*=m; return T;}
Edge& operator*=(C Matrix &m) {p[0]*=m; p[1]*=m; return T;}
Edge& operator/=(C Matrix3 &m) {return div(m);}
Edge& operator/=(C Matrix &m) {return div(m);}
friend Edge operator+ (C Edge &edge, C Vec &v) {return Edge(edge)+=v;}
friend Edge operator- (C Edge &edge, C Vec &v) {return Edge(edge)-=v;}
friend Edge operator* (C Edge &edge, Flt f) {return Edge(edge)*=f;}
friend Edge operator/ (C Edge &edge, Flt f) {return Edge(edge)/=f;}
friend Edge operator* (C Edge &edge, C Vec &v) {return Edge(edge)*=v;}
friend Edge operator/ (C Edge &edge, C Vec &v) {return Edge(edge)/=v;}
friend Edge operator* (C Edge &edge, C Matrix3 &m) {return Edge(edge)*=m;}
friend Edge operator/ (C Edge &edge, C Matrix3 &m) {return Edge(edge)/=m;}
friend Edge operator* (C Edge &edge, C Matrix &m) {return Edge(edge)*=m;}
friend Edge operator/ (C Edge &edge, C Matrix &m) {return Edge(edge)/=m;}
Edge& div (C Matrix3 &matrix); // transform by matrix inverse
Edge& div (C Matrix &matrix); // transform by matrix inverse
Edge& divNormalized(C Matrix3 &matrix); // transform by matrix inverse, this method is faster than 'div' however 'matrix' must be normalized
Edge& divNormalized(C Matrix &matrix); // transform by matrix inverse, this method is faster than 'div' however 'matrix' must be normalized
// draw
void draw(C Color &color=WHITE )C; // draw , this relies on active object matrix which can be set using 'SetMatrix' function
void draw(C Color &color , Flt width )C; // draw with width , this relies on active object matrix which can be set using 'SetMatrix' function
void draw(C Color &color0, C Color &color1)C; // draw with per-point color, this relies on active object matrix which can be set using 'SetMatrix' function
Edge() {}
Edge(C Vec &p ) {set(p , p );}
Edge(C Vec &p0, C Vec &p1 ) {set(p0, p1 );}
Edge(C Vec2 &p0, C Vec2 &p1, Flt z) {set(p0, p1, z);}
Edge(C Edge2 &edge , Flt z) {set(edge , z);}
CONVERSION Edge(C EdgeD &edge );
};
/******************************************************************************/
struct EdgeD // Edge 3D (double precision)
{
VecD p[2]; // points
// set
EdgeD& set(C VecD &p0, C VecD &p1 ) {p[0]=p0 ; p[1]=p1 ; return T;}
EdgeD& set(C VecD2 &p0, C VecD2 &p1, Dbl z) {p[0].set(p0,z); p[1].set(p1,z); return T;}
// get
Dbl centerX( )C {return Avg(p[0].x, p[1].x);} // center x
Dbl centerY( )C {return Avg(p[0].y, p[1].y);} // center y
Dbl centerZ( )C {return Avg(p[0].z, p[1].z);} // center z
VecD center ( )C {return VecD(centerX(), centerY(), centerZ());} // center
VecD delta ( )C {return p[1]-p[0];} // delta
VecD dir ( )C {return !delta();} // direction
Dbl length ( )C {return Dist (p[0] , p[1] );} // length
Dbl length2( )C {return Dist2(p[0] , p[1] );} // squared length
VecD lerp (Dbl s)C {return Lerp(p[0] , p[1] , s);} // lerp from p[0] to p[1]
Dbl lerpX (Dbl s)C {return Lerp(p[0].x, p[1].x, s);} // lerp from p[0].x to p[1].x
Dbl lerpY (Dbl s)C {return Lerp(p[0].y, p[1].y, s);} // lerp from p[0].y to p[1].y
Dbl lerpZ (Dbl s)C {return Lerp(p[0].z, p[1].z, s);} // lerp from p[0].z to p[1].z
// operations
EdgeD& reverse() {Swap(p[0], p[1]); return T;} // reverse the order of points
// transform
EdgeD& operator+=(C VecD &v) {p[0]+=v; p[1]+=v; return T;}
EdgeD& operator-=(C VecD &v) {p[0]-=v; p[1]-=v; return T;}
EdgeD& operator*=( Dbl r) {p[0]*=r; p[1]*=r; return T;}
EdgeD& operator/=( Dbl r) {p[0]/=r; p[1]/=r; return T;}
EdgeD& operator*=(C MatrixD &m) {p[0]*=m; p[1]*=m; return T;}
friend EdgeD operator+ (C EdgeD &edge, C VecD &v) {return EdgeD(edge)+=v;}
friend EdgeD operator- (C EdgeD &edge, C VecD &v) {return EdgeD(edge)-=v;}
friend EdgeD operator* (C EdgeD &edge, Dbl r) {return EdgeD(edge)*=r;}
friend EdgeD operator/ (C EdgeD &edge, Dbl r) {return EdgeD(edge)/=r;}
friend EdgeD operator* (C EdgeD &edge, C MatrixD &m) {return EdgeD(edge)*=m;}
// draw
void draw(C Color &color=WHITE )C; // draw , this relies on active object matrix which can be set using 'SetMatrix' function
void draw(C Color &color , Flt width )C; // draw with width , this relies on active object matrix which can be set using 'SetMatrix' function
void draw(C Color &color0, C Color &color1)C; // draw with per-point color, this relies on active object matrix which can be set using 'SetMatrix' function
EdgeD() {}
EdgeD(C VecD &p ) {set(p , p );}
EdgeD(C VecD &p0, C VecD &p1) {set(p0, p1);}
CONVERSION EdgeD(C Edge &edge );
};
/******************************************************************************/
struct Edge2_I : Edge2 // Edge 2D + information
{
Flt length; // length
Vec2 dir , // direction
normal; // normal
// set
void set(C Vec2 &a, C Vec2 &b, C Vec2 *normal=null);
void set(C Edge2 &edge ) {set(edge.p[0], edge.p[1]);}
Edge2_I() {}
Edge2_I(C Vec2 &a, C Vec2 &b, C Vec2 *normal=null) {set(a, b, normal);}
Edge2_I(C Edge2 &edge ) {set(edge );}
};
/******************************************************************************/
struct EdgeD2_I : EdgeD2 // Edge 2D + information (double precision)
{
Dbl length; // length
VecD2 dir , // direction
normal; // normal
// set
void set(C VecD2 &a, C VecD2 &b, C VecD2 *normal=null);
void set(C EdgeD2 &edge ) {set(edge.p[0], edge.p[1]);}
EdgeD2_I() {}
EdgeD2_I(C VecD2 &a, C VecD2 &b, C VecD2 *normal=null) {set(a, b, normal);}
EdgeD2_I(C EdgeD2 &edge ) {set(edge );}
};
/******************************************************************************/
struct Edge_I : Edge // Edge 3D + information
{
Flt length; // length
Vec dir ; // direction
// set
void set(C Vec &a, C Vec &b);
void set(C Edge &edge ) {set(edge.p[0], edge.p[1]);}
Edge_I() {}
Edge_I(C Vec &a, C Vec &b) {set(a, b);}
Edge_I(C Edge &edge ) {set(edge);}
};
/******************************************************************************/
struct EdgeD_I : EdgeD // Edge 3D + information (double precision)
{
Dbl length; // length
VecD dir ; // direction
// set
void set(C VecD &a, C VecD &b);
void set(C EdgeD &edge ) {set(edge.p[0], edge.p[1]);}
EdgeD_I() {}
EdgeD_I(C VecD &a, C VecD &b) {set(a, b);}
EdgeD_I(C EdgeD &edge ) {set(edge);}
};
/******************************************************************************/
struct PixelWalker // iterates through pixels of a rasterized edge
{
// get
Bool active()C {return _active ;} // if walker still active
C VecI2& pos ()C {return _pos_temp;} // get current position
// set
void start(C VecI2 &start, C VecI2 &end); // start walking from 'start' to 'end'
void start(C Vec2 &start, C Vec2 &end); // start walking from 'start' to 'end'
// operations
void step(); // make a single step
PixelWalker( ) {_active=false;}
PixelWalker(C VecI2 &start, C VecI2 &end) {T.start(start, end);}
PixelWalker(C Vec2 &start, C Vec2 &end) {T.start(start, end);}
#if !EE_PRIVATE
private:
#endif
Bool _active, _axis, _side_step;
Int _steps , _main_sign;
VecI2 _pos , _pos_temp;
Vec2 _posr, _step;
};
struct PixelWalkerMask : PixelWalker // iterates through pixels of a rasterized edge only within a specified mask
{
// set
void start(C VecI2 &start, C VecI2 &end, C RectI &mask); // start walking from 'start' to 'end', 'mask'=process pixels only within this inclusive rectangle
void start(C Vec2 &start, C Vec2 &end, C RectI &mask); // start walking from 'start' to 'end', 'mask'=process pixels only within this inclusive rectangle
// operations
void step(); // make a single step
PixelWalkerMask( ) {}
PixelWalkerMask(C VecI2 &start, C VecI2 &end, C RectI &mask) {T.start(start, end, mask);}
PixelWalkerMask(C Vec2 &start, C Vec2 &end, C RectI &mask) {T.start(start, end, mask);}
private:
RectI _mask;
};
/******************************************************************************/
struct PixelWalkerEdge // iterates through pixels of a rasterized line and returns intersections with the edges
{
// get
Bool active()C {return _active;} // if walker still active
C Vec2& pos ()C {return _posr ;} // get current position
// set
void start(C Vec2 &start, C Vec2 &end); // start walking from 'start' to 'end'
// operations
void step(); // make a single step
PixelWalkerEdge( ) {_active=false;}
PixelWalkerEdge(C Vec2 &start, C Vec2 &end) {T.start(start, end);}
#if !EE_PRIVATE
private:
#endif
Bool _active, _axis, _side_step;
Int _steps, _pos;
Vec2 _posr, _pos_next, _step, _pos_end;
};
struct PixelWalkerEdgeMask : PixelWalkerEdge // iterates through pixels of a rasterized line and returns intersections with the edges only within a specified mask
{
// set
void start(C Vec2 &start, C Vec2 &end, C RectI &mask); // start walking from 'start' to 'end', 'mask'=process pixels only within this inclusive rectangle
// operations
void step(); // make a single step
PixelWalkerEdgeMask( ) {}
PixelWalkerEdgeMask(C Vec2 &start, C Vec2 &end, C RectI &mask) {T.start(start, end, mask);}
private:
Rect _mask;
};
/******************************************************************************/
struct VoxelWalker // iterates through voxels of a rasterized edge
{
// get
Bool active()C {return _active ;} // if walker still active
C VecI& pos ()C {return _pos_temp;} // get current position
// set
void start(C VecI &start, C VecI &end); // start walking from 'start' to 'end'
void start(C Vec &start, C Vec &end); // start walking from 'start' to 'end'
// operations
void step(); // make a single step
VoxelWalker( ) {_active=false;}
VoxelWalker(C VecI &start, C VecI &end) {T.start(start, end);}
VoxelWalker(C Vec &start, C Vec &end) {T.start(start, end);}
private:
Bool _active;
Byte _side_step;
Int _steps, _main_sign;
VecI _axis; // 0, 1, 2 axis sorted by most important movement
VecI _pos , _pos_temp;
Vec _posr, _step;
};
/******************************************************************************/
inline Edge2 ::Edge2 (C EdgeD2 &edge) {p[0]=edge.p[0]; p[1]=edge.p[1];}
inline EdgeD2::EdgeD2(C Edge2 &edge) {p[0]=edge.p[0]; p[1]=edge.p[1];}
inline Edge ::Edge (C EdgeD &edge) {p[0]=edge.p[0]; p[1]=edge.p[1];}
inline EdgeD ::EdgeD (C Edge &edge) {p[0]=edge.p[0]; p[1]=edge.p[1];}
/******************************************************************************/
// distance between point and a straight line, 'line_dir'=line direction (must be normalized)
Flt DistPointLine(C Vec2 &point, C Vec2 &line_pos, C Vec2 &line_dir);
Dbl DistPointLine(C VecD2 &point, C VecD2 &line_pos, C VecD2 &line_dir);
Flt DistPointLine(C Vec &point, C Vec &line_pos, C Vec &line_dir);
Dbl DistPointLine(C VecD &point, C Vec &line_pos, C Vec &line_dir);
Dbl DistPointLine(C VecD &point, C VecD &line_pos, C VecD &line_dir);
// squared distance between point and a straight line, 'line_dir'=line direction (must be normalized)
Flt Dist2PointLine(C Vec2 &point, C Vec2 &line_pos, C Vec2 &line_dir);
Dbl Dist2PointLine(C VecD2 &point, C VecD2 &line_pos, C VecD2 &line_dir);
Flt Dist2PointLine(C Vec &point, C Vec &line_pos, C Vec &line_dir);
Dbl Dist2PointLine(C VecD &point, C Vec &line_pos, C Vec &line_dir);
Dbl Dist2PointLine(C VecD &point, C VecD &line_pos, C VecD &line_dir);
// distance between 2 straight lines
Flt DistLineLine(C Vec &pos_a, C Vec &dir_a, C Vec &pos_b, C Vec &dir_b);
// distance between point and an edge
Flt DistPointEdge(C Vec2 &point, C Vec2 &edge_a, C Vec2 &edge_b, DIST_TYPE *type=null);
Dbl DistPointEdge(C VecD2 &point, C VecD2 &edge_a, C VecD2 &edge_b, DIST_TYPE *type=null);
Flt DistPointEdge(C Vec &point, C Vec &edge_a, C Vec &edge_b, DIST_TYPE *type=null);
Dbl DistPointEdge(C VecD &point, C Vec &edge_a, C Vec &edge_b, DIST_TYPE *type=null);
Dbl DistPointEdge(C VecD &point, C VecD &edge_a, C VecD &edge_b, DIST_TYPE *type=null);
inline Flt Dist (C Vec2 &point, C Edge2 &edge , DIST_TYPE *type=null) {return DistPointEdge(point, edge.p[0], edge.p[1], type);}
inline Dbl Dist (C VecD2 &point, C EdgeD2 &edge , DIST_TYPE *type=null) {return DistPointEdge(point, edge.p[0], edge.p[1], type);}
inline Flt Dist (C Vec &point, C Edge &edge , DIST_TYPE *type=null) {return DistPointEdge(point, edge.p[0], edge.p[1], type);}
inline Dbl Dist (C VecD &point, C Edge &edge , DIST_TYPE *type=null) {return DistPointEdge(point, edge.p[0], edge.p[1], type);}
inline Dbl Dist (C VecD &point, C EdgeD &edge , DIST_TYPE *type=null) {return DistPointEdge(point, edge.p[0], edge.p[1], type);}
// squared distance between point and an edge
Flt Dist2PointEdge(C Vec2 &point, C Vec2 &edge_a, C Vec2 &edge_b, DIST_TYPE *type=null);
Dbl Dist2PointEdge(C VecD2 &point, C VecD2 &edge_a, C VecD2 &edge_b, DIST_TYPE *type=null);
Flt Dist2PointEdge(C Vec &point, C Vec &edge_a, C Vec &edge_b, DIST_TYPE *type=null);
Dbl Dist2PointEdge(C VecD &point, C Vec &edge_a, C Vec &edge_b, DIST_TYPE *type=null);
Dbl Dist2PointEdge(C VecD &point, C VecD &edge_a, C VecD &edge_b, DIST_TYPE *type=null);
inline Flt Dist2 (C Vec2 &point, C Edge2 &edge , DIST_TYPE *type=null) {return Dist2PointEdge(point, edge.p[0], edge.p[1], type);}
inline Dbl Dist2 (C VecD2 &point, C EdgeD2 &edge , DIST_TYPE *type=null) {return Dist2PointEdge(point, edge.p[0], edge.p[1], type);}
inline Flt Dist2 (C Vec &point, C Edge &edge , DIST_TYPE *type=null) {return Dist2PointEdge(point, edge.p[0], edge.p[1], type);}
inline Dbl Dist2 (C VecD &point, C Edge &edge , DIST_TYPE *type=null) {return Dist2PointEdge(point, edge.p[0], edge.p[1], type);}
inline Dbl Dist2 (C VecD &point, C EdgeD &edge , DIST_TYPE *type=null) {return Dist2PointEdge(point, edge.p[0], edge.p[1], type);}
// distance between 2 edges
Flt Dist(C Edge2 &a, C Edge2 &b);
Dbl Dist(C EdgeD2 &a, C EdgeD2 &b);
Flt Dist(C Edge &a, C Edge &b);
Dbl Dist(C EdgeD &a, C EdgeD &b);
// squared distance between 2 edges
Flt Dist2(C Edge2 &a, C Edge2 &b);
Dbl Dist2(C EdgeD2 &a, C EdgeD2 &b);
Flt Dist2(C Edge &a, C Edge &b);
Dbl Dist2(C EdgeD &a, C EdgeD &b);
// distance between edge and a plane
Flt Dist(C Edge &edge, C Plane &plane);
Vec2 NearestPointOnEdge(C Vec2 &point, C Vec2 &edge_a, C Vec2 &edge_b); // nearest point on edge
Vec NearestPointOnEdge(C Vec &point, C Vec &edge_a, C Vec &edge_b); // nearest point on edge
inline Vec2 NearestPointOnEdge(C Vec2 &point, C Edge2 &edge ) {return NearestPointOnEdge(point, edge.p[0], edge.p[1]);} // nearest point on edge
inline Vec NearestPointOnEdge(C Vec &point, C Edge &edge ) {return NearestPointOnEdge(point, edge.p[0], edge.p[1]);} // nearest point on edge
Vec NearestPointOnLine(C Vec &point, C Vec &line_pos, C Vec &line_dir); // nearest point on straight line , 'line_dir'=line direction (must be normalized)
Bool NearestPointOnLine(C Vec &pos_a, C Vec &dir_a, C Vec &pos_b, C Vec &dir_b, Edge &out); // nearest points on straight lines, return true is succesfull, put points to out.p[], 'dir_a', 'dir_b'=line directions (must be normalized)
Bool NearestPointOnLine(C VecD &pos_a, C VecD &dir_a, C VecD &pos_b, C VecD &dir_b, EdgeD &out); // nearest points on straight lines, return true is succesfull, put points to out.p[], 'dir_a', 'dir_b'=line directions (must be normalized)
// if points cuts edge (with epsilon)
Bool CutsPointEdge(C Vec2 &point, C Edge2_I &ei , Vec2 *cuts=null);
Bool CutsPointEdge(C VecD2 &point, C EdgeD2_I &ei , VecD2 *cuts=null);
Bool CutsPointEdge(C Vec &point, C Edge_I &ei , Vec *cuts=null);
Bool CutsPointEdge(C VecD &point, C EdgeD_I &ei , VecD *cuts=null);
inline Bool Cuts (C Vec2 &point, C Edge2 &edge, Vec2 *cuts=null) {return CutsPointEdge(point, Edge2_I (edge), cuts);}
inline Bool Cuts (C VecD2 &point, C EdgeD2 &edge, VecD2 *cuts=null) {return CutsPointEdge(point, EdgeD2_I(edge), cuts);}
inline Bool Cuts (C Vec &point, C Edge &edge, Vec *cuts=null) {return CutsPointEdge(point, Edge_I (edge), cuts);}
inline Bool Cuts (C VecD &point, C EdgeD &edge, VecD *cuts=null) {return CutsPointEdge(point, EdgeD_I (edge), cuts);}
// if edge cuts edge (with epsilon)
Int CutsEdgeEdge(C Edge2_I &a, C Edge2_I &b, Edge2 *cuts=null);
Int CutsEdgeEdge(C EdgeD2_I &a, C EdgeD2_I &b, EdgeD2 *cuts=null);
Int CutsEdgeEdge(C Edge_I &a, C Edge_I &b, Edge *cuts=null);
Int CutsEdgeEdge(C EdgeD_I &a, C EdgeD_I &b, EdgeD *cuts=null);
// if edge cuts plane (with epsilon)
Bool Cuts(C Edge &edge, C Plane &plane, Vec *cuts=null);
Bool Cuts(C EdgeD &edge, C PlaneM &plane, VecD *cuts=null);
// clip edge to plane (no epsilon)
Bool Clip(Edge2 &edge, C Plane2 &plane);
Bool Clip(EdgeD2 &edge, C PlaneD2 &plane);
Bool Clip(Edge &edge, C Plane &plane);
Bool Clip(EdgeD &edge, C PlaneD &plane);
// clip edge to plane (with epsilon)
Bool ClipEps(Edge2 &edge, C Plane2 &plane);
Bool ClipEps(EdgeD2 &edge, C PlaneD2 &plane);
Bool ClipEps(Edge &edge, C Plane &plane);
Bool ClipEps(EdgeD &edge, C PlaneD &plane);
// clip edge to rectangle (no epsilon)
Bool Clip(Edge2 &edge, C Rect &rect);
Bool Clip(EdgeD2 &edge, C RectD &rect);
// clip edge to box (no epsilon)
Bool Clip(Edge &edge, C Box &box);
Bool Clip(EdgeD &edge, C BoxD &box);
Bool Clip(Edge &edge, C Extent &ext);
// sweep
Bool SweepPointEdge(C Vec2 &point, C Vec2 &move, C Edge2_I &ei, Flt *hit_frac=null, Vec2 *hit_normal=null, Vec2 *hit_pos=null); // if moving point cuts through a static edge
Bool SweepPointEdge(C VecD2 &point, C VecD2 &move, C EdgeD2_I &ei, Dbl *hit_frac=null, VecD2 *hit_normal=null, VecD2 *hit_pos=null); // if moving point cuts through a static edge
// draw
void DrawArrow (C Color &color, C Vec &start, C Vec &end, Flt tip_radius=0.1f, Flt tip_length=0.1f);
void DrawArrow2(C Color &color, C Vec &start, C Vec &end, Flt width=0.02f, Flt tip_radius=0.1f, Flt tip_length=0.1f);
// subdivide
void SubdivideEdges(C CMemPtr<Vec > &src, MemPtr<Vec > dest); // subdivide continuous points from 'src' into 'dest'
void SubdivideEdges(C CMemPtr<VtxFull> &src, MemPtr<VtxFull> dest); // subdivide continuous points from 'src' into 'dest'
/******************************************************************************/
| true |