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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
e6d29edfbd78cb34f3d13e987bc0ebe6602ae803 | C++ | sonny-zhang/myC- | /example1_1.cpp | GB18030 | 1,233 | 3.765625 | 4 | [] | no_license | /*
ʶC++Ͷ
*/
#include <iostream> //ͷļ
using namespace std; //ʹռ
//int result(int, int); //resultԭ
//
//const int k = 2; //峣
//
//struct Point { //ṹpoint
// int x, y;
//};
/*****************************
result
ζab
ֵζ
*****************************/
//int result(int a, int b)
//{
// return a + b; //a + b
//}
//****************************
/*
int main() //Ϊ
{ //ʼ
int z(0), b(50); //ʼ
Point a; //ṹa
cout << "Կո֣"; //ʾϢ
cin >> a.x >> a.y; //ֵ
z = (a.x + a.y)*k; //
z = result(z, b); //
cout << "£" << endl; //Ϣ
cout << "((" << a.x << "+" << a.y //Ϣ
<< ")*" << k << ")+" << b //Ϣ
<< "=" << z //
<< endl; //
return z; //mainķֵ
} //
*/ | true |
8d3b3653abf68ebfdaed9ea839c6bc5fdab0edb7 | C++ | tran-nick/Learning-CPP | /Section18/IllegalBalanceException.h | UTF-8 | 312 | 2.734375 | 3 | [] | no_license | #pragma once
#include <iostream>
class IllegalBalanceException : public std::exception{
public:
IllegalBalanceException() {}
~IllegalBalanceException() {}
virtual const char* what() const noexcept override {
return "Illegal balance exception, balance cannot be negative number";
}
};
| true |
eb8db2ebad9cb63432b54f166fb04f3d7ffd8c9b | C++ | DronPascal/BMSTU-Cpp-Programming-basics | /3 Сем/Лаба1/MeshLoader/MeshLoader/MeshLoader.h | WINDOWS-1251 | 3,904 | 2.828125 | 3 | [] | no_license | #pragma once
#include "MeshDataTypes.h"
#include <vector>
#include <list>
#include <set>
#include <fstream>
#include <iostream>
#include <unordered_map>
// std::hash, std unordered_multimap<std::pair<unsigned int, unsigned int>, FiniteElement> Edge
namespace std
{
template<> struct hash<std::pair<unsigned int, unsigned int>>
{
std::size_t operator()(std::pair<unsigned int, unsigned int> const& p) const noexcept
{
std::size_t seed = p.first;
seed ^= stdext::hash_value(p.second) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
return seed;
}
};
}
namespace std
{
template<> struct hash<Edge>
{
std::size_t operator()(const Edge& edge) const noexcept
{
std::size_t seed = edge.first_node_id;
seed ^= stdext::hash_value(edge.second_node_id) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
return seed;
}
};
}
class MeshLoader
{
protected:
std::vector<Node> Nodes_Container;
std::vector<FiniteElement> FE_Container;
std::vector<BoundaryFiniteElement> BFE_Container;
//
std::unordered_multimap<std::pair<unsigned int, unsigned int>, FiniteElement> FE_based_on_Edge; //
std::vector<std::vector<Node>> AdjacentNodesContainer;
void make_FE_Edge_map();
public:
virtual void LoadMesh(const std::string&) = 0;
virtual ~MeshLoader() = default;
//, STL - ,
std::vector<Node>& Get_Nodes_Container();
std::vector<FiniteElement>& Get_FE_Container();
std::vector <BoundaryFiniteElement>& Get_BFE_Container();
//, ID
std::vector<FiniteElement> Get_FE_by_3ID(unsigned int, unsigned int, unsigned int) const;
//, , ID
std::vector<FiniteElement> Get_FE_by_Edge_Fast(unsigned int, unsigned int);
std::vector<FiniteElement> Get_FE_by_Edge_Slow(unsigned int, unsigned int) const;
//, ID ;
std::vector<Node> Get_BoundaryNodes_by_borderId(unsigned int) const;
//, ID ;
std::vector<FiniteElement> Get_FE_by_matId(unsigned int) const;
//, ID ;
std::vector<BoundaryFiniteElement> Get_BFE_by_borderId(unsigned int) const;
//, ( ).
void Add_NewNodes();
//, , n - n;
std::vector<std::vector<Node>> Get_AdjacentNodesContainer();
//, Node, Element BoundaryFiniteElement ;
void Print_Nodes_Container() const;
void Print_FE_Container() const;
void Print_BFE_Container() const;
void Print_MeshData() const;
void Print_Node(const Node&) const;
void Print_FiniteElement(const FiniteElement&) const;
void Print_BoundaryFiniteElement(const BoundaryFiniteElement&) const;
//
bool isVertex(unsigned int id, ...) const;
bool isVertex(const FiniteElement& fe) const;
}; | true |
5471482aed63b8ee324f8d5bdee1dd1ebf282eeb | C++ | shshun/algorithm | /백준5022(연결).cpp | UTF-8 | 2,132 | 2.65625 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
#include <string.h>
using namespace std;
//9:20
typedef pair<int, int> p;
int N, M;
int dx[4] = { 0,0,1,-1 };
int dy[4] = { 1,-1,0,0 };
int temp[102][102];
int arr[102][102];
p A[2], B[2];
bool isRange(int x, int y) {
if (x >= 0 && y >= 0 && x < 102 && y < 102) {
return true;
}
return false;
}
int bfs(p *input) {
queue<p> q;
int sX = input[0].first;
int sY = input[0].second;
int destX = input[1].first;
int destY = input[1].second;
q.push({ sX,sY });
int dist = 1;
while (!q.empty()) {
int s = q.size();
for (int i = 0; i < s; i++) {
int x = q.front().first;
int y = q.front().second;
q.pop();
if (x == destX && y == destY) return dist-1;
for (int k = 0; k < 4; k++) {
int nx = x + dx[k];
int ny = y + dy[k];
if (arr[nx][ny]==0 && isRange(nx, ny)) {
arr[nx][ny] = dist;
q.push({ nx,ny });
}
}
}
dist++;
}
return -1;
}
void findPath(p *input) {
int sX = input[0].first;
int sY = input[0].second;
int destX = input[1].first;
int destY = input[1].second;
int x = destX;
int y = destY;
int val = arr[x][y];
while (val != 1) {
for (int k = 0; k < 4; k++) {
int nx = x + dx[k];
int ny = y + dy[k];
if (isRange(nx, ny) && arr[nx][ny] == val - 1) {
temp[nx][ny] = 1;
val--;
x = nx;
y = ny;
break;
}
}
}
temp[sX][sY] = 1;
temp[destX][destY] = 1;
memcpy(arr, temp, sizeof(temp));
memset(temp, 0, sizeof(temp));
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cin >> N >> M;
for (int i = 0; i < 2; i++) {
int x, y;
cin >> y >> x;
A[i] = { x,y };
}
for (int i = 0; i < 2; i++) {
int x, y;
cin >> y >> x;
B[i] = { x,y };
}
int answer = 987654321;
int disA=bfs(A);
findPath(A);
int disB = bfs(B);
if (disB > 0) answer = disA + disB;
memset(arr, 0, sizeof(arr));
disB = bfs(B);
findPath(B);
disA = bfs(A);
if (disA > 0) answer = min(answer, disA + disB);
if (answer == 987654321) {
cout << "IMPOSSIBLE\n";
}
else {
cout << answer << endl;
}
return 0;
} | true |
c65ff6bc3c2413e510bbad7d419786915020875c | C++ | atifkarim/problem_solving | /cpp_practise/pointer_cpp/pointer_type_obj.cpp | UTF-8 | 695 | 3.921875 | 4 | [] | no_license | /***
* In this code usage of pointer type obj is shown.
* Also see calling_function_using_another_class.cpp code
***/
#include <iostream>
using namespace std;
class SUM{
public:
SUM(){cout<<"Free constructor\n";}
int a ; int b;
int do_sum(int x, int y);
};
int SUM::do_sum(int x, int y){
cout<<"result from sum function is: "<<x+y<<endl;
}
int main(){
int q; int p;
cout<<"Hey !!! give two integer\n";
cin>>q; cin>>p;
SUM *ptrobj;
ptrobj = new SUM(); // Used constructor.
ptrobj->a = 4;
ptrobj->b = 5;
ptrobj->do_sum(q,p);
delete ptrobj;
SUM obj_1;
obj_1.a = 1;
obj_1.b = 2;
obj_1.do_sum(q,p);
return 0;
} | true |
4fe22200e4d96d044601e90de9df22b6ff1e3f47 | C++ | qweilak/Golden-Axe-Tribute | /ModuleScenelvl1.h | UTF-8 | 1,273 | 2.609375 | 3 | [] | no_license | #ifndef __MODULESCENELVL1_H__
#define __MODULESCENELVL1_H__
#include "Module.h"
#include "Animation.h"
#include "Globals.h"
#include "Point.h"
#include "Timer.h"
struct Explosion
{
Animation animation;
fPoint point;
};
struct Collider;
struct Potion
{
Collider* collider;
fPoint position;
~Potion();
};
//Objects to draw
struct ObjectsToDraw {
SDL_Texture* texture;
float x;
float y;
float positionY;
SDL_Rect* rect;
float speed = 1.0f;
bool flip = false;
float scaleXY = 1;
bool operator < (const ObjectsToDraw& data) const { return (positionY < data.positionY); }
};
class ModuleScenelvl1 : public Module
{
public:
ModuleScenelvl1(bool start_enabled = true);
~ModuleScenelvl1();
bool Start();
update_status Update();
bool CleanUp();
virtual void OnCollision(Collider* a, Collider* b);
void AddPotion(float x, float y);
public:
std::vector<ObjectsToDraw> vectorPcNpc;
Collider* collider = nullptr;
int screenXZero, worldXmax;
private:
uint fx;
bool canContinue;
bool music_end;
std::vector<Potion*> potion;
SDL_Rect potionRect;
Explosion explosions[7];
SDL_Texture* background;
SDL_Texture* hud;
SDL_Rect hud_lifebars;
SDL_Rect hud_face;
SDL_Rect hud_magic;
Animation hud_continue;
Timer time;
};
#endif //__MODULESCENELVL1_H__ | true |
52a1d66c2a35a6e38d712269186e30047eeb2a2c | C++ | JayGitH/839C-language-and-data-structure | /839数据结构/c语言/6.2结构与函数.cpp | GB18030 | 2,351 | 3.40625 | 3 | [] | no_license | /*20181010()
lingr7
2018102021:05:25
20181020 */
middle = makepoint((screen.pt1.x + screen.pt2.x)/2,
(screen.pt1.y + screen.pt2.y)/2);
/* addpoint*/
struct point addpoint(struct point p1, struct point p2)
{
p1.x += p2.x;
p1.y += p2.y;
return p1;
}
/*ṹ͵IJҲֵͨݵ*/
/* ptinrectpھrڣ10*/
int ptinrect(struct point p, struct rect r){
return p.x >=r.pt1.x && p.x < r.pt2.x
&& p.y >=r.pt1.y && p.y < r.pt2.y;
}
/*һ淶ʽľεĺ*/
#define min(a,b) ((a) < (b) ? (a) : (b))
#define max(a,b) ((a) > (b) ? (a) : (b))
/*ʽpt1Сpt2*/
/*canonrect淶*/
struct rect canonrect(struct rect r){
struct rect temp;
temp.pt1.x = min(r.pt1.x, r.pt2.x);
temp.pt1.y = min(r.pt1.y, r.pt2.y);
temp.pt2.x = max(r.pt1.x, r.pt2.x);
temp.pt2.y = max(r.pt1.y, r,pt2.y);
return temp;
}
/*ݸĽṹܴʹָ뷽ʽЧͨȸṹЧҪ*/
struct point *pp;
/*ppΪһָstruct pointͶָ롣*/
struct point origin, *pp;
pp = &origin;
printf("origin is (%d,%d)\n", (*pp).x, (*pp).y); /*.ȼҪ**/
/*ṹָʹƵʺܸߣΪʹ÷㣬cṩһּдʽٶppһָṹָ*/
/*p->ṹԱ*/
printf("origin is (%d,%d)\n", pp->x, pp->y);
/*
*p->str ȡָstrָĶֵ
*p->str++ ȶȡָstrָĶֵȻٽstr+1;
(*p->str)++
*p++->strȶȡָstrֵָȻٽp1
*/
char *keyword[NKEYS];
int keycount[NKEYS];
/*ṹʵַʽ*/
struct key {
char *word;
int count;
}keytab[NKEYS];
struct key {
char *word;
int count;
};
struct key keytab[NKEYS];
/*ṹʼ*/
/*Ϊⲿ*/
struct key {
char *word;
int count;
} keytab[] ={
"auto", 0,
"break", 0,
"case", 0,
"char", 0,
"const", 0,
"continue", 0,
"default", 0,
/* ... */
"unsigned", 0,
"void", 0,
"volatile", 0,
"while", 0
} ;/**/
/*иȷÿһУÿṹijֵڻ*/
{"auto", 0},
{"break", 0},
{"case", 0},
| true |
239d9a471c1084de5867beb3824b59309d7c7a12 | C++ | ThinEureka/Tiny3D | /Win32Project1/shader/shaderprogram.cpp | UTF-8 | 4,663 | 2.59375 | 3 | [] | no_license | #include "shaderprogram.h"
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <string>
using namespace std;
//Got this from http://www.lighthouse3d.com/opengl/glsl/index.php?oglinfo
// it prints out shader info (debugging!)
void printShaderInfoLog(GLuint obj, const char* shaderStr)
{
int infologLength = 0;
int charsWritten = 0;
char *infoLog;
glGetShaderiv(obj, GL_INFO_LOG_LENGTH, &infologLength);
if (infologLength > 0)
{
infoLog = (char *)malloc(infologLength);
glGetShaderInfoLog(obj, infologLength, &charsWritten, infoLog);
printf("printShaderInfoLog: %s\n", infoLog);
printf("%s\n", shaderStr);
free(infoLog);
}
else{
printf("Shader Info Log: OK\n");
}
}
//Got this from http://www.lighthouse3d.com/opengl/glsl/index.php?oglinfo
// it prints out shader info (debugging!)
void printProgramInfoLog(GLuint obj)
{
int infologLength = 0;
int charsWritten = 0;
char *infoLog;
glGetProgramiv(obj, GL_INFO_LOG_LENGTH, &infologLength);
if (infologLength > 0)
{
infoLog = (char *)malloc(infologLength);
glGetProgramInfoLog(obj, infologLength, &charsWritten, infoLog);
printf("printProgramInfoLog: %s\n", infoLog);
free(infoLog);
}
else{
printf("Program Info Log: OK\n");
}
}
char* ShaderProgram::attach(const char* version, const char* attachStr, const char* shaderStr) {
if (!shaderStr) return NULL;
string shstr = string(version) + string("\n");
if (attachStr) shstr += string(attachStr) + string("\n");
shstr += string(shaderStr);
char* resStr = (char*)malloc(sizeof(char) * (shstr.length() + 1));
strcpy(resStr, shstr.data());
return resStr;
}
ShaderProgram::ShaderProgram(const char* vert, const char* frag, const char* defines, const char* tesc, const char* tese, const char* geom) {
char *vs = NULL, *fs = NULL, *tc = NULL, *te = NULL, *gs = NULL;
vertShader = NULL, fragShader = NULL, tescShader = NULL, teseShader = NULL, geomShader = NULL;
vertShader = glCreateShader(GL_VERTEX_SHADER);
fragShader = glCreateShader(GL_FRAGMENT_SHADER);
if (tesc) tescShader = glCreateShader(GL_TESS_CONTROL_SHADER);
if (tese) teseShader = glCreateShader(GL_TESS_EVALUATION_SHADER);
if (geom) geomShader = glCreateShader(GL_GEOMETRY_SHADER);
vs = textFileRead((char*)vert);
fs = textFileRead((char*)frag);
if (tesc) tc = textFileRead((char*)tesc);
if (tese) te = textFileRead((char*)tese);
if (geom) gs = textFileRead((char*)geom);
const char* version = "#version 450";
char* vv = attach(version, defines, vs);
char* ff = attach(version, defines, fs);
char* cc = attach(version, defines, tc);
char* ee = attach(version, defines, te);
char* gg = attach(version, defines, gs);
glShaderSource(vertShader, 1, &vv, NULL);
glShaderSource(fragShader, 1, &ff, NULL);
if (cc) glShaderSource(tescShader, 1, &cc, NULL);
if (ee) glShaderSource(teseShader, 1, &ee, NULL);
if (gg) glShaderSource(geomShader, 1, &gg, NULL);
free(vs);
free(fs);
if (tc) free(tc);
if (te) free(te);
if (gs) free(gs);
glCompileShader(vertShader);
glCompileShader(fragShader);
if (tescShader) glCompileShader(tescShader);
if (teseShader) glCompileShader(teseShader);
if (geomShader) glCompileShader(geomShader);
printf("%s: ", vert);
printShaderInfoLog(vertShader, vv);
printf("%s: ", frag);
printShaderInfoLog(fragShader, ff);
if (tesc) {
printf("%s: ", tesc);
printShaderInfoLog(tescShader, cc);
}
if (tese) {
printf("%s: ", tese);
printShaderInfoLog(teseShader, ee);
}
if (geom) {
printf("%s: ", geom);
printShaderInfoLog(geomShader, gg);
}
if (vv) free(vv);
if (ff) free(ff);
if (cc) free(cc);
if (ee) free(ee);
if (gg) free(gg);
shaderProg = glCreateProgram();
glAttachShader(shaderProg, vertShader);
glAttachShader(shaderProg, fragShader);
if (tescShader) glAttachShader(shaderProg, tescShader);
if (teseShader) glAttachShader(shaderProg, teseShader);
if (geomShader) glAttachShader(shaderProg, geomShader);
glLinkProgram(shaderProg);
}
ShaderProgram::~ShaderProgram() {
glDetachShader(shaderProg, vertShader);
glDetachShader(shaderProg, fragShader);
if (tescShader) glDetachShader(shaderProg, tescShader);
if (teseShader) glDetachShader(shaderProg, teseShader);
if (geomShader) glDetachShader(shaderProg, geomShader);
glDeleteShader(vertShader);
glDeleteShader(fragShader);
if (tescShader) glDeleteShader(tescShader);
if (teseShader) glDeleteShader(teseShader);
if (geomShader) glDeleteShader(geomShader);
glDeleteProgram(shaderProg);
}
void ShaderProgram::use() {
glUseProgram(shaderProg);
}
| true |
9bdafc02e1976404af347f488616d70d9daebe12 | C++ | Ilyagavrilin/onegin_io | /wrapper.cpp | UTF-8 | 1,673 | 2.84375 | 3 | [] | no_license | #include "wrapper.h"
int MainWrapper() {
const char* separator = "/-------------------------------------\n";
//names for files to work
const char * write_fname = "C:/Users/gavri/CLionProjects/onegin_indexed/write.txt";
const char* read_fname = "C:/Users/gavri/CLionProjects/onegin_indexed/get.txt";
//open file and cout how many symbols in it
size_t f_size = len_finder((char*)read_fname);
int f_handle_read = file_open(read_fname, 'r');
//initialize buffer for strings and fill it from file
char* buffer = (char* ) mem_aloc(f_size);
read_data(f_handle_read, buffer, f_size);
//separate strings in buffer by \n and count they
size_t string_num = strings_sep(buffer, f_size);
//close file with source text
file_close(f_handle_read);
// initialize struct for strings and write pointers to strings starts
text *strings = struct_initialize(string_num);
struct_fill(strings, string_num, buffer, f_size);
//sort strings using default functions
qsort(strings, string_num, sizeof(text), compare);
//write sorted strings to file
int file_handle_write = file_open(write_fname, 'w');
write_data(file_handle_write, strings, string_num);
write(file_handle_write, separator, strlen(separator));
//sort strings from endings and write sorted text
RevQSorter(strings, 0, string_num - 1);
write_data(file_handle_write, strings, string_num);
write(file_handle_write, separator, strlen(separator));
//write source text
write(file_handle_write, buffer, f_size);
Clean(buffer); //clean dynamic buffer and close file
file_close(file_handle_write);
return 0;
} | true |
74963ba9bded4ee2535c0c0bc70ed2bff880b4ae | C++ | marvsz/BP38Ergonomie | /model/bodyposture.cpp | UTF-8 | 1,223 | 2.90625 | 3 | [] | no_license | #include "bodyposture.h"
BodyPosture::BodyPosture()
{
id = -1;
legPosture = new QString("");
setHead(new Head());
setTorso(new Torso());
setLeftArm(new Arm());
setRightArm(new Arm());
setLeftLeg(new Leg());
setRightLeg(new Leg());
}
int BodyPosture::getID() const{
return id;
}
Head* BodyPosture::getHead() const{
return head;
}
void BodyPosture::setHead(Head *head){
this->head = head;
}
Torso* BodyPosture::getTorso() const{
return torso;
}
void BodyPosture::setTorso(Torso *torso){
this->torso = torso;
}
Arm* BodyPosture::getLeftArm() const{
return leftArm;
}
void BodyPosture::setLeftArm(Arm *arm){
leftArm = arm;
}
Arm* BodyPosture::getRightArm() const{
return rightArm;
}
void BodyPosture::setRightArm(Arm *arm){
rightArm = arm;
}
Leg* BodyPosture::getLeftLeg() const{
return leftLeg;
}
void BodyPosture::setLeftLeg(Leg *leg){
leftLeg = leg;
}
Leg* BodyPosture::getRightLeg() const{
return rightLeg;
}
void BodyPosture::setRightLeg(Leg *leg){
rightLeg = leg;
}
QString* BodyPosture::getLegPosture() const{
return legPosture;
}
void BodyPosture::setLegPosture(QString* legPosture){
this->legPosture = legPosture;
}
| true |
1fe2dcaa65b5774aeda693b5ed657e720f548a53 | C++ | ogsub/MIDI-And-Music-XML-Converter-And-Editor | /MIDI And Music XML Converter And Editor/Main.cpp | UTF-8 | 6,566 | 2.671875 | 3 | [
"MIT"
] | permissive |
#include "Kompozicija.h"
#include "Mapa.h"
#include "MIDIFormater.h"
#include "MXMLFormater.h"
#include "BMPFormater.h"
int main(int argc, char *argv[]) { //ime programa, putanja mape, putanja kompozicije, brojilac, imenilac
bool konvertovano = false;
int meni;
bool kraj = false;
Mapa mapa;
Kompozicija kompozicija;
std::vector<int> istorija;
mapa.otvoriMapu(argc, argv);
mapa.popuniTabeluKljucSlovo();
std::cout << "-----------------\n";
mapa.popuniTabeluKljucNota();
bool otvorena = false;
bool postavljenSimbol = false;
while (!kraj) {
std::cout << "Meni\n"
"1. Ucitavanje kompozicije\n"
"2. Prikazi prvi simbol\n"
"3. Nota napred\n"
"4. Nota nazad\n"
"5. Takt napred\n"
"6. Takt nazad\n"
"7. Ispisi simbole iz violinskog i bas sistema\n"
"8. Promeni oktavu kompozicije\n"
"9. Promeni takt kompozicije\n"
"10. Postavi povisilicu\n"
"11. Promeni oktavu note\n"
"12. Konvertuj u MIDI fajl\n"
"13. Konvertuj u MXML fajl\n"
"14.Ukloni povisilicu\n"
"15 Generisi BMI fajl (in progress)\n"
"16. Izadji\n";
std::cin >> meni;
switch (meni) {
case 1:
if (!otvorena) {
konvertovano = false;
kompozicija.otvoriKompoziciju(argc, argv);
kompozicija.ispisiFajl();
kompozicija.setTrajanjeTakta(argc, argv);
kompozicija.ucitajNote(mapa);
kompozicija.popuniPauzama();
otvorena = true;
}
else
std::cerr << "Kompozicija je vec otvorena\n";
break;
case 2:
if (otvorena) {
istorija.push_back(2);
kompozicija.prikaziPrviSimbol();
postavljenSimbol = true;
}
else
std::cerr << "Kompozicija nije otvorena\n";
break;
case 3:
if (!postavljenSimbol && otvorena) {
istorija.push_back(3);
kompozicija.prikaziPrviSimbol();
postavljenSimbol = true;
break;
}
else if (!otvorena) {
std::cerr << "Kompozicija nije otvorena\n";
break;
}
istorija.push_back(3);
kompozicija.nextSimbol();
kompozicija.ispisiSimbol();
break;
case 4:
if (!postavljenSimbol && otvorena) {
istorija.push_back(4);
kompozicija.prikaziPrviSimbol();
postavljenSimbol = true;
break;
}
else if(!otvorena) {
std::cerr << "Kompozicija nije otvorena\n";
break;
}
istorija.push_back(4);
kompozicija.prewSimbol();
kompozicija.ispisiSimbol();
break;
case 5:
if (!postavljenSimbol && otvorena) {
istorija.push_back(5);
kompozicija.prikaziPrviSimbol();
postavljenSimbol = true;
break;
}
else if(!otvorena){
std::cerr << "Kompozicija nije otvorena\n";
break;
}
istorija.push_back(5);
kompozicija.nextTakt();
kompozicija.ispisiSimbol();
break;
case 6:
if (!postavljenSimbol && otvorena) {
istorija.push_back(6);
kompozicija.prikaziPrviSimbol();
postavljenSimbol = true;
break;
}
else if (!otvorena) {
std::cerr << "Kompozicija nije otvorena\n";
break;
}
istorija.push_back(6);
kompozicija.prewTakt();
kompozicija.ispisiSimbol();
break;
case 7:
if (otvorena) {
istorija.push_back(7);
kompozicija.ispisLinijskihSistema();
}
else
std::cerr << "Kompozicija nije otvorena\n";
break;
case 8:
{
if (otvorena) {
istorija.push_back(8);
konvertovano = false;
int i;
std::cout << "Za koliko zelis da promenis oktavu? ";
std::cin >> i;
istorija.push_back(i);
kompozicija.pomeranjeKompozicije(i);
}
else std::cerr << "Kompozicija nije otvorena\n";
break;
}
case 9:
if (otvorena) {
konvertovano = false;
kompozicija.izmeniTakt(mapa, istorija, konvertovano, postavljenSimbol);
}
else std::cerr << "Kompozicija nije otvorena\n";
break;
case 10:
if (!otvorena) {
std::cerr << "Kompozicija nije otvorena\n";
break;
}
if (!postavljenSimbol) {
istorija.push_back(10);
kompozicija.prikaziPrviSimbol(false);
postavljenSimbol = true;
konvertovano = false;
kompozicija.setPovisilica();
}
else {
istorija.push_back(10);
konvertovano = false;
kompozicija.setPovisilica();
}
break;
case 11:
{
if (!otvorena) {
std::cerr << "Kompozicija nije otvorena\n";
break;
}
if (!postavljenSimbol) {
istorija.push_back(11);
kompozicija.prikaziPrviSimbol(false);
postavljenSimbol = true;
int i;
std::cout << "Unesi broj za koji zelis da izmenis oktavu\n";
std::cin >> i;
istorija.push_back(i);
kompozicija.izmeniOktavuNote(i);
}
break;
}
case 12:
{
if (otvorena) {
konvertovano = true;
std::unique_ptr<Formater> midi = std::make_unique<MIDIFormater>();
midi->konvertuj(mapa, &kompozicija);
}
else std::cout << "Kompozicija nije otvorena\n";
break;
}
case 13:
{
if (otvorena) {
konvertovano = true;
std::unique_ptr<Formater> mxml = std::make_unique<MXMLFormater>();
mxml->konvertuj(mapa, &kompozicija);
}
else std::cout << "Kompozicija nije otvorena\n";
break;
}
case 14: {
if (!otvorena) {
std::cerr << "Kompozicija nije otvorena\n";
break;
}
if (!postavljenSimbol) {
istorija.push_back(10);
kompozicija.prikaziPrviSimbol(false);
postavljenSimbol = true;
konvertovano = false;
kompozicija.ukliniPovisilicu();
}
else {
istorija.push_back(10);
konvertovano = false;
kompozicija.ukliniPovisilicu();
}
break;
}
case 15:
{
/*if (otvorena) {
int visina;
int sirina;
std::cout << "Unesi visinu\n";
std::cin >> visina;
std::cout << "Unesi sirinu\n";
std::cin >> sirina;
konvertovano = true;
std::unique_ptr<BMPFormater> bmp = std::make_unique<BMPFormater>(visina, sirina);
bmp->postaviPiksel(sirina / 2, visina / 2, 255, 255, 255);
bmp->ispisi("out.bmp");
}
else std::cout << "Kompozicija nije otvorena\n";*/
break;
}
case 16:
{
kraj = true;
if (!konvertovano) {
int optIzlaz = 0;
while (optIzlaz != 3) {
std::cout << "Nije nista konvertovano od zadnje promene.\n"
"1. Konvertuj u MIDI fajl\n"
"2. Konvertuj u MXML fajl\n"
"3. Napusti program\n";
std::cin >> optIzlaz;
switch (optIzlaz)
{
case 1:
{
std::unique_ptr<Formater> midi = std::make_unique<MIDIFormater>();
midi->konvertuj(mapa, &kompozicija);
exit(0);
break;
}
case 2:
{
std::unique_ptr<Formater> mxml = std::make_unique<MXMLFormater>();
mxml->konvertuj(mapa, &kompozicija);
exit(0);
break;
}
}
}
}
break;
}
}
}
}
| true |
382e3f057b73deabc59bcaf870fd3499019e7823 | C++ | upupming/algorithm | /acwing/算法竞赛进阶指南/0x12-队列/132. 小组队列.cpp | UTF-8 | 1,531 | 2.96875 | 3 | [
"MIT"
] | permissive | /*
维护 t 个队列,同时用 m[i] = j 表示第 i 类在第 j 个队列里面,o[j] = i
书上的做法:实际上是把 m 和 n 也当做一个队列来处理了,用一个存小组编号的队列维护当前的所有组,也能够实现按序的出队列。
*/
#include <cstring>
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
int t, m[1010], o[1010], cls[1000010], n, x, cnt, idx;
string cmd;
vector<queue<int>> qs;
int main() {
while (cin >> t, t) {
qs.clear();
cout << "Scenario #" << (++cnt) << endl;
memset(m, 0xff, sizeof(m));
memset(o, 0xff, sizeof(o));
idx = 0;
for (int i = 0; i < t; i++) {
cin >> n;
for (int j = 0; j < n; j++) {
cin >> x;
cls[x] = i;
}
}
while (cin >> cmd, cmd != "STOP") {
if (cmd[0] == 'E') {
cin >> x;
if (m[cls[x]] == -1) {
// 创建一个新的队列
qs.push_back(queue<int>());
m[cls[x]] = qs.size() - 1;
o[qs.size() - 1] = cls[x];
}
// 加入到对应的队列
qs[m[cls[x]]].push(x);
} else if (cmd[0] == 'D') {
cout << qs[idx].front() << endl;
qs[idx].pop();
if (qs[idx].empty()) m[o[idx]] = -1, o[idx] = -1, idx++;
}
}
cout << endl;
}
return 0;
} | true |
5dc778129b5ed6ac792eeb706d43568e35b19a29 | C++ | RsrnlWysxr/Data_structures | /LinkedList/LinkedQueue/main.cpp | UTF-8 | 411 | 3.0625 | 3 | [] | no_license | #include <iostream>
#include "LinkedQueue.h"
int main()
{
LinkedQueue<int>* link = new LinkedQueue<int>();
for(int i = 0 ; i < 10 ; ++i)
{
link->enqueue(i);
}
link->toString();
std::cout << "size:" << link->getSize() << std::endl;
std::cout << "getFront:" << link->getFront() << std::endl;
std::cout << "dequeue:" << link->dequeue() << std::endl;
link->toString();
} | true |
aba966982e2e8d966b829764f4da07402dba4c9c | C++ | iamgyu/DataStructure-Algorithm | /OpenAddressing/OpenAddressing/OpenAddressing.cpp | UHC | 3,391 | 3.15625 | 3 | [] | no_license | #include "OpenAddressing.h"
HashTable* OAHT_CreateHashTable(int TableSize)
{
HashTable* HT = (HashTable*)malloc(sizeof(HashTable));
HT->Table = (ElementType*)malloc(sizeof(ElementType) * TableSize);
memset(HT->Table, 0, sizeof(ElementType) * TableSize);
HT->TableSize = TableSize;
HT->OccupiedCount = 0;
return HT;
}
void OAHT_Set(HashTable** HT, KeyType Key, ValueType Value)
{
int KeyLen, Address, StepSize;
double Usage;
Usage = (double)(*HT)->OccupiedCount / (*HT)->TableSize;
if (Usage > 0.5) // 50% ؽ
{
OAHT_Rehash(HT);
}
KeyLen = strlen(Key);
Address = OAHT_Hash(Key, KeyLen, (*HT)->TableSize);
StepSize = OAHT_Hash2(Key, KeyLen, (*HT)->TableSize);
while ((*HT)->Table[Address].Status != EMPTY && strcmp((*HT)->Table[Address].Key, Key) != 0)
{
printf("Collision occured! : Key(%s), Address(%d), StepSize(%d)\n", Key, Address, StepSize);
Address = (Address + StepSize) % (*HT)->TableSize;
}
(*HT)->Table[Address].Key = (char*)malloc(sizeof(char) * (KeyLen + 1));
strcpy((*HT)->Table[Address].Key, Key);
(*HT)->Table[Address].Value = (char*)malloc(sizeof(char) * (strlen(Value) + 1));
strcpy((*HT)->Table[Address].Value, Value);
(*HT)->Table[Address].Status = OCCUPIED;
(*HT)->OccupiedCount++;
printf("Key(%s) entered at address(%d)\n", Key, Address);
}
ValueType OAHT_Get(HashTable* HT, KeyType Key)
{
int KeyLen = strlen(Key);
int Address = OAHT_Hash(Key, KeyLen, HT->TableSize);
int StepSize = OAHT_Hash2(Key, KeyLen, HT->TableSize);
while (HT->Table[Address].Status != EMPTY && strcmp(HT->Table[Address].Key, Key) != 0)
{
Address = (Address + StepSize) % HT->TableSize;
}
return HT->Table[Address].Value;
}
void OAHT_ClearElement(ElementType* Element)
{
if (Element->Status == EMPTY)
return;
free(Element->Key);
free(Element->Value);
}
void OAHT_DestroyHashTable(HashTable* HT)
{
// 1. ũ Ʈ ҿ ϱ
for (int i = 0; i < HT->TableSize; i++)
{
OAHT_ClearElement(&(HT->Table[i]));
}
// 2. ؽ ̺ ҿ ϱ
free(HT->Table);
free(HT);
}
int OAHT_Hash(KeyType Key, int KeyLength, int TableSize)
{
int HashValue = 0;
for (int i = 0; i < KeyLength; i++)
{
HashValue = (HashValue << 3) + Key[i];
}
HashValue = HashValue % TableSize;
return HashValue;
}
int OAHT_Hash2(KeyType Key, int KeyLength, int TableSize)
{
int HashValue = 0;
for (int i = 0; i < KeyLength; i++)
{
HashValue = (HashValue << 2) + Key[i];
}
// ʵ
// ̺ ũ 3
HashValue = HashValue % (TableSize - 3);
return HashValue + 1;
}
void OAHT_Rehash(HashTable** HT)
{
ElementType* OldTable = (*HT)->Table;
// ؽ ̺ ,
HashTable* NewHT = OAHT_CreateHashTable((*HT)->TableSize * 2);
printf("\nRehashed. New table size is : %d\n\n", NewHT->TableSize);
// ؽ ̺ ִ ؽ ̺ ű
for (int i = 0; i < (*HT)->TableSize; i++)
{
if (OldTable[i].Status == OCCUPIED)
{
OAHT_Set(&NewHT, OldTable[i].Key, OldTable[i].Value);
}
}
// ؽ ̺ ҸŲ
OAHT_DestroyHashTable(*HT);
// HT Ϳ ؽ ̺ ּҸ Ѵ
(*HT) = NewHT;
} | true |
f41178d086d35fe73f4a657873065c349fcdc7a6 | C++ | toivjon/sdl2-space-invaders | /include/state.h | UTF-8 | 1,028 | 3.046875 | 3 | [
"MIT"
] | permissive | /*! An abstraction for all available game states within the Space Invaders.
*
* Our implementation of the Space Invaders contains three different scenes,
* where one state is reserved for the welcoming (i.e. description) states,
* one state is for the player get-ready message and one is for the ingame.
*/
#ifndef SPACE_INVADERS_STATE_H
#define SPACE_INVADERS_STATE_H
#include <memory>
// forward declarations in the global namespace.
struct SDL_Renderer;
struct SDL_KeyboardEvent;
namespace space_invaders
{
class Game;
class State
{
public:
State(Game& game) : mGame(game) {}
virtual ~State() {}
virtual void update(unsigned long dt) = 0;
virtual void render(SDL_Renderer& renderer) = 0;
virtual void onEnter() = 0;
virtual void onExit() = 0;
virtual void onKeyUp(SDL_KeyboardEvent& event) = 0;
virtual void onKeyDown(SDL_KeyboardEvent& event) = 0;
protected:
Game& mGame;
};
typedef std::shared_ptr<State> StatePtr;
}
#endif | true |
46e39f9020257969c30df9bf5a2d9210411ce6cf | C++ | evanmiller067/cs261 | /assignments/production/production2/productiondb.h | UTF-8 | 960 | 3.046875 | 3 | [] | no_license | #ifndef PRODUCTIONDB_H
#define PRODUCTIONDB_H
#include <string>
#include <map>
#include "entry.h"
//class to store all data in maps and vectors
class productiondb
{
private:
typedef std::map<std::string stationName, stationdata*> stationMap;
stationMap stations;
public:
void addData(entry&);
stationMap::const_iterator getStationBegin() const {return stations.cbegin();}
stationMap::const_terator getStationEnd() const {return stations.cend();}
~productiondb();
};
class stationdata()
{
private:
std::map<int year, yeardata*> yearMap;
public:
~stationdata();
stationdata(std::string stationName);
};
class yeardata()
{
//all data for a year broken down by months.
//array of resourcecount objects, one per month
resourcecount resourceArray[12]; // = {resourcecount(0,0,0,0,0,0,0,0,0,0,0,0)};
};
class resourcecount()
{
private:
std::map<std::string resource, int amount> resourceMap;
public:
void getResource();
};
#endif
| true |
3d9ee151a5faed5c75e0d8f6c8fd0aff6440d82e | C++ | polyglotm/coding-dojo | /coding-challange/codewars/7kyu/2020-02-21~2020-07-31/from-the-minimum/from-the-minimum.cpp | UTF-8 | 457 | 2.890625 | 3 | [] | no_license | // https://www.codewars.com/kata/563b662a59afc2b5120000c6
// $ g++ -std=c++11 space.cpp
#include <iostream>
#include <string>
#include <vector>
#include <set>
using namespace std;
unsigned long long minValue(vector<int> values) {
std::set<int> set(values.begin(), values.end());
std::string s;
for (const auto &v: set) {
s += std::to_string(v);
}
return std::stoi(s);
}
int main() {
minValue({1, 3, 1});
return 0;
}
| true |
bfb629607520242ae74a865e08ebd26c93f25ad6 | C++ | Mukit09/UVA_Solution | /598.cpp | UTF-8 | 1,230 | 2.546875 | 3 | [] | no_license | #include<stdio.h>
#include<string.h>
long taken[15],u,v,fg,fg1,n;
char st[30],ch[15][50];
void rec(long ind,long l,long len)
{
long i;
if(l==len)
{
fg=1;
for(i=1;i<ind;i++)
{
if(taken[i]==1&&fg)
{
printf("%s",ch[i]);
fg=0;
}
else if(taken[i]==1&&!fg)
printf(", %s",ch[i]);
}
puts("");
return ;
}
for(i=ind;i<=n;i++)
{
if(taken[i]==0)
{
taken[i]=1;
rec(i+1,l+1,len);
taken[i]=0;
}
}
}
int main()
{
long t,i;
scanf("%ld",&t);
while(getchar()!='\n');
while(getchar()!='\n');
while(t--)
{
gets(st);
i=1;
while(gets(ch[i]))
{
if(strcmp(ch[i],"")==0)
break;
i++;
}
n=i-1;
fg1=1;
fg=u=v=0;
for(i=0;st[i];i++)
{
if(st[i]=='*')
{
fg=1;
break;
}
else if(st[i]>=48&&st[i]<=57&&fg1==1)
{
while(st[i]>=48&&st[i]<=57&&st[i])
{
u=u*10+(st[i]-48);
i++;
}
i--;
fg1=0;
}
else if(st[i]>=48&&st[i]<=57&&fg1==0)
{
while(st[i]>=48&&st[i]<=57&&st[i])
{
v=v*10+(st[i]-48);
i++;
}
i--;
}
}
if(fg)
u=1,v=n;
else if(u&&v==0)
u=u,v=u;
for(i=u;i<=v;i++)
{
printf("Size %ld\n",i);
rec(1,0,i);
puts("");
}
if(t)
printf("\n");
}
return 0;
} | true |
19320d1ae519ce60419ee6401961ae2a6b399a7c | C++ | abhisheksrivastava99/C-Problem-Solving-DSA | /Factors of a number.cpp | UTF-8 | 176 | 2.765625 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
int num;
cout << "Enter value of num: ";
cin >> num;
for(int i=1;i<=num;i++)
{
if(num%i==0){cout<<i<<endl;}
}
return 0;
}
| true |
8c18a62bed92b783e6b9146d13f3d366e68c59be | C++ | gregouar/VALAG | /Valag/src/core/StatesManager.cpp | UTF-8 | 1,867 | 2.953125 | 3 | [] | no_license | #include "Valag/core/StatesManager.h"
#include "Valag/core/GameState.h"
#include "Valag/utils/Logger.h"
namespace vlg
{
StatesManager::StatesManager() :
m_attachedApp(nullptr)
{
}
StatesManager::~StatesManager()
{
//dtor
}
void StatesManager::stop()
{
this->switchState(nullptr);
}
void StatesManager::switchState(GameState* state)
{
for(std::size_t i = 0; i < m_states.size() ; ++i)
m_states[i]->leaving();
m_states.clear();
if(state != nullptr)
{
m_states.push_back(state);
m_states.back()->setManager(this);
m_states.back()->entered();
}
}
void StatesManager::pushState(GameState* state)
{
if(m_states.back())
m_states.back()->obscuring();
m_states.push_back(state);
m_states.back()->setManager(this);
m_states.back()->entered();
}
GameState* StatesManager::popState()
{
if(m_states.empty())
{
Logger::error("Attempted to pop from an empty game state stack");
return (nullptr);
}
m_states.back()->leaving();
m_states.pop_back();
if(m_states.empty())
return (nullptr);
m_states.back()->revealed();
return m_states.back();
}
GameState* StatesManager::peekState()
{
if(m_states.empty())
return (nullptr);
return m_states.back();
}
void StatesManager::handleEvents(const EventsManager *eventsManager)
{
for(std::size_t i = 0; i < m_states.size() ; ++i)
m_states[i]->handleEvents(eventsManager);
}
void StatesManager::update(const Time &elapsedTime)
{
for(auto state : m_states)
state->update(elapsedTime);
}
void StatesManager::draw(RenderWindow *renderWindow)
{
for(auto state : m_states)
state->draw(renderWindow);
}
void StatesManager::attachApp(VApp* app)
{
m_attachedApp = app;
}
VApp* StatesManager::getApp()
{
return m_attachedApp;
}
}
| true |
012c68bc1f6bf1c5d96dffe4eb6634844eb1062e | C++ | eklavya1983/memcache | /src/Shard.cpp | UTF-8 | 3,360 | 2.546875 | 3 | [] | no_license | #include <Shard.h>
namespace memcache {
EmbeddedKvStoreShard::EmbeddedKvStoreShard(folly::EventBase *eb,
uint64_t maxCacheEntries)
: eb_(eb),
maxCacheEntries_(maxCacheEntries)
{
}
void EmbeddedKvStoreShard::init()
{
}
folly::Future<MessagePtr> EmbeddedKvStoreShard::handleGet(MessagePtr req)
{
return
via(eb_).then([this, req = std::move(req)]() mutable {
auto itr = cache_.find(req->key);
if (itr == cache_.end()) {
return Message::makeMessageWithStatus(req->header.opcode, STATUS_KEY_NOT_FOUND);
} else if (req->header.cas && req->header.cas != itr->second.version) {
return Message::makeMessageWithStatus(req->header.opcode, STATUS_KEY_NOT_FOUND);
} else {
/*
* 1. Update lru list by moving key to front
* 2. Update cach entry to point to lru key position
*/
lruList_.erase(itr->second.lruPos);
itr->second.lruPos = lruList_.insert(lruList_.begin(), req->key);
return Message::makeMessage(req->header.opcode, false, req->key, itr->second.value);
}
});
}
folly::Future<MessagePtr> EmbeddedKvStoreShard::handleSet(MessagePtr req)
{
return
via(eb_).then([this, req = std::move(req)]() mutable {
if (!req->value) {
return Message::makeMessageWithStatus(req->header.opcode, STATUS_INVALID_ARGS);
}
auto itr = cache_.find(req->key);
uint64_t retVersion;
if (itr != cache_.end()) {
/* Existing entry */
itr->second.version++;
retVersion = itr->second.version;
/*
* 1. Update lru list by moving key to front
* 2. Update cach entry to point to lru key position
*/
lruList_.erase(itr->second.lruPos);
itr->second.lruPos = lruList_.insert(lruList_.begin(), req->key);
} else {
/* New entry */
if (cache_.size() == maxCacheEntries_) {
/* Purge an entry from cache when cache is full */
auto keyToRemove = lruList_.back();
lruList_.pop_back();
auto itr = cache_.find(keyToRemove);
CHECK(itr != cache_.end());
cache_.erase(itr);
}
/* Update lru list by adding key to front */
auto lruEntryRef = lruList_.insert(lruList_.begin(), req->key);
/* Add new entry into cache */
retVersion = 1;
cache_[req->key] = CacheEntry{retVersion, lruEntryRef, *(req->value)};
}
auto rep = Message::makeMessageWithStatus(req->header.opcode, STATUS_OK);
rep->header.cas = retVersion;
return rep;
});
}
folly::Future<MessagePtr> EmbeddedKvStoreShard::handleDelete(MessagePtr req)
{
return
via(eb_).then([this, req = std::move(req)]() mutable {
auto itr = cache_.find(req->key);
if (itr == cache_.end()) {
return Message::makeMessageWithStatus(req->header.opcode, STATUS_KEY_NOT_FOUND);
} else {
lruList_.erase(itr->second.lruPos);
cache_.erase(itr);
return Message::makeMessageWithStatus(req->header.opcode, STATUS_OK);
}
});
}
} // namespace memcache
| true |
8f2ee1a5c091c12b378406c27df7ecd3db06ee08 | C++ | immortaldogg/CaroAI | /Classes/GameManager.cpp | UTF-8 | 791 | 2.515625 | 3 | [] | no_license | #include "GameManager.h"
#include "SimpleAudioEngine.h"
USING_NS_CC;
Node* GameManager::createNode()
{
return GameManager::create();
}
// Print useful error message instead of segfaulting when files are not there.
static void problemLoading(const char* filename)
{
printf("Error while loading: %s\n", filename);
printf("Depending on how you compiled you might have to add 'Resources/' in front of filenames in HelloWorldScene.cpp\n");
}
// on "init" you need to initialize your instance
bool GameManager::init()
{
//////////////////////////////
// 1. super init first
if ( !Node::init() )
{
return false;
}
// init starting value of the game state
this->turn = 0;
this->isOver = false;
return true;
}
void GameManager::make_play() {
} | true |
79d49ab2c5f6fe3ece37e20e88afb3ac3a0c7461 | C++ | thelastsupreme/cracking-the-coding-interview | /3.StacksAndQueues/3.5SortStack.cpp | UTF-8 | 1,113 | 4.3125 | 4 | [] | no_license | // Sort Stack: Write a program to sort a stack such that the smallest items are on the top. You can use
// an additional temporary stack, but you may not copy the elements into any other data structure
// (such as an array). The stack supports the following operations: push, pop, peek, and is Empty.
#include<iostream>
#include<stack>
#include<vector>
using namespace std;
//method 1 using a temp stack
void sort(stack<int>&s){
stack<int>r; //temp stack
while(!s.empty()){ //continue until given stack is not empty
int temp=s.top();
s.pop(); //put top item in s in temp
while(!r.empty()&& r.top()>temp){ //if r.top is greater push it to s
s.push(r.top());
r.pop();
}
r.push(temp); //then push your temp
}
while (!r.empty())
{
s.push(r.top());
r.pop();
}
}
int main(){
stack<int>s;
s.push(2);
s.push(9);
s.push(4);
s.push(3);
s.push(8);
s.push(1);
sort(s);
while (!s.empty())
{
cout<<s.top()<<endl;
s.pop();
}
} | true |
83b6b7031d99b31d8aeb13d5bca97721bebcac39 | C++ | mehrdad-shokri/cosix | /hw/vga.cpp | UTF-8 | 3,168 | 2.828125 | 3 | [
"BSD-2-Clause"
] | permissive | #include <oslibc/string.h>
#include <hw/vga.hpp>
using cloudos::vga_color;
using cloudos::vga_buffer;
static uint8_t make_color(vga_color fg, vga_color bg) {
return uint8_t(fg) | uint8_t(bg) << 4;
}
vga_buffer::vga_buffer(vga_color fg, vga_color bg, uint16_t *p, size_t w, size_t h)
: cursor_row(0)
, cursor_column(0)
, color(make_color(fg, bg))
, buffer(p)
, width(w)
, height(h)
{
clear_screen();
}
void vga_buffer::clear_screen()
{
for (size_t y = 0; y < height; ++y) {
for (size_t x = 0; x < width; ++x) {
putc_at(' ', color, x, y);
}
}
}
void vga_buffer::set_color(vga_color fg, vga_color bg) {
color = make_color(fg, bg);
}
void vga_buffer::get_color(vga_color *fg, vga_color *bg) {
if(fg) *fg = vga_color(color & 0x0f);
if(bg) *bg = vga_color((color >> 4) & 0x0f);
}
void vga_buffer::set_cursor(size_t row, size_t column) {
cursor_row = row;
cursor_column = column;
}
void vga_buffer::get_cursor(size_t *row, size_t *column) {
if(row) *row = cursor_row;
if(column) *column = cursor_column;
}
void vga_buffer::get_size(size_t *w, size_t *h) {
if(w) *w = width;
if(h) *h = height;
}
void vga_buffer::putc_at(char c, vga_color fg, vga_color bg, size_t x, size_t y) {
putc_at(c, make_color(fg, bg), x, y);
}
void vga_buffer::putc_at(char c, uint8_t col, size_t x, size_t y) {
const size_t index = y * width + x;
buffer[index] = uint16_t(c) | uint16_t(col) << 8;
}
void vga_buffer::getc_at(char *c, uint8_t *col, size_t x, size_t y) {
const size_t index = y * width + x;
uint16_t block = buffer[index];
if(c) {
*c = uint8_t(block & 0xff);
}
if(col) {
*col = uint8_t((block >> 8) & 0xff);
}
}
void vga_buffer::getc_at(char *c, vga_color *fg, vga_color *bg, size_t x, size_t y) {
char ch;
uint8_t col;
getc_at(&ch, &col, x, y);
if(c) *c = ch;
if(fg) *fg = vga_color(col & 0x0f);
if(bg) *bg = vga_color((col >> 4) & 0x0f);
}
void vga_buffer::putc(char c) {
switch(c) {
case '\n':
if(++cursor_row == height) {
scroll();
}
// TODO: \n should not fallthrough here; to move the cursor
// back to column 0 \r\n should be written (this is done by the
// terminal layer normally)
[[clang::fallthrough]];
case '\r':
cursor_column = 0;
break;
case '\b':
if(cursor_column == 0) {
if(cursor_row != 0) {
--cursor_row;
cursor_column = width - 1;
}
} else {
--cursor_column;
}
putc_at(' ', color, cursor_column, cursor_row);
break;
case '\t':
while(cursor_column % 8) {
putc(' ');
}
break;
case '\x1b':
putc('^');
putc('[');
break;
default:
putc_at(c, color, cursor_column, cursor_row);
if (++cursor_column == width) {
cursor_column = 0;
if (++cursor_row == height) {
scroll();
}
}
}
}
void vga_buffer::scroll() {
for(size_t y = 1; y < height; ++y) {
for(size_t x = 0; x < width; ++x) {
char prev_char;
uint8_t prev_color;
getc_at(&prev_char, &prev_color, x, y);
putc_at(prev_char, prev_color, x, y-1);
}
}
for(size_t x = 0; x < width; ++x) {
putc_at(' ', color, x, height - 1);
}
if(cursor_row > 0) {
--cursor_row;
}
}
void vga_buffer::write(const char *data) {
for(; *data != 0; data++) {
putc(*data);
}
}
| true |
e32b6133b4f3b86a7d0d3dfe053ec5a6caa79bf8 | C++ | sheikhafsar/1725_OOP | /CPP/Test/main.cpp | UTF-8 | 387 | 2.9375 | 3 | [] | no_license | #include <iostream>
#include "Staff.h"
#include "NonTeachingStaff.h"
#include<string>
using namespace std;
int main()
{
cout << "Hello world!" << endl;
NonTeachingStaff n1;
n1.setName("Anish","Rao");
n1.SetPay(992200);
n1.Setage(21);
cout << n1.getName() << endl;
cout << "age : " << n1.Getage() << " salary : " << n1.GetPay() << endl;
return 0;
}
| true |
c5f0c359a2e2ba782459fb61250303139e89764c | C++ | alexalkis/mcl | /InputLine.cc | UTF-8 | 14,838 | 3.03125 | 3 | [] | no_license | // The input line
#include "mcl.h"
#include "cui.h"
#include "Interpreter.h"
#include <sys/stat.h>
#include <time.h>
// A history for one input line
// This class is used internally by InputLine
class History {
public:
History(int _id);
~History();
void add (const char *s,time_t); // Add this string
const char * get (int no, time_t *timestamp); // Get this string.
int id; // Id number
private:
char **strings; // Array of strings
time_t *timestamps;
int max_history; // Max number of strings
int current; // Current place we will insert a new
};
History::History(int _id) : id (_id), current(0) {
max_history = config->getOption(opt_histsize);
strings = new char*[max_history];
timestamps = new time_t[max_history];
// Hmm, not sure about this
memset(strings,0, max_history * sizeof(char*));
}
History::~History() {
delete[] strings;
delete[] timestamps;
}
void History::add(const char *s,time_t t) {
// Don't store multiple strings that are exactly the same
if (current > 0 && !strcmp(s,strings[(current-1) % max_history]))
return;
if (strings[current % max_history])
free(strings[current % max_history]);
strings[current % max_history] = strdup(s);
timestamps[current % max_history] = t;
current++;
}
// getting number 1 gets you the LAST line
const char * History::get(int count, time_t* timestamp) {
if (count > min(current, max_history))
return NULL;
if (timestamp)
*timestamp = timestamps[(current - count) % max_history];
return strings[(current - count) % max_history];
}
// This class has a set of history arrays
// This is so they can save between invokactions of the input line in
// question without requiring globals
class HistorySet {
public:
~HistorySet() {
for (History *h = hist_list.rewind(); h; h = hist_list.next()) {
delete h;
hist_list.remove(h);
}
}
void saveHistory() {
if (config->getOption(opt_save_history)) {
FILE *fp = fopen(Sprintf("%s/.mcl/history", getenv("HOME")), "w");
if (fp) {
const char *s;
time_t t;
fchmod(fileno(fp), 0600);
FOREACH(History *,h,hist_list)
for (int i = config->getOption(opt_histsize) ; i > 0; i--)
if ((s = get((history_id)h->id,i, &t)))
fprintf(fp, "%d %ld %s\n", h->id, t, s);
fclose(fp);
}
}
}
void loadHistory() {
if (config->getOption(opt_save_history)) {
FILE *fp = fopen(Sprintf("%s/.mcl/history", getenv("HOME")), "r");
if (fp) {
int id;
time_t t;
char buf[1024];
while (3 == fscanf(fp, "%d %ld %1024[^\n]", &id, &t, buf))
add((history_id)id,buf,t);
fclose(fp);
}
}
}
const char *get (history_id id, int count, time_t* timestamp) {
return find(id)->get(count, timestamp);
}
void add (history_id id, const char *s, time_t t = 0) {
find(id)->add(s,t ? t : current_time);
}
private:
List<History*> hist_list;
History * find(int id) {
for (History *h = hist_list.rewind(); h; h = hist_list.next())
if (h->id == id)
return h;
History *new_hist = new History(id);
hist_list.insert(new_hist);
return new_hist;
}
};
static HistorySet history;
void load_history() {
history.loadHistory();
}
void save_history() {
history.saveHistory();
}
class InputHistorySelection : public Selection{
public:
InputHistorySelection(Window *parent, int w, int h, int x, int y, InputLine& _input, bool _enterExecutes, history_id _historyId) : Selection(parent,w,h,x,y),
inputLine(_input), enterExecutes(_enterExecutes), historyId(_historyId) {
const char *s;
for (int i = 1; (s = history.get(historyId,i, NULL)); i++)
prepend_string(s);
}
virtual void idle() {
doSelect(getSelection());
force_update();
}
virtual void doSelect(int no) {
time_t t;
char buf[64];
assert(history.get(historyId, getCount() - no, &t));
strftime(buf, sizeof(buf), "%H:%M:%S", localtime(&t));
const char *unit = "second";
int n = current_time - t;
if (n > 120) {
n /= 60;
unit = "minute";
if (n > 120) {
n /= 60;
unit = "hour";
if (n > 48) {
n /= 24;
unit = "day";
}
}
}
set_bottom_message(Sprintf("Executed on: %s (%d %s%s ago)", buf, n, unit, n == 1 ? "" : "s"));
}
virtual void doChoose(int no, int key) {
const char *s = history.get(historyId, getCount() - no,NULL);
assert(s != NULL);
inputLine.set(s);
if (enterExecutes && key == keyEnter)
inputLine.keypress(keyEnter);
die();
}
private:
InputLine& inputLine; // Input line to do the changes on
bool enterExecutes; // Enter sends \r to the input line too
history_id historyId; // History to get the data from
};
const char *szDefaultPrompt = "mcl>";
InputLine::InputLine(Window *_parent, int _w, int _h, Style _style, int _x, int _y, history_id _id)
: Window(_parent, _w, _h, _style, _x, _y),
cursor_pos(0), max_pos(0), left_pos(0), ready(false), id(_id), history_pos(0)
{
set_default_prompt();
}
void InputLine::set_default_prompt() {
strcpy(prompt_buf, szDefaultPrompt);
adjust();
dirty = true;
}
void InputLine::set(const char *s) {
strcpy (input_buf, s);
max_pos = strlen(input_buf);
cursor_pos = max_pos;
left_pos = 0;
adjust();
dirty = true;
}
void MainInputLine::set (const char *s) {
InputLine::set(s);
if (*s == NUL) { // clear, go back to standard size
move(0, parent->height-1);
resize(width, 1);
output->move(0,0);
}
}
// Handle a keypress
bool InputLine::keypress(int key) {
if (ready)
return true;
embed_interp->set("Key", key);
dirty = true; // let's just assume this to make things easier
int prev_len = max_pos;
if (embed_interp->run_quietly("keypress", input_buf, input_buf)) {
// This is tough - what do we adjust here
int new_len = strlen(input_buf);
max_pos += (new_len - prev_len);
cursor_pos += (new_len - prev_len);
cursor_pos = max(cursor_pos, 0);
// set Key to 0 if keypress handled. Ugh
if ((key = embed_interp->get_int("Key")) == 0)
return true;
}
if (key == key_ctrl_h || key == key_backspace) {
if (max_pos == 0 || cursor_pos == 0)
; //status->setf ("Nothing to delete");
else if (cursor_pos == max_pos) {
max_pos--;
cursor_pos--;
}
else { // we are in the middle of the input line
memmove(input_buf + cursor_pos - 1, input_buf + cursor_pos, max_pos - cursor_pos);
cursor_pos--;
max_pos--;
}
left_pos = max(0,left_pos-1);
}
else if (key == key_ctrl_a) {
cursor_pos = left_pos = 0;
}
else if (key == key_ctrl_c) { // save line to history but don't execute
if (strlen(input_buf) > 0) {
history.add (id, input_buf);
set("");
status->setf("Line added to history but not sent");
}
}
else if (key == key_ctrl_j || key == key_ctrl_k) { // delete until EOL
max_pos = cursor_pos;
}
else if (key == key_escape) {
set("");
}
else if (key == key_ctrl_e) { // go to eol
cursor_pos = max_pos;
adjust();
}
else if (key == key_ctrl_u) {
memmove(input_buf, input_buf+cursor_pos, max_pos - cursor_pos);
max_pos -= cursor_pos;
cursor_pos = 0;
adjust();
}
else if (key == key_ctrl_w) { // Delete word
// How long is the word?
int bow = cursor_pos - 1;
while (bow > 0 && isspace(input_buf[bow]))
bow--;
while (bow > 0 && !isspace(input_buf[bow]))
bow--;
if (bow > 0)
bow++; // Don't eat the space
if (bow >= 0 ) {
memmove(input_buf+bow, input_buf+cursor_pos, max_pos - cursor_pos);
max_pos -= cursor_pos - bow;
cursor_pos = bow;
adjust();
}
}
else if (key == key_delete) { // delete to the right
if (cursor_pos == max_pos)
status->setf ("Nothing to the right of here");
else {
memmove(input_buf+cursor_pos, input_buf + cursor_pos + 1, max_pos - cursor_pos);
max_pos--;
}
}
else if (key == keyEnter || key == key_kp_enter) { // return. finish this line
ready = true;
input_buf[max_pos] = NUL;
if ((int)strlen(input_buf) >= config->getOption(opt_histwordsize))
history.add (id, input_buf);
history_pos = 0; // Reset history cycling
cursor_pos = 0;
max_pos = left_pos = 0;
ready = false;
move(0, parent->height-1);
output->move(0,0);
resize(width, 1);
execute();
}
else if (key >= ' ' && key < 256) { // Normal key. Just insert
if (max_pos < MAX_INPUT_BUF-1) {
if (cursor_pos == max_pos) { // We are already at EOL
input_buf[max_pos++] = key;
cursor_pos++;
} else { // We are inserting somewhere in the middle
memmove(input_buf + cursor_pos +1, input_buf + cursor_pos, max_pos - cursor_pos);
max_pos++;
input_buf[cursor_pos++] = key;
}
adjust();
}
else
status->setf ("The input buffer is full");
}
else if (key == key_arrow_left) {
if (cursor_pos == 0)
status->setf ("Already at the far left of the input line.");
else
{
cursor_pos--;
left_pos = max(0,left_pos-1);
}
}
else if (key == key_arrow_right) {
if (cursor_pos == max_pos)
status->setf ("Already at the end of the input line.");
else
{
cursor_pos++;
if (cursor_pos > 7*width/8) // scroll only when we are approaching right margin
adjust();
}
}
else if (key == key_arrow_up) { // recall
int lines;
if (id == hi_none)
status->setf ("No history available");
else if (id != hi_generic && (lines = config->getOption(opt_historywindow)))
{
lines = min (parent->height-4, lines);
if (!history.get(id,1, NULL))
status->setf ("There are no previous commands");
else
{
if (lines > 3)
(void)new InputHistorySelection(parent, width, lines, 0, -(lines+2), *this, true, id);
// Window is to small; we need to cycle history in the input box
else {
(void)new MessageBox(screen, "Sorry, no history available", 0);
}
}
}
else {
const char *s;
if (!(s = history.get(id, history_pos+1, NULL)))
status->setf ("No previous history");
else {
set(s);
history_pos++;
}
}
}
else if (key == key_arrow_down) {
const char *s;
if (id == hi_none)
status->setf("No history available");
else if (history_pos <= 1 || !(s = history.get(id,history_pos-1, NULL)))
{
status->setf ("No next history");
history_pos = 0;
set("");
}
else
{
set(s);
history_pos--;
}
}
else
return false;
input_buf[max_pos] = NUL;
return true;
}
void InputLine::redraw() {
int prompt_len = strlen(prompt_buf);
gotoxy(0,0);
set_color(config->getOption(opt_inputcolor));
input_buf[max_pos] = NUL;
if (config->getOption(opt_multiinput) && isExpandable()) {
printf("%s%s%*s", prompt_buf, input_buf, (height*width)-prompt_len-max_pos, "");
if (is_focused())
set_cursor((cursor_pos+prompt_len)%width, (cursor_pos+prompt_len)/width);
} else {
printf("%s%s%-*.*s", prompt_buf, left_pos ? "<" : "",
width-1-prompt_len + (left_pos ? 0 : 1),
width-1-prompt_len + (left_pos ? 0 : 1),
input_buf+left_pos);
if (is_focused())
set_cursor(cursor_pos+prompt_len-left_pos + (left_pos ? 1 : 0) ,0);
}
dirty = false;
}
// If an input line is ready, move it over to buf
bool InputLine::getline(char *buf, bool fForce)
{
if (!ready && !fForce)
return false;
else
{
ready = false;
if (fForce)
input_buf[max_pos] = NUL;
strcpy (buf, input_buf);
max_pos = left_pos = 0;
return true;
}
}
void InputLine::adjust() {
if (config->getOption(opt_multiinput) && isExpandable()) {
while ( ((int)strlen(prompt_buf) + max_pos)/width >= height) {
move(parent_x, parent_y - 1);
resize(width, height+1);
output->move(0, 1-height);
}
}
else
while (1 + (int) strlen (prompt_buf) + cursor_pos - left_pos >= width)
left_pos++;
}
void InputLine::set_prompt (const char *s) {
const char *in;
char *out;
for (in = s, out = prompt_buf; *in && out-prompt_buf < MAX_PROMPT_BUF-1; in++)
if (*in == (signed char) SET_COLOR)
in++;
else if (*in == '\n' || *in == '\r')
*out++ = ' ';
else
*out++ = *in;
*out++ = NUL;
dirty = true;
}
MainInputLine::MainInputLine()
:InputLine(screen, wh_full, 1, None, 0, -1, hi_main_input) {
parent->focus(this);
}
void MainInputLine::execute() {
embed_interp->run_quietly("sys/userinput", input_buf, input_buf);
if (config->getOption(opt_expand_semicolon))
interpreter.add(input_buf, EXPAND_INPUT|EXPAND_SEMICOLON);
else
interpreter.add(input_buf, EXPAND_INPUT);
if (config->getOption (opt_echoinput)) // echo input if wanted
output->printf ("%c>> %s\n", SOFT_CR, input_buf);
}
| true |
b2acc7bc9e256f34cafa4d54a356ff10391c2724 | C++ | rbdannenberg/o2 | /src/sharedmem.cpp | UTF-8 | 23,771 | 2.5625 | 3 | [
"MIT"
] | permissive | // sharedmem.cpp -- a brige to shared memory O2 service
//
// Roger B. Dannenberg
// August 2020
/*
Supports multiple connections to shared memory processes.
All shared memory processes use the same heap, and O2_MALLOC
is lock-free and thread-safe.
Therefore, O2message types can be transferred directly to
shared memory queues without byte-swapping, copying, or
changing format.
The implementation is based on o2lite. Instead of O2lite_info
containing a Fds_info pointer (for the TCP connection) and the
udp_address, the O2sm_info contains an outgoing message queue.
Services provided by a shared memory process appear locally in the
services array entry as an O2sm_info, where messages can be directly
enqueued, making delivery quite fast and simple.
Received messages are all enqueued on a global o2sm_incoming queue,
which is checked by o2sm_poll. If messages are found, the entire queue
is atomically copied to a delivery queue, reversed, and then messages
are delivered to O2 in the correct order. Thus, O2sm_info do not
receive or deliver incoming messages to O2 -- it's handled by the
O2sm_protocol object.
Clock local time can be used from shared memory processes except
during a narrow window during o2_clock_set(), but this should
only be called when the main process is initializing and selecting
a clock source (if any), and only if a non-default clock is set.
If a non-default callback is provided, it must be reentrant for
shared memory processes.
o2_time_get() is more of a problem: If a shared memory process calls
o2_time_get() while clock synchronization is updating local_time_base
global_time_base, and clock_rate, an inconsistent time could be
computed. I'm not very positive on memory barriers because of
portability, cost, and the difficulty to get them right. Another
solution is we can store the offset from local to global time in a
single atomic long or long long, and check for ATOMIC_LONG_LOCK_FREE
or ATOMIC_LLONG_LOCK_FREE to make sure simple reads and writes are
atomic. This will not compute exactly the right clock value when
clock_rate is not 1, but since it is close to 1 and if the offset
is updated at o2_poll() rate, the error will be tiny. In fact, we
could dispense with computing time completely and just use
global values o2_local_now and o2_global_now, but since o2_poll()
may not be called as frequently as needed, it's better to recompute
as needed in each shared memory process.
Timing in shared memory process is simpler and more limited than in
O2. Incoming messages with timestamps must arrive in time order. A
timestamp out of order will be considered to be at the time just after
the previous timestamped message. Messages without timestamps,
however, are considered to be in a separate stream and their
processing is not delayed by timestamped messages.
The algorithm for message processing is:
First, move the entire incoming list atomically to a local list.
Run through the list, reversing the pointers (because the list is
LIFO). Then traverse the list in the new order (the actual message
arrival order), appending each message to either the timestamped
queue or the immediate queue. These lists can have head and tail
pointers to become efficient FIFO queues because there is no
concurrent access.
Next, deliver all messages in the timestamped queue that are ready.
These get priority because, presumably, the timestamps are there
to optimize timing accuracy. Next deliver all non-timestamped
messages. An option, if message delivery is expected to be time
consuming, is to check the timestamped queue after each immediate
message in case enough time has elapsed for the next timestamped
message to become ready.
After deliverying all immediate messages, return from o2sm_poll().
MEMORY, INITIALIZATION, FINALIZATION
We will call the main O2 thread just that. The shared memory process
will be called the O2SM thread in this section. The steps below are
marked with either "(O2 thread)" or "(O2SM thread)" to indicate which
thread should run the operation.
Ownership: Every shared memory process has an O2_context and an
O2sm_info. The O2sm_info is owned by the O2 thread because the
O2 thread manages all bridges and when bridges or protocols shut
down, the O2 thread deletes bridge protocols and bridge instances.
The O2_context is owned by the O2SM thread and is often in static
memory. The O2_context has a pointer to the O2sm_info instance
where messages are queued from O2 to O2SM.
Shutting down the O2SM thread should be initiated by the O2SM thread
by calling o2sm_finish(), which finishes the O2SM context and sends
an /_o2/o2sm/fin message to O2. The application should shut down
O2SM threads before calling o2_finish(). Otherwise, there will be
contexts owned by O2SM threads with references to O2sm_info
instances. If the O2 thread deletes them, it leaves dangling
pointers that could crash O2SM threads. If O2 thread leaves them,
then memory is leaked and the O2SM thread will crash anyway because
o2_finish will free the O2 heap.
There is a synchronization issue: When the O2 thread wants to finish
or exit, how does it know when all O2SM threads have finished? The
application is responsible for shutting down O2SM threads *before*
calling o2_finish. Normally, this should be done by sending messages.
There is no standard message or built-in mechanism for this, since
creating and exiting threads is not an O2 operation. After all
O2SM threads call o2sm_finish() and their fin messages are handled,
there will be no more O2sm_info instances, so the O2 thread should
wait for that. While waiting, the O2 thread must call o2_poll() to
receive and handle fin messages. To check for instances, use
o2_shmem_inst_count().
o2_shmem_initialize() - Initially, an array of O2sm_info* is
created, a new bridge protocol for "o2sm" is created, and a
handler is created for /_o2/o2sm/sv and /_o2/o2sm/fin. (O2 thread)
o2_shmem_inst_new() - creates a new O2sm_info. The O2sm_info must be
passed to the O2SM thread. It is also stored in the o2sm_bridges
array. (O2 thread)
o2_shmem_inst_count() - returns the number of shared memory instances.
o2sm_initialize() - installs an O2_context for the O2SM thread and
retains the Bridge_info* which contains a message queue for
messages from O2SM to O2*. The O2_context contains mappings from
addresses to handlers in path_tree and full_path_table. (O2SM
thread)
o2sm_get_id() - returns a unique ID for this bridged process. This
might be useful if you want to create a unique service that does
not conflict with any host services or services by other shared
memory or other bridged processes using other protocols,
e.g. o2lite. Note that *all* bridged processes and their host
share must have non-conflicting service names. While other full O2
processes can offer duplicated service names (and messages are
directed to the service provider with the highest pip:iip:port
name), duplicates are not allowed between hosts and their bridged
processes. (O2SM thread)
o2sm_service_new() - creates handlers on the O2 side via /_o2/o2sm/sv
messages. (O2SM thread)
o2sm_method_new() - inserts handlers into the O2_context mappings.
(O2SM thread)
o2sm_finish() - To shut down cleanly, first the O2SM thread should
stop calling o2sm_poll() and call o2sm_finish(), which frees the
O2SM O2_context structures (but not the O2sm_info), and calls
/_o2/o2sm/fin with the id as parameter. (O2SM thread)
o2_shmem_finish() - shuts down the entire "o2sm" protocol. First,
o2sm_bridges is searched and any instance there is deleted by
calling o2_shmem_inst_finish(). Then o2sm_bridges is freed.
Typical shared memory process organization is as follows:
#include "o2internal.h" // O2_context is not defined in o2.h, so use this
#include "sharedmem.h"
Bridge_info *smbridge = NULL; // global variable accessed by both threads
int main()
{
...
// create the shared memory process bridge (execute this in O2 thread):
int err = o2_shmem_initialize(); assert(err == O2_SUCCESS);
smbridge = o2_shmem_inst_new();
// create shared memory thread
err = pthread_create(&pt_thread_pid, NULL, &shared_memory_thread, NULL);
... run concurrently with the shared memory thread ...
... after shared memory thread shuts down, consider calling o2_poll()
... in case any "last dying words" were posted as incoming messages
o2_finish(); // closes the bridge and frees all memory, including
// chunks allocated by shared_memory_thread
}
#include "sharedmemclient.h"
void *shared_memory_thread(void *ignore) // the thread entry point
{
O2_context ctx;
o2sm_initialize(&ctx, smbridge); // connects us to bridge
... run the thread ...
o2sm_finish();
return NULL;
}
*/
#ifndef O2_NO_SHAREDMEM
#include "o2internal.h"
#include "o2atomic.h"
#include "services.h"
#include "message.h"
#include "msgsend.h"
#include "pathtree.h"
#include "o2mem.h"
#include "sharedmem.h"
O2queue o2sm_incoming;
Bridge_protocol *o2sm_protocol = NULL;
// Call to establish a connection from a shared memory process to
// O2. This runs in the O2 thread.
//
O2sm_info *o2_shmem_inst_new()
{
assert(o2sm_protocol); // did you remember to call o2_shmem_initialize()?
return new O2sm_info();
}
int o2_shmem_inst_count()
{
return o2sm_protocol ? o2sm_protocol->instances.size() : 0;
}
// retrieve all messages from head atomically. Then reverse the list.
//
O2message_ptr get_messages_reversed(O2queue *head)
{
// store a zero if nothing has changed
O2message_ptr all = (O2message_ptr) head->grab();
O2message_ptr msgs = NULL;
O2message_ptr next = NULL;
while (all) {
next = all->next;
all->next = msgs;
msgs = all;
all = next;
}
return msgs;
}
// Handler for !_o2/o2sm/sv message. This is to create/modify a
// service/tapper for o2sm client. Parameters are: ID, service-name,
// exists-flag, service-flag, and tapper-or-properties string.
// This is almost identical to o2lite_sv_handler.
//
static void o2sm_sv_handler(O2msg_data_ptr msgdata, const char *types,
O2arg_ptr *argv, int argc, const void *user_data)
{
O2err rslt = O2_SUCCESS;
O2_DBd(o2_dbg_msg("o2sm_sv_handler gets", NULL, msgdata, NULL, NULL));
// get the arguments: shared mem bridge id, service name,
// add-or-remove flag, is-service-or-tap flag, property string
// assumes o2sm is initialized, but it must be
// because the handler is installed
int id = argv[0]->i;
const char *serv = argv[1]->s;
bool add = argv[2]->i;
bool is_service = argv[3]->i;
const char *prtp = argv[4]->s;
O2tap_send_mode send_mode = (O2tap_send_mode) (argv[5]->i32);
o2_message_source = o2sm_protocol->find(id);
if (!o2_message_source) {
o2_drop_msg_data("o2sm_sv_handler could not locate O2sm_info", msgdata);
return;
}
if (add) { // add a new service or tap
if (is_service) {
rslt = Services_entry::service_provider_new(
serv, prtp, o2_message_source, o2_ctx->proc);
} else { // add tap
rslt = o2_tap_new(serv, o2_ctx->proc, prtp, send_mode);
}
} else {
if (is_service) { // remove a service
rslt = Services_entry::proc_service_remove(
serv, o2_ctx->proc, NULL, -1);
} else { // remove a tap
rslt = o2_tap_remove(serv, o2_ctx->proc, prtp);
}
}
if (rslt) {
char errmsg[100];
snprintf(errmsg, 100, "o2sm/sv handler got %s for service %s",
o2_error_to_string(rslt), serv);
o2_drop_msg_data(errmsg, msgdata);
}
return;
}
// Handler for "/_o2/o2sm/fin" message
static void o2sm_fin_handler(O2msg_data_ptr msgdata, const char *types,
O2arg_ptr *argv, int argc, const void *user_data)
{
O2_DBb(o2_dbg_msg("o2sm_fin_handler gets", NULL, msgdata, NULL, NULL));
O2sm_info *info = (O2sm_info *) o2sm_protocol->find(argv[0]->i);
if (info) {
info->o2_delete();
}
return;
}
O2err o2_shmem_initialize()
{
if (!o2_ensemble_name) {
return O2_NOT_INITIALIZED;
}
if (o2sm_protocol) return O2_ALREADY_RUNNING; // already initialized
o2sm_protocol = new O2sm_protocol();
o2_method_new_internal("/_o2/o2sm/sv", "isiisi", &o2sm_sv_handler,
NULL, false, true);
o2_method_new_internal("/_o2/o2sm/fin", "i", &o2sm_fin_handler,
NULL, false, true);
return O2_SUCCESS;
}
/************* functions to be called from shared memory thread ************/
#include "sharedmemclient.h"
O2time o2sm_time_get()
{
return (o2_clock_is_synchronized ?
o2_local_time() + o2_global_offset : -1);
}
O2err o2sm_service_new(const char *service, const char *properties)
{
if (!properties) {
properties = "";
} else assert(properties[0] == ';');
return o2sm_send_cmd("!_o2/o2sm/sv", 0.0, "isiisi", o2_ctx->binst->id,
service, true, true, properties, 0);
}
O2err o2sm_method_new(const char *path, const char *typespec,
O2method_handler h, void *user_data,
bool coerce, bool parse)
{
// o2_heapify result is declared as const, but if we don't share it, there's
// no reason we can't write into it, so this is a safe cast to (char *):
char *key = (char *) o2_heapify(path);
*key = '/'; // force key's first character to be '/', not '!'
// add path elements as tree nodes -- to get the keys, replace each
// "/" with EOS and o2_heapify to copy it, then restore the "/"
O2err ret = O2_NO_SERVICE;
#ifdef O2SM_PATTERNS
Handler_entry *full_path_handler;
char *remaining = key + 1;
char name[NAME_BUF_LEN];
char *slash = strchr(remaining, '/');
if (slash) *slash = 0;
Services_entry **services = Services_entry::find(remaining);
// but with a shared memory thread, we don't support multiple service
// providers, so services is either NULL, a Handler_entry, or a Hash_node
O2node *node = (O2node *) *services;
// note that slash has not been restored (see o2_service_replace below)
// services now is the existing services_entry node if it exists.
// slash points to end of the service name in the path.
if (!node) goto free_key_return; // cleanup and return
#endif
O2string types_copy = NULL;
int types_len = 0;
if (typespec) {
types_copy = o2_heapify(typespec);
if (!types_copy) goto free_key_return;
// coerce to int to avoid compiler warning -- this could overflow but
// only in cases where it would be impossible to construct a message
types_len = (int) strlen(typespec);
}
Handler_entry *handler;
handler = new Handler_entry(NULL, h, user_data, key, types_copy,
types_len, coerce, parse);
// key gets set below with the final node of the address
#ifdef O2SM_PATTERNS
// case 1: method is global handler for entire service replacing a
// Hash_node with specific handlers: remove the Hash_node
// and insert a new O2TAG_HANDLER as local service.
// case 2: method is a global handler, replacing an existing global handler:
// same as case 1 so we can use o2_service_replace to clean up the
// old handler rather than duplicate that code.
// case 3: method is a specific handler and a global handler exists:
// replace the global handler with a Hash_node and continue to
// case 4
// case 4: method is a specific handler and a Hash_node exists as the
// local service: build the path in the tree according to the
// the remaining address string
// support pattern matching by adding this path to the path tree
while ((slash = strchr(remaining, '/'))) {
*slash = 0; // terminate the string at the "/"
o2_string_pad(name, remaining);
*slash = '/'; // restore the string
remaining = slash + 1;
// if necessary, allocate a new entry for name
hnode = hnode.tree_insert_node(name);
assert(hnode);
o2_mem_check(hnode);
// node is now the node for the path up to name
}
// node is now where we should put the final path name with the handler;
// remaining points to the final segment of the path
handler->key = o2_heapify(remaining);
if ((ret = o2_node_add(hnode->insert(handler))) {
goto error_return_3;
}
// make an entry for the full path table
full_path_handler = O2_MALLOCT(handler_entry);
memcpy(full_path_handler, handler, sizeof *handler); // copy info
if (types_copy) types_copy = o2_heapify(typespec);
full_path_handler->type_string = types_copy;
handler = full_path_handler;
#else // if O2_NO_PATTERNS:
handler->key = handler->full_path;
handler->full_path = NULL;
#endif
// put the entry in the full path table
return o2_ctx->full_path_table.insert(handler);
#ifdef O2SM_PATTERNS
error_return_3:
if (types_copy) O2_FREE((void *) types_copy);
#endif
O2_FREE(handler);
free_key_return: // not necessarily an error (case 1 & 2)
O2_FREE(key);
return ret;
}
static void append_to_schedule(O2message_ptr msg)
{
msg->next = NULL;
if (o2_ctx->schedule_head == NULL) {
o2_ctx->schedule_head = o2_ctx->schedule_tail = msg;
} else {
o2_ctx->schedule_tail->next = msg;
o2_ctx->schedule_tail = msg;
}
}
O2err o2sm_message_send(O2message_ptr msg)
{
o2sm_incoming.push((O2list_elem *) msg);
return O2_SUCCESS;
}
O2err o2sm_send_finish(O2time time, const char *address, bool tcp_flag)
{
O2message_ptr msg = o2_message_finish(time, address, tcp_flag);
if (!msg) return O2_FAIL;
return o2sm_message_send(msg);
}
O2err o2sm_send_marker(const char *path, double time, bool tcp_flag,
const char *typestring, ...)
{
va_list ap;
va_start(ap, typestring);
O2message_ptr msg;
O2err rslt = o2_message_build(&msg, time, NULL, path,
typestring, tcp_flag, ap);
if (rslt != O2_SUCCESS) {
return rslt; // could not allocate a message!
}
return o2sm_message_send(msg);
}
int o2sm_dispatch(O2message_ptr msg)
{
bool delivered = false;
// printf("o2sm_dispatch %s\n", msg->data.address);
assert(msg->data.address[0] == '/' || msg->data.address[0] == '!');
#ifdef O2SM_PATTERNS
O2node *service = o2_msg_service(&msg->data, &services);
if (service) {
#endif
char *address = msg->data.address;
// STEP 2: Isolate the type string, which is after the address
const char *types = o2_msg_types(msg);
#ifdef O2SM_PATTERNS
// STEP 3: If service is a Handler, call the handler directly
if (ISA_HANDLER(service)) {
o2_call_handler((handler_entry_ptr) service, &msg->data, types);
delivered = true;
// STEP 4: If path begins with '!', or O2_NO_PATTERNS, full path lookup
} else if (ISA_HASH(service) && (address[0] == '!')) {
#endif
O2node *handler;
address[0] = '/'; // must start with '/' to get consistent hash
handler = *o2_ctx->full_path_table.lookup(address);
if (handler && ISA_HANDLER(handler)) {
TO_HANDLER_ENTRY(handler)->invoke(&msg->data, types);
delivered = true;
}
#ifdef O2SM_PATTERNS
}
// STEP 5: Use path tree to find handler
else if (ISA_HASH(service)) {
char name[NAME_BUF_LEN];
address = strchr(address + 1, '/'); // search for end of srvc name
if (address) {
delivered = o2_find_handlers_rec(address + 1, name,
(o2_node_ptr) service, &msg->data, types);
}
}
}
#endif
if (!delivered) {
o2_drop_msg_data("no handler was found", &msg->data);
}
O2_FREE(msg);
return O2_SUCCESS;
}
// This polling routine drives communication and is called from the
// shared memory process thread
void o2sm_poll()
{
O2sm_info *o2sm = (O2sm_info *) (o2_ctx->binst);
o2sm->poll_outgoing();
}
// Here, the o2sm thread polls for messages coming from the O2 process
void O2sm_info::poll_outgoing()
{
O2time now = o2sm_time_get();
O2message_ptr msgs = get_messages_reversed(&outgoing);
O2message_ptr next;
// sort msgs into immediate and schedule
O2message_ptr *prevptr = &msgs;
while (*prevptr) {
// printf("poll_outgoing msg %p\n", *prevptr);
if ((*prevptr)->data.timestamp != 0) {
next = (*prevptr)->next;
append_to_schedule(*prevptr);
*prevptr = next;
} else {
prevptr = &(*prevptr)->next;
}
}
// msgs is left with zero timestamp messages
O2message_ptr head = o2_ctx->schedule_head;
if (now < 0) { // no clock! free the messages
while (head) {
O2_DBB(o2_dbg_msg("Incoming to shmem thread dropped for no clock",
head, &head->data, NULL, NULL));
next = head->next;
O2_FREE(head);
head = next;
}
} else { // send timestamped messages that are ready to go
while (head && head->data.timestamp < now) {
O2_DBB(o2_dbg_msg("Incoming to shmem thread ready now",
head, &head->data, NULL, NULL));
next = head->next;
o2sm_dispatch(head);
head = next;
}
}
o2_ctx->schedule_head = head;
while (msgs) { // send all zero-timestamp messages
O2_DBB(o2_dbg_msg("Incoming to shmem thread zero timestamp",
msgs, &msgs->data, NULL, NULL));
next = msgs->next;
o2sm_dispatch(msgs);
msgs = next;
}
}
void o2sm_initialize(O2_context *ctx, Bridge_info *inst)
{
O2_DBb(printf("%s o2sm_initialize ctx %p Bridge_info %p\n",
o2_debug_prefix, ctx, inst));
o2_ctx = ctx;
// local memory allocation will use malloc() to get a chunk on the
// first call to O2_MALLOC by the shared memory thread. If
// o2_memory() was called with mallocp = false, the thread
// will fail to allocate any memory.
// Therefore, if mallocp is false, you should:
// o2_ctx->chunk = <chunk of memory for o2sm allocations when
// freelists do not have suitable free objects>
// o2_ctx->remaining = <size of o2_ctx->chunk>
// The chunk will not be freed by O2 and should either be static or it
// should not be freed until O2 finishes. (Note that the lifetime of this
// chunk is longer than the lifetime of the shared memory thread because
// memory gets passed around as messages.)
o2_ctx->proc = NULL;
o2_ctx->binst = inst;
o2_ctx->schedule_head = NULL;
o2_ctx->schedule_tail = NULL;
}
void o2sm_finish()
{
assert(o2_ctx);
assert(o2_ctx->binst);
// make message before we free the message construction area
o2_send_start();
o2_add_int32(o2_ctx->binst->id);
O2message_ptr msg = o2_message_finish(0.0, "/_o2/o2sm/fin", true);
// free the o2_ctx data
O2_DBb(printf("%s o2sm_finish finishing O2_context@%p\n",
o2_debug_prefix, o2_ctx));
o2_ctx->finish();
o2_ctx = NULL;
// notify O2 to remove bridge: does not require o2_ctx
o2sm_message_send(msg);
}
#endif
| true |
dfabb22bcde060f619b0c129adb5c3f9b572d877 | C++ | yingfeng/integer_encoding_library_sparklezzz | /include/Simple16_x64.hpp | UTF-8 | 5,282 | 2.59375 | 3 | [] | no_license | #ifndef SIMPLE16_X64_HPP_
#define SIMPLE16_X64_HPP_
#include "Compressor.hpp"
#include <stdint.h>
namespace paradise {
namespace index {
class Simple16_x64: public Compressor {
public:
Simple16_x64() {
}
virtual ~Simple16_x64() {
}
public:
virtual int
encodeUint32(char* des, const uint32_t* src, uint32_t encodeNum);
virtual int
decodeUint32(uint32_t* des, const char* src, uint32_t decodeNum);
virtual int
encodeUint16(char* des, const uint16_t* src, uint32_t encodeNum);
virtual int
decodeUint16(uint16_t* des, const char* src, uint32_t decodeNum);
virtual int encodeUint8(char* des, const uint8_t* src, uint32_t encodeNum);
virtual int decodeUint8(uint8_t* des, const char* src, uint32_t decodeNum);
template<typename T>
static int encode(char* des, const T* src, uint32_t length);
template<typename T>
static int decode(T* des, const char* src, int length);
template<typename T>
static int s16_encode(uint64_t* des, const T* src, int left);
template<typename T>
static int s16_decode(T* des, uint64_t src);
virtual std::string getCompressorName() {
return "simple16_x64";
}
virtual Compressor* clone();
private:
static uint8_t bitSizeArr[16][60];
static uint8_t codeNum[16];
};
template<typename T>
int Simple16_x64::encode(char* des, const T* src, uint32_t encodeNum) {
uint64_t* desInt = (uint64_t *) des;
int left = encodeNum;
int ret;
while (left > 0) {
ret = s16_encode(desInt, src, left);
src += ret;
left -= ret;
desInt++;
}
return (char*) desInt - des;
}
template<typename T>
int Simple16_x64::decode(T* des, const char* src, int decodeNum) {
int num;
uint64_t* input = (uint64_t*) src;
int left = decodeNum;
while (left > 0) {
num = s16_decode(des, *input);
input++;
left -= num;
des += num;
}
return (char*) input - src;
}
template<typename T>
int Simple16_x64::s16_encode(uint64_t* des, const T* src, int left) {
uint32_t pos, num2code, shift;
uint64_t maskVal = 1, tmpVal;
for (uint64_t bitNum = 0; bitNum < 16; bitNum++) {
(*des) = bitNum << 60;
if (left < codeNum[bitNum]) {
continue;
}
num2code = codeNum[bitNum];
for (pos = 0, shift = 0; (pos < num2code) && ((tmpVal = *(src + pos))
< (maskVal << bitSizeArr[bitNum][pos]));) {
(*des) += (tmpVal << shift);
shift += bitSizeArr[bitNum][pos];
pos++;
}
if (pos == num2code) {
(src) += num2code;
break;
}
}
return num2code;
}
template<typename T>
int Simple16_x64::s16_decode(T* des, uint64_t src) {
/*
uint8_t num = (src) >> 60;
int enNum = codeNum[num];
uint8_t * decodeArr = bitSizeArr[num];
uint8_t bitPos = 0;
for (int i = 0; i < enNum; i++) {
*des = (src >> bitPos) & ((1U << decodeArr[i]) - 1);
++des;
bitPos += decodeArr[i];
}
return enNum;
*/
uint8_t num = (src) >> 60;
switch (num) {
case 0: {
for (int i = 0; i < 60; ++i) {
*des = (src >> i) & 1;
++des;
}
break;
}
case 1: {
for (int i = 0; i < 60;) {
*des = (src >> i) & 1;
++des;
++i;
*des = (src >> i) & 3;
++des;
i = i + 2;
}
break;
}
case 2: {
for (int i = 0; i < 60; i = i + 2) {
*des = (src >> i) & 3;
++des;
}
break;
}
case 3: {
for (int i = 0; i < 60;) {
*des = (src >> i) & 3;
i = i + 2;
++des;
*des = (src >> i) & 7;
i = i + 3;
++des;
}
break;
}
case 4: {
for (int i = 0; i < 60; i = i + 3) {
*des = (src >> i) & 7;
++des;
}
break;
}
case 5: {
for (int i = 0; i < 60; i = i + 4) {
*des = (src >> i) & 15;
++des;
}
break;
}
case 6:
for (int i = 0; i < 60; i = i + 5) {
*des = (src >> i) & 31;
++des;
}
break;
case 7:
for (int i = 0; i < 60; i = i + 6) {
*des = (src >> i) & 63;
++des;
}
break;
case 8:
*des = (src) & 255;
++des;
*des = (src >> 8) & 127;
++des;
*des = (src >> 15) & 255;
++des;
*des = (src >> 23) & 127;
++des;
*des = (src >> 30) & 255;
++des;
*des = (src >> 38) & 127;
++des;
*des = (src >> 45) & 255;
++des;
*des = (src >> 53) & 127;
++des;
break;
case 9:
*des = (src) & 511;
des++;
*des = (src >> 9) & 255;
des++;
*des = (src >> 17) & 511;
des++;
*des = (src >> 26) & 255;
des++;
*des = (src >> 34) & 511;
des++;
*des = (src >> 43) & 255;
des++;
*des = (src >> 51) & 511;
des++;
break;
case 10:
*des = (src) & 1023;
des++;
*des = (src >> 10) & 1023;
des++;
*des = (src >> 20) & 1023;
des++;
*des = (src >> 30) & 1023;
des++;
*des = (src >> 40) & 1023;
des++;
*des = (src >> 50) & 1023;
des++;
break;
case 11:
*des = (src) & 4095;
des++;
*des = (src >> 12) & 4095;
des++;
*des = (src >> 24) & 4095;
des++;
*des = (src >> 36) & 4095;
des++;
*des = (src >> 48) & 4095;
des++;
break;
case 12:
*des = (src) & 32767;
++des;
*des = (src >> 15) & 32767;
++des;
*des = (src >> 30) & 32767;
++des;
*des = (src >> 45) & 32767;
++des;
break;
case 13:
*des = (src) & ((1 << 20) - 1);
++des;
*des = (src >> 20) & ((1 << 20) - 1);
++des;
*des = (src >> 40) & ((1 << 20) - 1);
++des;
break;
case 14:
*des = (src) & ((1 << 30) - 1);
++des;
*des = (src >> 30) & ((1 << 30) - 1);
++des;
break;
case 15:
*des = (src) & ((1LL << 60) - 1);
++des;
break;
}
return codeNum[num];
}
}
}
#endif /* SIMPLE16_X64_HPP_ */
| true |
360bf04ed38cfc294a4338a4ae893a723b467e50 | C++ | zhaoyiru/Stanford-CS106B-Assignments-and-Handouts | /Handout8/Handout8.1.a.cpp | UTF-8 | 567 | 3.078125 | 3 | [] | no_license |
void Buffer::moveToWordBegin() {
// if the character to the left of the cursor is a space
// move back until it no longer is to skip over any
// spaces that appear after the word
while (cursor - 1 >= 0 && isspace(text[cursor - 1])) {
moveCursorBackward();
}
// now move to the front of the word we are currently at -
// meaning the letter to the left of the cursor is a space or
// the cursor is at the beginning of the buffer
while (cursor - 1 >= 0 && !isspace(text[cursor - 1])) {
moveCursorBackward();
}
}
| true |
a71fc55274d7e95540eb6f20a04f02186a04dd44 | C++ | worldden/gkrellm | /main.cpp | UTF-8 | 1,846 | 2.59375 | 3 | [] | no_license | // ************************************************************************** //
// //
// ::: :::::::: //
// main.cpp :+: :+: :+: //
// +:+ +:+ +:+ //
// By: ddehtyar <ddehtyar@student.unit.ua> +#+ +:+ +#+ //
// +#+#+#+#+#+ +#+ //
// Created: 2018/10/13 13:04:12 by ddehtyar #+# #+# //
// Updated: 2018/10/13 13:04:13 by ddehtyar ### ########.fr //
// //
// ************************************************************************** //
#include <unistd.h>
#include <string.h>
#include <iostream>
#include "graphic.hpp"
#include "DateTime.hpp"
#include "Ncurses.hpp"
int main (int ac, char *av[]) {
std::string input;
if (ac != 2){
system("printf '\e[8;56;50t'");
std::cout << "Select display" << std::endl << "1: Graphic" << std::endl << "2: Terminal" << std::endl;
std::cin >> input;
}
if ((ac == 2 && !strcmp(av[1], "1")) || input == "1")
{
// std::cout << "Grafic" << std::endl;
Graphic graph;
try {
graph.start();
}
catch (...) {
}
}
else if ((ac == 2 && !strcmp(av[1], "2")) || input == "2")
{
// std::cout << "Ncerces" << std::endl;
// system("printf '\e[8;50;50t'");
Ncurses term;
try {
term.start();
}
catch (...){
}
}
else
std::cout << "ERROR: Please Select1 or 2." << std::endl;
return 0;
}
| true |
07c2b85960581fc3068e95925f7dd5db4f338ac3 | C++ | PanCheng111/leetcode | /2/test.cpp | UTF-8 | 1,456 | 3.421875 | 3 | [] | no_license | #include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode *head = NULL;
ListNode *tail = NULL;
int add = 0;
while (l1 != NULL || l2 != NULL) {
int tmp = add;
if (l1) tmp += l1->val;
if (l2) tmp += l2->val;
if (tmp >= 10) {
tmp -= 10;
add = 1;
}
else add = 0;
if (head == NULL) {
head = new ListNode(tmp);
tail = head;
}
else {
tail->next = new ListNode(tmp);
tail = tail->next;
}
if (l1) l1 = l1->next;
if (l2) l2 = l2->next;
}
if (add == 1) {
tail->next = new ListNode(add);
}
return head;
}
};
int main() {
ListNode *l1 = new ListNode(1);
l1->next = new ListNode(8);
//l1->next->next = new ListNode(3);
ListNode *l2 = new ListNode(0);
//l2->next = new ListNode(6);
//l2->next->next = new ListNode(4);
Solution s;
ListNode *ret = s.addTwoNumbers(l1, l2);
while (ret != NULL) {
printf("%d->", ret->val);
ret = ret->next;
}
printf("\n");
return 0;
} | true |
4d28455fbb0b0f63f2b5c4fed08f724cea0558ef | C++ | Mmchips/miniature-train | /School_Assignments/lab-env-master/projects/S0008E_Lab3-Skinning/code/Animation.cpp | UTF-8 | 3,688 | 2.515625 | 3 | [
"MIT"
] | permissive | //
// Created by ivoako-5 on 9/19/17.
//
#include <config.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <iostream>
#include "Animation.h"
#include <sys/time.h>
bool Animation::loadAnim(const char* fileName)
{
struct stat st;
stat(fileName, &st);
size_t size = st.st_size;
int fd = open(fileName, O_RDONLY);
void* ptr = mmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
void* start = ptr;
if (ptr != (void*)-1)
{
Nax3Header* naxHead = (Nax3Header*) ptr;
ptr += sizeof(Nax3Header);
if(naxHead->numClips > 0)
{
groupArrPtr = new Nax3Group[naxHead->numClips];
keyArrPtr = new Vector4D[naxHead->numKeys];
size_t numClips = (size_t) naxHead->numClips;
for (int clipIndex = 0; clipIndex < numClips; clipIndex++)
{
Nax3Clip *naxClip = (Nax3Clip *) ptr;
ptr += sizeof(Nax3Clip);
groupArrPtr[clipIndex].clip = *naxClip;
for (int eventIndex = 0; eventIndex < naxClip->numEvents; eventIndex++)
{
Nax3AnimEvent* naxEvent = (Nax3AnimEvent*)ptr;
ptr += sizeof(Nax3AnimEvent);
}
groupArrPtr[clipIndex].curveList = new Nax3Curve[naxClip->numCurves];
for (int curveIndex = 0; curveIndex < naxClip->numCurves; curveIndex++)
{
Nax3Curve* naxCurve = (Nax3Curve*)ptr;
ptr += sizeof(Nax3Curve);
groupArrPtr[clipIndex].curveList[curveIndex] = *naxCurve;
}
}
size_t numKeys = (size_t)naxHead->numKeys;
for (int keyIndex = 0; keyIndex < numKeys; keyIndex++)
{
Vector4D* key = (Vector4D*)ptr;
ptr += sizeof(Vector4D);
keyArrPtr[keyIndex] = *key;
}
}
munmap(start, size);
return true;
}
return false;
}
void Animation::updateAnimation(Skeleton *skel, int clipIndex, float dt)
{
Nax3Clip clip = groupArrPtr[clipIndex].clip;
time += dt;
if (time > clip.keyDuration) {
nextKeyFrame++;
time = 0;
//Change keyframe
}
if(nextKeyFrame >= clip.numKeys)
{
//if next keyframe would be out of range set keyFrameIndex to 0
nextKeyFrame = 0;
}
keyFrameIndex = nextKeyFrame > 0 ? nextKeyFrame -1 : clip.numKeys-1;
Vector4D curPosKey, curRotKey, nextPosKey, nextRotKey;
float frameDuration = time/clip.keyDuration;
for (int i=0; i<skel->joints.size(); i++)
{
int key = groupArrPtr[clipIndex].curveList[i*4].firstKeyIndex + keyFrameIndex * clip.keyStride;
int nextKey = groupArrPtr[clipIndex].curveList[i*4].firstKeyIndex + clip.keyStride*nextKeyFrame;
curPosKey = this->keyArrPtr[key];
curRotKey = this->keyArrPtr[key+1];
nextPosKey = this->keyArrPtr[nextKey];
nextRotKey = this->keyArrPtr[nextKey+1];
Vector4D curPos(curPosKey[0], curPosKey[1], curPosKey[2], 1);
Vector4D curRot(curRotKey[0], curRotKey[1], curRotKey[2], curRotKey[3]);
Vector4D nextPos(nextPosKey[0], nextPosKey[1], nextPosKey[2], 1);
Vector4D nextRot(nextRotKey[0], nextRotKey[1], nextRotKey[2], nextRotKey[3]);
Vector4D pos = Vector4D::lerp(curPos, nextPos, frameDuration);
Vector4D rot = Vector4D::slerp(curRot, nextRot, frameDuration);
Matrix4D rotMat;
rotMat = Matrix4D::QuatToMat(rot);
rotMat.transpose();
rotMat.setPosition(pos);
skel->tempJoints[i].transform = rotMat;
}
} | true |
ce06a3963f8b5439662e5e260a690b71a582f11d | C++ | lets-code-together/lets-code-together | /AlgorithmsBasic/3-DP1/11057_1.cpp | UHC | 598 | 3.34375 | 3 | [] | no_license | /* () N ־ ϴ α ۼ 0 ۰*/
#include<iostream>
using namespace std;
long long d[1001][10];
const long long mod = 10007;
int main()
{
for (int i = 1; i <= 1000; i++)
{
for (int j = 0; j <= 9; j++)
{
if (i == 1)
d[i][j] = 1;
else if(i > 1)
{
for (int k = 0; k <= j; k++)
{
d[i][j] += d[i - 1][k];
}
d[i][j] %= mod;
}
}
}
int n;
long long ans = 0;
cin >> n;
for (int j = 0; j <= 9; j++)
ans += d[n][j];
cout << ans % mod;
} | true |
b8457517bf3f9c5aa8eb4687e3f376bcbf374aa6 | C++ | neilsong/USACO | /Star League Gold/deskserving/Source.cpp | UTF-8 | 475 | 2.53125 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int main(void) {
int n;
cin >> n;
queue<int>line;
vector <vector <int>> desk(n);
char place;
cin >> place;
int x;
cin >> x;
line.push(x);
while (!line.empty()) {
char action;
int num;
cin >> action >> num;
if (action == 'C') {
line.push(num);
}
else {
desk[num-1].push_back(line.front());
line.pop();
}
}
for (auto i : desk) {
for (auto j : i) {
cout << j << " ";
}
cout << endl;
}
} | true |
8eabf69753b215ff3b6602ac03aa424f66aaede6 | C++ | dubshfjh/LeetCode | /164.cpp | UTF-8 | 2,955 | 3.390625 | 3 | [] | no_license | 桶排序,不管数据是否均匀分布,其时间复杂度和空间复杂度都是O(n),参见算法导论112-113
首先设定相同大小的n个桶[本题设定size个桶,每个桶的容量:bucketsize = 1 + max-min/(size-1)],将每个nums[i]放到所属的第nums[i]/bucketsize个桶中,再执行插入排序
#include <iostream>
#include <vector>
#include <list>
#include <iterator>
#include <algorithm>
#include <limits.h>
using namespace std;
class Solution {
public:
int maximumGap(vector<int>& nums) {
int size,bucketsize;
size = nums.size();
if(size < 2){
return 0;
}
//题意中只说了所有数都是非负数,但所有的数字都可能取同一个值,所以设定size个桶共同存储最多(max-min+1)个元素,当桶大小(max-min+1)/(size-1) 不为整数时,指定bucketsize += 1,e.g bucketsize=3.36时应制定它为4!!!而且(INT_MAX-0+1) = INT_MIN < 0,所以不妨设每个桶大小为(max-min)/(size-1),此时size个桶也足够存储所有元素了
int max_ele,min_ele;
max_ele = INT_MIN;
min_ele = INT_MAX;
for(int i=0;i<size;i++){
min_ele = min(nums[i],min_ele);
max_ele = max(nums[i],max_ele);
}
bucketsize = 1+(max_ele - min_ele)/(size-1);//每个桶的大小都相同,设定共有size个桶,nums[i]被分配到第0个..第size-1个桶中的一个
cout<<bucketsize<<",,,"<<min_ele<<",,,"<<max_ele<<",,,"<<size<<endl;
list<int> temp;
list<int>::iterator it;
vector<list<int>> buckets(size,temp);
for(int i=0;i<size;i++){//size个元素插入size个桶
int bucket_id = (nums[i] - min_ele)/bucketsize;
// cout<<bucket_id<<",,,";
if(buckets.size()==0){
buckets[bucket_id].push_back(nums[i]);
}
else{
it = buckets[bucket_id].begin();
while(it!=buckets[bucket_id].end() && (*it)<nums[i]){
it++;
}
buckets[bucket_id].insert(it,nums[i]);
}
}
int gap,pre;
gap = pre = INT_MIN;
for(int i=0;i<size;i++){//从前往后遍历size个桶,依次计算排好序的元素间gap
if(buckets[i].size()==0){
continue;
}
it = buckets[i].begin();
// cout<<pre<<",,,"<<*it<<endl;
if(pre == INT_MIN){
pre = *it;
it++;
}
while(it != buckets[i].end()){
gap = max(gap,*(it)-pre);
pre = *it;
it++;
}
}
return gap;
}
};
int main(){
int a[]={0,1,3,50,51,54,58,75,89,99};
vector<int> num(a,a+10);
Solution sol=Solution();
int res = sol.maximumGap(num);
cout<<res<<endl;
return 0;
}
| true |
bf2b2df3353967edc48ccae9bd5df6890d2cc003 | C++ | RokwonK/Problem_solving | /Baekjoon/1405_미친_로봇.cpp | UTF-8 | 1,422 | 3.015625 | 3 | [] | no_license | #include<iostream>
#include<vector>
#include<string.h>
using namespace std;
int N;
// 0 1 2 3
long double east, west, south, north;
long double percent;
int check[35][35];
vector<long double> route;
void backtracking(int x, int y, int direct) {
if (check[x][y] == 1)
return;
if (route.size() == N) {
long double part = 1;
for (int i = 0; i < N; i++)
part *= route[i];
percent += part;
return;
}
check[x][y] = 1;
for(int i = 0; i < 4; i++) {
if (i == direct)
continue;
if ( i == 0 ){
route.push_back(east);
backtracking(x,y+1, 1);
}
else if ( i == 1 ) {
route.push_back(west);
backtracking(x,y-1, 0);
}
else if ( i == 2 ) {
route.push_back(south);
backtracking(x+1,y, 3);
}
else {
route.push_back(north);
backtracking(x-1,y, 2);
}
route.pop_back();
}
check[x][y] = 0;
}
int main(void) {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.precision(14);
memset(check, 0, sizeof(check));
percent = 0.0;
cin >> N;
cin >> east >> west >> south >> north;
east /= 100;
west /= 100;
south /= 100;
north /= 100;
backtracking(15, 15, -1);
cout << percent << '\n';
return 0;
} | true |
0e15989aa024dfdb4dec096894d327445fa156ba | C++ | ZoeMilbauer/Flight-Simulator---Project1 | /Division.cpp | UTF-8 | 204 | 2.890625 | 3 | [] | no_license | #include "Division.h"
Division::Division(Expression* left, Expression* right) : BinaryExpression(left, right) {};
double Division::calculate() {
return (*left).calculate() / (*right).calculate();
}
| true |
689415583791d5739dd80e89d447c515d09cf233 | C++ | shenh10/leetcode | /bitManipulation/numberOf1Bits/source.cpp | UTF-8 | 1,524 | 3.546875 | 4 | [] | no_license | /*
Problem:
Given an integer, write a function to determine if it is a power of two.
Solution:
O(n) complexity:
*/
#include "iostream"
#include <vector>
#include <map>
#include <algorithm>
#include <cmath>
#include <limits>
using namespace std;
template <typename T>
void printVec(vector<T> vec){
cout<<"[";
for (int i = 0; i< vec.size(); i++){
cout<< vec[i]<<" ";
}
cout<<"]"<<endl;
}
template<typename T, int N> struct vector_wrapper {
vector_wrapper(T (&a)[N]) {
std::copy(a, a + N, std::back_inserter(v));
}
std::vector<T> v;
};
template <typename T>
void print2DVec(vector<vector<T> > vec){
cout<<"[";
for (int i = 0; i< vec.size(); i++){
printVec(vec[i]);
}
cout<<"]"<<endl;
}
class Solution {
public:
int hammingWeight(uint32_t n) {
int number = 0;
while(n!=0){
if(n & 1) {
number ++;
}
n>>=1;
}
return number;
}
};
#define COL 4
int main( int argc, char* argv[]){
Solution* sl = new Solution();
/*int arr[ ROW ][ COL ] = {{1,3,5,7},{10,11,16,20},{23,30,34,50}};
vector<vector<int> > vec(ROW, vector<int>(COL));
for(int i = 0 ; i< ROW; i++)
vec[i].assign(arr[i],arr[i]+COL);
print2DVec(vec);*/
int arr[] = {0, 1, 3};
vector<int> vec;
vec.assign(arr, arr+3);
cout<< sl->hammingWeight(11);
//printVec(rv);
// cout<<(bl == true? 1 :0);
return 0;
}
| true |
23b24c89ea1284c72b17ef88c455f4dea7c4993e | C++ | rosecodym/space-boundary-tool | /src/Core/src/area.cpp | UTF-8 | 4,598 | 2.6875 | 3 | [] | no_license | #include "precompiled.h"
#include "area.h"
#include "equality_context.h"
#include "geometry_common.h"
#include "stringification.h"
namespace geometry_2d {
area::area(const std::vector<std::vector<point_2>> & loops) : use_nef(loops.size() > 1) {
if (use_nef) {
nef_rep = wrapped_nef_polygon(loops);
}
else {
simple_rep = polygon_2(loops.front().begin(), loops.front().end());
ensure_counterclockwise();
assert(simple_rep.is_empty() || simple_rep.is_simple());
}
}
area::area(const std::vector<polygon_2> & loops) : use_nef(loops.size() > 1) {
if (use_nef) {
nef_rep = wrapped_nef_polygon(loops);
}
else {
simple_rep = loops.front();
ensure_counterclockwise();
assert(simple_rep.is_empty() || simple_rep.is_simple());
}
}
area & area::operator = (const area & src) {
if (&src != this) {
use_nef = src.use_nef;
if (!use_nef) { simple_rep = src.simple_rep; }
else { nef_rep = src.nef_rep; }
}
return *this;
}
area & area::operator = (area && src) {
if (&src != this) {
use_nef = src.use_nef;
if (!use_nef) { simple_rep = std::move(src.simple_rep); }
else { nef_rep = std::move(src.nef_rep); }
}
return *this;
}
void area::promote() const {
if (!use_nef) {
use_nef = true;
nef_rep = wrapped_nef_polygon(simple_rep);
}
}
void area::ensure_counterclockwise() {
if (!use_nef && simple_rep.is_clockwise_oriented()) {
simple_rep.reverse_orientation();
}
}
boost::optional<polygon_2> area::outer_bound() const {
auto pwhs = to_pwhs();
return pwhs.size() == 1 ? pwhs.front().outer() : boost::optional<polygon_2>();
}
std::vector<polygon_2> area::to_simple_convex_pieces() const {
if (!use_nef && simple_rep.is_convex()) { return std::vector<polygon_2>(1, simple_rep); }
else {
promote();
return nef_rep.to_simple_convex_pieces();
}
}
bool area::any_points_satisfy_predicate(const std::function<bool(point_2)> & pred) const {
if (!use_nef) {
return std::find_if(simple_rep.vertices_begin(), simple_rep.vertices_end(), pred) != simple_rep.vertices_end();
}
else {
return nef_rep.any_points_satisfy_predicate(pred);
}
}
std::string area::to_string() const {
if (use_nef) { return nef_rep.to_string(); }
else { return reporting::to_string(simple_rep); }
}
area & area::operator += (const area & other) {
if (is_empty()) { *this = other; }
else if (!other.is_empty()) {
promote_both(*this, other);
nef_rep += other.nef_rep;
}
return *this;
}
area & area::operator -= (const area & other) {
if (!is_empty() && !other.is_empty()) {
promote_both(*this, other);
nef_rep -= other.nef_rep;
}
return *this;
}
area & area::operator *= (const area & other) {
if (is_empty() ||
other.is_empty() ||
!CGAL::do_overlap(bbox(), other.bbox()))
{
clear();
}
else {
promote_both(*this, other);
nef_rep *= other.nef_rep;
}
return *this;
}
area & area::operator ^= (const area & other) {
if (is_empty()) { *this = other; }
else if (!other.is_empty()) {
promote_both(*this, other);
nef_rep ^= other.nef_rep;
}
return *this;
}
bool area::do_intersect(const area & a, const area & b) {
if (a.is_empty() || b.is_empty() || !CGAL::do_overlap(a.bbox(), b.bbox())) { return false; }
if (!a.use_nef && !b.use_nef && a.simple_rep == b.simple_rep) { return true; }
promote_both(a, b);
return wrapped_nef_polygon::do_intersect(a.nef_rep, b.nef_rep);
}
bool operator == (const area & a, const area & b) {
if (a.is_empty() && b.is_empty()) { return true; }
if (!a.use_nef && !b.use_nef) { return a.simple_rep == b.simple_rep; }
area::promote_both(a, b);
return a.nef_rep == b.nef_rep;
}
bool operator >= (const area & a, const area & b) {
if (b.is_empty()) { return true; }
if (a.is_empty()) { return false; }
area::promote_both(a, b);
return a.nef_rep >= b.nef_rep;
}
void area::clear() {
simple_rep.clear();
nef_rep.clear();
use_nef = false;
}
std::vector<polygon_with_holes_2> area::to_pwhs() const {
if (!use_nef) {
return std::vector<polygon_with_holes_2>(1, polygon_with_holes_2(std::vector<point_2>(simple_rep.vertices_begin(), simple_rep.vertices_end()), std::vector<std::vector<point_2>>()));
}
else {
return nef_rep.to_pwhs();
}
}
NT area::regular_area() const {
if (use_nef) { return nef_rep.outer_regular_area(); }
else { return geometry_common::regular_area(simple_rep); }
}
area area::snap(equality_context * c) const {
if (use_nef) {
auto snapped = nef_rep.update_all([c](const point_2 & p) {
return c->snap(p);
});
return snapped.is_valid(*c) ? area(std::move(snapped)) : area();
}
else { return area(c->snap(simple_rep)); }
}
} // namespace geometry_2d | true |
413e9a763ed0dfa2b1a95383549cc15f8f0a34c1 | C++ | xyhStruggler/COMS327 | /xiao_yuhan.assignment-1.08/object.cpp | UTF-8 | 2,869 | 3.03125 | 3 | [] | no_license | #include <vector>
#include "object.h"
#include "dungeon.h"
#include "utils.h"
#include <cstring>
int16_t *object_get_pos(object *o)
{
return o->position;
}
object::object(const object_description &o)
{
symbol = object_symbol[o.get_type()];
name = o.get_name().c_str();
desc = o.get_description().c_str();
type = o.get_type();
color = o.get_color();
hit = o.get_hit().roll();
damage = &o.get_damage();
dodge = o.get_dodge().roll();
def = o.get_defence().roll();
weight = o.get_weight().roll();
speed = o.get_speed().roll();
attr = o.get_attribute().roll();
val = o.get_value().roll();
}
void display_object(dungeon_t *d)
{
int x, y;
for(y = 0; y < DUNGEON_Y; y++){
for(x = 0; x < DUNGEON_X; x++){
if(d->object_map[y][x]){
if(charxy(x, y)) object_set_undisplay(d->object_map[y][x]);
else object_set_display(d->object_map[y][x]);
}
}
}
}
void gen_object(dungeon_t *d)
{
int i;
for (i = 0; i < 100; i++){
object *o;
const std::vector<object_description> &v = d->object_descriptions;
const object_description &od = v[rand_range(0, v.size() - 1)];
o = new object(od);
pair_t p;
uint32_t room;
room = rand_range(1, d->num_rooms - 1);
p[dim_y] = rand_range(d->rooms[room].position[dim_y],
(d->rooms[room].position[dim_y] +
d->rooms[room].size[dim_y] - 1));
p[dim_x] = rand_range(d->rooms[room].position[dim_x],
(d->rooms[room].position[dim_x] +
d->rooms[room].size[dim_x] - 1));
o->position[dim_y] = p[dim_y];
o->position[dim_x] = p[dim_x];
if(charpair(p)) o->display = 0;
else o->display = 1;
d->object_map[p[dim_y]][p[dim_x]] = o;
}
}
void object_delete(object *o)
{
delete o;
}
char object_get_symbol(object *o)
{
return o->symbol;
}
const char *object_get_name(object *o)
{
return o->name;
}
object_type_t object_get_type(object *o)
{
return o->type;
}
uint32_t object_get_color(object *o)
{
return o->color;
}
int32_t object_get_hit(object *o)
{
return o->hit;
}
const dice *object_get_damage(object *o)
{
return o->damage;
}
int32_t object_get_dodge(object *o)
{
return o->dodge;
}
int32_t object_get_def(object *o)
{
return o->def;
}
int32_t object_get_weight(object *o)
{
return o->weight;
}
int32_t object_get_speed(object *o)
{
return o->speed;
}
int32_t object_get_attr(object *o)
{
return o->attr;
}
int32_t object_get_val(object *o)
{
return o->val;
}
int16_t object_get_position_x(object *o)
{
return o->position[dim_x];
}
int16_t object_get_position_y(object *o)
{
return o->position[dim_y];
}
int32_t object_get_display(object *o)
{
return o->display;
}
int32_t object_set_display(object *o)
{
return o->display = 1;
}
int32_t object_set_undisplay(object *o)
{
return o->display = 0;
}
| true |
423772e23fa45b55f9e65c9b2345383203664526 | C++ | andens/master-thesis | /thesis-project/src/config-setter/config-setter.cpp | UTF-8 | 2,068 | 2.96875 | 3 | [] | no_license | #include "config-setter.h"
#include <algorithm>
#include <array>
bool ConfigSetter::more() const {
return next_config_ != configurations_.end();
}
void ConfigSetter::next_config(std::function<void(Configuration const&)> const& impl) {
if (more()) {
impl(*next_config_);
next_config_++;
}
}
ConfigSetter::ConfigSetter(uint32_t max_draw_calls) {
// Create the configurations we will use
std::array<Renderer::RenderStrategy, 3> strategies {
Renderer::RenderStrategy::Regular,
Renderer::RenderStrategy::MDI,
Renderer::RenderStrategy::DGC,
};
std::array<Renderer::Flush, 3> flushes {
Renderer::Flush::Never,
Renderer::Flush::Once,
Renderer::Flush::Individual,
};
std::for_each(strategies.begin(), strategies.end(), [this, &flushes, max_draw_calls](Renderer::RenderStrategy s) {
for (auto flush : flushes) {
// We don't really care about flush behavior for regular rendering. `Never`
// will suffice just to have something and the rest are ignored.
if (s == Renderer::RenderStrategy::Regular && flush != Renderer::Flush::Never) {
continue;
}
uint32_t pipeline_step = max_draw_calls / 10;
if (max_draw_calls % 10 != 0) throw;
for (int pipeline_switches = 1; pipeline_switches <= max_draw_calls; pipeline_switches += pipeline_step) {
// Should be multiples of |pipeline_step| from now on
if (pipeline_switches == pipeline_step + 1) {
pipeline_switches--;
}
for (int update_ratio = 0; update_ratio <= 100; update_ratio += 10) {
Configuration c {};
c.strategy = s;
c.num_pipeline_commands = pipeline_switches;
c.update_ratio = update_ratio;
c.flush_behavior = flush;
configurations_.push_back(c);
}
}
}
});
next_config_ = configurations_.begin();
}
uint32_t ConfigSetter::num_configurations() const {
return static_cast<uint32_t>(configurations_.size());
}
void ConfigSetter::first_config() {
next_config_ = configurations_.begin();
}
| true |
c458eb2116148e5f8878be5d92017c3ecfa06e6c | C++ | Jarskih/Bomberman2 | /Caligula/Entity.h | UTF-8 | 1,108 | 2.921875 | 3 | [] | no_license | #pragma once
/*
* Entity.h
* Base class for entities
* Holds colliders and sprites
* Has entity type which is used for detecting what entity is colliding with
*/
enum EntityType
{
PLAYER,
ENEMY,
BLOCK,
BOMB,
FLAME,
POWER_UP,
};
// Base Class for all entity types
class Sprite;
class SpriteSheet;
class Collider;
struct SDL_Renderer;
class Entity
{
protected:
int m_x;
int m_y;
float m_scale;
bool m_active; // If inactive, do not update
bool m_visible; // If inactive, do not render
Sprite* m_sprite;
SpriteSheet* m_spriteSheet;
Collider* m_collider;
EntityType m_type;
int m_block_type;
public:
int GetBlockType() const { return m_block_type; };
EntityType GetType() const { return m_type; };
bool IsActive() const { return m_active; }
bool IsVisible() const { return m_visible; }
virtual ~Entity() {};
Collider* GetCollider() const { return m_collider; };
int GetPositionX() const { return m_x; };
int GetPositionY() const { return m_y; };
virtual void Render(SDL_Renderer* p_renderer) {};
virtual void Update() = 0;
virtual void OnCollision(Entity* p_other) {};
};
| true |
3b595fa3642162ed65493cccf504881b3227c015 | C++ | paulhuggett/digraph-hash | /src/lib/hash.cpp | UTF-8 | 2,112 | 3 | 3 | [
"MIT"
] | permissive | #include "hash.hpp"
#include <algorithm>
#include "vertex.hpp"
namespace {
enum class tags : char {
backref = 'R',
digest = 'D',
end = 'E',
vertex = 'V',
};
} // end anonymous namespace
size_t hash::bytes_ = 0;
#ifdef FNV1_HASH_ENABLED
void hash::update_vertex (vertex const & x) noexcept {
static constexpr auto tag = tags::vertex;
update (&tag, sizeof (tag));
auto const & name = x.name ();
update (name.c_str (), name.length () + 1U);
}
void hash::update_backref (size_t const backref) noexcept {
static constexpr auto tag = tags::backref;
update (&tag, sizeof (tag));
update (&backref, sizeof (backref));
}
void hash::update_digest (digest const & d) noexcept {
static constexpr auto tag = tags::digest;
update (&tag, sizeof (tag));
update (&d, sizeof (d));
}
void hash::update_end () noexcept {
static constexpr auto tag = tags::digest;
update (&tag, sizeof (tag));
}
void hash::update (void const * ptr, size_t const size) noexcept {
auto * const p = reinterpret_cast<uint8_t const *> (ptr);
std::for_each (p, p + size, [this] (uint8_t c) {
state_ = (state_ ^ static_cast<uint64_t> (c)) * fnv1a_64_prime;
});
bytes_ += size;
}
#else // FNV1_HASH_ENABLED
using namespace std::string_literals;
std::string hash::prefix () const {
return (state_.length () > 0) ? "/"s : ""s;
}
void hash::update_vertex (vertex const & x) {
auto const add = prefix () + static_cast<char> (tags::vertex) + x.name ();
bytes_ += add.length ();
state_ += add;
}
void hash::update_backref (size_t const backref) {
auto const add = prefix () + static_cast<char> (tags::backref) + std::to_string (backref);
bytes_ += add.length ();
state_ += add;
}
void hash::update_digest (digest const & d) {
auto const add = prefix () /*+ static_cast<char> (tags::digest)*/ + d;
bytes_ += add.length ();
state_ += add;
}
void hash::update_end () {
static constexpr auto c = static_cast<char> (tags::end);
bytes_ += sizeof (c);
state_ += c;
}
#endif // FNV1_HASH_ENABLED
| true |
49e36fbcc09227936a03e7b7fdc20aec340ca58f | C++ | persesvilhena/c_cplus_studies | /AED1/EXERCICIOS/LISTA10/exer06.cpp | UTF-8 | 489 | 2.875 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
void mm(void){
int x=0;
float v[5] = {0}, maior = 0, menor = 9999;
for(x=0;x<5;x++){
printf("valor: ");
scanf("%f", &v[x]);
}
for(x=0;x<5;x++){
if(v[x] > maior){
maior = v[x];
}
if(v[x] < menor){
menor = v[x];
}
}
printf("\nMaior: %.2f\nMenor: %.2f\n", maior, menor);
}
main(){
mm();
system("pause");
}
| true |
f82c053337c089228cbbd645add151c5b1cc7e7e | C++ | aardvarkk/pixellate | /geomalgorithms.h | WINDOWS-1252 | 4,949 | 3.296875 | 3 | [] | no_license | #ifndef GEOMALGORITHMS_H
#define GEOMALGORITHMS_H
#include <cmath>
// http://geomalgorithms.com/a06-_intersect-2.html
// Copyright 2001 softSurfer, 2012 Dan Sunday
// This code may be freely used and modified for any purpose
// providing that this copyright notice is included with it.
// SoftSurfer makes no warranty for this code, and cannot be held
// liable for any real or imagined damage resulting from its use.
// Users of this code must verify correctness for their application.
// Assume that classes are already given for the objects:
// Point and Vector with
// coordinates {float x, y, z;}
// operators for:
// == to test equality
// != to test inequality
// (Vector)0 = (0,0,0) (null vector)
// Point = Point Vector
// Vector = Point - Point
// Vector = Scalar * Vector (scalar product)
// Vector = Vector * Vector (cross product)
// Line and Ray and Segment with defining points {Point P0, P1;}
// (a Line is infinite, Rays and Segments start at P0)
// (a Ray extends beyond P1, but a Segment ends at P1)
// Plane with a point and a normal {Point V0; Vector n;}
// Triangle with defining vertices {Point V0, V1, V2;}
// Polyline and Polygon with n vertices {int n; Point *V;}
// (a Polygon has V[n]=V[0])
//===================================================================
#define SMALL_NUM 0.00000001 // anything that avoids division overflow
// dot product (3D) which allows vector operations in arguments
#define dot(u,v) ((u).x * (v).x + (u).y * (v).y + (u).z * (v).z)
struct Coord3D
{
float x, y, z;
Coord3D()
{
*this = Coord3D(0);
}
template<typename T>
Coord3D(T x, T y, T z)
{
this->x = static_cast<float>(x);
this->y = static_cast<float>(y);
this->z = static_cast<float>(z);
}
template<typename T>
Coord3D(T val)
{
this->x = static_cast<float>(val);
this->y = static_cast<float>(val);
this->z = static_cast<float>(val);
}
void operator=(Coord3D const& p)
{
this->x = p.x;
this->y = p.y;
this->z = p.z;
}
Coord3D operator*(Coord3D const& v)
{
return Coord3D(
this->y * v.z - this->z * v.y,
this->z * v.x - this->x * v.z,
this->x * v.y - this->y * v.x);
}
bool operator==(Coord3D const& v) const
{
return (this->x == v.x) && (this->y == v.y) && (this->z == v.z);
}
template<typename T>
Coord3D operator*(T scalar)
{
return Coord3D(this->x * scalar, this->y * scalar, this->z * scalar);
}
Coord3D operator+(Coord3D const& p) const
{
return Coord3D(this->x + p.x, this->y + p.y, this->z + p.z);
}
Coord3D operator-(Coord3D const& v) const
{
return Coord3D(this->x - v.x, this->y - v.y, this->z - v.z);
}
};
typedef Coord3D Point;
typedef Coord3D Vector;
struct Ray
{
Point P0, P1;
};
struct Triangle
{
Point V0, V1, V2;
};
// intersect3D_RayTriangle(): find the 3D intersection of a ray with a triangle
// Input: a ray R, and a triangle T
// Output: *I = intersection point (when it exists)
// Return: -1 = triangle is degenerate (a segment or point)
// 0 = disjoint (no intersect)
// 1 = intersect in unique point I1
// 2 = are in the same plane
int intersect3D_RayTriangle( Ray R, Triangle T, Point* I )
{
Vector u, v, n; // triangle vectors
Vector dir, w0, w; // ray vectors
float r, a, b; // params to calc ray-plane intersect
// get triangle edge vectors and plane normal
u = T.V1 - T.V0;
v = T.V2 - T.V0;
n = u * v; // cross product
if (n == (Vector)0) // triangle is degenerate
return -1; // do not deal with this case
dir = R.P1 - R.P0; // ray direction vector
w0 = R.P0 - T.V0;
a = -dot(n,w0);
b = dot(n,dir);
if (fabs(b) < SMALL_NUM) { // ray is parallel to triangle plane
if (a == 0) // ray lies in triangle plane
return 2;
else return 0; // ray disjoint from plane
}
// get intersect point of ray with triangle plane
r = a / b;
if (r < 0.0) // ray goes away from triangle
return 0; // => no intersect
// for a segment, also test if (r > 1.0) => no intersect
*I = dir * r + R.P0; // intersect point of ray and plane
// is I inside T?
float uu, uv, vv, wu, wv, D;
uu = dot(u,u);
uv = dot(u,v);
vv = dot(v,v);
w = *I - T.V0;
wu = dot(w,u);
wv = dot(w,v);
D = uv * uv - uu * vv;
// get and test parametric coords
float s, t;
s = (uv * wv - vv * wu) / D;
if (s < 0.0 || s > 1.0) // I is outside T
return 0;
t = (uv * wu - uu * wv) / D;
if (t < 0.0 || (s + t) > 1.0) // I is outside T
return 0;
return 1; // I is in T
}
#endif | true |
521f40da4af79baba327521b1ee05ad79b7813d3 | C++ | alex08d/Vacuum-Cleaner | /Vacuum_cleaner/main.cpp | UTF-8 | 24,676 | 2.625 | 3 | [] | no_license | #include <iostream>
#include <string.h>
#include <stdlib.h>
using namespace std;
struct eveniment
{
char* den;
};
struct stare
{
char* nume;
};
typedef struct eveniment ev;
typedef struct stare st;
void populare_stari(st* stari)//am predefinit numele starilor pentru a facilita partea de afisare a mesajelor
{
stari[0].nume=(char*)malloc(sizeof(char)*50);
strcpy(stari[0].nume," starea initiala ");
stari[1].nume=(char*)malloc(sizeof(char)*50);
strcpy(stari[1].nume," curatare in mod automat ");
stari[2].nume=(char*)malloc(sizeof(char)*50);
strcpy(stari[2].nume," curatare manuala prin intermediul aplicatiei ");
stari[3].nume=(char*)malloc(sizeof(char)*50);
strcpy(stari[3].nume," scanare ");
stari[4].nume=(char*)malloc(sizeof(char)*50);
strcpy(stari[4].nume," pornire ultrasunete ");
stari[5].nume=(char*)malloc(sizeof(char)*50);
strcpy(stari[5].nume," ocolire ");
stari[6].nume=(char*)malloc(sizeof(char)*50);
strcpy(stari[6].nume," eliberare tub curatare ");
stari[7].nume=(char*)malloc(sizeof(char)*50);
strcpy(stari[7].nume," curatare colt ");
stari[8].nume=(char*)malloc(sizeof(char)*50);
strcpy(stari[8].nume," incheiere program de curatare ");
stari[9].nume=(char*)malloc(sizeof(char)*50);
strcpy(stari[9].nume," intoarcere la statia de incarcare ");
stari[10].nume=(char*)malloc(sizeof(char)*50);
strcpy(stari[10].nume," defect ");
stari[11].nume=(char*)malloc(sizeof(char)*50);
strcpy(stari[11].nume," necesitate schimbare sac ");
stari[12].nume=(char*)malloc(sizeof(char)*50);
strcpy(stari[12].nume," animal detectat a doua oara ");
stari[13].nume=(char*)malloc(sizeof(char)*50);
strcpy(stari[13].nume," avertizarea sonora a utilizatorului ");
stari[14].nume=(char*)malloc(sizeof(char)*50);
strcpy(stari[14].nume," intoarcere ");
}
void populare_ev(ev* evenimente)//s-au predefinit numele evenimentelor in scopul facilitarii afisarii mesajelor
{
evenimente[0].den=(char*)malloc(sizeof(char)*100);
strcpy(evenimente[0].den," Evenimentul nu este valid ");
evenimente[1].den=(char*)malloc(sizeof(char)*100);
strcpy(evenimente[1].den," pornire automata a procesului de curatare ");
evenimente[2].den=(char*)malloc(sizeof(char)*100);
strcpy(evenimente[2].den," controlarea procesului de catre utilizator ");
evenimente[3].den=(char*)malloc(sizeof(char)*100);
strcpy(evenimente[3].den," aparitie obstacol ");
evenimente[4].den=(char*)malloc(sizeof(char)*100);
strcpy(evenimente[4].den," detectare animal ");
evenimente[5].den=(char*)malloc(sizeof(char)*100);
strcpy(evenimente[5].den," detectare obiect ");
evenimente[6].den=(char*)malloc(sizeof(char)*100);
strcpy(evenimente[6].den," alungare animal ");
evenimente[7].den=(char*)malloc(sizeof(char)*100);
strcpy(evenimente[7].den," evitare obstacol ");
evenimente[8].den=(char*)malloc(sizeof(char)*100);
strcpy(evenimente[8].den," detectare colt ");
evenimente[9].den=(char*)malloc(sizeof(char)*100);
strcpy(evenimente[9].den," sistemul de actionare este functional ");
evenimente[10].den=(char*)malloc(sizeof(char)*100);
strcpy(evenimente[10].den," detectare baterie descarcata ");
evenimente[11].den=(char*)malloc(sizeof(char)*100);
strcpy(evenimente[11].den," defectiune ");
evenimente[12].den=(char*)malloc(sizeof(char)*100);
strcpy(evenimente[12].den," reset ");
evenimente[13].den=(char*)malloc(sizeof(char)*100);
strcpy(evenimente[13].den," reluare curatare ");
evenimente[14].den=(char*)malloc(sizeof(char)*100);
strcpy(evenimente[14].den," sac plin ");
evenimente[15].den=(char*)malloc(sizeof(char)*100);
strcpy(evenimente[15].den," terminare incarcare ");
evenimente[16].den=(char*)malloc(sizeof(char)*100);
strcpy(evenimente[16].den," terminare curatare colt ");
evenimente[17].den=(char*)malloc(sizeof(char)*100);
strcpy(evenimente[17].den," aparitie scari ");
evenimente[18].den=(char*)malloc(sizeof(char)*100);
strcpy(evenimente[18].den," scari evitate ");
evenimente[19].den=(char*)malloc(sizeof(char)*100);
strcpy(evenimente[19].den," terminare curatare ");
evenimente[20].den=(char*)malloc(sizeof(char)*100);
strcpy(evenimente[20].den," animalul nu se misca ");
}
void populare_delta(int** matr) //matricea reprezinta defapt functia de tranzitie
{
matr[0][1]=1;
matr[0][2]=2;
matr[1][2]=2;
matr[1][3]=3;
matr[1][8]=6;
matr[1][10]=9;
matr[1][14]=11;
matr[1][17]=14;
matr[1][19]=8;
matr[2][1]=1;
matr[2][19]=8;
matr[3][4]=4;
matr[3][5]=5;
matr[4][4]=12;
matr[4][6]=1;
matr[5][7]=1;
matr[6][9]=7;
matr[6][11]=10;
matr[7][16]=1;
matr[9][15]=1;
matr[9][11]=10;
matr[10][12]=15;
matr[11][13]=1;
matr[12][20]=13;
matr[13][7]=1;
matr[14][18]=1;
}
void populare_matrice(int** matr)
{
for(int i=0;i<15;i++)
for(int j=0;j<7;j++)
matr[i][j]=0;
matr[1][0]=1;
matr[1][1]=1;
matr[1][2]=1;
matr[1][3]=1;
matr[1][4]=1;
matr[1][5]=1;
matr[3][6]=1;
matr[4][6]=1;
matr[4][0]=1;
matr[12][0]=1;
matr[12][6]=1;
matr[13][0]=1;
matr[13][6]=1;
matr[14][3]=1;
matr[5][0]=1;
matr[11][4]=1;
matr[9][5]=1;
}
struct aspirator
{
int dis_obst_stanga,dist_obst_dreapta,dist_obst_fata;//distantele returnate de cei 3 senzori
int dis_sol;//distanta pana la sol returnata de senzorul amplasat in partea din fata jos
int nivel_baterie;//nivelul bateriei
int nivel_sac;//cat de plin este recipietul de colectare
int nivel_termic;//valoarea termica in grade returnata de senzorul termic
int stare;//starea in care se afla aspiratorul
};
typedef struct aspirator asp;
void afis_asp(asp robot)
{
cout<<endl<<endl<<"Statusul actual al robotului este"<<endl;
cout<<"Distanta obstacol stanga : "<<robot.dis_obst_stanga<<endl;
cout<<"Distanta obstacol dreapta : "<<robot.dist_obst_dreapta<<endl;
cout<<"Distanta obstacol fata : "<<robot.dist_obst_fata<<endl;
cout<<"Distanta sol : "<<robot.dis_sol<<endl;
cout<<"Nivel sac : "<<robot.nivel_sac<<endl;
cout<<"Nivel baterie : "<<robot.nivel_baterie<<endl;
cout<<"Nivel termic : "<<robot.nivel_termic<<endl<<endl;
}
void afis_posibilitati(ev* evenimente,int** matrice,int stare)
{
for(int j=1;j<21;j++)
{
if(matrice[stare][j]!=0)
cout<<j<<". - "<<evenimente[j].den<<endl;
}
}
char** init_variabile()//am creat
{
char **Comb_variabile;
Comb_variabile=(char**)malloc(sizeof(char*)*7);
for(int i=0;i<7;i++)
Comb_variabile[i]=(char*)malloc(sizeof(char)*50);
strcpy(Comb_variabile[0],"Distanta fata ");
strcpy(Comb_variabile[1],"Distanta fata si stanga ");
strcpy(Comb_variabile[2],"Distanta fata si dreapta ");
strcpy(Comb_variabile[3],"Distanta sol ");
strcpy(Comb_variabile[4],"Nivel sac ");
strcpy(Comb_variabile[5],"Nivel baterie ");
strcpy(Comb_variabile[6],"Nivel termic ");
return Comb_variabile;
}
int afis_variante(int ** matr,char** comb,int stare)//afiseaza variabile interna care pot fi modificate dintr o anumita stare
{
int nr=0;
for(int j=0;j<7;j++)
if(matr[stare][j] !=0 )
{
cout<<j<<".-"<<comb[j]<<endl;
nr++;
}
return nr;
}
int returnare_eveniment(int** delta,int stare,int stare_noua)//afiseaza evenimentele posibile dintr-o stare
{
for(int i=0;i<15;i++)
for(int j=0;j<21;j++)
if(delta[stare][j]==stare_noua)
return j;
return 0;
}
int main()
{
//Initializari
st* stari;
ev* evenimente;
int** delta,**matr_adiacenta;
int evenim,var,var1,var2,verificare;//nr evenimentului citit de la tastatura
char* raspuns,*mod,**Comb_var;
raspuns=(char*)malloc(sizeof(char)*3);
mod=(char*)malloc(sizeof(char)*20);
delta=(int**)malloc(sizeof(int*)*15);
for(int i=0;i<15;i++)
{
delta[i]=(int*)malloc(sizeof(int)*21);
}
for(int i=0;i<=14;i++)
for(int j=0;j<=20;j++)
delta[i][j]=0;
populare_delta(delta);
matr_adiacenta=(int**)malloc(sizeof(int*)*15);
for(int i=0;i<15;i++)
{
matr_adiacenta[i]=(int*)malloc(sizeof(int)*7);
}
populare_matrice(matr_adiacenta);
stari=(st*)malloc(sizeof(st)*15);
populare_stari(stari);
evenimente=(ev*)malloc(sizeof(ev)*20);
populare_ev(evenimente);
Comb_var=init_variabile();
asp robot;
robot.dist_obst_dreapta=100;//distanta in cm ,1 metru fiind distanta maxima la care senzorul poate vedea
robot.dis_obst_stanga=100;
robot.dist_obst_fata=100;
robot.nivel_baterie=100;
robot.dis_sol=4;
robot.nivel_sac=0;
robot.nivel_termic=10;//temperatura normala dintr-o camera;
robot.stare=0;//Initializare cu starea initiala automatului
system("Color 70");
cout<<" |||||||| |||||||| |||||||||| ||||||||| "<<endl;
cout<<" || || || || || || || || || ||"<<endl;
cout<<" || || || || || || || || || ||"<<endl;
cout<<" |||||||| || || |||||||||| || |||||||||||| ||||||||||||"<<endl;
cout<<" |||| || || || || || || ||"<<endl;
cout<<" || || || || || || || || || ||"<<endl;
cout<<" || || || || || || || ||"<<endl;
cout<<" || || |||||||| |||||||||| |||||||||"<<endl<<endl<<endl;
cout<<" Bun venit ! \n\n Pentru incetarea simularii introduceti orice numar negativ ca eveniment.\n \n Te rugam sa selectezi un mod de curatare prin introducerea numarului corespunzator : \n "<<endl;
afis_posibilitati(evenimente,delta,robot.stare);
cin>>evenim;
robot.stare=delta[robot.stare][evenim];
afis_asp(robot);
cout<<"\nVa rugam sa alegeti modul in care doriti sa treceti la o noua stare : \n1.Evenimente\n2.Variabile \n3.Terminare (pentru a incheia simularea)\n";
cin>>mod;
while(strcmp(mod,"Terminare")!=0)
{
if(strcmp(mod,"Evenimente")==0)
{
cout<<"Evenimentele disponibile din aceasta stare sunt :"<<endl;
afis_posibilitati(evenimente,delta,robot.stare);
cout<<"Alegeti un eveniment : ";
cin>>evenim;
if(evenim<0) break;
if(delta[robot.stare][evenim] != 0)
{
if(delta[robot.stare][evenim] == 1)//Se revine la anumiti parametri normali pentru starea de curatare automata
{
robot.dist_obst_dreapta=100;
robot.dis_obst_stanga=100;
robot.dist_obst_fata=100;
robot.nivel_sac=0;
robot.nivel_termic=10;
robot.nivel_baterie=100;
}
if(delta[robot.stare][evenim] == 3)//Detectarea unui obstacol duce la o distanta in fata de 2 sau sau mai mica de 2
{
robot.dist_obst_dreapta=100;
robot.dis_obst_stanga=100;
robot.dist_obst_fata=2;
robot.nivel_sac=0;
robot.nivel_termic=10;
}
if(delta[robot.stare][evenim] == 4)//Detectarea unui animal ar modifica valoarea returnata de senzorul termic mai mare ca fiind de 25
{
robot.dist_obst_dreapta=100;
robot.dis_obst_stanga=100;
robot.dist_obst_fata=2;
robot.nivel_sac=0;
robot.nivel_termic=35;
}
if(delta[robot.stare][evenim] == 6)//Detectarea unui colt modifica atat distanta fata cat si una din dinstantele stanga sau dreapta . Am ales stanga.
{
robot.dist_obst_dreapta=100;
robot.dis_obst_stanga=2;
robot.dist_obst_fata=2;
robot.nivel_sac=0;
robot.nivel_termic=10;
}
if(delta[robot.stare][evenim] == 9)//Se considera ca bateria este descarcata cand nivelul ajunge la 10 sau mai putin de 10%
{
robot.dist_obst_dreapta=100;
robot.dis_obst_stanga=100;
robot.dist_obst_fata=100;
robot.nivel_baterie=10;//se presupune ca robotul poate ajunge cu 10% baterie inapoi la statia de incarcare
robot.nivel_sac=0;
robot.nivel_termic=10;
}
if(delta[robot.stare][evenim] == 11)//Nivelul sacului ajunge la 100% cand
{
robot.dist_obst_dreapta=100;
robot.dis_obst_stanga=100;
robot.dist_obst_fata=100;
robot.nivel_sac=100;
robot.nivel_termic=10;
}
if(delta[robot.stare][evenim] == 14)//Distanta fata e sol devine mai mare de 4 atunci cand se detecteaza scarile
{
robot.dist_obst_dreapta=100;
robot.dis_obst_stanga=100;
robot.dist_obst_fata=100;
robot.dis_sol=6;
robot.nivel_sac=100;
robot.nivel_termic=10;
}
if(delta[robot.stare][evenim] == 8)
{
cout<<" |||||||| |||||||| || || |||||||||"<<endl;
cout<<" || || || || ||| || || || "<<endl;
cout<<" || || || || || | || || || "<<endl;
cout<<" || || || || || | || |||||| "<<endl;
cout<<" || || || || || | || || "<<endl;
cout<<" || || || || || | || || || "<<endl;
cout<<" || || || || || ||| || ||"<<endl;
cout<<" |||||||| |||||||| || || |||||||||"<<endl<<endl<<endl;
break;
}
if(delta[robot.stare][evenim] == 15)
robot.stare=0;
else
robot.stare=delta[robot.stare][evenim];
cout<<"------------------------------------------------------------------";
afis_asp(robot);
cout<<endl<<"Starea in care se afla robotul este : "<<stari[robot.stare].nume<<endl<<endl;
cout<<endl;
cout<<"------------------------------------------------------------------"<<endl;
}
else
{
cout<<evenimente[0].den<<endl;
cout<<"Daca doriti sa introduceti alt eveniment tastati DA in caz contrar NU :"<<endl;
cin>>raspuns;
if(strcmp(raspuns,"DA")==0)
{
cout<<"Introduceti un alt eveniment : "<<endl;
cin>>evenim;
}
}
}
if(strcmp(mod,"Variabile")==0)
{
int copy_stare =robot.stare;
cout<<"Din aceasta stare se pot schimba doar urmatoarele variabile"<<endl;
int nr=afis_variante(matr_adiacenta,Comb_var,robot.stare);
if(nr!=0)
{
cin>>var;
cout<<"Introduceti ";
cout<<Comb_var[var];
if(var !=1 && var!=2)
cin>>var1;
else
cin>>var1>>var2;
if(var == 0) robot.dist_obst_fata=var1;
if(var == 1)
{
robot.dis_obst_stanga=var2;
robot.dist_obst_fata=var1;
}
if(var == 2)
{
robot.dist_obst_dreapta=var2;
robot.dist_obst_fata=var1;
}
if(var == 3) robot.dis_sol=var1;
if(var == 4) robot.nivel_sac=var1;
if(var == 5) robot.nivel_baterie=var1;
if(var == 6) robot.nivel_termic=var1;
verificare=0;
if(robot.stare == 1)
{
if(robot.dist_obst_fata <=2)
{
if(robot.dist_obst_dreapta <=2 || robot.dis_obst_stanga <=2)
{
int stare_noua=6;
evenim=returnare_eveniment(delta,robot.stare,stare_noua);
cout<<"Se intampla evenimentul : "<<evenimente[evenim].den<<endl;
robot.stare=delta[robot.stare][evenim];
verificare=1;//Daca robotul a realizat deja o tranzitie dintr-o stare in alta sa nu se mai efecueze celelalte verificari
}
else
{
int stare_noua=3;
evenim=returnare_eveniment(delta,robot.stare,stare_noua);
cout<<"Se intampla evenimentul : "<<evenimente[evenim].den<<endl;
robot.stare=3;
verificare=1;
}
}
else
{
if(robot.dis_sol > 4)
{
int stare_noua=14;
evenim=returnare_eveniment(delta,robot.stare,stare_noua);
cout<<"Se intampla evenimentul : "<<evenimente[evenim].den<<endl;
robot.stare=delta[robot.stare][evenim];
verificare=1;
}
else
{
if(robot.nivel_baterie <=10)
{
int stare_noua=9;
evenim=returnare_eveniment(delta,robot.stare,stare_noua);
cout<<"Se intampla evenimentul : "<<evenimente[evenim].den<<endl;
robot.stare=delta[robot.stare][evenim];
verificare=1;
}
else if(robot.nivel_sac >=90)
{
int stare_noua=11;
evenim=returnare_eveniment(delta,robot.stare,stare_noua);
cout<<"Se intampla evenimentul : "<<evenimente[evenim].den<<endl;
robot.stare=delta[robot.stare][evenim];
verificare=1;
}
}
}
}
if(robot.stare==3 && verificare!=1)
{
if(robot.nivel_termic >= 25)
{
int stare_noua=4;
evenim=returnare_eveniment(delta,robot.stare,stare_noua);
cout<<endl<<"Se intampla evenimentul : "<<evenimente[evenim].den<<endl;
robot.stare=4;
verificare=1;
}
else
{
int stare_noua=5;
evenim=returnare_eveniment(delta,robot.stare,stare_noua);
cout<<endl<<"Se intampla evenimentul : "<<evenimente[evenim].den<<endl;
robot.stare=delta[robot.stare][evenim];
verificare=1;
}
}
if(robot.stare==5 && verificare!=1)
{
if(robot.dist_obst_fata > 2)
{
int stare_noua=4;
evenim=returnare_eveniment(delta,robot.stare,stare_noua);
cout<<endl<<"Se intampla evenimentul : "<<evenimente[evenim].den<<endl;
robot.stare=delta[robot.stare][evenim];
verificare=1;
}
}
if(robot.stare==4 && verificare!=1)
{
if(robot.nivel_termic < 25)
{
int stare_noua=1;
evenim=returnare_eveniment(delta,robot.stare,stare_noua);
cout<<endl<<"Se intampla evenimentul : "<<evenimente[evenim].den<<endl;
robot.stare=delta[robot.stare][evenim];
robot.dist_obst_fata=100;
verificare=1;
}
else
{
int stare_noua=12;
evenim=returnare_eveniment(delta,robot.stare,stare_noua);
cout<<endl<<"Se intampla evenimentul : "<<evenimente[evenim].den<<endl;
robot.stare=delta[robot.stare][evenim];
verificare=1;
}
}
if(robot.stare==12 && verificare!=1)
{
if(robot.nivel_termic < 25)
{
int stare_noua=1;
evenim=returnare_eveniment(delta,robot.stare,stare_noua);
cout<<endl<<"Se intampla evenimentul : "<<evenimente[evenim].den<<endl;
robot.stare=delta[robot.stare][evenim];
robot.dist_obst_fata=100;
verificare=1;
}
else
{
int stare_noua=13;
evenim=returnare_eveniment(delta,robot.stare,stare_noua);
cout<<endl<<"Se intampla evenimentul : "<<evenimente[evenim].den<<endl;
robot.stare=delta[robot.stare][evenim];
verificare=1;
}
}
if(robot.stare==13 && verificare!=1 )
{
if(robot.dist_obst_fata > 2)
{
int stare_noua=1;
evenim=returnare_eveniment(delta,robot.stare,stare_noua);
cout<<endl<<"Se intampla evenimentul : "<<evenimente[evenim].den<<endl;
robot.stare=delta[robot.stare][evenim];
verificare=1;
}
}
if(robot.stare==11)
{
if(robot.nivel_sac == 0)
{
int stare_noua=1;
evenim=returnare_eveniment(delta,robot.stare,stare_noua);
cout<<endl<<"Se intampla evenimentul : "<<evenimente[evenim].den<<endl;
robot.stare=delta[robot.stare][evenim];
verificare=1;
}
}
if(robot.stare==9 && verificare!=1)
{
if(robot.nivel_baterie == 100)
{
int stare_noua=1;
evenim=returnare_eveniment(delta,robot.stare,stare_noua);
cout<<endl<<"Se intampla evenimentul : "<<evenimente[evenim].den<<endl;
robot.stare=delta[robot.stare][evenim];
verificare=1;
}
}
if(robot.stare==14 && verificare!=1)
{
if(robot.dis_sol <=4 )
{
int stare_noua=1;
evenim=returnare_eveniment(delta,robot.stare,stare_noua);
cout<<endl<<"Se intampla evenimentul : "<<evenimente[evenim].den<<endl;
robot.stare=delta[robot.stare][evenim];
verificare=1;
}
}
if(copy_stare == robot.stare)
{
cout<<"Robotul ramane in starea de "<<stari[robot.stare].nume;
}
else
{
cout<<"Noua stare a robtului este "<<stari[robot.stare].nume<<endl;
afis_asp(robot);
}
}
}
cout<<"\nVa rugam sa alegeti modul in care doriti sa treceti la o noua stare : \n1.Evenimente\n2.Variabile \n3.Termiare (pentru a incheia simularea)\n";
cin>>mod;
}
return 0;
}
| true |
d87336de58afed20d13ace4b4b1f599f2c5b9a65 | C++ | zimengyang/Graphics_MIS_PT | /src/raytracing/integrator.h | UTF-8 | 2,033 | 2.625 | 3 | [] | no_license | #pragma once
#include <la.h>
#include <raytracing/ray.h>
#include <raytracing/intersection.h>
#include <raytracing/intersectionengine.h>
#include <scene/scene.h>
class Scene;
//The Integrator class recursively evaluates the path a ray takes throughout a scene
//and computes the color a ray becomes as it bounces.
//It samples the materials, probability density functions, and BRDFs of the surfaces the ray hits
//to do this.
class Integrator
{
public:
int Number_Light;
int Number_BRDF;
Integrator();
Integrator(Scene *s);
virtual glm::vec3 TraceRay(Ray r, unsigned int depth);
void SetDepth(unsigned int depth);
Scene* scene;
IntersectionEngine* intersection_engine;
unsigned int getMaxDepth(){return max_depth;}
//random number generator and uniform distribution
int seed;
std::mt19937 generator;//(std::chrono::system_clock::now().time_since_epoch().count());
std::uniform_real_distribution<float> uniform_distribution;//(0.0f,1.0f);
float PowerHeuristic(const float &pdf_s, const float &n_s, const float &pdf_f, const float &n_f);
glm::vec3 MIS_SampleLight(Intersection&, Ray&, Geometry* &);
glm::vec3 MIS_SampleBRDF(Intersection&, Ray&, Geometry *&);
glm::vec3 MIS_SampleLight_Ld(Intersection&, Ray&, Geometry *&);
glm::vec3 MIS_SampleBRDF_Ld(Intersection&, Ray&, Geometry *&, glm::vec3&); // return brdf sample direction
glm::vec3 EstimateDirectLight(Intersection&, Ray&, Geometry* &,glm::vec3&);
//glm::vec3 EstimateIndirectLight(Intersection &, Ray &, glm::vec3 &,float &pdf);
glm::vec3 EstimateLight(Geometry* &light, Ray r, unsigned int depth);
bool RussianRoulette(const glm::vec3 &color,const int& depth);
float throughput;
protected:
unsigned int max_depth;//Default value is 5.
};
class DirectLightingIntegrator : public Integrator
{
public:
DirectLightingIntegrator();
virtual glm::vec3 TraceRay(Ray r, unsigned int depth);
};
| true |
1ce9e85a4664c9bf4d352280db701a1f99221d2b | C++ | gittykrish/Competitive_Programming | /Codechef/HOWMANY.cpp | UTF-8 | 369 | 2.8125 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main() {
// your code goes here
int t,count=0;
cin>>t;
while(t>0){
count +=1;
t /=10;
}
if(count==1 || count==0) cout<<"1";
else if(count==2) cout<<"2";
else if(count==3) cout<<"3";
else cout<<"More than 3 digits";
return 0;
}
| true |
049a1b791c73079d3a2a9ebe569b9c55041f2b80 | C++ | vatsalsharma376/Algo-n-ds | /MO_Algorithm.cpp | UTF-8 | 1,228 | 2.90625 | 3 | [] | no_license | //MO's Algorithm O(m+n * sqrt(n)) No updates and offline queries Sample Range Sum Query
// 0 base indexing
#include <bits/stdc++.h>
using namespace std;
int block=0;
vector<pair<int,int> >quer;
bool cmp(pair<int,int> a,pair<int,int> b){ // Arrange by blocks of sqrt(n)
if(a.first/block!=b.first/block) return a.first/block<b.first/block;
return a.second<b.second;
}
void mos(vector<int> lis,int n,int q){
block=(int)sqrt(n);
sort(quer.begin(),quer.end(),cmp);
int currL=0,currR=0,currS=0;
int l,r;
for(int i=0;i<q;i++){
l=quer[i].first; r=quer[i].second;
while(currL<l){ // REMOVE EXTRA Elements
currS-=lis[currL];
currL++;
}
while(currL>l){
currS+=lis[currL-1];
currL--;
}
while(currR<=r){
currS+=lis[currR];
currR++;
}
while(currR>r+1){
currS-=lis[currR-1];
currR--;
}
cout<<"Sum is "<<currS<<"\n";
}
}
int main(){
int n;
int q;
cin>>n>>q;
vector<int> lis(n);
//vector<pair<int,int> >quer;
for(int i=0;i<n;i++){
cin>>lis[i]; // Taking in inputs
}
int l=0,r=0;
for(int i=0;i<q;i++){
cin>>l>>r; // Accept the queries
quer.push_back(make_pair(l,r));
}
mos(lis,n,q);
return 0;
}
| true |
4879e1ad37385e2b05fc3f7e988fbbcee95aa6e9 | C++ | MaxGarden/CurveEditor | /CurveEditor/Source/CurveEditor/CurveEditorTool.cpp | UTF-8 | 3,752 | 2.796875 | 3 | [] | no_license | #include "pch.h"
#include "CurveEditorTool.h"
class CCurveEditorComponentTool final : public ICurveEditorComponentTool
{
public:
CCurveEditorComponentTool() = default;
virtual ~CCurveEditorComponentTool() override final = default;
virtual void OnAcquired(const CCurveEditorToolEvent& event) override final;
virtual void OnReleased(const CCurveEditorToolEvent& event) override final;
virtual void OnDragBegin(const CCurveEditorToolMouseButtonEvent& event) override final;
virtual void OnDragUpdate(const CCurveEditorToolMouseDragEvent& event) override final;
virtual void OnDragEnd(const CCurveEditorToolMouseButtonEvent& event) override final;
virtual void OnMouseMove(const CCurveEditorToolMouseEvent& event) override final;
virtual void OnWheel(const CCurveEditorToolMouseWheelEvent& event) override final;
virtual void OnClickDown(const CCurveEditorToolMouseButtonEvent& event) override final;
virtual void OnClickUp(const CCurveEditorToolMouseButtonEvent& event) override final;
virtual void OnModifierActivated(const CCurveEditorToolModifierEvent& event) override final;
virtual void OnModifierDeactivated(const CCurveEditorToolModifierEvent& event) override final;
virtual bool AddComponent(ICurveEditorToolUniquePtr&& component) override final;
private:
template<typename Method, typename... Arguments>
void NotifyComponents(Method method, Arguments&&... arguments)
{
for (const auto& component : m_Components)
{
if (component)
(component.get()->*method)(std::forward<Arguments>(arguments)...);
}
}
private:
std::vector<ICurveEditorToolUniquePtr> m_Components;
};
void CCurveEditorComponentTool::OnAcquired(const CCurveEditorToolEvent& event)
{
NotifyComponents(&ICurveEditorTool::OnAcquired, event);
}
void CCurveEditorComponentTool::OnReleased(const CCurveEditorToolEvent& event)
{
NotifyComponents(&ICurveEditorTool::OnReleased, event);
}
void CCurveEditorComponentTool::OnDragBegin(const CCurveEditorToolMouseButtonEvent& event)
{
NotifyComponents(&ICurveEditorTool::OnDragBegin, event);
}
void CCurveEditorComponentTool::OnDragUpdate(const CCurveEditorToolMouseDragEvent& event)
{
NotifyComponents(&ICurveEditorTool::OnDragUpdate, event);
}
void CCurveEditorComponentTool::OnDragEnd(const CCurveEditorToolMouseButtonEvent& event)
{
NotifyComponents(&ICurveEditorTool::OnDragEnd, event);
}
void CCurveEditorComponentTool::OnMouseMove(const CCurveEditorToolMouseEvent& event)
{
NotifyComponents(&ICurveEditorTool::OnMouseMove, event);
}
void CCurveEditorComponentTool::OnWheel(const CCurveEditorToolMouseWheelEvent& event)
{
NotifyComponents(&ICurveEditorTool::OnWheel, event);
}
void CCurveEditorComponentTool::OnClickDown(const CCurveEditorToolMouseButtonEvent& event)
{
NotifyComponents(&ICurveEditorTool::OnClickDown, event);
}
void CCurveEditorComponentTool::OnClickUp(const CCurveEditorToolMouseButtonEvent& event)
{
NotifyComponents(&ICurveEditorTool::OnClickUp, event);
}
void CCurveEditorComponentTool::OnModifierActivated(const CCurveEditorToolModifierEvent& event)
{
NotifyComponents(&ICurveEditorTool::OnModifierActivated, event);
}
void CCurveEditorComponentTool::OnModifierDeactivated(const CCurveEditorToolModifierEvent& event)
{
NotifyComponents(&ICurveEditorTool::OnModifierDeactivated, event);
}
bool CCurveEditorComponentTool::AddComponent(ICurveEditorToolUniquePtr&& component)
{
if (!component)
return false;
m_Components.emplace_back(std::move(component));
return true;
}
ICurveEditorComponentToolUniquePtr ICurveEditorComponentTool::Create()
{
return std::make_unique<CCurveEditorComponentTool>();
} | true |
1acb9ebf80a2b94f1a0fc4af624d12361a439b7c | C++ | CLPeterson/DurableCorrectness | /src/petra/dev/src/romulus/benchmarks/pq-ll-enq-deq.cpp | UTF-8 | 2,508 | 2.859375 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <fstream>
#include <cstring>
#include "benchmarks/PBenchmarkQueues.hpp"
#include "datastructures/pqueues/RomLogLinkedListQueue.hpp"
#include "datastructures/pqueues/RomLRLinkedListQueue.hpp"
int main(void) {
const std::string dataFilename {"data/pq-ll-enq-deq.txt"};
vector<int> threadList = { 1, 2, 4, 8, 16, 24, 32, 48, 64 }; // For the laptop or AWS c5.2xlarge
const int numPairs = 10*1000*1000; // Number of pairs of items to enqueue-dequeue. 10M for the paper
const int numRuns = 1; // 5 runs for the paper
const int EMAX_CLASS = 10;
uint64_t results[EMAX_CLASS][threadList.size()];
std::string cNames[EMAX_CLASS];
int maxClass = 0;
// Reset results
std::memset(results, 0, sizeof(uint64_t)*EMAX_CLASS*threadList.size());
for (unsigned it = 0; it < threadList.size(); it++) {
auto nThreads = threadList[it];
int ic = 0;
PBenchmarkQueues bench(nThreads);
std::cout << "\n----- Persistent Queues (Linked-Lists) numPairs=" << numPairs << " threads=" << nThreads << " runs=" << numRuns << " -----\n";
results[ic][it] = bench.enqDeq<RomLogLinkedListQueue<uint64_t>,romuluslog::RomulusLog>(cNames[ic], numPairs, numRuns);
ic++;
results[ic][it] = bench.enqDeq<RomLRLinkedListQueue<uint64_t>,romuluslr::RomulusLR> (cNames[ic], numPairs, numRuns);
ic++;
//results[ic][it] = bench.enqDeqNoTransaction<PMichaelScottQueue<uint64_t>> (cNames[ic], numPairs, numRuns);
//ic++;
//results[ic][it] = bench.enqDeqNoTransaction<MichaelScottQueue<uint64_t>> (cNames[ic], numPairs, numRuns);
//ic++;
// TODO: Add memory reclamation to Michal's queue... use Andreia's technique, or just fill up the pool
maxClass = ic;
}
// Export tab-separated values to a file to be imported in gnuplot or excel
ofstream dataFile;
dataFile.open(dataFilename);
dataFile << "Threads\t";
// Printf class names
for (int ic = 0; ic < maxClass; ic++) dataFile << cNames[ic] << "\t";
dataFile << "\n";
for (int it = 0; it < threadList.size(); it++) {
dataFile << threadList[it] << "\t";
for (int ic = 0; ic < maxClass; ic++) dataFile << results[ic][it] << "\t";
dataFile << "\n";
}
dataFile.close();
std::cout << "\nSuccessfuly saved results in " << dataFilename << "\n";
return 0;
}
| true |
a7579fa8eb5ec30df6158e9dc29a5a0b873f6203 | C++ | anu1meha/perfbench | /src/tenant.h | UTF-8 | 2,422 | 2.609375 | 3 | [] | no_license | #ifndef TENANT_H
#define TENANT_H 1
#include <string>
#include <arpa/inet.h>
#include "testcases.h"
#include "Controller.h"
#include "systemstate.h"
#include "signals.h"
namespace testcases {
class BaseTestCase;
}
/**
* The Tenant class. Holds and creates the testcase object.
*/
class Tenant {
public:
int id; /**< The tenants id */
testcases::BaseTestCase* testcase; /**< The testcase */
bool finished; /**< Tenant finished? */
bool connected; /**< Tenants OpenFlow Handshake done? */
std::string switch_type; /**< The switch type the tenant is using */
/**
* Constructor class to initialize the tenant and set up the testcase
* @param ip the ip as a string
* @param port the port as a string
* @param testcase_s the testcase name
* @param pps
* @param send_intvl
* @param intraBurstTime
* @param len
* @param max_packets
* @param cooldown_time
* @param nolog
* @param noreport
* @param livedata
* @param livedata_suffix
* @param ofVersion
* @param dataplane_ip
* @param dataplane_mac
* @param dataplane_intf
* @param logfile
* @param tcpnodelay
* @param switchIP
* @param switchPort
* @param sw_type
* @param bsizeschedDistr
* @param btimeschedDistr
* @param schedFile
* @param num_switches
*/
Tenant(std::string ip, std::string port, std::string testcase_s,
int pps, int send_intvl, int intraBurstTime, int len, int max_packets, int cooldown_time, bool nolog, bool noreport,
bool livedata, std::string livedata_suffix, int ofVersion, std::string dataplane_ip,
std::string dataplane_mac, std::string dataplane_intf, std::string logfile, bool tcpnodelay,
std::string switchIP, int switchPort, std::string sw_type, std::string bsizeschedDistr, std::string btimeschedDistr, std::string schedFile,
int num_switches);
~Tenant();
/**
* Start the tenant
*/
void start();
/**
* Stop the tenant
*/
void stop();
/**
* Called when tenant OF Handshake is done
*/
void tenant_connected();
/**
* Called when tenant controller connection disconnects
*/
void tenant_disconnected();
/**
* Called when tenant failed (e.g. connection reset)
*/
void tenant_failed();
/**
* Called when tenant finished its testcase
*/
void testcase_finished();
};
#endif
#pragma once
| true |
074bd5c9a35d535b40fcdc9d22b028e84ea1e949 | C++ | kiranraj2208/calendar-cum-Events-manager | /Calendar.h | UTF-8 | 6,298 | 3.265625 | 3 | [] | no_license | #include<iostream>
#include<fstream>
#include<vector>
#include<algorithm>
#include<cstdlib>
using namespace std;
std::string get_string();
int dates[] = {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
string days[] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
string months[] = {"", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
void read_from_file();
class calendar{
private:
int dd;
int mm;
int yy;
int h;
static int count;
string Event;
void write_into_file(calendar);
void search_event(int m, int d = 0);
friend void read_from_file();
friend bool compare(calendar, calendar);
static void init()
{
if(count++ == 0)
read_from_file();
}
bool leap(int y);
void final_write();
int get_day();
public:
calendar(int y = 2018, int m = 1, int d = 1):yy(y), mm(m), dd(d){init();
dates[2] = (leap(yy))?29 : 28;
if(mm > 12 || mm < 1 || dd > dates[mm] || dd < 1)
{
cout << "Invalid Entry of date\n";
exit(0);
}
}
void display_month(int);
void display_day();
void display_year();
void operator()(int y, int m, int d);
void set_event();
void menu();
void change_date();
void delete_event(int,int,int);
~calendar(){}
};
int calendar::count = 0;
vector<calendar>events;
void calendar::operator()(int y = 2018, int m = 1, int d = 1)
{
yy = y;
mm = m;
dd = d;
dates[2] = (leap(yy))? 29: 28;
if(mm > 12 || mm < 1 || dd > dates[mm] || dd < 1)
{
cout << "Invalid Entry of date\n";
exit(0);
}
}
bool compare(calendar b, calendar c)
{
if(b.yy < c.yy)
return true;
else if (b.yy > c.yy)
return false;
else if(b.mm < c.mm)
return true;
else if(b.mm > c.mm)
return false;
else if (b.dd < c.dd)
return true;
else
return false;
}
int calendar::get_day()
{
int m = mm;
int y = yy;
if(mm == 1)
{
m = 13;
y--;
}
if(mm == 2)
{
m = 14;
y--;
}
int q = dd;
int k = y % 100;
int j = y / 100;
h = q + 13*(m+1)/5 + k + k/4 + j/4 + 5*j;
h = h % 7;
return h;
}
bool calendar::leap(int y)
{
if(yy%100 == 0 && yy%400 == 0 || yy%4 == 0 && yy%100 != 0)
return true;
return false;
}
void calendar::display_month(int m = 0)
{
int mon = mm;
if(m != 0)
mm = m;
else
m = mm;
int dat = dd;
dd = 1;
int d = get_day();
int i = (d+6) % 7;
dates[2] = (leap(yy))? 29: 28;
cout << "\t\t" << months[m] << " " << yy << endl;
cout << "---------------------------------------------------\n";
cout << "Sun\tMon\tTue\tWed\tThu\tFri\tSat\n";
cout << "---------------------------------------------------\n";
for(int j = 0; j < i; j++)
cout << " \t";
for(int j = 1; j <= dates[m]; j++)
{
cout << j << "\t";
if((j+i)%7 == 0)
cout << endl;
}
cout << "\n---------------------------------------------------\n\n";
search_event(m);
mm = mon;
dd = dat;
}
void calendar::display_year()
{
for(int i = 1; i <= 12; i++)
display_month(i);
}
void calendar::display_day(){
int day = (get_day()+6)%7;
cout << yy << "/"<< mm << "/" << dd << ":" << days[day] << endl;
search_event(mm, dd);
}
void read_from_file()
{
fstream file("events_file.txt", ios::in);
if(file == NULL)
{
file.open("events_file.txt", ios::out);
file.close();
return;
}
calendar cal;
events.clear();
int d, m, y;
string E;
while(file >> y)
{
file >> m;
file >> d;
file.ignore();
getline(file, E);
cal.dd = d;
cal.mm = m;
cal.yy = y;
cal.Event = E;
events.push_back(cal);
}
sort(events.begin(), events.end(), compare);
file.close();
}
void calendar::write_into_file(calendar cal)
{
fstream file("events_file.txt", ios::out | ios::app);
file << cal.yy << " ";
file << cal.mm << " ";
file << cal.dd << endl;
file << cal.Event << endl;
file.close();
}
void calendar::set_event()
{
string str;
int n;
cout << "Enter the event on the entered date:";
cin.ignore();
getline(cin, str);
Event = str;
events.push_back(*this);
sort(events.begin(), events.end(), compare);
}
void calendar::final_write()
{
fstream file("events_file.txt", ios::out);
file.clear();
file.close();
sort(events.begin(), events.end(), compare);
for(vector<calendar>::iterator it = events.begin(); it != events.end(); it++)
write_into_file(*it);
}
void calendar::search_event(int m, int d)
{
int flag = 0;
for(vector<calendar>::iterator it = events.begin(); it != events.end(); it++)
{
if(it->yy == yy && it->mm == m && d == 0)
{
string s = months[m];
cout << s.substr(0, 3) << " " << (it)->dd << ":" << it->Event << endl;
flag = 1;
}
else if(it->yy == yy && it->mm == mm && d != 0 && it->dd == d)
{
cout << it->Event << endl;
flag = 1;
}
}
if(flag == 0)
cout << "No Events\n";
cout << endl;
}
void calendar::change_date()
{
int y, m, d;
cout << "Enter the year, month, date:";
cin >> y >> m >> d;
this->operator()(y, m, d);
}
void calendar::delete_event(int y = 0, int m = 0, int d = 0)
{
int flag = 0;
if(y == 0 || m == 0 || d == 0)
{
cout << "Enter the year, month, day:";
cin >> y >> m >> d;
}
for(vector<calendar>::iterator it = events.begin(); it != events.end(); it++)
{
if(it->yy == y && it->mm == m && it->dd == d)
{
events.erase(it);
cout << "Events deleted\n";
flag = 1;
break;
}
}
if(flag == 0)
cout << "No Events\n";
}
void calendar::menu()
{
cout << "\nCurrent date:" << yy << "/" << mm << "/" << dd << endl;
cout << "Menu\n";
cout << "\t1.Display events of current year.\n";
cout << "\t2.Display events of current month.\n";
cout << "\t3.Display events of current day.\n";
cout << "\t4.Change date\n";
cout << "\t5.Set event on current day.\n";
cout << "\t6.Set event on other day.\n";
cout << "\t7.Delete events on current day.\n";
cout << "\t8.Delete events on other day.\n";
cout << "\t9.Exit(Please terminate program only by this method).\n";
short int choice;
cin >> choice;
calendar cal = *this;
switch(choice)
{
case 1:display_year();break;
case 2:display_month();break;
case 3:display_day();break;
case 4:change_date();break;
case 5:set_event();break;
case 6:change_date();set_event();this->operator()(cal.yy, cal.mm, cal.dd);break;
case 7:delete_event(this->yy, this->mm, this->dd);break;
case 8:delete_event();break;
default:final_write();exit(0);
}
menu();
}
| true |
bec443ec8f9a42e76d5da5124dfddb7712fef8d0 | C++ | cat1984x/Learning_Cpp_Primer | /exercises/8/8_4.cpp | UTF-8 | 430 | 3.15625 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
int main(int argc, char *argv[])
{
if(argc > 1)
{
vector<string> c;
string a;
ifstream in(argv[1]);
if(in)
{
while(getline(in, a))
c.push_back(a);
in.close();
for(auto i : c)
cout << i << endl;
}
else
cout << "can't open" << endl;
}
else
cout << "Input the file name." << endl;
return 0;
} | true |
83be38df144ab624dc2b3b551a9654693d8c3432 | C++ | mZarifa/CSCI-2270 | /Exam 3/Q3/Graph.cpp | UTF-8 | 2,231 | 3.5625 | 4 | [] | no_license | #include <vector>
#include <iostream>
#include <queue>
#include "Graph.hpp"
using namespace std;
/* ----------------------------------------
TODO: Complete the method below.
You may add helpers, headers (if necessary)
Helper functions should not be part of the class.
*/
void Graph::vertexAtDepth(string start, int k)
{
// YOUR CODE HERE
return;
}
// ----------------------------------------
void Graph::addEdge(string s1, string s2, bool create_node)
{
// arg: create_node (default: true) creates the nodes if they don't exist in graph
// assumes user won't insert duplicate edges
vertex* v1 = findVertexPointer(s1);
vertex* v2 = findVertexPointer(s2);
if (!v1 && create_node) {
addVertex(s1);
v1 = findVertexPointer(s1);
}
if (!v2 && create_node) {
addVertex(s2);
v2 = findVertexPointer(s2);
}
if(v1 && v2 && v1 != v2) {
adjVertex av1, av2;
// edge from v2 to v1
av1.v = v1;
v2->adj.push_back(av1);
// edge from v1 to v2
av2.v = v2;
v1->adj.push_back(av2);
}
}
void Graph::addVertex(string n){
vertex* exists = findVertexPointer(n);
if(!exists){
vertex* v = new vertex;
v->name = n;
vertices.push_back(v);
}
}
void Graph::display(){
cout << endl << endl;
for(int i = 0; i < vertices.size(); i++) {
cout << vertices[i]->name << " : ";
for(int j = 0; j < vertices[i]->adj.size(); j++) {
cout << vertices[i]->adj[j].v->name << " -> ";
}
cout << "NULL" << endl;
}
cout << endl;
}
vertex* Graph::findVertexPointer(string toFind)
{
for(int i = 0; i < vertices.size(); i++) {
if(vertices[i]->name == toFind) {
return vertices[i];
}
}
return nullptr;
}
void Graph::setDistanceZero()
{
for(int i = 0; i < vertices.size(); i++) {
vertices[i]->distance = 0;
}
}
void Graph::setDistanceInfinity()
{
for(int i = 0; i < vertices.size(); i++) {
vertices[i]->distance = 1000000;
}
}
void Graph::setVisitedFalse()
{
for(int i = 0; i < vertices.size(); i++) {
vertices[i]->visited = false;
}
}
| true |
00255277ec942ddf8e83a5c8bd1012bbcbb6a0e6 | C++ | grievejia/tpa | /include/TaintAnalysis/Support/TaintMemo.h | UTF-8 | 969 | 2.640625 | 3 | [
"MIT"
] | permissive | #pragma once
#include "TaintAnalysis/Support/ProgramPoint.h"
#include "TaintAnalysis/Support/TaintStore.h"
namespace taint
{
class TaintMemo
{
private:
std::unordered_map<ProgramPoint, TaintStore> memo;
public:
using const_iterator = decltype(memo)::const_iterator;
TaintMemo() = default;
// Return NULL if key not found
const TaintStore* lookup(const ProgramPoint& pLoc) const
{
auto itr = memo.find(pLoc);
if (itr == memo.end())
return nullptr;
else
return &itr->second;
}
bool insert(const ProgramPoint& pp, const tpa::MemoryObject* obj, TaintLattice tVal)
{
auto itr = memo.find(pp);
if (itr == memo.end())
{
itr = memo.insert(std::make_pair(pp, TaintStore())).first;
}
return itr->second.weakUpdate(obj, tVal);
}
void update(const ProgramPoint& pp, TaintStore&& store)
{
memo[pp] = std::move(store);
}
const_iterator begin() const { return memo.begin(); }
const_iterator end() const { return memo.end(); }
};
} | true |
2784456b5f5352da0e60d878b1a061fcd04884c8 | C++ | maryana-la/cpp_modules | /cpp04/ex02/Dog.hpp | UTF-8 | 378 | 2.640625 | 3 | [] | no_license | #include "Animal.hpp"
#include "Brain.hpp"
#ifndef DOG_HPP
#define DOG_HPP
class Dog : public Animal {
private:
Brain* _mozgi;
public:
Dog();
Dog(const Dog& other);
virtual ~Dog();
Dog& operator= (const Dog& other);
virtual void makeSound() const;
void setIdea(const std::string& line);
std::string getIdea(int i) const;
};
#endif //DOG_HPP
| true |
c270558784e108a4400d08d33e90851047cfb814 | C++ | Manoama/Methods | /ЛР2/met_lab2.cpp | UTF-8 | 2,991 | 3.296875 | 3 | [] | no_license | #include<iostream>
#include<cmath>
using namespace std;
void print_vector(double T[4],string name)
{
cout << name << ":" << endl;
for (int i = 0; i < 4; i++)
cout << "\t[" << T[i] << "]" << endl;
}
void print_Matrix(double T[4][4], string name)
{
cout << "Matrix "<< name << ":" << endl;
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
cout << T[i][j] << " ";
cout << endl;
}
}
int main()
{
double A[4][4] = {
{5.5, 7, 6, 5.5},
{7, 10.5, 8, 7},
{6, 8, 10.5, 9},
{5.5, 7, 9, 10.5}
};
double B[4] = {23, 32, 33, 31};
double L[4][4] = {
{0, 0, 0, 0},
{0, 0, 0, 0},
{0, 0, 0, 0},
{0, 0, 0, 0}
};
cout << endl;
print_Matrix(A,"A");
cout << endl;
print_vector(B,"B");
cout << endl;
print_Matrix(L,"L");
cout << endl;
// 1. Create L-matrix:
// 1.1 L[0][0]:
L[0][0] = sqrt(A[0][0]);
print_Matrix(L,"L");
cout << endl;
//1.2 L[j][0]:
for (int i = 1; i < 4; i++)
{
L[i][0] = A[i][0] / L[0][0];
print_Matrix(L,"L");
cout << endl;
}
//1.3 L[i][i] and L[i][j] (j < i):
for (int i = 1; i < 4; i++)
{
double sum_d = 0;
double sum_nd = 0;
for (int j = 1; j <= i; j++)
{
if (i == j)
{
sum_d = 0;
for (int k = 0; k < j; k++)
sum_d += pow(L[i][k], 2);
L[i][i] = sqrt(A[i][i] - sum_d);
print_Matrix(L,"L");
cout << endl;
}
else
{
sum_nd = 0;
for (int k = 0; k < j; k++)
sum_nd += L[i][k] * L[j][k];
L[i][j] = (A[i][j] - sum_nd) / L[j][j];
print_Matrix(L,"L");
cout << endl;
}
}
}
print_Matrix(L,"L");
// 2. Reverse:
// 2.1. Y:
double Y[4] = { 0 };
Y[0] = B[0] / L[0][0];
for (int i = 1; i < 4; i++)
{
double sum = 0;
for (int k = 0; k < i; k++)
sum += L[i][k] * Y[k];
Y[i] = (B[i] - sum) / L[i][i];
}
print_vector(Y,"Y");
//2.2 X:
double X[4] = { 0 };
X[3] = Y[3] / L[3][3];
for (int i = 2; i >= 0; i--)
{
double sum = 0;
for (int k = i + 1; k < 4; k++)
sum += L[k][i] * X[k];
X[i] = (Y[i] - sum) / L[i][i];
}
cout << endl;
print_vector(X,"X");
// 3. Check correctness
double R[4] = { 0 };
for (int i = 0; i < 4; i++)
{
double sum = 0;
for (int j = 0; j < 4; j++)
{
sum += A[i][j] * X[j];
}
R[i] = sum;
}
for (int i = 0; i < 4; i++)
R[i] -= B[i];
cout << endl;
print_vector(R,"(Ax - b)");
return 0;
} | true |
b8ac8db8e629b86c6e4ae8e002671d202374ff43 | C++ | Hausdorffcode/leetcode_cpp | /Palindrome Partitioning.cpp | UTF-8 | 1,134 | 3.5 | 4 | [] | no_license | //https://leetcode.com/problems/palindrome-partitioning/#/description
//dfs
//time O(2^n), space O(n)
class Solution {
public:
vector<vector<string>> partition(string s) {
vector<vector<string>> ret;
vector<string> path;
dfs(ret, path, s, 0, 1);
return ret;
}
private:
void dfs(vector<vector<string>> &ret, vector<string> &path, string &s, int prev, int cur) {
if (cur == s.size()) {
if (isP(s, prev, cur-1)) {
path.push_back(s.substr(prev, cur-prev));
ret.push_back(path);
path.pop_back(); //重要!
}
return;
}
if (isP(s, prev, cur-1)) {
path.push_back(s.substr(prev, cur-prev));
dfs(ret, path, s, cur, cur+1);
path.pop_back();
}
dfs(ret, path, s, prev, cur+1);
}
bool isP(string s, int start, int end) {
while (start < end) {
if (s[start] != s[end]) {
return false;
}
start++;
end--;
}
return true;
}
}; | true |
91c8a0d0ad710bd2b42ebb9face261be6c60274d | C++ | flylong0204/projects | /src/osg/osgGraphicals/GraphicalsKeyHandler.cc | UTF-8 | 1,643 | 2.609375 | 3 | [] | no_license | // ==========================================================================
// GraphicalsKeyHandler class member function definitions
// ==========================================================================
// Last modified on 11/6/05; 12/7/05
// ==========================================================================
#include "osg/osgGraphicals/GraphicalsGroup.h"
#include "osg/osgGraphicals/GraphicalsKeyHandler.h"
#include "osg/ModeController.h"
using std::cout;
using std::endl;
// ---------------------------------------------------------------------
// Initialization, constructor and destructor functions:
// ---------------------------------------------------------------------
void GraphicalsKeyHandler::allocate_member_objects()
{
}
void GraphicalsKeyHandler::initialize_member_objects()
{
GraphicalsGroup_ptr=NULL;
}
GraphicalsKeyHandler::GraphicalsKeyHandler(ModeController* MC_ptr)
{
allocate_member_objects();
initialize_member_objects();
ModeController_ptr=MC_ptr;
}
GraphicalsKeyHandler::GraphicalsKeyHandler(
GraphicalsGroup* GG_ptr,ModeController* MC_ptr)
{
allocate_member_objects();
initialize_member_objects();
GraphicalsGroup_ptr=GG_ptr;
ModeController_ptr=MC_ptr;
}
GraphicalsKeyHandler::~GraphicalsKeyHandler()
{
}
// ---------------------------------------------------------------------
ModeController* const GraphicalsKeyHandler::get_ModeController_ptr()
{
return ModeController_ptr;
}
// ---------------------------------------------------------------------
GraphicalsGroup* const GraphicalsKeyHandler::get_GraphicalsGroup_ptr()
{
return GraphicalsGroup_ptr;
}
| true |
8e82ad05c5db2edeb08a4ec3bcbf9441b14f07ae | C++ | jonathanxqs/lintcode | /87.cpp | UTF-8 | 2,398 | 3.765625 | 4 | [
"MIT"
] | permissive | /**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: The root of the binary search tree.
* @param value: Remove the node with given value.
* @return: The root of the binary search tree after removal.
*/
TreeNode* removeNode(TreeNode* root, int value) {
// write your code here
if (root == NULL)
return NULL;
TreeNode * head = new TreeNode();
head->left = root;
TreeNode * tmp = root, *father = head;
cout<<head->val<<endl;
while (tmp != NULL) {
if (tmp->val == value)
break;
father = tmp;
if (tmp->val > value)
tmp = tmp->left;
else
tmp = tmp->right;
}
if (tmp == NULL)
return head->left;
if (tmp->right == NULL) {
if (father->left == tmp)
father->left = tmp->left;
else
father->right = tmp->left;
} else
if (tmp->right->left == NULL) {
if (father->left == tmp)
father->left = tmp->right;
else
father->right = tmp->right;
tmp->right->left = tmp->left;
} else {
father = tmp->right;
TreeNode * cur = tmp->right->left;
while (cur->left != NULL) {
father = cur;
cur = cur->left;
}
tmp->val = cur->val;
father->left = cur->right;
}
return head->left;
}
};
// 1. root node is the target node: find the right most node if its left child and replace the root node
// 2. target node has no child leaf: set its parent left/right child to null
// 3. target node has only one child: replace target node with that child
// 4. target node has both children: find the right most leaf of its left children and replace the target node;
// remember to set its parent child to null and replace children of this node to the target node children
// (another corner case: check if its child is itself)
// most left subnode in the right tree or most right node in the left subtree | true |
4862cdb3683feba7eceb8d27848749a246daa048 | C++ | KimDinh/UVa-Online-Judge-Practice | /UVa 10106.cpp | UTF-8 | 760 | 2.71875 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
#include <cmath>
#include <string>
using namespace std;
int main() {
string s1, s2;
while(getline(cin, s1)) {
getline(cin, s2);
reverse(s1.begin(), s1.end());
reverse(s2.begin(), s2.end());
int a[502], first=0;
for(int i=0; i<502; i++)
a[i] = 0;
for(int i=0; i<s1.length(); i++)
for(int j=0; j<s2.length(); j++)
a[i+j] += (s1[i]-'0')*(s2[j]-'0');
for(int i=0; i<501; i++) {
a[i+1] += a[i]/10;
a[i] %= 10;
if(a[i+1]!=0)
first = i+1;
}
for(int i=first; i>=0; i--)
cout << a[i];
cout << endl;
}
return 0;
}
| true |
c9a47a7ae19657d4b6b867236314d58631e99142 | C++ | elitelau/lalr1_parser | /grammar_config.h | UTF-8 | 2,365 | 2.765625 | 3 | [] | no_license | #ifndef _GRAMMAR_CONFIG_H
#define _GRAMMAR_CONFIG_H
#include "scanner.h"
#include "grammar.h"
#include <stdio.h>
const int SYM_DIRVATION = 1000;
#define O_DIRIVATION O_ASSIGN // !! in BNF, there is no denotion of assignment operation , but instand of dirivation
#define O_SELECTION O_OR // '|', not "||"
//typedef Grammar::Productions Productions;
class GrammarConfig
{
public:
GrammarConfig( const char* pFileName ) : m_sFileName(pFileName)
{}
// read in all the productions from grammar file
bool ReadInProductions( char (&szPrompt)[100] );
private:
class GrammarScanner : public Scanner
{
public:
GrammarScanner( FILE* f ) : Scanner(f)
{}
virtual Token* GetToken(void);
const char* GetKeyword( const char* str )
{
return m_dfaIdentifier.getKeyword( str );
}
};
class GrammarParser
{
public:
GrammarParser( FILE* f ) : _nMaxSymbolCount(10), _nMaxRuleCount(5), _nMaxProductionCount(1000), _nUnrecognizedTerminal(-1), _scanner(f), _tok( NULL )
{}
~GrammarParser()
{
Clear();
}
bool Parse( char (&szPrompt)[100] );
void Clear() // free all the tokens
{
for( TokIter it = _tok_lst.begin(); it != _tok_lst.end(); ++it )
delete *it;
_tok_lst.clear();
}
private:
void production_list(void);
void production( Grammar::NonTerminal*& n, Grammar::Productions& ps );
void rule_id( Grammar::NonTerminal*& n );
void rule_list( Grammar::Productions& ps );
void rule( Grammar::Production*& p );
void symbol( Grammar::Symbol*& sym );
void match( int tok_type );
Token* getTok(void)
{
_tok = _scanner.GetToken();
while( _tok->_tok == PSEUDO ) // get a token that is not psuedo
{
_tok_lst.push_back(_tok);
_tok = _scanner.GetToken();
}
_tok_lst.push_back(_tok);
return _tok;
}
int getTokenKind(const char* str);
private:
int _nMaxSymbolCount; // the maximum symbols a rule can contain
int _nMaxRuleCount; // the maximum rules a production can contain
int _nMaxProductionCount; // the maximum productions
int _nUnrecognizedTerminal;
private:
GrammarScanner _scanner;
Token* _tok;
typedef list<Token*> Tokens;
typedef Tokens::iterator TokIter;
Tokens _tok_lst; // !!! used for collect all the memories occupied by tokens, and thus freed memory at a time finally
};
string m_sFileName; // the name of grammar file
};
#endif
| true |
af6d724a7fbd909e120fdd65b87272ae38a61417 | C++ | lyMeiSEU/SEU_beat_plane | /ConsoleApplication1/ConsoleApplication1/FileOperation.cpp | GB18030 | 1,397 | 3.1875 | 3 | [] | no_license | #include "pch.h"
#include <fstream>
#include <io.h>
#include "FileOperation.h"
#pragma warning(disable : 4996)
FileOperation::FileOperation(string dir)
{
// m_strPathֵ
string path = _pgmptr; // exeļĿ¼*.exe
m_strPath = path.substr(0, path.find_last_of('\\') + 1);
m_strPath += dir;
if (!IsExisteDirectory(m_strPath))
{
string str = "md \"" + m_strPath + "\"";
system(str.c_str());
}
}
FileOperation::~FileOperation(void)
{
}
bool FileOperation::CreateFileW(string filename)
{
string path = m_strPath + '\\' + filename;
fstream file;
file.open(path, ios::out);
if (!file)
{
return false;
}
file.close();
return true;
}
bool FileOperation::DeleteFile(string filename)
{
string path = m_strPath + '\\' + filename;
// int remove(char *filename);
// ɾļɹ0-1
if (-1 == remove(path.c_str()))
{
return false;
}
return true;
}
bool FileOperation::AlterFileName(string filename, string newname)
{
string path = m_strPath + '\\' + filename;
newname = m_strPath + '\\' + newname;
// int rename(char *oldname, char *newname);
// ļ,ɹ0-1
if (-1 == rename(path.c_str(), newname.c_str()))
{
return false;
}
return true;
}
bool FileOperation::IsExisteDirectory(string path)
{
if (-1 != _access(path.c_str(), 0))
{
return true;
}
return false;
} | true |
56b1edc3060a16fb9ff526630dc111f596a94a5a | C++ | eagee/SwimFishySwim | /IAudio.h | UTF-8 | 1,116 | 2.9375 | 3 | [] | no_license | // IAudio.h
// Defines the simple interface for all audio protocols (midi, mp3, pcm, controller)
// Author(s): Eagan Rackley
#ifndef IAUDIO_H
#define IAUDIO_H
///<summary>
/// // Defines the simple interface for all audio protocols (midi, mp3, pcm, controller)
///</summary>
class IAudio
{
public:
IAudio(){}
virtual ~IAudio(){}
///<summary>
/// Loads data into memory from a file ...
///</summary>
virtual void loadFromFile(const char *fileName) = 0;
///<summary>
/// Plays the audio once then stops.
///</summary>
virtual void playOnce() = 0;
///<summary>
/// Plays the audio over and over again ad infinitium.
///</summary>
virtual void playLooped() = 0;
///<summary>
/// Stops playing the audio and resets all counters.
///</summary>
virtual void stop() = 0;
///<summary>
/// Pauses the audio where it is so that playing can resume from the same point.
///</summary>
virtual void pause() = 0;
///<summary>
/// Returns true if the audio is currently being played, otherwise false...
///</summary>
virtual bool isPlaying() = 0;
};
#endif
| true |
f459050d69b6cbbea73d041ec63db1735480afe1 | C++ | Moseasirius/Algorithm | /algorithm/Sort/IndexHeap.h | UTF-8 | 5,273 | 3.734375 | 4 | [] | no_license | //
// Created by mo on 2021/7/24.
//
#ifndef SORT_INDEXHEAP_H
#define SORT_INDEXHEAP_H
//索引堆
//数据和索引分开存储
//构建堆的过程和对数据的操作对索引操作就行
template<typename Item>
class IndexMaxHeap {
private:
Item *data;
int *indexes;
int *reverse;
int count;
int capacity;
void shiftUp(int k) {
while (k > 1 && data[indexes[k / 2]] < data[indexes[k]])//k>1防止越界父节点的元素值是否小于子节点
{
swap(indexes[k / 2], indexes[k]);
reverse[k / 2] = k / 2;
reverse[k] = k;
k /= 2;//更新k
}
}
void shiftDown(int k) {
//判断k节点有孩子,这里判断左孩子,一棵完全二叉树中,可能只有左孩子而没有右孩子,不可能只有右孩子而没有左孩子
while (2 * k <= count) {
int j = 2 * k;//在此轮循环中,data[k]和data[j]交换位置
if (j + 1 <= count && data[indexes[j + 1]] > data[indexes[j]])//说明有右孩子,而且右孩子的值比左孩子的值大
{
j = j + 1;
}
// data[j] 是 data[2*k]和data[2*k+1]中的最大值
if (data[indexes[k]] >= data[indexes[j]])
break;
swap(indexes[k], indexes[j]);//可以优化,不用每一遍都swap,可以最后再交换(插入排序优化 思想)
reverse[indexes[k]] = k;
reverse[indexes[j]] = j;
k = j;
}
}
public:
//构造函数,构造一个空堆,可容纳capacity个元素
IndexMaxHeap(int capacity) {
data = new Item[capacity + 1];//因为我们从数组下标索引1开始存数据
indexes = new int[capacity + 1];
reverse = new int[capacity + 1];
for (int i = 0; i <= capacity; i++) {
reverse[i] = 0;
}
count = 0;
this->capacity = capacity;
}
//Heapify
IndexMaxHeap(Item array[], int n) {
data = new Item[n + 1];
capacity = n;
for (int i = 0; i < n; i++) {
data[i + 1] == array[i];
}
count = n;
for (int i = count / 2; i >= 1; i--) {
shiftDown(i);
}
}
//析构函数
~IndexMaxHeap() {
delete[] data;
delete[] indexes;
delete[] reverse;
}
//返回堆中元素的个数
int size() {
return count;
}
// 返回一个布尔值, 表示索引堆中是否为空
bool isEmpty() {
return count == 0;
}
// 向最大索引堆中插入一个新的元素, 新元素的索引为i, 元素为item
// 传入的i对用户而言,是从0索引的
void insert(int i, Item item)//内部1从开始,外部从0开始,用户看不到
{
assert(count + 1 <= capacity);
assert(i + 1 >= 1 && i + 1 <= capacity);
i = i + 1;
data[i] = item;//隐藏数组越界问题,可以先判断后开辟新的空间解决
indexes[count + 1] = i;
reverse[i] = count + 1;
count++;
shiftUp(count);
}
void print() {
for (int i = 1; i <= size(); i++) {
cout << data[i] << " ";
}
cout << endl;
}
// 从最大索引堆中取出堆顶元素, 即索引堆中所存储的最大数据
Item extractMax() {
assert(count > 0);
Item ret = data[indexes[1]];
swap(indexes[1], indexes[count]);
reverse[indexes[1]] = 1;
reverse[indexes[count]] = 0;
count--;
shiftDown(1);
return ret;
}
// 从最大索引堆中取出堆顶元素的索引
int extractMaxIndex() {
assert(count > 0);
Item ret = indexes[1] - 1;
swap(indexes[1], indexes[count]);
reverse[indexes[1]] = 1;
reverse[indexes[count]] = 0;
count--;
shiftDown(1);
return ret;
}
//获取最大索引堆中堆顶元素
Item getMax() {
assert(count > 0);
return data[indexes[1]];
}
//获取最大索引堆中堆顶元素元素的索引
int getMaxIndex() {
assert(count > 0);
return indexes[1] - 1;
}
bool contain(int i) {
assert(i + 1 >= 1 && i + 1 <= capacity);
return reverse[i + 1] != 0;
}
// 获取最大索引堆中索引为i的元素
Item getItem(int i) {
assert(contain(i));
return data[i + 1];
}
// 将最大索引堆中索引为i的元素修改为newItem
void change(int i, Item newItem) {
assert(contain(i));
i += 1;
data[i] = newItem;
//找到Indexes[j]=i,j表示data[i]在堆中的位置
//之后再shiftDown(j)和shiftUp(j)
// for(int j=1;j<=count;j++)
// {
// if(indexes[j]==i)
// {
// shiftDown(j);
// shiftUp(j);
// }
// }
int j = reverse[i];
shiftDown(j);
shiftUp(j);
}
};
#endif //SORT_INDEXHEAP_H
| true |
ce07636eff3169d7f7a5536d62e6d9dd8d1162c7 | C++ | mrcarlino/AI-for-Game-Programming | /Pathfinding_ASCII/Pathfinding/Pathfinding.cpp | UTF-8 | 5,565 | 3.265625 | 3 | [] | no_license | #include "pch.h"
#include <GridHelper.h>
#include <StopWatch.h>
#include "BreadthFirstSearch.h"
#include "GreedyBestFirst.h"
#include "AStar.h"
#include "Dijkstra.h"
using namespace std;
using namespace Library;
void DrawGrid(Graph graph, int32_t graphWidth, int32_t graphHeight, set<shared_ptr<Library::Node>> closedSet, shared_ptr<Library::Node> start, shared_ptr<Library::Node> end);
set<shared_ptr<Library::Node>> BuildPath(set<shared_ptr<Library::Node>> closedSet, shared_ptr<Library::Node> end);
int main(int argc, char* argv[])
{
Pathfinding::BreadthFirstSearch BFS;
Pathfinding::GreedyBestFirst Greedy;
Pathfinding::AStar AStar;
Pathfinding::Dijkstra Dijkstra;
string filename = (argc == 2 ? argv[1] : "Content\\Grid.grid");
set<shared_ptr<Library::Node>> closedSet;
StopWatch stopwatch;
int32_t gridWidth;
int32_t gridHeight;
Graph graph = GridHelper::LoadGridFromFile(filename, gridWidth, gridHeight);
int startX, startY, endX, endY;
string algorithm, restart;
// program loop
while (true)
{
// user selection and input
cout << "Please enter which algorithm you would like to run:" << endl << endl;
cout << " a - Breadth First Search" << endl;
cout << " b - Greedy Best First Search" << endl;
cout << " c - Dijkstra's Algorithm" << endl;
cout << " d - A*" << endl;
cout << " exit - Quit Program" << endl << endl;
cout << "Choice: ";
cin >> algorithm;
while (algorithm != "a" && algorithm != "b" && algorithm != "c" && algorithm != "d" && algorithm != "exit")
{
cout << endl << "Not a valid choice, try again..." << endl << endl << "Choice: ";
cin >> algorithm;
}
if (algorithm == "exit")
break;
// select start and end nodes
cout << endl << "---Enter coordinates for the 10x10 grid---" << endl;
cout << "Start node coordinates x y: ";
cin >> startX >> startY;
cout << "End node coordinates x y: ";
cin >> endX >> endY;
system("cls");
auto start = graph.At(startX, startY);
auto end = graph.At(endX, endY);
cout << "Grid Size: " << gridWidth << "x" << gridHeight << endl;
cout << "Start Node: (" << startX << ", " << startY << ")" << endl;
cout << "End Node: (" << endX << ", " << endY << ")" << endl;
// BFS
if (algorithm == "a")
{
cout << endl << "Breadth First Search" << endl;
stopwatch.Start();
BFS.FindPath(start, end, closedSet);
stopwatch.Stop();
DrawGrid(graph, gridWidth, gridHeight, closedSet, start, end);
}
// Greedy
else if (algorithm == "b")
{
cout << endl << "Greedy Best First Search" << endl;
stopwatch.Start();
Greedy.FindPath(start, end, closedSet);
stopwatch.Stop();
DrawGrid(graph, gridWidth, gridHeight, closedSet, start, end);
}
// Dijkstras
else if (algorithm == "c")
{
cout << endl << "Dijkstra's Algorithm" << endl;
stopwatch.Start();
Dijkstra.FindPath(start, end, closedSet);
stopwatch.Stop();
DrawGrid(graph, gridWidth, gridHeight, closedSet, start, end);
}
// A*
else if (algorithm == "d")
{
cout << endl << "A*" << endl;
stopwatch.Start();
AStar.FindPath(start, end, closedSet);
stopwatch.Stop();
DrawGrid(graph, gridWidth, gridHeight, closedSet, start, end);
}
else
{
cout << "Invalid input, please try again!";
}
if (start->Type() == NodeType::Normal && end->Type() == NodeType::Normal)
{
cout << endl << "Elapsed Time (ms): " << stopwatch.ElapsedMilliseconds().count() << endl;
cout << "Visitied Nodes: " << closedSet.size() << endl << endl;
}
closedSet.clear();
stopwatch.Reset();
cout << "restart - Choose Again" << endl;
cout << "exit - Quit Program" << endl;
cout << endl << "Choice: ";
cin >> restart;
while (restart != "restart" && restart != "exit")
{
cout << endl << "Not a valid choice, try again..." << endl << endl << "Choice: ";
cin >> restart;
}
if (restart == "exit")
break;
else
system("cls");
}
return 0;
}
void DrawGrid(Graph graph, int32_t graphWidth, int32_t graphHeight, set<shared_ptr<Library::Node>> closedSet, shared_ptr<Library::Node> start, shared_ptr<Library::Node> end)
{
start->SetParent(nullptr);
string displayString;
set<shared_ptr<Library::Node>> fullPath = BuildPath(closedSet, end);
for (int i = 0; i < graphWidth; i++)
{
for (int j = 0; j < graphHeight; j++)
{
shared_ptr<Node> node = graph.At(j, i);
if (node == start && node->Type() == NodeType::Normal)
displayString = " S ";
else if (node == end && node->Type() == NodeType::Normal)
displayString = " E ";
else if (fullPath.count(node) && node->Type() == NodeType::Normal && (start->Type() == NodeType::Normal && end->Type() == NodeType::Normal))
displayString = " X ";
else if (node->Type() == NodeType::Wall)
displayString = " | ";
else
displayString = " - ";
cout << displayString;
}
cout << endl;
}
if (fullPath.size() == 0)
cout << endl << "No path was found!" << endl << endl;
if (start->Type() == NodeType::Wall)
cout << endl << "Start node is on a wall..." << endl << endl;
else if (end->Type() == NodeType::Wall)
cout << endl << "End node is on a wall..." << endl << endl;
}
set<shared_ptr<Library::Node>> BuildPath(set<shared_ptr<Library::Node>> closedSet, shared_ptr<Library::Node> end)
{
set<shared_ptr<Library::Node>> path;
shared_ptr<Library::Node> current = end;
if (!closedSet.empty() && closedSet.count(end))
{
// end node
path.insert(current);
while (current->Parent().expired() == false)
{
current = current->Parent().lock();
path.insert(current);
}
}
return path;
}
| true |
246db7f31cd8acf59f3ba8ade2f11884d42d97fe | C++ | larsbuntemeyer/tracy | /source/vector3d.h | UTF-8 | 926 | 3.203125 | 3 | [] | no_license | //vector3d.h
#ifndef _VECTOR3D_
#define _VECTOR3D_
#include <iostream>
class vector3d {
public:
vector3d(void);
vector3d(float x_in, float y_in, float z_in);
~vector3d();
float getLength();
void Normalize();
static float Dot(vector3d x, vector3d y);
vector3d getNormalVector();
float getX(){return x;};
float getY(){return y;};
float getZ(){return z;};
float Dot(vector3d a);
void setCoordinates(float x_in, float y_in, float z_in);
void print(std::string name);
void operator+=(vector3d A);
void operator-=(vector3d A);
void operator*=(float a);
friend vector3d operator + (vector3d A, vector3d B);
friend vector3d operator - (vector3d A, vector3d B);
friend float operator * (vector3d A, vector3d B);
friend vector3d operator * (float a, vector3d B);
float x,y,z;
private:
};
#endif
| true |
5dd11fd6fc2ac9d0d15a346d0461be9bfb140aba | C++ | Mathematicator/Pokemon- | /Potion.h | WINDOWS-1252 | 1,061 | 2.65625 | 3 | [] | no_license | /*
* _ _ _ _ _ ___ _ _ _____ _ _ _ _ _
* | \_/ |/ \| \| | | o \/ \| |// __|| \_/ |/ \| \| |
* | \_/ ( o ) \\ | | _( o ) (| _| | \_/ ( o ) \\ |
* |_| |_|\_/|_|\_| |_| \_/|_|\\___||_| |_|\_/|_|\_|
*
Par: Lebbat badreddine
*/
#ifndef POTION_H
#define POTION_H
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include "Monster.h"
#include "Object.h"
/*
Les objets affectant une donne (CPotion) (rgnration de point de vie, augmentation de lattaque, ..)
*/
class CPotion : public CObject
{
protected:
// Membre de la classe
float m_lifeRecup;
float m_attackValue;
public:
// mthodes de la classe
void PotionLifeRecupe(CMonster *Monster);
void PotionAttackValue(CMonster *Monster);
void virtual useObject(CTerrain *terrain, CMonster *monster);
void virtual printObject();
type_object virtual getType();
CPotion(string name, float lifeRecup, float attackValue);
~CPotion();
};
#endif | true |
a5c953daaa8372c97c38ea57a6124256366389dc | C++ | Akash16s/Simple-Maze-Solver | /Maze_Solver2.0.ino | UTF-8 | 10,930 | 2.703125 | 3 | [] | no_license | const int trigPinF=13,echoPinF=12,trigPinR=11,echoPinR=10,trigPinL=9,echoPinL=8; //Ultrasonic Pins
const int rightUp=7,rightDown=6,leftUp=5,leftDown=4; //Motor Pins
int orientation=0; /* 0
2 1
3*/
int walldistance=5,walldistanceMin=3;
int initial=0,noOfPoint=0;
int pos[100][4]; //1=persent not searched and 0 = searched
int back=0;
void setup() {
pinMode(trigPinF,OUTPUT);
pinMode(echoPinF,INPUT);
pinMode(trigPinR,OUTPUT);
pinMode(echoPinR,INPUT);
pinMode(trigPinL,OUTPUT);
pinMode(echoPinL,INPUT);
pinMode(rightUp,OUTPUT);
pinMode(rightDown,OUTPUT);
pinMode(leftUp,OUTPUT);
pinMode(leftDown,OUTPUT);
}
void loop() {
delay(2000); //for 2 seconds delay for intial movement
forwards();
if(distance(trigPinR,echoPinR)<walldistanceMin){
analogWrite(rightUp,100); //rightwards movement
digitalWrite(rightDown,LOW);
analogWrite(leftUp,50);
digitalWrite(leftDown,LOW);
}
if(distance(trigPinL,echoPinL)<walldistanceMin){
analogWrite(rightUp,50); //leftwards movement
digitalWrite(rightDown,LOW);
analogWrite(leftUp,100);
digitalWrite(leftDown,LOW);
}
forwards();
if(back==1){
backwardAlgo();
}
else{
long distanceF=distance(trigPinF,echoPinF);
long distanceR=distance(trigPinR,echoPinR);
long distanceL=distance(trigPinL,echoPinL);
if(distanceF>walldistance && distanceR>walldistance && distanceL>walldistance) allClear();
else if (distanceF<walldistance && distanceR>walldistance && distanceL>walldistance) exceptForward();
else if (distanceF>walldistance && distanceR>walldistance && distanceL<walldistance) exceptLeft();
else if(distanceF>walldistance && distanceR<walldistance && distanceL>walldistance) exceptRight();
else if(distanceF<walldistance && distanceR>walldistance && distanceL<walldistance) onlyRight();
else if (distanceF<walldistance && distanceR<walldistance && distanceL>walldistance) onlyLeft();
else if (distanceF<walldistance && distanceR<walldistance && distanceL<walldistance) backMove();
}
}
//The Distance function
long distance(int trigPin,int echoPin)
{// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
long duration = pulseIn(echoPin, HIGH);
long distance= duration*0.034/2;
return distance;
}
void allClear(){ //in this case all three sides are free
noOfPoint++;
switch(orientation){
case 0: {pos[noOfPoint][0]=1;
pos[noOfPoint][1]=0;
pos[noOfPoint][2]=1;
pos[noOfPoint][3]=0;}break;
case 1:{pos[noOfPoint][0]=1;
pos[noOfPoint][1]=1;
pos[noOfPoint][2]=0;
pos[noOfPoint][3]=0;}break;
case 2:{pos[noOfPoint][0]=0;
pos[noOfPoint][1]=0;
pos[noOfPoint][2]=1;
pos[noOfPoint][3]=1;}break;
case 3:{pos[noOfPoint][0]=0;
pos[noOfPoint][1]=1;
pos[noOfPoint][2]=0;
pos[noOfPoint][3]=1;}break;
}
rightwards();
if(orientation==3) orientation=0; //this is orientation designator
else orientation++;
}
void exceptForward(){
noOfPoint++;
switch(orientation){
case 0: {pos[noOfPoint][0]=0;
pos[noOfPoint][1]=0;
pos[noOfPoint][2]=1;
pos[noOfPoint][3]=0;}break;
case 1:{pos[noOfPoint][0]=1;
pos[noOfPoint][1]=0;
pos[noOfPoint][2]=0;
pos[noOfPoint][3]=0;}break;
case 2:{pos[noOfPoint][0]=0;
pos[noOfPoint][1]=0;
pos[noOfPoint][2]=0;
pos[noOfPoint][3]=1;}break;
case 3:{pos[noOfPoint][0]=0;
pos[noOfPoint][1]=1;
pos[noOfPoint][2]=0;
pos[noOfPoint][3]=0;}break;
}
rightwards();
if(orientation==3) orientation=0; //this is orientation designator
else orientation++;
}
void exceptLeft(){
noOfPoint++;
switch(orientation){
case 0: {pos[noOfPoint][0]=1;
pos[noOfPoint][1]=0;
pos[noOfPoint][2]=0;
pos[noOfPoint][3]=0;}break;
case 1:{pos[noOfPoint][0]=0;
pos[noOfPoint][1]=1;
pos[noOfPoint][2]=0;
pos[noOfPoint][3]=0;}break;
case 2:{pos[noOfPoint][0]=0;
pos[noOfPoint][1]=0;
pos[noOfPoint][2]=2;
pos[noOfPoint][3]=0;}break;
case 3:{pos[noOfPoint][0]=0;
pos[noOfPoint][1]=0;
pos[noOfPoint][2]=0;
pos[noOfPoint][3]=3;}break;
}
rightwards();
if(orientation==3) orientation=0; //this is orientation designator
else orientation++;
}
void exceptRight(){
noOfPoint++;
switch(orientation){
case 0: {pos[noOfPoint][0]=0;
pos[noOfPoint][1]=0;
pos[noOfPoint][2]=1;
pos[noOfPoint][3]=0;}break;
case 1:{pos[noOfPoint][0]=1;
pos[noOfPoint][1]=0;
pos[noOfPoint][2]=0;
pos[noOfPoint][3]=0;}break;
case 2:{pos[noOfPoint][0]=0;
pos[noOfPoint][1]=0;
pos[noOfPoint][2]=0;
pos[noOfPoint][3]=1;}break;
case 3:{pos[noOfPoint][0]=0;
pos[noOfPoint][1]=1;
pos[noOfPoint][2]=0;
pos[noOfPoint][3]=0;}break;
}
forwards();
if(orientation==3) orientation=0; //this is orientation designator
else orientation++;
}
void onlyRight(){
rightwards();
if(orientation==3) orientation=0; //this is orientation designator
else orientation++;
}
void onlyLeft(){
leftwards();
if(orientation==3) orientation=0; //this is orientation designator
else orientation--;
}
void backMove(){
back=1;
switch(orientation){
case 0: orientation=3; break;
case 1: orientation=2; break;
case 2:orientation=1; break;
case 3:orientation=0; break;
}
backwards();
forwards();
}
void backwardAlgo(){ //this is for backward direction
int f,r,l,b;
pos[noOfPoint][0]=f;
pos[noOfPoint][1]=r;
pos[noOfPoint][2]=l;
pos[noOfPoint][3]=b;
switch(orientation){
case 0: if(f==1&&r==1&&l==1){
rightwards();
pos[noOfPoint][1]=0;
}
else if(f==0&&r==1&&l==1){
rightwards();
pos[noOfPoint][1]=0;
}
else if(f==1&&r==0&&l==1){
forwards();
pos[noOfPoint][0]=0;
}
else if(f==1&&r==1&&l==0){
forwards();
pos[noOfPoint][0]=0;
}
else if(f==1&&r==0&&l==0){
forwards();
pos[noOfPoint][0]=0;
}
else if(f==0&&r==1&&l==0){
rightwards();
pos[noOfPoint][1]=0;
}
else if(f==0&&r==0&&l==1){
leftwards();
pos[noOfPoint][2]=0;
}
break;
case 1: if(f==1&&r==1&&b==1){
rightwards();
pos[noOfPoint][3]=0;
}
else if(f==0&&r==1&&b==1){
rightwards();
pos[noOfPoint][3]=0;
}
else if(f==1&&r==0&&b==1){
rightwards();
pos[noOfPoint][3]=0;
}
else if(f==1&&r==1&&b==0){
forwards();
pos[noOfPoint][1]=0;
}
else if(f==1&&r==0&&b==0){
leftwards();
pos[noOfPoint][0]=0;
}
else if(f==0&&r==1&&b==0){
forwards();
pos[noOfPoint][1]=0;
}
else if(f==0&&r==0&&b==1){
rightwards();
pos[noOfPoint][3]=0;
}
break;
case 2: if(f==1&&l==1&&b==1){
rightwards();
pos[noOfPoint][0]=0;
}
else if(f==0&&l==1&&b==1){
forwards();
pos[noOfPoint][2]=0;
}
else if(f==1&&l==0&&b==1){
rightwards();
pos[noOfPoint][0]=0;
}
else if(f==1&&l==1&&b==0){
rightwards();
pos[noOfPoint][0]=0;
}
else if(f==1&&l==0&&b==0){
rightwards();
pos[noOfPoint][0]=0;
}
else if(f==0&&l==1&&b==0){
forwards();
pos[noOfPoint][2]=0;
}
else if(f==0&&l==0&&b==1){
leftwards();
pos[noOfPoint][3]=0;
}
break;
case 3: if(r==1&&l==1&&b==1){
rightwards();
pos[noOfPoint][2]=0;
}
else if(r==0&&l==1&&b==1){
rightwards();
pos[noOfPoint][2]=0;
}
else if(r==1&&l==0&&b==1){
forwards();
pos[noOfPoint][3]=0;
}
else if(r==1&&l==1&&b==0){
rightwards();
pos[noOfPoint][2]=0;
}
else if(r==1&&l==0&&b==0){
leftwards();
pos[noOfPoint][1]=0;
}
else if(r==0&&l==1&&b==0){
rightwards();
pos[noOfPoint][2]=0;
}
else if(r==0&&l==0&&b==1){
forwards();
pos[noOfPoint][3]=0;
}
break;
}
}
//All Movement
void rightwards()
{
analogWrite(rightUp,75); //rightwards movement till delay
analogWrite(rightDown,LOW);
analogWrite(leftUp,LOW);
digitalWrite(leftDown,75);
delay(2000);
digitalWrite(rightUp,LOW);
digitalWrite(rightDown,LOW);
digitalWrite(leftUp,LOW);
digitalWrite(leftDown,LOW);
}
void forwards()
{
analogWrite(rightUp,75);
analogWrite(rightDown,LOW);
analogWrite(leftUp,25);
digitalWrite(leftDown,LOW);
}
void leftwards(){
analogWrite(rightUp,LOW); //leftwards
analogWrite(rightDown,75);
analogWrite(leftUp,75);
analogWrite(leftDown,LOW);
delay(2000);
digitalWrite(rightUp,LOW);
digitalWrite(rightDown,LOW);
digitalWrite(leftUp,LOW);
digitalWrite(leftDown,LOW);
}
void backwards()
{
analogWrite(rightUp,75); //rightwards movement till delay
analogWrite(rightDown,LOW);
analogWrite(leftUp,LOW);
digitalWrite(leftDown,75);
delay(8000);
digitalWrite(rightUp,LOW);
digitalWrite(rightDown,LOW);
digitalWrite(leftUp,LOW);
digitalWrite(leftDown,LOW);
}
| true |
fc5bfc7563ede38091a35ae92f8b56d70db6369c | C++ | iwiwi/bip2 | /src/vc_solver/pre_reducer.cc | UTF-8 | 4,990 | 2.59375 | 3 | [] | no_license | #include "common.h"
#include "pre_reducer.h"
namespace vc_solver {
double pre_reducer::stat_time_total_ = 0;
pre_reducer::pre_reducer(const vector<pair<int, int> >& original_edges,
const vector<double>& original_weight) {
original_edges_ = original_edges;
original_weight_ = original_weight;
V_ = original_weight.size();
adj_.assign(V_, vector<int>());
for (auto e : original_edges) {
adj_[e.first ].emplace_back(e.second);
adj_[e.second].emplace_back(e.first);
}
weight_ = original_weight;
status_.assign(V_, NORMAL);
}
void pre_reducer::reduce() {
rep (iteration, 10) {
modified_ = false;
reduce_low_degree();
reduce_domination();
if (!modified_) break;
}
JLOG_ADD_OPEN("reduction") {
JLOG_PUT("num_deleted_vs", count(all(status_), DELETED));
JLOG_PUT("num_fixed_vs", count(all(status_), FIXED));
}
}
void pre_reducer::get_reduced_problem(vector<pair<int, int> >& reduced_edges,
vector<double>& reduced_weight) {
int red_num_v = 0;
v_red2org_.clear();
v_org2red_.assign(V_, -1);
rep (ov, V_) {
if (status_[ov] == NORMAL) {
v_red2org_.emplace_back(ov);
v_org2red_[ov] = red_num_v++;
}
}
reduced_weight.resize(red_num_v);
rep (rv, red_num_v) {
reduced_weight[rv] = original_weight_[v_red2org_[rv]];
}
reduced_edges.clear();
for (auto p : original_edges_) {
if (v_org2red_[p.first] >= 0 && v_org2red_[p.second] >= 0) {
reduced_edges.emplace_back(v_org2red_[p.first],
v_org2red_[p.second]);
}
}
}
double pre_reducer::get_fixed_weight() {
double w = 0;
rep (v, V_) if (status_[v] == FIXED) w += weight_[v];
return w;
}
double pre_reducer::get_original_solution(const vector<int>& reduced_solution,
vector<int>& original_solution) {
double w = 0;
original_solution.clear();
for (int rv : reduced_solution) {
int ov = v_red2org_[rv];
original_solution.emplace_back(ov);
w += original_weight_[ov];
}
rep (ov, V_) {
if (status_[ov] == FIXED) {
original_solution.emplace_back(ov);
w += original_weight_[ov];
}
}
return w;
}
void pre_reducer::reduce_low_degree() {
STAT_TIMER(stat_time_total_) {
vector<int> deg(V_, 0);
rep (v, V_) {
if (status_[v] != NORMAL) continue;
for (int u : adj_[v]) ++deg[u];
}
// TODO: degree 2
queue<int> que;
rep (v, V_) {
if (deg[v] <= 1 && status_[v] == NORMAL) que.push(v);
}
while (!que.empty()) {
int v = que.front();
que.pop();
if (status_[v] != NORMAL) continue;
if (deg[v] == 0) {
status_[v] = DELETED;
modified_ = true;
} else if (deg[v] == 1) {
// Find the only one neighbor vertex
int u = -1;
for (int x : adj_[v]) {
if (status_[x] == NORMAL) {
assert(u == -1);
u = x;
}
}
assert(u != -1);
if (weight_[u] > weight_[v]) continue;
// Fix |u| and remove edges from |u|
for (int x : adj_[u]) {
if (--deg[x] <= 1 && status_[v] == NORMAL) que.push(x);
}
fix_vertex(u);
status_[v] = DELETED;
modified_ = true;
} else {
assert(false);
}
}
}
}
void pre_reducer::reduce_domination() {
STAT_TIMER(stat_time_total_) {
rep (v, V_) sort(all(adj_[v]));
vector<bool> a(V_, false);
rep (v, V_) {
if (status_[v] != NORMAL) continue;
a[v] = true;
for (int u : adj_[v]) a[u] = true;
for (int u : adj_[v]) {
if (status_[u] != NORMAL) continue;
if (weight_[v] > weight_[u] ||
adj_[v].size() < adj_[u].size()) continue;
for (int x : adj_[u]) if (!a[x]) goto dmp;
// |v| dominates |u|
status_[v] = FIXED;
modified_ = true;
break;
dmp:;
}
a[v] = false;
for (int u : adj_[v]) a[u] = false;
}
purify_edges();
}
}
///////////////////////////////////////////////////////////////////////////////
// Graph manipulation
///////////////////////////////////////////////////////////////////////////////
void pre_reducer::purify_edges() {
rep (v, V_) {
if (status_[v] != NORMAL) {
adj_[v].clear();
} else {
adj_[v].erase(remove_if(all(adj_[v]),
[&](int u) { return status_[u] != NORMAL; }),
adj_[v].end());
}
}
}
void pre_reducer::remove_edge(int u, int v) {
modified_ = true;
// TODO: slow?
adj_[u].erase(remove(all(adj_[u]), v), adj_[u].end());
adj_[v].erase(remove(all(adj_[v]), u), adj_[v].end());
}
void pre_reducer::fix_vertex(int v) {
modified_ = true;
assert(status_[v] == NORMAL);
status_[v] = FIXED;
for (int u : adj_[v]) {
adj_[u].erase(remove(all(adj_[u]), v), adj_[u].end());
}
adj_[v].clear();
}
} // namespace vc_solver
| true |
69ff999a9635239c722464989b016bc391d8d8a3 | C++ | khm2034/baekjoonAlgorithms | /src/11000/test.cpp | UHC | 34,643 | 2.609375 | 3 | [] | no_license | //#include<iostream>
//#include<string>
//#include<memory.h>
//#define QUEUESIZE 2505
//using namespace std;
//
//int R, C;
//int map[51][51];
//int visit_w[51][51];
//int visit_s[51][51];
//struct qu {
// pair<int, int> q[QUEUESIZE];
// int rear, front;
// qu() { rear = front = 0; }
// void push(int x, int y)
// {
// rear++;
// rear = rear % QUEUESIZE;
// q[rear].first = x;
// q[rear].second = y;
// }
// pair<int, int> pop()
// {
// front++;
// front = front % QUEUESIZE;
// return q[front];
// }
//};
//qu q_s, q_w;
//int dx[4] = { 1, 0, -1, 0 };
//int dy[4] = { 0, 1, 0, -1 };
//bool safe(int x, int y)
//{
// return x >= 0 && x < C && y >= 0 && y < R;
//}
//void bfs_w()
//{
// while (q_w.front != q_w.rear)
// {
// pair<int, int> t = q_w.pop();
// int tx, ty;
// for (int i = 0; i < 4; i++)
// {
// tx = t.first + dx[i];
// ty = t.second + dy[i];
// if (safe(tx, ty) && !map[ty][tx] && !visit_w[ty][tx])
// {
// visit_w[ty][tx] = visit_w[t.second][t.first] + 1;
// q_w.push(tx, ty);
// }
// }
// }
//}
//int bfs_s()
//{
// while (q_s.front != q_s.rear)
// {
// pair<int, int> t = q_s.pop();
// int tx, ty;
// for (int i = 0; i < 4; i++)
// {
// tx = t.first + dx[i];
// ty = t.second + dy[i];
//
// if (safe(tx, ty))
// {
// if (map[ty][tx] == 1)
// return visit_s[t.second][t.first];
// else if (map[ty][tx] != -1 && !visit_s[ty][tx] && ((visit_w[ty][tx] > visit_s[t.second][t.first] + 1) || (visit_w[ty][tx] == 0)))
// {
// visit_s[ty][tx] = visit_s[t.second][t.first] + 1;
// q_s.push(tx, ty);
// }
// }
// }
// }
// return 0;
//}
//int main()
//{
// freopen("input.txt", "r", stdin);
// cin >> R >> C;
// string s;
// for (int i = 0; i < R; i++)
// {
// cin >> s;
// for (int j = 0; s[j]; j++)
// {
// if (s[j] == 'D') map[i][j] = 1;
// else if(s[j] == '.') map[i][j] = 0;
// else if (s[j] == 'X') map[i][j] = -1;
// else if (s[j] == 'S')
// {
// q_s.push(j, i);
// visit_s[i][j] = 1;
// }
// else if (s[j] == '*')
// {
// q_w.push(j, i);
// visit_w[i][j] = 1;
// }
// }
// }
// bfs_w();
// int ret = bfs_s();
// if (ret)
// cout << ret << "\n";
// else
// cout << "KAKTUS\n";
// return 0;
//}
//#include<iostream>
//#include<string>
//#include<memory.h>
//#define QUEUESIZE 100
//using namespace std;
//
//int map[13][7];
//bool visit[13][7];
//string s;
//pair<int, int> q[QUEUESIZE];
//int front, rear;
//int dx[4] = { 1, 0, -1, 0 };
//int dy[4] = { 0, 1, 0, -1 };
//void push(int x, int y)
//{
// rear++;
// rear = rear % QUEUESIZE;
// q[rear].first = x;
// q[rear].second = y;
//}
//pair<int, int> pop()
//{
// front++;
// front = front % QUEUESIZE;
// return q[front];
//}
//bool safe(int x, int y)
//{
// return x >= 0 && x < 6 && y >= 0 && y < 12;
//}
//bool bfs(int x, int y, int color)
//{
// pair<int, int> r_l[100];
// int r_idx = 0;
// push(x, y);
// visit[y][x] = true;
// r_l[r_idx].first = x;
// r_l[r_idx++].second = y;
// while (front != rear)
// {
// pair<int, int> t = pop();
// int tx, ty;
// for (int i = 0; i < 4; i++)
// {
// tx = t.first + dx[i];
// ty = t.second + dy[i];
// if (safe(tx, ty) && !visit[ty][tx] && map[ty][tx] == color)
// {
// push(tx, ty);
// visit[ty][tx] = true;
// r_l[r_idx].first = tx;
// r_l[r_idx++].second = ty;
// }
// }
// }
// if (r_idx < 4)
// return false;
// for (int i = 0; i < r_idx; i++)
// map[r_l[i].second][r_l[i].first] = 0;
// return true;
//}
//void drop()
//{
// for (int i = 0; i < 6; i++)
// {
// int lo, hi, diff;
// bool flag = false;
// for (int j = 11; j >= 0; j--)
// {
// if (!map[j][i])
// {
// lo = j;
// j--;
// while(1)
// {
// if (map[j][i] || j == 0)
// break;
// j--;
// }
// diff = lo - j;
// while (1)
// {
// if (!map[j][i] || j==0)
// break;
// j--;
// }
// hi = j;
// for (int k = lo; k >= hi + diff; k--)
// {
// map[k][i] = map[k - diff][i];
// map[k - diff][i] = 0;
// }
// }
// }
// }
//}
//int main()
//{
// for (int i = 0; i < 12; i++)
// {
// cin >> s;
// for (int j = 0; s[j]; j++)
// {
// if (s[j] == '.')
// map[i][j] = 0;
// else if (s[j] == 'R')
// map[i][j] = 1;
// else if (s[j] == 'G')
// map[i][j] = 2;
// else if (s[j] == 'B')
// map[i][j] = 3;
// else if (s[j] == 'P')
// map[i][j] = 4;
// else if (s[j] == 'Y')
// map[i][j] = 5;
// }
// }
//
// int cnt = 0;
// while (1)
// {
// memset(visit, false, sizeof(visit));
// int flag = false;
// for (int i = 0; i < 12; i++)
// for (int j = 0; j < 6; j++)
// {
// if (map[i][j] && !visit[i][j])
// flag = flag | bfs(j, i, map[i][j]);
// }
// if (!flag)
// break;
// cnt++;
// drop();
// }
// cout << cnt << "\n";
// return 0;
//}
//#include<iostream>
//#include<algorithm>
//#define QUEUESIZE 10005
//using namespace std;
//
//int N, M, K;
//int map[101][101];
//bool visit[101][101];
//int sx, sy, ex, ey;
//pair<int, int> q[QUEUESIZE];
//int front, rear;
//int dx[4] = { 1, 0, -1, 0 };
//int dy[4] = { 0, 1, 0, -1 };
//int result[2501];
//int result_idx;
//void push(int x, int y)
//{
// rear++;
// rear = rear % QUEUESIZE;
// q[rear].first = x;
// q[rear].second = y;
//}
//pair<int, int> pop()
//{
// front++;
// front = front % QUEUESIZE;
// return q[front];
//}
//bool safe(int x, int y)
//{
// return x >= 0 && x < N && y >= 0 && y < M;
//}
//int bfs(int x, int y)
//{
// int ret = 1;
// push(x, y);
// visit[y][x] = true;
// while (rear != front)
// {
// pair<int, int> t = pop();
// int tx, ty;
// for (int i = 0; i < 4; i++)
// {
// tx = t.first + dx[i];
// ty = t.second + dy[i];
// if (safe(tx, ty) && !visit[ty][tx] && !map[ty][tx])
// {
// ret++;
// visit[ty][tx] = true;
// push(tx, ty);
// }
// }
// }
// return ret;
//}
//
//int main()
//{
// cin >> M >> N >> K;
// for (int i = 0; i < K; i++)
// {
// cin >> sx >> sy >> ex >> ey;
// for (int j = sy; j < ey; j++)
// for (int k = sx; k < ex; k++)
// map[j][k] = 1;
// }
//
// for (int i = 0; i < M; i++)
// for (int j = 0; j < N; j++)
// if (!map[i][j] && !visit[i][j])
// result[result_idx++] = bfs(j, i);
// sort(result, result + result_idx);
// cout << result_idx << "\n";
// for (int i = 0; i < result_idx; i++)
// cout << result[i] << " ";
// cout << "\n";
// return 0;
//}
//#include<iostream>
//#include<memory.h>
//#define QUEUESIZE 2505
//using namespace std;
//
//int W, H;
//int map[51][51];
//bool visit[51][51];
//pair<int, int> q[2505];
//int front, rear;
//int dx[8] = {1, 1, 0, -1, -1, -1, 0, 1};
//int dy[8] = { 0, 1, 1, 1, 0, -1, -1, -1};
//void push(int x, int y)
//{
// rear++;
// rear = rear % QUEUESIZE;
// q[rear].first = x;
// q[rear].second = y;
//}
//pair<int, int> pop()
//{
// front++;
// front = front % QUEUESIZE;
// return q[front];
//}
//bool safe(int x, int y)
//{
// return x >= 0 && x < W && y >= 0 && y < H;
//}
//
//void bfs(int x, int y)
//{
// push(x, y);
// visit[y][x] = true;
// while (rear != front)
// {
// pair<int, int> t = pop();
// int tx, ty;
// for (int i = 0; i < 8; i++)
// {
// tx = t.first + dx[i];
// ty = t.second + dy[i];
// if (safe(tx, ty) && map[ty][tx] && !visit[ty][tx])
// {
// visit[ty][tx] = true;
// push(tx, ty);
// }
// }
// }
//}
//
//int main()
//{
// while (1)
// {
// memset(map, 0, sizeof(map));
// memset(visit, false, sizeof(visit));
// cin >> W >> H;
// if (!W && !H)
// break;
// for(int i=0; i<H; i++)
// for (int j = 0; j < W; j++)
// cin >> map[i][j];
//
// int cnt = 0;
// for (int i = 0; i < H; i++)
// for (int j = 0; j < W; j++)
// if (map[i][j] && !visit[i][j])
// {
// bfs(j, i);
// cnt++;
// }
// cout << cnt << "\n";
// }
// return 0;
//}
//#include<iostream>
//#include<memory.h>
//#define QUEUESIZE 2505
//using namespace std;
//
//int N, M, K;
//int T;
//int map[51][51];
//bool visit[51][51];
//
//pair<int, int> q[QUEUESIZE];
//int rear, front;
//
//int dx[4] = { 1, 0, -1, 0 };
//int dy[4] = { 0, 1, 0, -1 };
//void push(int x, int y)
//{
// rear++;
// rear = rear % QUEUESIZE;
// q[rear].first = x;
// q[rear].second = y;
//}
//
//pair<int, int> pop()
//{
// front++;
// front = front % QUEUESIZE;
// return q[front];
//}
//
//bool safe(int x, int y)
//{
// return x >= 0 && x < M && y >= 0 && y < N;
//}
//
//void bfs(int x, int y)
//{
// push(x, y);
// visit[y][x] = true;
// while (front != rear)
// {
// pair<int, int> t = pop();
// int tx, ty;
// for (int i = 0; i < 4; i++)
// {
// tx = t.first + dx[i];
// ty = t.second + dy[i];
// if (safe(tx, ty) && map[ty][tx] && !visit[ty][tx])
// {
// visit[ty][tx] = true;
// push(tx, ty);
// }
// }
// }
//}
//
//int main()
//{
// cin >> T;
// for (int tc = 0; tc < T; tc++)
// {
// memset(map, 0, sizeof(map));
// memset(visit, false, sizeof(visit));
// cin >> M >> N >> K;
// int x, y;
// int cnt = 0;
// for (int i = 0; i < K; i++)
// {
// cin >> x >> y;
// map[y][x] = 1;
// }
// for(int i=0; i<N; i++)
// for (int j = 0; j < M; j++)
// {
// if (map[i][j] && !visit[i][j])
// {
// bfs(j, i);
// cnt++;
// }
// }
//
// cout << cnt << "\n";
// }
// return 0;
//}
////#include<iostream>
////#include<cstdio>
////#include<memory.h>
////#define QUEUESIZE (1000*1000*5)
////using namespace std;
////
////int N, M;
////int map[1001][1001];
////int dx[4] = { 1, 0, -1, 0 };
////int dy[4] = { 0, -1, 0, 1 };
////pair<int, int> q[QUEUESIZE];
////
////int rear = 0;
////int front = 0;
////int ret = 0;
////void push(int x, int y)
////{
//// rear++;
//// rear = rear%QUEUESIZE;
//// q[rear].first = x;
//// q[rear].second = y;
////}
////pair<int, int> pop()
////{
//// front++;
//// front = front%QUEUESIZE;
//// return q[front];
////}
////
////bool safe(int x, int y)
////{
//// return x >= 0 && x < N && y >= 0 && y < M;
////}
////
////void bfs()
////{
//// while (rear != front)
//// {
//// pair<int, int> t = pop();
//// for (int i = 0; i < 4; i++)
//// {
//// int tmp_x = t.first + dx[i];
//// int tmp_y = t.second + dy[i];
//// if (safe(tmp_x, tmp_y) && map[tmp_y][tmp_x] == 0)
//// {
//// map[tmp_y][tmp_x] = map[t.second][t.first] + 1;
//// push(tmp_x, tmp_y);
//// if (ret < map[tmp_y][tmp_x]-1)
//// ret = map[tmp_y][tmp_x]-1;
//// }
//// }
//// }
////}
////int chk()
////{
//// for (int i = 0; i < M; i++)
//// for (int j = 0; j < N; j++)
//// if (!map[i][j])
//// return -1;
//// return ret;
////}
////int main()
////{
//// scanf("%d%d", &N, &M);
//// int tmp;
//// for (int i = 0; i < M; i++)
//// for (int j = 0; j < N; j++)
//// {
//// scanf("%d", &tmp);
//// if (tmp == 1)
//// push(j, i);
//// map[i][j] = tmp;
//// }
////
//// bfs();
//// printf("%d\n", chk());
//// return 0;
////}
////
////#include<iostream>
////#include<cstdio>
////#include<algorithm>
////using namespace std;
////
////int N;
////int map[26][26];
////bool visit[26][26];
////char s[26];
////int dx[4] = { 1, 0, -1, 0 };
////int dy[4] = { 0 ,1, 0, -1 };
////int ret[25 * 25];
////int ret_idx = 0;
////bool safe(int x, int y)
////{
//// return x >= 0 && x < N && y >= 0 && y < N;
////}
////
////void dfs(int x, int y)
////{
//// visit[y][x] = true;
//// ret[ret_idx]++;
//// for (int i = 0; i < 4; i++)
//// {
//// int tx = x + dx[i];
//// int ty = y + dy[i];
//// if (safe(tx, ty) && map[ty][tx] && !visit[ty][tx])
//// {
//// dfs(tx, ty);
//// }
//// }
////
////}
////int main()
////{
//// scanf("%d", &N);
//// for (int i = 0; i < N; i++)
//// {
//// scanf("%s", s);
//// for (int j = 0; s[j]; j++)
//// map[i][j] = s[j] - '0';
//// }
//// int total = 0;
//// for (int i = 0; i < N; i++)
//// for (int j = 0; j < N; j++)
//// if (map[i][j] && !visit[i][j])
//// {
//// total++;
//// dfs(j, i);
//// ret_idx++;
//// }
//// printf("%d\n", total);
//// sort(ret, ret + total, cmp);
//// for (int i = 0; i < ret_idx; i++)
//// printf("%d\n", ret[i]);
//// return 0;
////}
////
////#include<iostream>
////#include<cstdio>
////typedef long long ll;
////using namespace std;
////
////int N, M;
////ll arr[1000001];
////ll le, ri;
////int main()
////{
//// scanf("%d%d", &N, &M);
//// for (int i = 0; i < N; i++)
//// {
//// scanf("%lld", &arr[i]);
//// if (ri < arr[i])
//// ri = arr[i];
//// }
//// ll ret = -1;
//// ll mid;
//// while (le <= ri)
//// {
//// mid = (ri + le) / 2;
//// ll sum = 0;
//// for (int i = 0; i < N; i++)
//// if(arr[i] > mid)
//// sum += arr[i] - mid;
////
//// if (sum >= M)
//// {
//// if (ret < mid)
//// ret = mid;
//// le = mid+1;
//// }
//// else if (sum < M)
//// ri = mid-1;
//// }
//// printf("%lld\n", ret);
//// return 0;
////}
////
////#include<iostream>
////#include<cstdio>
////#define QUEUESIZE (1000*1000*5)
////using namespace std;
////
////int N, M;
////int map[1001][1001];
////int visit[1001][1001][2];
////char s[1001];
////int dx[4] = { 1, 0, -1, 0 };
////int dy[4] = { 0 ,1, 0, -1 };
////pair<int, int> q[QUEUESIZE];
////int front, rear;
////void push(int x, int y)
////{
//// rear++;
//// rear = rear%QUEUESIZE;
//// q[rear].first = x;
//// q[rear].second = y;
////}
////pair<int, int> pop()
////{
//// front++;
//// front = front%QUEUESIZE;
//// return q[front];
////}
////bool safe(int x, int y)
////{
//// return x >= 0 && x < M && y >= 0 && y < N;
////}
////void bfs()
////{
//// visit[0][0][0] = 1;
//// push(0, 0);
//// while (rear != front)
//// {
//// pair<int, int> t = pop();
//// int tx, ty;
//// for (int i = 0; i < 4; i++)
//// {
//// tx = t.first + dx[i];
//// ty = t.second + dy[i];
//// if (safe(tx, ty))
//// {
//// if (map[ty][tx] == 1 && !visit[ty][tx][1] && visit[t.second][t.first][0])
//// {
//// visit[ty][tx][1] = visit[t.second][t.first][0] + 1;
//// push(tx, ty);
//// }
//// else if (!map[ty][tx])
//// {
//// bool flag = false;
//// if(!visit[ty][tx][0] && visit[t.second][t.first][0])
//// flag = visit[ty][tx][0] = visit[t.second][t.first][0] + 1;
//// if(!visit[ty][tx][1] && visit[t.second][t.first][1])
//// flag = visit[ty][tx][1] = visit[t.second][t.first][1] + 1;
////
//// if (flag)
//// push(tx, ty);
//// }
//// }
//// }
//// }
////}
////int main()
////{
//// scanf("%d%d", &N, &M);
//// for (int i = 0; i < N; i++)
//// {
//// scanf("%s", s);
//// for (int j = 0; j < M; j++)
//// map[i][j] = s[j] - '0';
//// }
//// bfs();
//// int& ret0 = visit[N - 1][M - 1][0];
//// int& ret1 = visit[N - 1][M - 1][1];
//// int ret = (ret0 < ret1) ? (ret0 > 0 ? ret0 : ret1) : (ret1 > 0 ? ret1 : ret0);
//// printf("%d\n", ret > 0 ? ret : -1);
////
//// return 0;
////}
////#include <iostream>
////#include <cstdio>
////#include <cstring>
////using namespace std;
////
////struct student
////{
//// char hak[30];
//// char name[10];
////};
////
////student stack[10];
////int top = 0;
////
////bool empty()
////{
//// return top == 0;
////}
////
////void push(char* hak, char* name)
////{
//// strcpy(stack[top].hak, hak);
//// strcpy(stack[top++].name, name);
////}
////
////student pop()
////{
//// return stack[--top];
////}
////
////int main()
////{
//// char tmp_hak[30];
//// char tmp_name[10];
//// for (int i = 0; i < 3; i++)
//// {
//// scanf("%s%s", tmp_hak, tmp_name);
//// push(tmp_hak, tmp_name);
//// }
//// student tmp;
//// for (int i = 0; i < 3; i++)
//// {
//// tmp = pop();
//// printf("hak : %s\n name : %s\n", tmp.hak, tmp.name);
//// }
////}
//
//
//#define _CRT_SECURE_NO_WARNINGS
//#include <stdio.h>
//#include <stdlib.h>
//
//int map[1001][1001];
//
//int main()
//{
// int row, col;
// int ci = 0;
// int count = 0;
// int counti = 0, countj = 0;
// int store_i[100] = { 0, };
// int store_j[100] = { 0, };
// int stack = 0;
//
// scanf("%d %d", &col, &row);
//
// if (2 <= col && col <= 1000)
// {
// if (2 <= row && row <= 1000)
// {
// int **m = malloc(sizeof(int *)*row); //2迭 Ҵ
//
// for (int i = 0; i < row; i++)
// {
// m[i] = malloc(sizeof(int) * col);
// }
//
// for (int i = 0; i < row; i++) //2迭
// {
// for (int j = 0; j < col; j++)
// {
// scanf("%d", &m[i][j]);
// }
// }
//
// while (1)
// {
// for (int i = 0; i < row; i++) //1ġŽ
// {
// for (int j = 0; j < col; j++)
// {
// if (m[i][j] == 1)
// {
// store_i[counti] = i; // 1 ִ ġ
// store_j[countj] = j;
// ++counti;
// ++countj;
// }
// }
// }
//
// for (ci = 0; ci < counti; ci++) //
// {
// if (m[store_i[ci] - 1][store_j[ci]] != 0 && m[store_i[ci] + 1][store_j[ci]] != 0 && m[store_i[ci]][store_j[ci] - 1] != 0 && m[store_i[ci]][store_j[ci] + 1] != 0)
// {
// stack++;
// printf("%d", count);
// break;
// }
// }
//
//
// for (ci = 0; ci < counti; ci++)
// {
// if (store_i[ci] - 1 <= 0)
// {
// m[store_i[ci] - 1][store_j[ci]] = m[0][store_j[ci]];
// if (m[store_i[ci] - 1][store_j[ci]] == 0)
// {
// m[store_i[ci] - 1][store_j[ci]] = 1;
// }
// }
//
// if (store_i[ci] + 1 >= row)
// {
// m[store_i[ci] + 1][store_j[ci]] = m[row][store_j[ci]];
// if (m[store_i[ci] + 1][store_j[ci]] == 0)
// {
// m[store_i[ci] + 1][store_j[ci]] = 1;
// }
// }
//
// if (store_j[ci] - 1 <= 0)
// {
// m[store_i[ci]][store_j[ci] - 1] = m[store_i[ci]][0];
// if (m[store_i[ci]][store_j[ci] - 1] == 0)
// {
// m[store_i[ci]][store_j[ci] - 1] = 1;
// }
// }
//
// if (store_j[ci] + 1 >= col)
// {
// m[store_i[ci]][store_j[ci] + 1] = m[store_i[ci]][col];
// if (m[store_i[ci]][store_j[ci] + 1] == 0)
// {
// m[store_i[ci]][store_j[ci] + 1] = 1;
// }
// }
// }
// count++;
// }
// }
// }
//}
// dfs bfs
//#include <iostream>
//#include <algorithm>
//#include <vector>
//#include <memory.h>
//#define QUEUESIZE 1000005
//using namespace std;
//
//vector<int> graph[1001];
//bool visit[1001];
//int N, M, V;
//int q[QUEUESIZE];
//int front, rear;
//void push(int x)
//{
// rear++;
// rear = rear % QUEUESIZE;
// q[rear] = x;
//}
//int pop()
//{
// front++;
// front = front % QUEUESIZE;
// return q[front];
//}
//void bfs(int n)
//{
// cout << n << " ";
// push(n);
// visit[n] = true;
// while (rear != front)
// {
// int t = pop();
// int ts = graph[t].size();
// for (int i = 0; i < ts; i++)
// {
// if (!visit[graph[t][i]])
// {
// cout << graph[t][i] << " ";
// visit[graph[t][i]] = true;
// push(graph[t][i]);
// }
// }
// }
//}
//void dfs(int n)
//{
// int size = graph[n].size();
// if (!size)
// return;
// visit[n] = true;
// cout << n << " ";
// for (int i = 0; i < size; i++)
// if (!visit[graph[n][i]])
// dfs(graph[n][i]);
//}
//int main()
//{
// cin >> N >> M >> V;
// int to, from;
// for (int i = 0; i < M; i++)
// {
// cin >> from >> to;
// graph[from].push_back(to);
// graph[to].push_back(from);
// }
// for (int i = 0; i < N; i++)
// sort(graph[i].begin(), graph[i].end());
// dfs(V);
// memset(visit, false, sizeof(visit));
// cout << "\n";
// bfs(V);
// cout << "\n";
// return 0;
//}
// ġ
//#include <iostream>
//#include <string>
//#include <memory.h>
//#define QUEUESIZE 100005
//using namespace std;
//
//int map[1001][1001];
//int visit[1001][1001];
//int H, W, N;
//pair<int, int> q[QUEUESIZE];
//int front, rear;
//int dx[4] = { 1, 0, -1, 0 };
//int dy[4] = { 0, 1, 0, -1 };
//int st = 1;
//void push(int x, int y)
//{
// rear++;
// rear = rear % QUEUESIZE;
// q[rear].first = x;
// q[rear].second = y;
//}
//pair<int, int> pop()
//{
// front++;
// front = front % QUEUESIZE;
// return q[front];
//}
//bool safe(int x, int y)
//{
// return x >= 0 && x < W && y >= 0 && y < H;
//}
//
//int bfs()
//{
// while (rear != front)
// {
// pair<int, int> t = pop();
// int tx, ty;
// for (int i = 0; i < 4; i++)
// {
// tx = t.first + dx[i];
// ty = t.second + dy[i];
// if (safe(tx, ty) && !visit[ty][tx] && map[ty][tx] != -1)
// {
// visit[ty][tx] = visit[t.second][t.first]+1;
// if (map[ty][tx] == st)
// {
// if (st == N)
// return visit[ty][tx];
// st++;
// int tmp = visit[ty][tx];
// memset(visit, false, sizeof(visit));
// front = rear = 0;
// push(tx, ty);
// visit[ty][tx] = tmp;
// break;
// }
//
// push(tx, ty);
// }
// }
// }
//}
//int main()
//{
// cin >> H >> W >> N;
// string s;
// for (int i = 0; i < H; i++)
// {
// cin >> s;
// for (int j = 0; s[j]; j++)
// {
// if (s[j] == 'S')
// {
// push(j, i);
// visit[i][j] = 1;
// }
// else if (s[j] == 'X')
// map[i][j] = -1;
// else if (s[j] >= '1' && s[j] <= '9')
// map[i][j] = s[j] - '0';
// }
// }
// cout << bfs()-1 << "\n";
// return 0;
//}
// ֱ
//#include<iostream>
//#define INF 2e10
//using namespace std;
//typedef long long ll;
//int N;
//int arr[101];
//int oper[4];
//ll max_v = -INF;
//ll min_v = INF;
//void func(int n, ll val)
//{
// if (n == N-1)
// {
// if (val > max_v)
// max_v = val;
// if (val < min_v)
// min_v = val;
// return;
// }
//
// for (int i = 0; i < 4; i++)
// if (oper[i])
// {
// oper[i]--;
// switch (i)
// {
// case 0:
// func(n + 1, val + arr[n + 1]);
// break;
// case 1:
// func(n + 1, val - arr[n + 1]);
// break;
// case 2:
// func(n + 1, val * arr[n + 1]);
// break;
// case 3:
// func(n + 1, val / arr[n + 1]);
// break;
// }
// oper[i]++;
// }
//}
//int main()
//{
// cin >> N;
// for (int i = 0; i < N; i++)
// cin >> arr[i];
// for (int i = 0; i < 4; i++)
// cin >> oper[i];
// func(0, arr[0]);
// cout << max_v << "\n";
// cout << min_v << "\n";
// return 0;
//}
// Ʈ ̵
//#include<iostream>
//#include<memory.h>
//#define QUEUESIZE 90005
//using namespace std;
//
//int visit[301][301];
//int T, l;
//int sx, sy, ex, ey;
//int dx[8] = { 1, 2, 2, 1, -1, -2 ,-2 ,-1 };
//int dy[8] = { -2, -1, 1, 2, 2, 1, -1, -2 };
//pair<int, int> q[QUEUESIZE];
//int front, rear;
//void push(int x, int y)
//{
// rear++;
// rear = rear % QUEUESIZE;
// q[rear].first = x;
// q[rear].second = y;
//}
//pair<int, int>pop()
//{
// front++;
// front = front % QUEUESIZE;
// return q[front];
//}
//bool safe(int x, int y)
//{
// return x >= 0 && x < l && y >= 0 && y < l;
//}
//int bfs()
//{
// while (rear != front)
// {
// pair<int, int> t = pop();
// int tx, ty;
// for (int i = 0; i < 8; i++)
// {
// tx = t.first + dx[i];
// ty = t.second + dy[i];
// if (safe(tx, ty) && !visit[ty][tx])
// {
// visit[ty][tx] = visit[t.second][t.first] + 1;
// if (tx == ex && ty == ey)
// return visit[ty][tx];
// push(tx, ty);
// }
// }
// }
// return 1;
//}
//int main()
//{
// cin >> T;
// for (int tc = 0; tc < T; tc++)
// {
// cin >> l;
// memset(visit, false, sizeof(visit));
// front = rear = 0;
// cin >> sx >> sy >> ex >> ey;
// push(sx, sy);
// visit[sy][sx] = 1;
// cout << bfs() - 1 << "\n";
// }
// return 0;
//}
//
//#include <iostream>
//#include <string>
//#include <memory.h>
//#define QUEUESIZE 2505
//using namespace std;
//
//int map[51][51];
//int visit[51][51];
//int W, H;
//int dx[4] = { 1, 0, -1, 0 };
//int dy[4] = { 0, 1, 0, -1 };
//pair<int, int> q[QUEUESIZE];
//int front, rear;
//int ret = -1e9;
//void push(int x, int y)
//{
// rear++;
// rear = rear % QUEUESIZE;
// q[rear].first = x;
// q[rear].second = y;
//}
//pair<int, int>pop()
//{
// front++;
// front = front % QUEUESIZE;
// return q[front];
//}
//bool safe(int x, int y)
//{
// return x >= 0 && x < W && y >= 0 && y < H;
//}
//void bfs(int x, int y)
//{
// int cur_max = -1e9;
// memset(visit, 0, sizeof(visit));
// push(x, y);
// visit[y][x] = 1;
// while (rear != front)
// {
// pair<int, int> t = pop();
// int tx, ty;
// for (int i = 0; i < 4; i++)
// {
// tx = t.first + dx[i];
// ty = t.second + dy[i];
// if (safe(tx, ty) && !visit[ty][tx] && !map[ty][tx])
// {
// visit[ty][tx] = visit[t.second][t.first] + 1;
// push(tx, ty);
// if (cur_max < visit[ty][tx])
// cur_max = visit[ty][tx];
// }
// }
// }
// if (ret < cur_max)
// ret = cur_max;
//}
//int main()
//{
// cin >> H >> W;
// string s;
// for (int i = 0; i < H; i++)
// {
// cin >> s;
// for (int j = 0; s[j]; j++)
// if (s[j] == 'W')
// map[i][j] = 1;
// else
// map[i][j] = 0;
// }
//
// for (int i = 0; i < H; i++)
// for (int j = 0; j < W; j++)
// if(!map[i][j])
// bfs(j, i);
// cout << ret - 1 << "\n";
// return 0;
//}
//
//#include<iostream>
//#include<memory.h>
//#define QUEUESZIE 90005
//using namespace std;
//
//int map[301][301];
//bool visit[301][301];
//int dx[4] = { 1, 0, -1, 0 };
//int dy[4] = { 0, 1, 0, -1 };
//int N, M;
//pair<int, int> q[QUEUESZIE];
//int front, rear, result;
//void push(int x, int y)
//{
// rear++;
// rear = rear % QUEUESZIE;
// q[rear].first = x;
// q[rear].second = y;
//}
//pair<int, int>pop()
//{
// front++;
// front = front % QUEUESZIE;
// return q[front];
//}
//bool safe(int x, int y)
//{
// return x >= 0 && x < M && y >= 0 && y < N;
//}
//void bfs(int x, int y)
//{
// push(x, y);
// visit[y][x] = true;
// while (rear != front)
// {
// pair<int, int> t = pop();
// int tx, ty;
// for (int i = 0; i < 4; i++)
// {
// tx = t.first + dx[i];
// ty = t.second + dy[i];
// if (safe(tx, ty))
// {
// if (map[ty][tx] && !visit[ty][tx])
// {
// visit[ty][tx] = true;
// push(tx, ty);
// }
// else if (!map[ty][tx] && !visit[ty][tx])
// {
// map[t.second][t.first]--;
// if (map[t.second][t.first] < 0)
// map[t.second][t.first] = 0;
// }
// }
// }
// }
//}
//int main()
//{
// cin >> N >> M;
// for (int i = 0; i < N; i++)
// for (int j = 0; j < M; j++)
// cin >> map[i][j];
//
// while (1)
// {
// int cnt = 0;
// memset(visit, false, sizeof(visit));
// for(int i=0; i<N; i++)
// for(int j=0; j<M; j++)
// if (map[i][j] && !visit[i][j])
// {
// cnt++;
// bfs(j, i);
// }
// if (!cnt)
// {
// cout << "0\n";
// break;
// }
// else if (cnt >= 2)
// {
// cout << result << "\n";
// break;
// }
// result++;
// }
// return 0;
//}
//
//#include<iostream>
//#include<string>
//#include<memory.h>
//#define QUEUESIZE 1000005
//using namespace std;
//
//struct qu {
// int front, rear;
// pair<int, int> q[QUEUESIZE];
// qu() { front = rear = 0;}
// void push(int x, int y)
// {
// rear++;
// rear = rear % QUEUESIZE;
// q[rear].first = x;
// q[rear].second = y;
// }
// pair<int, int> pop()
// {
// front++;
// front = front % QUEUESIZE;
// return q[front];
// }
//};
//qu q_f, q_s;
//int map[1001][1001];
//int visit_s[1001][1001];
//int visit_f[1001][1001];
//int dx[4] = { 1, 0, -1, 0 };
//int dy[4] = { 0, 1, 0, -1 };
//int T, W, H;
//string s;
//bool safe(int x, int y)
//{
// return x >= 0 && x < W && y >= 0 && y < H;
//}
//void bfs_f()
//{
// while (q_f.front != q_f.rear)
// {
// pair<int, int> t = q_f.pop();
// int tx, ty;
// for (int i = 0; i < 4; i++)
// {
// tx = t.first + dx[i];
// ty = t.second + dy[i];
// if (safe(tx, ty) && !map[ty][tx] && !visit_f[ty][tx])
// {
// visit_f[ty][tx] = visit_f[t.second][t.first] + 1;
// q_f.push(tx, ty);
// }
// }
// }
//}
//int bfs_s()
//{
// while (q_s.front != q_s.rear)
// {
// pair<int, int> t = q_s.pop();
// int tx, ty;
// for (int i = 0; i < 4; i++)
// {
// tx = t.first + dx[i];
// ty = t.second + dy[i];
// if (safe(tx, ty) && !map[ty][tx] && !visit_s[ty][tx]
// && (visit_f[ty][tx] > visit_s[t.second][t.first] + 1 || !visit_f[ty][tx]))
// {
// visit_s[ty][tx] = visit_s[t.second][t.first] + 1;
// q_s.push(tx, ty);
// }
// else if (!safe(tx, ty))
// {
// q_s.front = q_s.rear = 0;
// return visit_s[t.second][t.first];
// }
// }
// }
// return -1;
//}
//int main()
//{
// cin >> T;
// for (int tc = 0; tc < T; tc++)
// {
// memset(visit_s, 0, sizeof(visit_s));
// memset(visit_f, 0, sizeof(visit_f));
//
// cin >> W >> H;
// for (int i = 0; i < H; i++)
// {
// cin >> s;
// for (int j = 0; s[j]; j++)
// {
// switch (s[j])
// {
// case '#':
// map[i][j] = -1;
// break;
// case '.':
// map[i][j] = 0;
// break;
// case '*':
// q_f.push(j, i);
// visit_f[i][j] = 1;
// break;
// case '@':
// q_s.push(j, i);
// visit_s[i][j] = 1;
// break;
// }
// }
// }
// bfs_f();
// int ret = bfs_s();
// if (ret == -1)
// cout << "IMPOSSIBLE\n";
// else
// cout << ret << "\n";
// }
// return 0;
//}
//丶2
//#include <cstdio>
//#include <iostream>
//#define QUEUESIZE 1000005
//using namespace std;
//
//struct p {
// int x, y, z;
//};
//int M, N, H;
//int map[101][101][101];
//int dx[6] = { 1, 0, -1, 0, 0, 0 };
//int dy[6] = { 0, 1, 0, -1, 0, 0 };
//int dz[6] = { 0, 0, 0, 0, 1, -1 };
//p q[QUEUESIZE];
//int front, rear;
//void push(int x, int y, int z)
//{
// rear++;
// rear = rear % QUEUESIZE;
// q[rear].x = x;
// q[rear].y = y;
// q[rear].z = z;
//}
//p pop()
//{
// front++;
// front = front % QUEUESIZE;
// return q[front];
//}
//
//bool safe(int x, int y, int z)
//{
// return x >= 0 && x < M && y >= 0 && y < N && z >= 0 && z < H;
//}
//
//void bfs()
//{
// while (front != rear)
// {
// p t = pop();
// int tx, ty, tz;
// for (int i = 0; i < 6; i++)
// {
// tx = t.x + dx[i]; ty = t.y + dy[i]; tz = t.z + dz[i];
// if (safe(tx, ty, tz) && !map[tz][ty][tx])
// {
// map[tz][ty][tx] = map[t.z][t.y][t.x] + 1;
// push(tx, ty, tz);
// }
// }
// }
//}
//
//int main()
//{
// scanf("%d%d%d", &M, &N, &H);
// for (int i = 0; i < H; i++)
// for (int j = 0; j < N; j++)
// for (int k = 0; k < M; k++)
// {
// scanf("%d", &map[i][j][k]);
// if (map[i][j][k] == 1)
// push(k, j, i);
// }
// bfs();
// int ret = 0;
// for (int i = 0; i < H; i++)
// for (int j = 0; j < N; j++)
// for (int k = 0; k < M; k++)
// {
// if (!map[i][j][k])
// {
// printf("-1\n");
// return 0;
// }
// if (ret < map[i][j][k])
// ret = map[i][j][k];
// }
// printf("%d\n", ret-1);
// return 0;
//}
//N Queen
//#include<iostream>
//#include<cstdio>
//#include<memory.h>
//using namespace std;
//
//int N;
//int dx[3] = { 1, 0 ,-1 };
//int dy[3] = { 1, 1, 1 };
//int ret;
//void func(int n, int* left, int* mid, int* right)
//{
// if (n == N)
// {
// ret++;
// return;
// }
//
// int n_left[16] = { 0, };
// int n_mid[16] = { 0, };
// int n_right[16] = { 0, };
// for (int i = 0; i < N; i++)
// {
// if (left[i])
// if (i > 0)
// n_left[i - 1] = 1;
// if (mid[i])
// n_mid[i] = 1;
// if (right[i])
// if (i < N - 1)
// n_right[i + 1] = 1;
//
// }
// for (int i = 0; i < N; i++)
// {
// if (!n_left[i] && !n_right[i] && !n_mid[i])
// {
// n_left[i] = n_right[i] = n_mid[i] = 1;
// func(n + 1, n_left, n_mid, n_right);
// n_left[i] = n_right[i] = n_mid[i] = 0;
// }
// }
//}
//int main()
//{
// int left[16] = { 0, };
// int mid[16] = { 0, };
// int right[16] = { 0, };
// scanf("%d", &N);
// func(0, left, mid, right);
// printf("%d\n", ret);
//
//
// return 0;
//}
//#include<iostream>
//#include<cstdio>
//using namespace std;
//
//int N;
//int ret;
//void func(int n, int left, int mid, int right)
//{
// if (n == N)
// {
// ret++;
// return;
// }
//
// int n_left = 0;
// int n_mid = 0;
// int n_right = 0;
// for (int i = 1; i < 1<<N; i = i<<1)
// {
// if (left & i)
// n_left |= i<<1;
// if (mid & i)
// n_mid |= i;
// if (right&i)
// n_right |= i>>1;
// }
// for (int i = 1; i < 1<<N; i = i<<1)
// {
// if (!(n_left &i) && !(n_right&i) && !(n_mid&i))
// {
// n_left |= i;
// n_right |= i;
// n_mid |= i;
// func(n + 1, n_left, n_mid, n_right);
// n_left &= ~i;
// n_right &= ~i;
// n_mid &= ~i;
// }
// }
//}
//int main()
//{
// int left = 0;
// int mid = 0;
// int right = 0;
// scanf("%d", &N);
// func(0, left, mid, right);
// printf("%d\n", ret);
// return 0;
//}
// ȣ
//#include<iostream>
//#include<cstdio>
//#include<algorithm>
//using namespace std;
//
//int L, C;
//char arr[16];
//char ret[16];
//void func(int l, int idx, int c, int v)
//{
// if (l == L)
// {
// if (c >= 2 && v >= 1)
// printf("%s\n", ret);
// return;
// }
//
//
// for (int i = idx; i < C; i++)
// {
// ret[l] = arr[i];
// if (ret[l] == 'a' || ret[l] == 'e' || ret[l] == 'o'
// || ret[l] == 'i' || ret[l] == 'u')
// func(l + 1, i+1, c, v + 1);
// else
// func(l + 1, i+1, c+1, v);
// ret[l] = '\0';
// }
//}
//int main()
//{
// scanf("%d %d", &L, &C);
// for (int i = 0; i < C; i++)
// scanf(" %c", &arr[i]);
// sort(arr, arr + C);
// func(0,0,0,0);
// return 0;
//}
//ACM Craft
//#include<iostream>
//#include<cstdio>
//#include<vector>
//#include<memory.h>
//using namespace std;
//
//int T, N, K, W;
//int to, from;
//int time[1001];
//vector<int> graph[1001];
//bool visit[1001];
//
//int dfs(int n)
//{
// int size = graph[n].size();
// if (size == 0)
// return 0;
// int max = 0;
// for (int i = 0; i < size; i++)
// {
// int pre = graph[n][i];
// if (!visit[pre])
// {
// visit[pre] = true;
// time[pre] += dfs(pre);
// }
// if (max < time[pre])
// max = time[pre];
// }
// return max;
//}
//
//int main()
//{
// scanf("%d", &T);
// for (int tc = 0; tc < T; tc++)
// {
// memset(time, 0, sizeof(time));
// memset(visit, 0, sizeof(visit));
// for (int i = 1; i <= N; i++)
// graph[i].clear();
// scanf("%d%d", &N, &K);
// for (int i = 1; i <= N; i++)
// scanf("%d", &time[i]);
// for (int i = 0; i < K; i++)
// {
// scanf("%d%d", &to, &from);
// graph[from].push_back(to);
// }
// scanf("%d", &W);
// printf("%d\n", dfs(W)+time[W]);
// }
// return 0;
//}
//#include<iostream>
//#include<cstdio>
//#include<vector>
//#include<memory.h>
//using namespace std;
//
//int T, N, K, W;
//int to, from;
//int time[1001];
//vector<int> graph[1001];
//int visit[1001];
//
//int dfs(int n)
//{
// int size = graph[n].size();
// if (size == 0)
// return 0;
// int max = -1e9;
// for (int i = 0; i < size; i++)
// {
// int pre = graph[n][i];
// if (visit[pre] == -1)
// visit[pre] += (dfs(pre) + time[pre] +1);
// if (max < visit[pre])
// max = visit[pre];
// }
// return max;
//}
//
//int main()
//{
// scanf("%d", &T);
// for (int tc = 0; tc < T; tc++)
// {
// memset(time, 0, sizeof(time));
// memset(visit, -1, sizeof(visit));
// for (int i = 1; i <= N; i++)
// graph[i].clear();
// scanf("%d%d", &N, &K);
// for (int i = 1; i <= N; i++)
// scanf("%d", &time[i]);
// for (int i = 0; i < K; i++)
// {
// scanf("%d%d", &to, &from);
// graph[from].push_back(to);
// }
// scanf("%d", &W);
// printf("%d\n", dfs(W) + time[W]);
// }
// return 0;
//} | true |
273820a37d315ce5b868f60c8e08c8adc9f9f092 | C++ | tensorflow/tensorflow | /tensorflow/tsl/platform/stringprintf_test.cc | UTF-8 | 3,785 | 2.625 | 3 | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla",
"BSD-2-Clause"
] | permissive | /* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/tsl/platform/stringprintf.h"
#include <string>
#include "tensorflow/tsl/platform/test.h"
namespace tsl {
namespace strings {
namespace {
TEST(PrintfTest, Empty) {
EXPECT_EQ("", Printf("%s", string().c_str()));
EXPECT_EQ("", Printf("%s", ""));
}
TEST(PrintfTest, Misc) {
// MSVC does not support $ format specifier.
#if !defined(_MSC_VER)
EXPECT_EQ("123hello w", Printf("%3$d%2$s %1$c", 'w', "hello", 123));
#endif // !_MSC_VER
}
TEST(AppendfTest, Empty) {
string value("Hello");
const char* empty = "";
Appendf(&value, "%s", empty);
EXPECT_EQ("Hello", value);
}
TEST(AppendfTest, EmptyString) {
string value("Hello");
Appendf(&value, "%s", "");
EXPECT_EQ("Hello", value);
}
TEST(AppendfTest, String) {
string value("Hello");
Appendf(&value, " %s", "World");
EXPECT_EQ("Hello World", value);
}
TEST(AppendfTest, Int) {
string value("Hello");
Appendf(&value, " %d", 123);
EXPECT_EQ("Hello 123", value);
}
TEST(PrintfTest, Multibyte) {
// If we are in multibyte mode and feed invalid multibyte sequence,
// Printf should return an empty string instead of running
// out of memory while trying to determine destination buffer size.
// see b/4194543.
char* old_locale = setlocale(LC_CTYPE, nullptr);
// Push locale with multibyte mode
setlocale(LC_CTYPE, "en_US.utf8");
const char kInvalidCodePoint[] = "\375\067s";
string value = Printf("%.*s", 3, kInvalidCodePoint);
// In some versions of glibc (e.g. eglibc-2.11.1, aka GRTEv2), snprintf
// returns error given an invalid codepoint. Other versions
// (e.g. eglibc-2.15, aka pre-GRTEv3) emit the codepoint verbatim.
// We test that the output is one of the above.
EXPECT_TRUE(value.empty() || value == kInvalidCodePoint);
// Repeat with longer string, to make sure that the dynamically
// allocated path in StringAppendV is handled correctly.
int n = 2048;
char* buf = new char[n + 1];
memset(buf, ' ', n - 3);
memcpy(buf + n - 3, kInvalidCodePoint, 4);
value = Printf("%.*s", n, buf);
// See GRTEv2 vs. GRTEv3 comment above.
EXPECT_TRUE(value.empty() || value == buf);
delete[] buf;
setlocale(LC_CTYPE, old_locale);
}
TEST(PrintfTest, NoMultibyte) {
// No multibyte handling, but the string contains funny chars.
char* old_locale = setlocale(LC_CTYPE, nullptr);
setlocale(LC_CTYPE, "POSIX");
string value = Printf("%.*s", 3, "\375\067s");
setlocale(LC_CTYPE, old_locale);
EXPECT_EQ("\375\067s", value);
}
TEST(PrintfTest, DontOverwriteErrno) {
// Check that errno isn't overwritten unless we're printing
// something significantly larger than what people are normally
// printing in their badly written PLOG() statements.
errno = ECHILD;
string value = Printf("Hello, %s!", "World");
EXPECT_EQ(ECHILD, errno);
}
TEST(PrintfTest, LargeBuf) {
// Check that the large buffer is handled correctly.
int n = 2048;
char* buf = new char[n + 1];
memset(buf, ' ', n);
buf[n] = 0;
string value = Printf("%s", buf);
EXPECT_EQ(buf, value);
delete[] buf;
}
} // namespace
} // namespace strings
} // namespace tsl
| true |
09b760c23494767f216856b2ace222721857de95 | C++ | SpringMT/intruduction_to_algorithms | /2_getting_started/LinearSearchRec.cc | UTF-8 | 880 | 3.65625 | 4 | [] | no_license | #include <stdio.h>
#include <iostream>
#include <string>
// http://www.geeksforgeeks.org/linear-search/
void printArray(int arr[], int n) {
int i;
for (i=0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
}
void printInfo(std::string test, int n) {
printf("[INFO] %s %d \n", test.c_str(), n);
}
int binarySearch(int arr[], int start, int end, int target) {
if (end >= start ) {
int mid = start + (end - start) / 2;
printInfo("mid", arr[mid]);
if (arr[mid] == target) return mid;
if (arr[mid] > target) return binarySearch(arr, start, mid - 1, target);
return binarySearch(arr, mid + 1, end, target);
}
return -1;
}
int main() {
int arr[] = {2, 18, 25, 27, 43, 44, 79};
int n = sizeof(arr)/sizeof(arr[0]);
int target = 44;
int res = binarySearch(arr, 0, n - 1, target);
printInfo("Result", res);
return 0;
}
| true |
4a812ba7d950abfb342d66e449ce27a174e80331 | C++ | sebasluna/taller3 | /Ctaller3IF.cpp | UTF-8 | 388 | 3.25 | 3 | [] | no_license | //NOMBRE: Par o Impar
//AUTOR: Luis Sebastian Urbano Luna
//FECHA:
//RESUMEN: Programa para saber si el numero es par o impar
#include <iostream>
#include <stdio.h>
using namespace std;
int main(){
int lNumero;
printf("ingrese su numero\n");
scanf("%d",&lNumero);
if(lNumero%2==0){
printf("el numero es Par\n");
}else{
printf("el numero es Impar\n");
}
return 0;
}
| true |
d3f212adf84f588c86f6a5008ab32efb8cac91df | C++ | tonipes/swift-c-interop | /libraryx/libraryx.cpp | UTF-8 | 203 | 2.515625 | 3 | [] | no_license | #include "libraryx.h"
long factorial(long n) {
long result = 1;
for(int i = 1; i <= n; i++) {
result = result * i;
}
return result;
}
long addFoo(Foo foo) {
return foo.a + foo.b;
}
| true |
3a0dcd4ac186fee2076f205d79b5465cf1fddfa0 | C++ | RyanAdamsGD/RayTracer | /RayTracer/ConvexPartCylinder.h | UTF-8 | 820 | 2.640625 | 3 | [] | no_license | #ifndef CONVEXPARTCYLINER_H
#define CONVEXPARTCYLINER_H
#include "GeometricObject.h"
class ConvexPartCylinder:public GeometricObject
{
BoundingBox bbox;
BoundingBox createBoundingBox()const;
float y0, y1, radius, inverseRadius, azimuthMin, azimuthMax;
public:
ConvexPartCylinder(void);
ConvexPartCylinder(float y0, float y1, float radius, float azimuthMax = 360.0f, float azimuthMin = 0.0f);
virtual ~ConvexPartCylinder(void);
virtual BoundingBox getBoundingBox()const;
virtual bool shadowHit(const Ray& ray, float& tmin) const;
virtual bool hit(const Ray& ray, float& tmin, ShadeRec& sr) const;
void setY0(float value);
void setY1(float value);
void setRadius(float value);
inline void setAzimuthMin(float value) {azimuthMin=value;}
inline void setAzimuthMax(float value) {azimuthMax=value;}
};
#endif | true |
58f673b312c986af06da34018996278ea551fab3 | C++ | adityasunny1189/C-PlusPlus_Basics | /codingNinjas/Recursion/print_pattern.cpp | UTF-8 | 402 | 3.34375 | 3 | [] | no_license | #include <iostream>
using namespace std;
int printPattern(int n) {
if(n <= 0) {
cout << n << " ";
return n + 5;
}
cout << n << " ";
int smallAns = printPattern(n - 5);
cout << smallAns << " ";
return smallAns + 5;
}
int main() {
//code
int t;
cin >> t;
while(t--) {
int n;
cin >> n;
int no = printPattern(n);
cout << endl;
}
return 0;
}
| true |
f07d2db1d45ccb2c5bf4eda39bf461361ed14941 | C++ | Ashna-Nawar-Ahmed/2nd-year-2nd-semester | /Algorithm Lab/Offlines/offline 7/bellmanford_anika.cpp | UTF-8 | 1,694 | 3.1875 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int d[100],parent[100];
struct edge
{
int u,v,w;
};
vector<edge> edges;
void relax(int u,int v,int w)
{
if(d[v]>(d[u]+w))
{
d[v]=(d[u]+w);
parent[v]=u;
}
}
void find_path(int des)
{
if(parent[des]==-1)
return;
else
find_path(parent[des]);
cout<<" "<<des<<" ";
}
void bellFord(int st,int nodes)
{
for(int i=0;i<nodes;i++)
{
d[i]=INT_MAX;
parent[i]=-1;
}
d[st]=0;
for(int i=0;i<nodes-1;i++)
{
int sz = edges.size();
for(int j=0;j<sz;j++)
{
edge e=edges[j];
relax(e.u,e.v,e.w);
}
}
int sz=edges.size();
for(int i=0;i<sz;i++)
{
edge e=edges[i];
if(d[e.v]>(d[e.u]+e.w))
{
cout<<"\nThere is a negative loop in the graph.....\n";
return;
}
}
cout<<"Distance from all node from source and path"<<endl;
cout<<"Source->Destination\tDistance\tPath"<<endl;
for(int i=0;i<nodes;i++)
{
cout<<" "<<st<<" -> "<<i<<"\t :\t "<<d[i]<<"\t\t";
if(i>0)
{
cout<<st<<" ";
find_path(i);
}
else
{
//cout<<"No path";
cout<<"No Path";
//cout<<"1";
}
cout<<endl;
}
}
int main()
{
int N,E;
cout<<"Nodes: ";
cin>>N;
cout<<"Edges: ";
cin>>E;
cout<<"Input Graph:\n";
for(int i=0;i<E;i++)
{
edge a;
cin>>a.u>>a.v>>a.w;
edges.push_back(a);
}
//cout<<"Input Start and End point:";
// int st,en;
//cin>>st;
bellFord(0,N);
return 0;
}
| true |
ab8b609cece1ac1149e9f257c607a129bf766294 | C++ | YichengZhong/Top-Interview-Questions | /665.非递减数列/checkPossibility.cpp | UTF-8 | 494 | 2.734375 | 3 | [
"MIT"
] | permissive | class Solution {
public:
bool checkPossibility(vector<int>& nums) {
int flag=0;
for(int i=0;i<nums.size()-1;++i)
{
if(nums[i]<=nums[i+1])
continue;
else
{
flag++;
if(flag>1) return false;
if (i > 0 && nums[i+1] < nums[i-1])
{
nums[i + 1] = nums[i];
}
}
}
return true;
}
}; | true |
feefb0dc272390d0bb81dd773e5465ebdadbae02 | C++ | cstegmayr/bitsoccer | /src/Brick.cpp | UTF-8 | 8,175 | 2.796875 | 3 | [] | no_license | #include "Brick.h"
#include "Renderer.h"
#include "Vec3.h"
#include <string.h> // For memset
#define _USE_MATH_DEFINES
#include <math.h>
namespace bitsoccer
{
Brick::Brick()
: m_row(0)
, m_col(0)
, m_originX(0)
, m_originY(0)
{
// initialize everything green
for (int i = 0; i < Direction::NumDirections; ++i)
m_colors[i] = Color::Green;
m_hitSurface.state = HitState::Released;
m_hitSurface.width = GetSize();
m_hitSurface.height = GetSize();
Renderer::RegisterHitSurface(&m_hitSurface);
}
Brick::~Brick()
{
Renderer::UnregisterHitSurface(&m_hitSurface);
}
void Brick::SetColor( Direction::Type dir, Color::Type color )
{
m_colors[dir] = color;
}
void Brick::NotifyPosition( u32 row, u32 col, BrickAnimation::Type animationType )
{
if (animationType != BrickAnimation::None)
{
CreateKeyFramesToPos(row, col, animationType);
}
m_row = row;
m_col = col;
m_hitSurface.startX = GetX();
m_hitSurface.startY = GetY();
}
Color::Type Brick::GetColor( Direction::Type dir ) const
{
return m_colors[dir];
}
bool Brick::IsGoal( Player::Type player )
{
for ( u32 i = 0; i < Direction::NumDirections; ++i )
{
// Definition of a goal is that all colors are the same.
// Player::Red == Color::Red and Player::Blue == Color::Blue
if ( m_colors[i] != (Color::Type)player )
return false; // If any of the colors differ from the player-color, this is no goal
}
// All colors are same as player color.
return true;
}
void Brick::RotateCCW()
{
Color::Type first = m_colors[0];
m_colors[0] = m_colors[1];
m_colors[1] = m_colors[2];
m_colors[2] = m_colors[3];
m_colors[3] = first;
}
void Brick::RotateCW()
{
Color::Type first = m_colors[3];
m_colors[3] = m_colors[2];
m_colors[2] = m_colors[1];
m_colors[1] = m_colors[0];
m_colors[0 ] = first;
}
Vec3 ColorDarken( const Vec3& color )
{
double darkMod = 0.8;
Vec3 newColor = color;// Vec3(darkMod, darkMod, darkMod) * color;
return newColor;
}
Vec3 ColorPuls( const Vec3& color )
{
double pulse_time = 2.0;
double m = cosf((modf(glfwGetTime() / pulse_time, &pulse_time)*2.0-1.0) * M_PI) * 0.2;
Vec3 pulseCol(color.r > color.g && color.r > color.b, color.g > color.r && color.g > color.b, color.b > color.r && color.b > color.g);
pulseCol *= m;
Vec3 newColor = pulseCol + color;
return newColor;
}
void Brick::Draw(BrickMode::Type brickMode, Color::Type playerColor)
{
const Vec3 colors[] = {
Vec3(0.7f, 0.0f, 0.0f), // Red
Vec3(0.2f, 0.2f, 0.8f), // Blue
Vec3(0.0f, 0.6f, 0.0f), // Green
Vec3(0.7f, 0.0f, 0.0f), // RedGoal
Vec3(0.0f, 0.0f, 0.7f)}; // BlueGoal
u32 size = GetSize();
u32 posX = GetX();
u32 posY = GetY();
s32 depthOffset = 0;
if (m_currentAnimation.HasKeyFrames())
{
posX = (u32)m_currentAnimation.GetCurrentFrame().position.x;
posY = (u32)m_currentAnimation.GetCurrentFrame().position.y;
depthOffset += 2;
}
u32 halfSize = size / 2;
u32 width = 8;
u32 centerX = posX + halfSize;
u32 centerY = posY + halfSize;
Vec3 brickColor(0.5f, 0.5f, 0.5f);
if ( brickMode == BrickMode::Normal )
brickColor = Vec3( 0.8f, 0.8f, 0.8f );
if ( brickMode & BrickMode::RedGoal )
brickColor = brickColor * Vec3( 1.0f, 0.0f, 0.0f );
if ( brickMode & BrickMode::BlueGoal )
brickColor = brickColor * Vec3( 0.0f, 0.0f, 1.0f );
if ( brickMode & BrickMode::PossibleMove )
brickColor = brickColor * Vec3( 1.9f, 0.05f, 1.9f );
glBegin(GL_TRIANGLES);
{
glColor3f(brickColor.r, brickColor.g, brickColor.b );
glVertex3i(posX, posY, depthOffset);
glColor3f(brickColor.r, brickColor.g, brickColor.b );
glVertex3i(posX, posY+size, depthOffset);
glColor3f(brickColor.r, brickColor.g, brickColor.b );
glVertex3i(posX+size, posY, depthOffset);
// Background upper
glColor3f(brickColor.r, brickColor.g, brickColor.b );
glVertex3i(posX+size, posY+size, depthOffset);
glColor3f(brickColor.r, brickColor.g, brickColor.b );
glVertex3i(posX+size, posY, depthOffset);
glColor3f(brickColor.r, brickColor.g, brickColor.b );
glVertex3i(posX, posY+size, depthOffset);
// TRI NORTH
Vec3 color = colors[m_colors[Direction::North]];
if ( m_colors[Direction::North] == playerColor && m_colors[Direction::North] != Color::Green )
color = bitsoccer::ColorPuls(color);
else if ( m_colors[Direction::North] != Color::Green )
color = bitsoccer::ColorDarken(color);
glColor3f(color.r, color.g, color.b);
glVertex3i(centerX, centerY, 1+depthOffset);
glColor3f(color.r, color.g, color.b);
glVertex3i(centerX+width, centerY+halfSize, 1+depthOffset);
glColor3f(color.r, color.g, color.b);
glVertex3i(centerX-width, centerY+halfSize, 1+depthOffset);
// TRI EAST
color = colors[m_colors[Direction::East]];
if ( m_colors[Direction::East] == playerColor && m_colors[Direction::East] != Color::Green )
color = bitsoccer::ColorPuls(color);
else if ( m_colors[Direction::East] != Color::Green )
color = bitsoccer::ColorDarken(color);
glColor3f(color.r, color.g, color.b);
glVertex3i(centerX, centerY, 1+depthOffset);
glColor3f(color.r, color.g, color.b);
glVertex3i(centerX+halfSize, centerY+width, 1+depthOffset);
glColor3f(color.r, color.g, color.b);
glVertex3i(centerX+halfSize, centerY-width, 1+depthOffset);
// TRI SOUTH
color = colors[m_colors[Direction::South]];
if ( m_colors[Direction::South] == playerColor && m_colors[Direction::South] != Color::Green )
color = bitsoccer::ColorPuls(color);
else if ( m_colors[Direction::South] != Color::Green )
color = bitsoccer::ColorDarken(color);
glColor3f(color.r, color.g, color.b);
glVertex3i(centerX, centerY, 1+depthOffset);
glColor3f(color.r, color.g, color.b);
glVertex3i(centerX+width, centerY-halfSize, 1+depthOffset);
glColor3f(color.r, color.g, color.b);
glVertex3i(centerX-width, centerY-halfSize, 1+depthOffset);
// TRI WEST
color = colors[m_colors[Direction::West]];
if ( m_colors[Direction::West] == playerColor && m_colors[Direction::West] != Color::Green )
color = bitsoccer::ColorPuls(color);
else if ( m_colors[Direction::West] != Color::Green )
color = bitsoccer::ColorDarken(color);
glColor3f(color.r, color.g, color.b);
glVertex3i(centerX, centerY, 1+depthOffset);
glVertex3i(centerX-halfSize, centerY+width, 1+depthOffset);
glVertex3i(centerX-halfSize, centerY-width, 1+depthOffset);
}
glEnd();
if (m_currentAnimation.HasKeyFrames() && m_currentAnimation.HasPlayedToEnd())
{
m_currentAnimation.ClearKeyFrames();
}
}
void Brick::Update(float deltaTime)
{
// Update AnimatableObject
if (m_currentAnimation.HasKeyFrames())
m_currentAnimation.AddTime(deltaTime);
}
void Brick::NotifyPauseInAnimation()
{
s32 oldX = GetX();
s32 oldY = GetY();
const Frame& currentEndFrame = m_currentAnimation.GetLastKeyFrame();
Frame kf;
kf.position = Vec2(oldX, oldY);
kf.rotation = currentEndFrame.rotation;
kf.time = currentEndFrame.time;
m_currentAnimation.AddKeyFrame(kf);
kf.time += 1.0f;
m_currentAnimation.AddKeyFrame(kf);
}
///////////////////////////////////////////////////////
// PRIVATE METHODS
///////////////////////////////////////////////////////
void Brick::CreateKeyFramesToPos(u32 row, u32 col, BrickAnimation::Type animationType)
{
s32 oldX = GetX();
s32 oldY = GetY();
s32 newX = col * (GetSize()+GetMargin()) + m_originX;
s32 newY = row * (GetSize()+GetMargin()) + m_originY;
const Frame& currentEndFrame = m_currentAnimation.GetLastKeyFrame();
Frame kf;
kf.position = Vec2(oldX, oldY);
kf.rotation = currentEndFrame.rotation;
kf.time = currentEndFrame.time;
m_currentAnimation.AddKeyFrame(kf);
kf.position = Vec2(newX, newY);
kf.time += 1.0f;
m_currentAnimation.AddKeyFrame(kf);
//printf("start pos: [%.2f, %.2f] rot: %.2f time: %.2f\n", start.position.x, start.position.y, start.rotation, start.time);
//printf(" end pos: [%.2f, %.2f] rot: %.2f time: %.2f\n", end.position.x, end.position.y, end.rotation, end.time);
}
void Brick::CreateKeyFramesToRotate(bool CW)
{
}
}
| true |
7072547229912c5916332d014b0b3fda0981b40b | C++ | st3v3nmw/competitive-programming | /kattis/Repeated_Substrings.cpp | UTF-8 | 2,671 | 2.625 | 3 | [
"MIT"
] | permissive | #include <bits/stdc++.h>
using namespace std;
#define eol "\n"
#define _(x) #x << "=" << to_str(x) << ", "
#define debug(x) { ostringstream stream; stream << x; string s = stream.str(); cout << s.substr(0, s.length() - 2) << eol; }
string to_string(basic_string<char>& x) { return "\"" + x + "\""; }
string to_string(char x) { string r = ""; r += x; return "\'" + r + "\'";}
string to_string(bool x) { return x ? "true" : "false"; }
template <typename T> string to_str(T x) { return to_string(x); }
template <typename T1, typename T2> string to_str(pair<T1, T2> x) { return "(" + to_str(x.first) + ", " + to_str(x.second) + ")"; }
template <typename T> string to_str(vector<T> x) { string r = "{"; for (auto t : x) r += to_str(t) + ", "; return r.substr(0, r.length() - 2) + "}"; }
template <typename T> string to_str(set<T> x) { string r = "{"; for (auto t : x) r += to_str(t) + ", "; return r.substr(0, r.length() - 2) + "}"; }
template <typename T1, typename T2> string to_str(map<T1, T2> x) { string r = "{"; for (auto t : x) r += to_str(t.first) + ": " + to_str(t.second) + ", "; return r.substr(0, r.length() - 2) + "}"; }
#define ll long long
const ll MOD = 1e9 + 7;
// TODO: Optimize this
vector<ll> s_array;
const vector<ll>& suffix_array(const string& s) {
s_array.clear();
for (ll i = 0; i < s.size(); i++)
s_array.push_back(i);
size_t t = s.size();
auto cmp = [&s, &t](ll a, ll b) {
ll l = a > b ? t - a + 1 : t - b + 1;
for (ll i = 0; i < l; i++) {
if (s[a + i] > s[b + i])
return true;
else if (s[a + i] < s[b + i])
return false;
}
return true;
};
sort(s_array.begin(), s_array.end(), cmp);
return s_array;
}
ll n_repeated_substrs(const string& s) {
vector<ll> arr = suffix_array(s), lcp;
lcp.push_back(0);
size_t t = s.size();
auto commonPrefixLength = [&s, &t](ll a, ll b) {
ll l = a > b ? t - a + 1 : t - b + 1;
for (ll i = 0; i < l; i++) {
if (s[a + i] != s[b + i])
return i;
}
return l;
};
for (ll i = 1; i < s.size(); i++)
lcp.push_back(commonPrefixLength(arr[i-1], arr[i]));
unordered_set<string> substrs;
string p, w;
for (ll i = 1; i < lcp.size(); i++) {
w = s.substr(arr[i]);
for (ll j = 1; j <= lcp[i]; j++)
substrs.insert(w.substr(0, j));
}
return substrs.size();
}
int main() {
ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
int t;
cin >> t;
string s;
while (t--) {
cin >> s;
cout << n_repeated_substrs(s) << eol;
}
} | true |
5555b7aa3e058d9eeaee94a3df4728aeecef4787 | C++ | DylanDjaw/algorithms4 | /ch.1/1_3_1_7_evaluate.cc | UTF-8 | 1,603 | 3.828125 | 4 | [] | no_license | #include <iostream>
#include <vector>
#include <stack>
#include <string>
using namespace std;
//算数表达式计算示意版,仅支持全部运算带括号,操作数为个位数
double evaluate(string s){
if(s.size() <= 0){
cout << "wrong input" << endl;
return -1;
}
//操作数
stack<double> nums;
//运算符
stack<char> ops;
double v;
for(char c : s){
//若c为数字
if(c <= 0x39 && c >= 0x30)
nums.push(c - 0x30); //将c的数值压进操作数栈
//若c为运算符
if('+' == c || '-' == c || '*' == c || '/' == c)
ops.push(c); //将c压入运算符栈
//若c为右括号
if(')' == c){
//取出两个操作数和一个运算符,将其计算后压入操作数栈
v = nums.top();
nums.pop();
switch (ops.top()){
case '+':
v += nums.top();
break;
case '-':
v = nums.top() - v;
break;
case '*':
v *= nums.top();
break;
case '/':
v = nums.top() / v;
break;
default:
cout << "ops stack error" << endl;
break;
}
ops.pop();
nums.pop();
nums.push(v);
}
}
return v;
}
int main(){
string s = "((1+(2*(3+4)/(1*2)))-((5-6)/(2-1)))";
cout << evaluate(s) << endl;
} | true |
38cba8ddc0323348ff061dfc86965f148bb8861a | C++ | caozongli/Mempool | /MemPooling.cpp | UTF-8 | 2,639 | 3.390625 | 3 | [] | no_license | #include <iostream>
#include <cstdlib>
#include <cstdio>
using namespace std;
struct LinkedPointer{
void* ptr;
LinkedPointer* Next;
};
class A
{
// virtual void test();
// virtual void test2();
// A():age(1), sex(true), bchild(false){}
// void SetAge(int age) { this->age = age; }
// static void* operator new(size_t size)
// {
// return malloc(size);
// }
// static void operator delete(void *p, size_t size)
// {
// free(p);
// }
private:
int age;
bool bchild;
bool sex;
public:
struct Obj{struct Obj* Next;};
static Obj* Header;
A():age(0), sex(true), bchild(false)
{
}
void* operator new(size_t size);
void operator delete(void* p, size_t size);
static LinkedPointer *linkedPtr;
static bool IsValidPtr(void* ptr)
{
if(linkedPtr->ptr<=ptr && ptr<(((char*)linkedPtr->ptr)+16))
{
return true;
}
return false;
}
static int mallocCount;
};
LinkedPointer* A::linkedPtr = nullptr;
int A::mallocCount = 0;
A::Obj* A::Header = nullptr;
static void* A::operator new(size_t size)
{
if(nullptr == Header)
{
if(mallocCount>=1)
{
return ::operator new(size);
}
size_t total = size * 2;
void * temp = malloc(total);
if(nullptr == temp)
{
return nullptr;
}
mallocCount++;
Header = (Obj*) temp;
Obj* tempItem = Header;
for(int i=1; i<2; i++)
{
void* ptr = (char*)tempItem + size;
tempItem->Next = (Obj*)ptr;
tempItem = tempItem->Next;
}
tempItem->Next = nullptr;
LinkedPointer* linkPtr = new LinkedPointer();
linkPtr->ptr = temp;
if(nullptr == linkedPtr)
{
linkedPtr = linkPtr;
}
else
{
linkedPtr->Next = linkedPtr;
}
}
Obj* Ret = Header;
Header = Header->Next;
return Ret;
}
static void A::operator delete(void* p, size_t size)
{
if(!IsValidPtr(p))
{
::operator delete(p);
return;
}
if(nullptr==Header)
{
Header = (Obj*)p;
}
((Obj*)p)->Next = Header;
Header->Next = (Obj*)p;
}
struct ff{struct ff *next;};
int main()
{
A* a1 = new A();
A* a2 = new A();
A* a3 = new A();
delete a1;
delete a2;
delete a3;
cout << sizeof(ff) << endl;
system("pause");
return 0;
}
| true |
fb179a57646b2c8a1ac80ee588a9f301a16cfddc | C++ | rajendrabaskota/data-structures | /generalPurpose.cpp | UTF-8 | 879 | 3.015625 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main(){
int n, inp, x=0, y;
cin >> n;
vector<int> integers;
vector<int> answer;
for(int i=0; i<n; i++){
cin >> inp;
integers.push_back(inp);
}
sort(integers.begin(), integers.end());
y = n/2;
int ptr1, ptr2;
ptr1 = 0;
ptr2 = y;
while(ptr1 < y){
answer.push_back(integers[ptr2]);
answer.push_back(integers[ptr1]);
ptr1++;
ptr2++;
}
while(ptr2 < n){
answer.push_back(integers[ptr2]);
ptr2++;
}
for(int i=1; i<n; i=i+2){
if(i+1 < n){
if(answer[i-1] > answer[i] && answer[i+1] > answer[i]){
x++;
}
}
}
cout << x << endl;
for(int i=0; i<n; i++){
cout << answer[i] << endl;
}
return 0;
}
| true |
4c92355d336ff2bbf8eb04f782e5a432b5de42a7 | C++ | COP3503-UF-Project-Team-3/Final-Project | /src/char-creator.cpp | UTF-8 | 1,340 | 3.59375 | 4 | [] | no_license | #include "char-creator.h"
#include <iostream>
using namespace std;
Player newChar() {
cout << endl;
cout << "Character Creation" << endl;
// Declare a new `Player` object
Player p(false);
// Build the object field-by-field
string name;
cout << "Enter a name: ";
cin >> name;
p.name = name;
// Choosing stats
const int NUM_POINTS = 10;
cout << endl;
cout << "Please choose how to allocate points into the following attributes: " << endl;
cout << "\t" << "- Intelligence" << endl;
cout << "\t" << "- Strength" << endl;
cout << "Number of points available: " << NUM_POINTS << endl;
cout << endl;
int in;
int str;
bool valid = false;
while (!valid) {
cout << "How many points would you like to allocate into intelligence? ";
cin >> in;
cout << "How many points would you like to allocate into strength? ";
cin >> str;
if (!cin.good()) {
//Error check
cout << "Invalid Input!" << endl;
cin.clear();
cin.ignore(256, '\n');
} else if (in < 0 || str < 0) {
cout << "You must enter positive numbers." << endl;
} else if (in + str != NUM_POINTS) {
cout << "The numbers must add to the number of available points." << endl;
} else {
valid = true;
}
cout << endl;
}
p.intelligence = in;
p.strength = str;
// Default values
p.dollars = 0;
p.hours = 18;
p.day = 1;
return p;
}
| true |
613958d449df74d11b5d73161da63e7315ce0b07 | C++ | supakritk/BitCars | /BitCars/Gameplay.cpp | UTF-8 | 2,784 | 2.90625 | 3 | [] | no_license | #include "Gameplay.hpp"
Gameplay::Gameplay()
{
}
Gameplay::~Gameplay()
{
}
void Gameplay::initialization(std::vector<std::string> &map) {
this->setCurrentMap(map);
this->addCar();
}
void Gameplay::playGame(const int& key_input) {
if (key_input != NO_INPUT) {
this->addCar();
}
this->moveAllCar();
}
float Gameplay::getTimeCriteria() {
return GAMEPLAY_GAP;
}
void Gameplay::gotoxy(const SHORT& x, const SHORT& y)
{
COORD p = { x, y };
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), p);
}
void Gameplay::setCurrentMap(std::vector<std::string> &map) {
for (int i = 0; i < static_cast<int>(map.size()); i++) {
currentmap.push_back(map[i]);
}
}
void Gameplay::addCar() {
cars.push_back(std::make_shared<Car>());
for (int j = 0; j < static_cast<int>(currentmap.size()); j++) {
for (int i = 0; i < static_cast<int>(currentmap[j].size()); i++) {
if (currentmap[j].at(i) == EMPTY_SPACE) {
if (this->hasNoOtherCar(car_amount, i, j)) {
cars[car_amount]->setX(i);
cars[car_amount]->setY(j);
cars[car_amount]->setOldX(-1);
cars[car_amount]->setOldY(-1);
this->moveOneCar(i, j, i, j);
car_amount++;
return;
}
}
}
}
}
bool Gameplay::hasNoOtherCar(int mycar, int x, int y) {
for (int i = 0; i < static_cast<int>(cars.size()); i++) {
if (i != mycar) {
if (x != cars[i]->getX()) {
if (y != cars[i]->getY()) {
return false;
}
}
}
}
return true;
}
void Gameplay::moveAllCar() {
for (int i = 0; i < static_cast<int>(cars.size()); i++) {
int x = cars[i]->getX();
int y = cars[i]->getY();
if (combinedCondition(i, x + 1, y)) {
this->moveOneCar(x, y, x + 1, y);
cars[i]->setX(x + 1);
cars[i]->setY(y);
}
else if (combinedCondition(i, x, y + 1)) {
this->moveOneCar(x, y, x, y + 1);
cars[i]->setX(x);
cars[i]->setY(y + 1);
}
else if (combinedCondition(i, x - 1, y)) {
this->moveOneCar(x, y, x - 1, y);
cars[i]->setX(x - 1);
cars[i]->setY(y);
}
else if (combinedCondition(i, x, y - 1)) {
this->moveOneCar(x, y, x, y - 1);
cars[i]->setX(x);
cars[i]->setY(y - 1);
}
cars[i]->setOldX(x);
cars[i]->setOldY(y);
}
}
bool Gameplay::isReturn(int mycar, int x, int y) {
if (x == cars[mycar]->getOldX()) {
if (y == cars[mycar]->getOldY()) {
return true;
}
}
return false;
}
bool Gameplay::combinedCondition(int mycar, int x, int y) {
if (currentmap[y].at(x) == EMPTY_SPACE) {
if (hasNoOtherCar(mycar, x, y)) {
if (!isReturn(mycar, x, y)) {
return true;
}
}
}
return false;
}
void Gameplay::moveOneCar(int x1, int y1, int x2, int y2) {
this->gotoxy(static_cast<SHORT>(x1), static_cast<SHORT>(y1));
std::cout << SPACE;
this->gotoxy(static_cast<SHORT>(x2), static_cast<SHORT>(y2));
std::cout << CAR_ICON;
} | true |
c5dea258d25bc69fe3acc897af5052fd39c56da0 | C++ | antbenar/Redes | /Chat/client.cpp | UTF-8 | 1,835 | 2.59375 | 3 | [] | no_license | #include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <string>
#include <iostream>
using namespace std;
int create_client(){
struct sockaddr_in stSockAddr;
int Res;
int SocketFD = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
int n;
if (-1 == SocketFD)
{
perror("cannot create socket");
exit(EXIT_FAILURE);
}
memset(&stSockAddr, 0, sizeof(struct sockaddr_in));
stSockAddr.sin_family = AF_INET;
stSockAddr.sin_port = htons(1100);
Res = inet_pton(AF_INET, "192.168.1.60", &stSockAddr.sin_addr);
if (0 > Res)
{
perror("error: first parameter is not a valid address family");
close(SocketFD);
exit(EXIT_FAILURE);
}
else if (0 == Res)
{
perror("char string (second parameter does not contain valid ipaddress");
close(SocketFD);
exit(EXIT_FAILURE);
}
if (-1 == connect(SocketFD, (const struct sockaddr *)&stSockAddr, sizeof(struct sockaddr_in)))
{
perror("connect failed");
close(SocketFD);
exit(EXIT_FAILURE);
}
return SocketFD;
}
int main(void)
{
int SocketFD = create_client();
string buffer;
char buf[256];
string client_user = "Anthony";
write(SocketFD,client_user.c_str(),client_user.size());
char server_user[256];
read(SocketFD,server_user,255);
cout << "Server: [" << server_user <<"] - Client: [" << client_user << "]" << endl;
while( buf != "END" ){
cout << "[" << client_user << "]: ";
cin >> buffer;
write(SocketFD, buffer.c_str() , buffer.size());
if ( buffer == "END" ) break;
bzero(buf,256);
read(SocketFD,buf,255);
cout << "[" << server_user << "]: " << buf << endl;
}
shutdown(SocketFD, SHUT_RDWR);
close(SocketFD);
return 0;
}
// fuser -k -n tcp 1100
| true |
188684550718e36f03018fd1de50ff87cf374865 | C++ | j40903272/dsp2017 | /hw3/dsp_hw3/test_env/mydisambig.cpp | UTF-8 | 3,143 | 2.671875 | 3 | [] | no_license | #include <stdio.h>
#include <string>
#include <string.h>
#include <vector>
#include <iterator>
#include <map>
#include <Ngram.h>
using namespace std;
typedef map<string, vector<string> > MAP;
typedef struct{
int idx;
string str;
double prob;
}DPNode;
inline vector<string> sentence_preprocess(char buf[]){
vector<string> chars;
char *token = strtok(buf, " ");
while(token != NULL){
chars.push_back(token);
token = strtok(NULL, " ");
}
return chars;
}
inline void buildmap(MAP& Map){
FILE *fp = fopen("ZhuYin-Big5.map", "r");
char buf[65536];
while(fgets(buf, sizeof(buf), fp) != NULL){
char *token = strtok(buf, " ");
string key(token);
token = strtok(NULL, " \n");
while(token != NULL){
Map[key].push_back(token);
token = strtok(NULL, " \n");
}
}
Map["\n"].push_back("</s>");
}
inline double ngramProb(Vocab& voc, Ngram& lm, const char *a, const char *b){
VocabIndex wid1 = voc.getIndex(a);
VocabIndex wid2 = voc.getIndex(b);
if(wid1 == Vocab_None)
wid1 = voc.getIndex(Vocab_Unknown);
if(wid2 == Vocab_None)
wid2 = voc.getIndex(Vocab_Unknown);
VocabIndex context[] = {wid1, Vocab_None};
return lm.wordProb(wid2, context);
}
inline double ngramProb(Vocab& voc, Ngram& lm, const char *a, const char *b, const char *c){
VocabIndex wid1 = voc.getIndex(a);
VocabIndex wid2 = voc.getIndex(b);
VocabIndex wid3 = voc.getIndex(c);
if(wid1 == Vocab_None)
wid1 = voc.getIndex(Vocab_Unknown);
if(wid2 == Vocab_None)
wid2 = voc.getIndex(Vocab_Unknown);
if(wid3 == Vocab_None)
wid3 = voc.getIndex(Vocab_Unknown);
VocabIndex context[] = {wid2, wid1, Vocab_None};
return lm.wordProb(wid3, context);
}
vector<string> viterbi(const vector<string>& chars, Vocab& voc, Ngram& lm, MAP& Map){
vector<vector<DPNode> > table;
vector<DPNode> last;
last.push_back((DPNode){0, "<s>", 1.0});
table.push_back(last);
for(auto i = chars.begin() ; i != chars.end() ; i++){
int ii = distance(chars.begin(), i);
last.clear();
for(auto j = Map[*i].begin() ; j != Map[*i].end() ; j++){
double maxprob = -100000.0;
int maxidx = 0;
for(int k = 0 ; k < table[ii].size() ; k++){
double prob = table[ii][k].prob + ngramProb(voc, lm, table[ii][k].str.data(), j->data());
if(prob > maxprob){
maxprob = prob;
maxidx = k;
}
}
last.push_back((DPNode){maxidx, *j, maxprob});
}
table.push_back(last);
}
vector<string> output;
int idx = 0;
for(int i = table.size()-1 ; i >= 0 ; i--){
output.push_back(table[i][idx].str);
idx = table[i][idx].idx;
}
return output;
}
int main(int argc, char* argv[]){
if(argc != 4){
printf("Usage : ./mydisambig [input file] [lm] [order]");
exit(0);
}
int order = atoi(argv[3]);
Vocab voc;
Ngram lm(voc, order);
File lmfile(argv[2], "r");
lm.read(lmfile);
lmfile.close();
MAP Map;
buildmap(Map);
char buf[512];
FILE *input = fopen(argv[1], "r");
while(fgets(buf, sizeof(buf), input) != NULL){
vector<string> chars = sentence_preprocess(buf);
vector<string> output = viterbi(chars, voc, lm, Map);
for(int len = output.size()-1 ; len >= 0 ; len--)
printf("%s%c", output[len].data(), " \n"[len==0]);
}
} | true |
049ca971a09195524fddda83451e69ae80ec0692 | C++ | NaSchkafu/univermec | /inc/objects/param/paramtapertrans.hpp | UTF-8 | 1,431 | 2.515625 | 3 | [] | no_license | #ifndef __PARAMTAPERTRANS_HPP__
#define __PARAMTAPERTRANS_HPP__
#include "../iparamtrans.hpp"
namespace objects
{
namespace details
{
/// Tapering transformation for parametric surfaces
/**
*
*
*/
template<typename T>
class ParamTaperTrans : public IParamTrans
{
public:
/**
* Ctor
*
* @param child surface to transform
* @param kx tapering factor x
* @param ky tapering factor y
* @param sz scaling z axis
*
*/
ParamTaperTrans(IParamSurface *child, const T& kx, const T &ky, const T& sz);
virtual ~ParamTaperTrans();
private:
// IParamSurface
virtual const IParamSurface& child_() const;
virtual unsigned d_dim_() const;
virtual core::arith::ivector domain_() const;
virtual const functions::IVFunction& p_fun_() const;
virtual const functions::IVFunction* p_normals_() const;
// IGeoObj
virtual const functions::IFunction& cf_() const;
virtual IGeoObj* clone_() const;
virtual unsigned dim_() const;
virtual const functions::IVFunction* normals_() const;
private:
std::unique_ptr<IParamSurface> m_child;
std::unique_ptr<functions::IVFunction> m_pf;
std::unique_ptr<functions::IVFunction> m_npf;
std::unique_ptr<functions::IFunction> m_cf;
};
}
}
#endif /*__PARAMTAPERTRANS_HPP__*/
| true |
0d920809d24fd178cac16e2c510a7936a3dc7e8f | C++ | ClawmanCat/FP2 | /semifunctional/functional.hpp | UTF-8 | 2,687 | 3.296875 | 3 | [] | no_license | #pragma once
#include <cstddef>
#include <functional>
#include <array>
#define fwd(x) std::forward<decltype(x)>(x)
#define lam(var, ...) [&](var) { return __VA_ARGS__; }
#define generic(fn) [](auto&&... args) { return fn(fwd(args)...); }
#define compare_as(name, ...) [&](const auto& a, const auto& b) { \
auto value_of = [&](const auto& name) { __VA_ARGS__; }; \
return value_of(a) < value_of(b); \
}
namespace sf {
constexpr inline auto identity = [](const auto& x) -> decltype(auto) { return x; };
template <typename T>
constexpr auto convert(void) {
return [](auto&& elem) { return T { fwd(elem) }; };
}
// Creates a function that produces the given value.
constexpr auto produce(auto&& value) {
return [value = fwd(value)] (auto...) { return value; };
}
// Creates a function which either returns the result of the second or the third predicate,
// depending on the first predicate.
constexpr auto pick(auto condition, auto if_true, auto if_false) {
return [=](auto&&... args) -> decltype(auto) {
return condition(args...) ? if_true(fwd(args)...) : if_false(fwd(args)...);
};
}
// Creates a function which checks if a value is equal to the pre-provided value.
constexpr auto equal(auto&& value) {
return [value = fwd(value)](const auto& other) { return other == value; };
}
// Given two fields a and b, creates a function that returns the value in the field that is not equal to the provided value.
constexpr decltype(auto) get_other(auto field_a, auto field_b, auto&& value) {
return [=, value = fwd(value)](const auto& obj) -> decltype(auto) {
return obj.*field_a == value ? obj.*field_b : obj.*field_a;
};
}
constexpr auto non_equal(auto&& value) {
return [value = fwd(value)](const auto& other) { return other == value; };
}
constexpr auto conjunction(auto a, auto b) {
return [=](auto&&... args) { return a(args...) && b(args...); };
}
constexpr auto disjunction(auto a, auto b) {
return [=](auto&&... args) { return a(args...) || b(args...); };
}
// Constructs an array filled with the result of invoking pred for each element.
template <typename T, std::size_t N, typename Pred>
constexpr std::array<T, N> create_filled_array(Pred pred) {
return [&] <std::size_t... Is> (std::index_sequence<Is...>) {
return std::array<T, N> { pred(Is)... };
}(std::make_index_sequence<N>());
}
} | true |
3866aaf656ba97aee1d19cec394933ea994f8315 | C++ | scabsy/ICT398-Milestone-2 | /SlashStudios/GameObject.cpp | UTF-8 | 3,809 | 2.625 | 3 | [] | no_license | #include "GameObject.h"
#include <iostream>
GameObject::GameObject()
{
//node = 0;
}
GameObject::GameObject(path modelPath, vector3df position, vector3df rotation, float scale, bool createCollision, ISceneManager* smgr)
{
node = 0;
node = (IAnimatedMeshSceneNode*)smgr->addAnimatedMeshSceneNode(smgr->getMesh(modelPath),0);
SetPosition(position);
SetRotation(rotation);
SetScale(scale);
for (unsigned int i = 0; i < node->getMaterialCount(); i++)
{
node->getMaterial(i).Lighting=false;
node->getMaterial(i).NormalizeNormals=false;
}
if(createCollision)
CreateAABB();
}
void GameObject::SetPosition(vector3df newPos)
{
g_position=newPos;
node->setPosition(g_position);
}
void GameObject::SetOldPosition(vector3df newOldPos)
{
g_oldPosition = newOldPos;
}
vector3df GameObject::GetPosition()
{
if (node != 0)
return node->getPosition();
else
return g_position;
}
void GameObject::SetRotation(vector3df newRot)
{
g_rotation=newRot;
node->setRotation(g_rotation);
//aabb.
}
vector3df GameObject::GetRotation()
{
return g_rotation;
}
void GameObject::SetScale(float newScale)
{
g_scale = newScale;
node->setScale(vector3df(newScale));
}
float GameObject::GetScale()
{
return g_scale;
}
void GameObject::SetInteractor(GameObject* i)
{
interactor = i;
}
void GameObject::SetInteractee(GameObject* i)
{
interactee = i;
}
ISceneNode* GameObject::GetNode()
{
return node;
}
void GameObject::SetNode(ISceneNode* n)
{
node = n;
}
void GameObject::SetAABB(aabbox3d<f32> naabb)
{
aabb = naabb;
}
void GameObject::CreateAABB()
{
vector3df tmpMin;
vector3df tmpMax;
aabbox3df tmpAABB;
vector3d<f32>* edges = new vector3d<f32>[8];
tmpMin = ((IAnimatedMeshSceneNode*)node)->getMesh()->getBoundingBox().MinEdge*GetScale();
tmpMax = ((IAnimatedMeshSceneNode*)node)->getMesh()->getBoundingBox().MinEdge*GetScale();
aabb=aabbox3df(tmpMin,tmpMax);
aabb.getEdges(edges);
}
void GameObject::Update(list<GameObject*> gos)
{
}
void GameObject::Interact(GameObject* ninteractor)
{
}
bool GameObject::CheckCollision(GameObject* other)
{
vector3df thisPos = GetPosition();
vector3df otherPos = other->GetPosition();
aabbox3df thisAABB = GetAABB();
aabbox3df otherAABB = other->GetAABB();
float TxDistBy2 = (thisAABB.MaxEdge.X-thisAABB.MinEdge.X)/2;
float TyDistBy2 = (thisAABB.MaxEdge.Y-thisAABB.MinEdge.Y)/2;
float TzDistBy2 = (thisAABB.MaxEdge.Z-thisAABB.MinEdge.Z)/2;
float OxDistBy2 = (otherAABB.MaxEdge.X-otherAABB.MinEdge.X)/2;
float OyDistBy2 = (otherAABB.MaxEdge.Y-otherAABB.MinEdge.Y)/2;
float OzDistBy2 = (otherAABB.MaxEdge.Z-otherAABB.MinEdge.Z)/2;
if(thisPos.X + TxDistBy2/2<otherPos.X - OxDistBy2/2 || otherPos.X + OxDistBy2/2<thisPos.X - TxDistBy2/2)
{
return false;
}
//if (thisPos.Y + TyDistBy2 / 2<otherPos.Y - OyDistBy2 / 2 || otherPos.Y + OyDistBy2 / 2<thisPos.Y - TyDistBy2 / 2)
//{
// return false;
//}
if(thisPos.Z + TzDistBy2/2<otherPos.Z - OzDistBy2/2 || otherPos.Z + OzDistBy2/2<thisPos.Z - TzDistBy2/2)
{
return false;
}
return true;
}
void GameObject::AddAffordance(std::string affName, float affVal)
{
affordances.push_back(new Affordance(affName,affVal));
}
bool GameObject::MatchAffordances(GameObject* other)
{
for (size_t i = 0; i < affordances.size(); i++)
{
for (size_t j = 0; j < other->affordances.size(); j++)
{
//cout << affordances[i]->GetName() << ": " << affordances[i]->GetValue() << " " << other->affordances[j]->GetName() << ": " << other->affordances[j]->GetValue() << endl;
if (affordances[i]->Compare(other->affordances[j]))
{
return true;
}
}
}
return false;
}
bool GameObject::MatchAffordances( Affordance* afford)
{
for (size_t j = 0; j < affordances.size(); j++)
{
if (afford->Compare(affordances[j]))
{
return true;
}
}
return false;
} | true |
1e70e8909720a80eba3f4e9e5de0bb122cfe3409 | C++ | UnknownFreak/OneFlower | /Project/File/CfgParser.cpp | UTF-8 | 3,158 | 2.875 | 3 | [] | no_license | #include "CfgParser.hpp"
#include <Module/Logger/OneLogger.hpp>
namespace File::Resource::Config
{
ConfigParser::ConfigParser()
{
}
ConfigParser::ConfigParser(const Core::String& configFile)
{
load(configFile);
}
void ConfigParser::comment(const Core::String& comment)
{
sections[comment] = {};
}
void ConfigParser::comment(const Core::String& section, const Core::String& comment)
{
sections[section].put("#" + comment, "");
}
void ConfigParser::clear()
{
sections.clear();
}
void ConfigParser::load()
{
load(fileName);
}
void ConfigParser::load(const Core::String& configFile)
{
fileName = configFile;
clear();
std::ifstream file(fileName);
{
if (file.is_open())
{
Engine::GetModule<EngineModule::Logger::OneLogger>().getLogger("ConfigParser").Debug("Begin parsing configuration file", fileName);
Core::String section = "";
Core::String line;
while (std::getline(file, line))
{
bool bcomment = false;
bool bsection = false;
if (line[0] == '#' || line[0] == ';')
bcomment = true;
else if (line[0] == '[' && line[line.size() - 1] == ']')
bsection = true;
if (bsection)
{
section = line.substr(1, line.size() - 2);
sections[section] = {};
}
else if (section.size())
{
if (bcomment)
comment(section, line.substr(1));
else
{
Core::String the_comment = "";
auto commentpos = line.find_first_of(";");
if (commentpos != std::string::npos)
the_comment = line.substr(commentpos);
else
commentpos = line.size();
auto pos = line.find_first_of("=");
auto key = Core::trim(line.substr(0, pos));
auto value = Core::String(line.begin() + pos + 1, line.begin() + commentpos);
value = Core::trim(value);
put(section, key, value, the_comment);
}
}
else if (section.size() == 0 && bcomment)
comment(line.substr(1));
}
Engine::GetModule<EngineModule::Logger::OneLogger>().getLogger("ConfigParser").Debug("Finished parsing configuration file", fileName);
}
else
{
Engine::GetModule<EngineModule::Logger::OneLogger>().getLogger("ConfigParser").Error("Unable to open config file: ", fileName);
}
}
file.close();
}
void ConfigParser::save()
{
save(fileName);
}
void ConfigParser::save(const Core::String& configFile)
{
fileName = configFile;
//Engine::GetModule<EngineModule::Logger::OneLogger>().getLogger("ConfigParser").Debug("Begin writing configuration file ", fileName);
std::ofstream file(fileName);
{
for (auto& x : sections)
{
if (x.first[0] == '#' || x.first[0] == ';')
file << x.first << std::endl;
else
{
file << "[" << x.first << "]" << std::endl;
for (auto& y : x.second.values)
{
file << y.first;
if (!(y.first[0] == '#' || y.first[0] == ';'))
file << " = " << y.second;
file << std::endl;
}
}
}
}
//Engine::GetModule<EngineModule::Logger::OneLogger>().getLogger("ConfigParser").Debug("Finished writing configuration file ", fileName);
file.flush();
file.close();
}
}; | true |
b83ee573a47845378093b9c83e6a535477892fb3 | C++ | vivekmaurya1505/CPP | /CPP/Codes/Day1/4.2 function overloading case2 .cpp | UTF-8 | 473 | 3.875 | 4 | [] | no_license | #include<stdio.h>
//Function having same name and same number of arguments but
//differs in type of arguments
int sum(int n1, int n2) // sum@@int, int
{
return n1+n2;
}
float sum(int n1, float n2) // sum@@int, float
{
return n1+n2;
}
int main(void)
{
int result=0;
float result1=0;
result= sum(10, 20); // sum@@int, int
printf("\n sum@int, int =%d", result);
result1= sum(10, 40.2f); // sum@@int,float
printf("\n sum@int,float =%.2f", result1);
return 0;
}
| true |
b6590ec701365f0f0eedfaa7c21cd1cf2427d751 | C++ | fry1999/Spoj-ptit | /PTIT136C.cpp | UTF-8 | 272 | 2.546875 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main(){
long n, a[101][101];
cin>>n;
for(int i=1; i<=n ; i++){
for(int j=1; j<=n; j++){
cin>>a[i][j];
}
}
long x=(a[1][2] + a[1][3] - a[2][3])/2;
cout<<x<<" ";
for(int i=2; i<=n; i++){
cout<<a[1][i]-x<<" ";
}
}
| true |
2f72eaf15a41671dde31a36b6740fba2841a31c9 | C++ | Dhrubajyoti12/interviewbit-problems | /Heaps And Maps/lru-cache.cpp | UTF-8 | 967 | 3.171875 | 3 | [] | no_license | #include<list>
#define NOT_FOUND -1
struct item{
int key; int value;
item(int k, int v): key(k), value(v) {}
};
list<item> *lee;
unordered_map< int, list<item>::iterator > *hmap;
int cap;
LRUCache::LRUCache(int capacity) {
cap = capacity;
lee = new list<item>;
hmap = new unordered_map<int, list<item>::iterator >;
}
int LRUCache::get(int key) {
unordered_map<int, list<item>::iterator>::iterator saga = hmap->find(key);
// if key's not in the cache, return
if(saga == hmap->end()) return NOT_FOUND;
item found = *(saga->second);
lee->erase(saga->second);
lee->push_front(found);
(*hmap)[key] = lee->begin();
return found.value;
}
void LRUCache::set(int key, int value) {
int saga = get(key);
if(saga == NOT_FOUND){
if(lee->size() == cap){
int last_key = lee->back().key;
hmap->erase(last_key);
lee->pop_back();
}
lee->push_front(item{key, value});
(*hmap)[key] = lee->begin();
}
else{
lee->front().value = value;
}
}
| true |
b4012f965c4061004886f93be33821d5ff464ec9 | C++ | arthurherbout/crypto_code_detection | /data/crypto-competitions/files/main.cpp | UTF-8 | 5,325 | 2.984375 | 3 | [] | no_license | #include <string.h>
#include <iostream>
#include "keccak.h"
#include "gambit.h"
/* DISCLAIMER
* This is NOT a reference implementation!
* This is a quick and dirty implementation. The software is not thoroughly
* tested, and not at all tested on platforms other than Intel x86,
* Windows OS, and CodeBlocks/GNU compiler. Once tested and verified, the
* purpose of this program is to print test vectors to stdout that can
* be compared to the output of another implementation.
*/
using namespace std;
using namespace keccak;
using namespace gambit;
void coutarray(uint8_t *buf, int len)
{
for (int i=0; i < len; i++)
cout << std::hex << (int)(buf[i]/16) << (int)(buf[i]%16) << std::dec;
}
void test256(salt &salt, const char *pwd, unsigned int pwd_len,
const uint64_t* ROM, unsigned int ROM_len,
unsigned int t, unsigned int m)
{
seed256 sd;
gambit256(salt, pwd, pwd_len, ROM, ROM_len, t, m, sd);
cout << " sd256: ";
coutarray(sd, 32);
cout << endl;
}
void test512(salt &salt, const char *pwd, unsigned int pwd_len,
const uint64_t* ROM, unsigned int ROM_len,
unsigned int t, unsigned int m)
{
seed512 sd;
gambit512(salt, pwd, pwd_len, ROM, ROM_len, t, m, sd);
cout << " sd512: ";
coutarray(sd, 32);
cout << endl << " ";
coutarray(sd+32, 32);
cout << endl;
}
int main()
{
cout << "state size: " << sizeof(keccak_state) << endl;
keccak_state A;
cout << std::hex;
cout << "state after init: " << A.word_read(0) << ","
<< A.word_read(1) << ", ..." << endl;
A.f();
cout << "state after f(): " << A.word_read(0) << ","
<< A.word_read(1) << ", ..." << endl;
salt salt;
char pwd[151];
unsigned int pwd_len = 0;
unsigned int t = 128;
unsigned int m = 511;
uint64_t ROM[128] = {0};
unsigned int ROM_len = 1;
cout << endl << "SALT" << endl;
for (int i = 1; i <= 128; i*=2)
{
memset(salt, 0, sizeof(salt));
salt[15 - ((i-1) / 8)] = (1 << ((i-1) % 8));
cout << "salt: ";
coutarray(salt, 16);
cout << endl;
test256(salt, pwd, pwd_len, ROM, ROM_len, t, m);
test512(salt, pwd, pwd_len, ROM, ROM_len, t, m);
}
memset(salt, 0, sizeof(salt));
cout << endl << "PASSWORD" << endl;
for (int i = 2; i > -3; i--)
{
memset(pwd, 0x00, 152);
cout << "pwd: " << std::dec << (i+152)%152 << " * 0x00" << endl;
test256(salt, pwd, (i+152)%152, ROM, ROM_len, t, m);
cout << "pwd: " << std::dec << (i+120)%120 << " * 0x00" << endl;
test512(salt, pwd, (i+120)%120, ROM, ROM_len, t, m);
if (i != 0)
{
memset(pwd, 0x01, 152);
cout << "pwd: " << std::dec << (i+152)%152 << " * 0x01" << endl;
test256(salt, pwd, (i+152)%152, ROM, ROM_len, t, m);
cout << "pwd: " << std::dec << (i+120)%120 << " * 0x01" << endl;
test512(salt, pwd, (i+120)%120, ROM, ROM_len, t, m);
memset(pwd, 0x4A, 152);
cout << "pwd: " << std::dec << (i+152)%152 << " * 0x4A" << endl;
test256(salt, pwd, (i+152)%152, ROM, ROM_len, t, m);
cout << "pwd: " << std::dec << (i+120)%120 << " * 0x4A" << endl;
test512(salt, pwd, (i+120)%120, ROM, ROM_len, t, m);
memset(pwd, 0xFF, 152);
cout << "pwd: " << std::dec << (i+152)%152 << " * 0xFF" << endl;
test256(salt, pwd, (i+152)%152, ROM, ROM_len, t, m);
cout << "pwd: " << std::dec << (i+120)%120 << " * 0xFF" << endl;
test512(salt, pwd, (i+120)%120, ROM, ROM_len, t, m);
}
}
cout << endl << "T/M" << endl;
for (t = 1; t < 40000; t = t*9/4)
{
for (m = (t * 21 / 2 - 1) | 1; m > 0; m = (m==1)? 0 : (m / 3) | 1)
{
cout << std::dec << "t: " << t << " m: " << m << endl;
test256(salt, pwd, pwd_len, ROM, ROM_len, t, m);
}
for (m = (t * 17 / 2 - 1) | 1; m > 0; m = (m==1)? 0 : (m / 3) | 1)
{
cout << std::dec << "t: " << t << " m: " << m << endl;
test512(salt, pwd, pwd_len, ROM, ROM_len, t, m);
}
}
cout << endl << "DERIVATION" << endl;
pwd_len = 0;
t = 16;
m = 25;
{
seed256 sd;
dkid256 dkid;
uint8_t key[16];
gambit256(salt, pwd, pwd_len, ROM, ROM_len, t, m, sd);
for (int i = 1; i <= 1024; i*=2)
{
memset(dkid, 0, sizeof(dkid));
dkid[((i-1) / 8)] = (1 << ((i-1) % 8));
gambit256(sd, dkid, key, 16);
cout << "256 dkid: bit" << i-1 << " set" << endl << " key: ";
coutarray(key, 16);
cout << endl;
}
}
{
seed512 sd;
dkid512 dkid;
uint8_t key[16];
gambit512(salt, pwd, pwd_len, ROM, ROM_len, t, m, sd);
for (int i = 1; i <= 1024; i*=2)
{
memset(dkid, 0, sizeof(dkid));
dkid[((i-1) / 8)] = (1 << ((i-1) % 8));
gambit512(sd, dkid, key, 16);
cout << "512 dkid: bit" << i-1 << " set" << endl << " key: ";
coutarray(key, 16);
cout << endl;
}
}
return 0;
}
| true |
5ef2bce6e0ef8c8192cc7415a7ada8d014903abb | C++ | IronyGames/LudumDare38 | /CinderProject/include/StaticGardenGoalLogic.h | UTF-8 | 539 | 2.640625 | 3 | [] | no_license |
#pragma once
#include "IGardenGoalLogic.h"
class StaticGardenGoalLogic : public IGardenGoalLogic
{
public:
StaticGardenGoalLogic( boost::optional<CoordsInt> seedPosition_, std::vector<CoordsInt> occupiedPositions_, std::string entityType_ );
boost::optional<CoordsInt> getSeedPosition() const override;
std::vector<CoordsInt> getOccupiedPositions() const override;
std::string getEntityType() const override;
private:
boost::optional<CoordsInt> seedPosition;
std::vector<CoordsInt> occupiedPositions;
std::string entityType;
}; | true |
98a74bb58b68421a94e1ec3a63360b50e59999be | C++ | log0div0/coro | /coro_test/TestStrandPool.cpp | UTF-8 | 1,593 | 3.03125 | 3 | [
"MIT"
] | permissive | #include <atomic>
#include <catch.hpp>
#include "coro/StrandPool.h"
using namespace coro;
TEST_CASE("StrandPool::cancelAll", "[StrandPool]") {
StrandPool pool;
pool.exec([] {
Coro::current()->yield({TokenThrow});
});
pool.exec([] {
Coro::current()->yield({TokenThrow});
});
pool.cancelAll();
REQUIRE_NOTHROW(pool.waitAll(false));
}
TEST_CASE("StrandPool stress test", "[StrandPool]") {
StrandPool pool;
for (int i = 0; i < 20; i++) {
std::shared_ptr<Strand> strand = pool.exec([] {
for(int i=0; i < 10000; i++) {
Strand::current()->post([coro = Coro::current()]() { coro->resume("test"); });
Coro::current()->yield({"test"});
}
});
}
REQUIRE_NOTHROW(pool.waitAll(false));
}
TEST_CASE("Cyclical StrandPools posting", "[StrandPool]") {
StrandPool firstPool, secondPool;
uint64_t firstCounter = 0, secondCounter = 0;
std::shared_ptr<Strand> firstStrand, secondStrand;
Coro *firstCoro, *secondCoro;
firstStrand = firstPool.exec([&] {
firstCoro = Coro::current();
firstCoro->yield({"first"});
while (firstCounter < 10000) {
secondStrand->post([&] {
secondCoro->resume("second");
});
firstCounter++;
firstCoro->yield({"first"});
}
});
secondStrand = secondPool.exec([&] {
secondCoro = Coro::current();
firstStrand->post([&] {
firstCoro->resume("first");
});
while (secondCounter < 10000) {
secondCounter++;
secondCoro->yield({"second"});
firstStrand->post([&] {
firstCoro->resume("first");
});
}
});
REQUIRE_NOTHROW(firstPool.waitAll(false));
REQUIRE_NOTHROW(secondPool.waitAll(false));
} | true |
2b4a8a301f69e7b1728a3cd4d163f1aa92ac48bf | C++ | f26401004/UVA_practice | /uva10986.cpp | UTF-8 | 1,855 | 3.34375 | 3 | [] | no_license | #include <iostream>
#include <queue>
#define INF 2000000
using namespace std;
typedef struct Edge {
int start;
int end;
int cost;
struct Edge* next;
} edge;
typedef struct EdgeNode {
struct Edge* next;
} edgenode;
int n, m, start, target;
edgenode* edges[20005];
int dist[20005];
void init()
{
for (int i = 0 ; i < 20005 ; ++i)
{
dist[i] = INF;
edges[i] = new edgenode;
edges[i]->next = NULL;
}
}
void BellmanFord()
{
dist[start] = 0;
queue<int> q;
bool inqueue[20005] = {false};
q.push(start);
inqueue[start] = true;
while(!q.empty())
{
int x = q.front();
q.pop();
inqueue[x] = false;
for (edge* i = edges[x]->next ; i != NULL ; i = i->next)
{
if (dist[i->start] + i->cost < dist[i->end])
{
dist[i->end] = dist[i->start] + i->cost;
if (!inqueue[i->end])
{
q.push(i->end);
inqueue[i->end] = true;
}
}
}
}
}
void addEdge(int n1, int n2, int c)
{
edge* t1 = new edge;
t1->start = n1;
t1->end = n2;
t1->cost = c;
t1->next = NULL;
edge* t2 = new edge;
t2->start = n2;
t2->end = n1;
t2->cost = c;
t2->next = NULL;
if (edges[n1]->next == NULL)
edges[n1]->next = t1;
else
{
edge* iter = edges[n1]->next;
while(iter->next != NULL)
iter = iter->next;
iter->next = t1;
}
if (edges[n2]->next == NULL)
edges[n2]->next = t2;
else
{
edge* iter = edges[n2]->next;
while(iter->next != NULL)
iter = iter->next;
iter->next = t2;
}
}
int main()
{
int case_num;
cin >> case_num;
for (int i = 0 ; i < case_num ; ++i)
{
init();
cin >> n >> m >> start >> target;
for (int j = 0 ; j < m ; ++j)
{
int n1, n2, c;
cin >> n1 >> n2 >> c;
addEdge(n1, n2, c);
}
BellmanFord();
if (dist[target] < INF)
cout << "Case #" << i+1 << ": " << dist[target] << endl;
else
cout << "Case #" << i+1 << ": unreachable" << endl;
}
return 0;
}
| true |