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 |
---|---|---|---|---|---|---|---|---|---|---|---|
ff75d392e0f5548ef35eff9fea64ec52a5efa309
|
C++
|
WhiteRabbit-21/C-Exercise
|
/HM-23/B2-pointer.cpp
|
UTF-8
| 1,022 | 3.4375 | 3 |
[] |
no_license
|
#include <iostream>
using namespace std;
int main() {
//2. Дано чотири цілочисельних змінних і невизначений вказівник. Направити вказівник на першу-ліпшу парну змінну і вивести значення вказівника або надати вказівнику значення nullptr та повідомити, що парних змінних немає.
int a, b, c, d;
cout << "Enter a" << endl;
cin >> a;
cout << "Enter b" << endl;
cin >> b;
cout << "Enter c" << endl;
cin >> c;
cout << "Enter d" << endl;
cin >> d;
int *pnt;
if (a % 2 == 0) {
pnt = &a;
cout << "pnt is " << *pnt << endl;
}
else if (b % 2 == 0) {
pnt = &b;
cout << "pnt is " << *pnt << endl;
}
else if (c % 2 == 0) {
pnt = &c;
cout << "pnt is " << *pnt << endl;
}
else if (d % 2 == 0) {
pnt = &d;
cout << "pnt is " << *pnt << endl;
}
else {
pnt = nullptr;
cout << "Not found even`s numbers" << endl;
}
}
| true |
a098cedb400d8df3cd5659291391e3b415ef967d
|
C++
|
aiyi-wq/HaizeiOJ
|
/OJ-217.cpp
|
UTF-8
| 647 | 2.703125 | 3 |
[] |
no_license
|
/*************************************************************************
> File Name: OJ-217.cpp
> Author:
> Mail:
> Created Time: Tue 19 May 2020 10:35:51 AM CST
************************************************************************/
#include<iostream>
#include<algorithm>
using namespace std;
int num[100005] = {0};
int cmp(int a, int b) {
return a > b;
}
int main() {
int n, m = 0;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> num[i];
}
sort(num, num + n, cmp);
for (int i = 0; i < n; i++) {
if (num[i] >= num[n / 2]) m++;
}
printf("%d %d\n", num[n / 2], m);
return 0;
}
| true |
0c6d69b35e3462c58b7dda8e1afa63ebad283b3c
|
C++
|
ddonix/sfjs2
|
/1587/20214364_AC_0ms_0kB.cpp
|
UTF-8
| 1,350 | 2.859375 | 3 |
[] |
no_license
|
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
using namespace std;
int main()
{
int wh[12];
int a,b,c,i;
int a0,b0,c0;
while(scanf("%d", &wh[0]) != EOF)
{
for(i = 1; i < 12; i++)
scanf("%d", &wh[i]);
a = wh[0];
b = wh[1];
if ((a == wh[2] && b == wh[3]) || (a == wh[3] && b == wh[2]))
{
if (wh[4] == a || wh[4] == b)
c = wh[5];
else if (wh[5] == a || wh[5] == b)
c = wh[4];
else if (wh[4] == wh[5])
c = wh[4];
else
c = 0;
}
else
{
if (wh[2] == a || wh[2] == b)
c = wh[3];
else if (wh[3] == a || wh[3] == b)
c = wh[2];
else if (wh[2] == wh[3])
c = wh[2];
else
c = 0;
}
if (c == 0)
{
printf("IMPOSSIBLE\n");
continue;
}
a0 = b0 = 0;
c0 = 1;
for(i = 2; i < 12; i += 2)
{
if (((wh[i] == a && wh[i+1] == b) || (wh[i] == b && wh[i+1] == a)) && c0 < 2)
{
wh[i] = 0;
wh[i+1] = 0;
c0++;
continue;
}
if (((wh[i] == a && wh[i+1] == c) || (wh[i] == c && wh[i+1] == a)) && b0 < 2)
{
wh[i] = 0;
wh[i+1] = 0;
b0++;
continue;
}
if (((wh[i] == b && wh[i+1] == c) || (wh[i] == c && wh[i+1] == b)) && a0 < 2)
{
wh[i] = 0;
wh[i+1] = 0;
a0++;
continue;
}
}
if (a0 == 2 && b0 == 2 && c0 ==2)
printf("POSSIBLE\n");
else
printf("IMPOSSIBLE\n");
}
}
| true |
515692163aecb55a8aad0d985b6a417486f2fbe1
|
C++
|
RPG-RAH/Bounding-Box-Collision-OpenGL
|
/Shader.h
|
UTF-8
| 2,275 | 2.828125 | 3 |
[] |
no_license
|
#include <string>
#include <sstream>
#include <fstream>
#include <GL/glew.h>
#include <glm/glm.hpp>
using namespace glm;
using namespace std;
class Shader
{
private :
GLuint vs,fs,program;
string vertexShaderData;
string fragmentShaderData;
string readShaderFile(string);
fstream file;
public :
Shader(string);
~Shader();
void setMVP(mat4,mat4,mat4);
void useProgram() {glUseProgram(program);}
void checkError(GLuint,GLenum);
};
Shader::Shader(string fileLocation)
{
vs = glCreateShader(GL_VERTEX_SHADER);
fs = glCreateShader(GL_FRAGMENT_SHADER);
vertexShaderData = readShaderFile(fileLocation+".vs");
fragmentShaderData = readShaderFile(fileLocation+".fs");
const GLchar* vertexText = vertexShaderData.c_str();
const GLchar* fragmentText = fragmentShaderData.c_str();
glShaderSource(vs,1,&vertexText,NULL);
glShaderSource(fs,1,&fragmentText,NULL);
glCompileShader(vs);
checkError(vs,GL_COMPILE_STATUS);
glCompileShader(fs);
checkError(fs,GL_COMPILE_STATUS);
program = glCreateProgram();
glAttachShader(program,vs);
glAttachShader(program,fs);
glLinkProgram(program);
checkError(program,GL_LINK_STATUS);
}
string Shader::readShaderFile(string fileName)
{
string line;
ostringstream s;
file.open(fileName);
while(!file.eof())
{
getline(file,line);
s<<line<<endl;
}
file.close();
return s.str();
}
void Shader::checkError(GLuint id,GLenum flag)
{
int result;
GLchar infoLog[1024];
if(vs==id||fs==id) glGetShaderiv(id,flag,&result);
else glGetProgramiv(id,flag,&result);
if(!result)
{
if(vs==id||fs==id)
{
glGetShaderInfoLog(id,sizeof(infoLog),NULL,infoLog);
cout<<"Shader : "<<infoLog<<endl;
}
else
{
glGetProgramInfoLog(id,sizeof(infoLog),NULL,infoLog);
cout<<"Program : "<<infoLog<<endl;
}
}
}
void Shader::setMVP(mat4 model,mat4 view,mat4 projection)
{
glUniformMatrix4fv(glGetUniformLocation(program,"model"),1,GL_FALSE,&model[0][0]);
glUniformMatrix4fv(glGetUniformLocation(program,"view"),1,GL_FALSE,&view[0][0]);
glUniformMatrix4fv(glGetUniformLocation(program,"projection"),1,GL_FALSE,&projection[0][0]);
}
Shader::~Shader()
{
glDetachShader(program,vs);
glDetachShader(program,fs);
glDeleteShader(vs);
glDeleteShader(fs);
glDeleteProgram(program);
}
| true |
2ac4edb51f9981f815947e962f5843bbdc0da5c6
|
C++
|
learnability/NASM
|
/main.cpp
|
UTF-8
| 1,202 | 3.953125 | 4 |
[] |
no_license
|
#include <iostream>
#include<stdlib.h>
#include <math.h>
using namespace std;
//function to check if an operator is valid
bool check(char op)
{
switch(op)
{
case '+': return true;
case '-':return true;
case '*':return true;
case '/':return true;
case 'l':return true;
case '%':return true;
case '^':return true;
default : return false;
}
return false;
}
float operation(char op, int a, int b)
{
float result;
switch(op)
{
case '+':result = a+b;
break;
case '-':result = a-b;
break;
case '*':result = a*b;
break;
case '/':result = a/b;
break;
case '%':result = a%b;
break;
case 'l':result = log(a) ;
break;
case '^':result = pow(a,b);
}
return result;
}
main()
{
char operator_ ;
int operand_1,operand_2;
cout<<"Enter the operator (+ - * / ^)" ; // asks the user to enter the operation + - * / ^
cin>>operator_;
//check if operator is valid
if(!(check(operator_)))
cout<<"Invalid operator";
else
{
cout<<"Enter operand 1 \n";
cin>>operand_1;
if(operator_!='l')
{
cout<<"Enter operand 2\n";
cin>>operand_2;
}
float result;
result = operation(operator_,operand_1,operand_2);
cout<<"result\n"<<result<<"\n";
}
}
| true |
bec142a203503f9633c926ead7681dea9354bbf1
|
C++
|
irenemengual/trabajo-informatica
|
/Inicio.cpp
|
WINDOWS-1250
| 5,785 | 2.5625 | 3 |
[] |
no_license
|
#include "Inicio.h"
Inicio::Inicio()
{
//La variable estado se inicializa a INICIO de juego
estado = INICIO;
contador = 0;
}
Inicio::~Inicio()
{
}
void Inicio::tecla(unsigned char key)
{
if (key == 'c') ETSIDI::stopMusica();
//if (key == 'c') ETSIDI::stopMusica();
if (estado == INICIO)
{
if (key == '1')
{
estado = JUGVSMAQ;
Juego.Inicializa(estado);
}
if (key == '2')
{
estado = JUGVSJUG;
Juego.Inicializa(estado);
}
if (key == 'r' || key == 'R')
{
estado = REGLAS;
}
if (key == 'e' || key == 'E') {
exit(0);
}
}
if (estado == REGLAS)
{
if (key == '1')
{
estado = JUGVSMAQ;
Juego.Inicializa(estado);
}
if (key == '2')
{
estado = JUGVSJUG;
Juego.Inicializa(estado);
}
if (key == 'e' || key == 'E')
{
exit(0);
}
}
if (estado == FINJ1 || estado == FINJ2)
{
if (key == 'e' || key == 'E') {
exit(0);
}
}
Juego.Tecla(key);
}
void Inicio::dibuja()
{
//si el juego esta en modo INICIO se imprime por pantalla un menu
if (estado == INICIO) {
gluLookAt(0, 7.5, 30, // posicion del ojo
0.0, 7.5, 0.0, // hacia que punto mira (0,7.5,0)
0.0, 1.0, 0.0); // definimos hacia arriba (eje Y)
//Ponemos fondo a la pantalla de incicio)
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, ETSIDI::getTexture("imagenes/menufinal2.png").id);
//dibujo del plano donde est la foto
glDisable(GL_LIGHTING);
glBegin(GL_POLYGON);
glColor3f(1, 1, 1);
glTexCoord2d(0, 1); glVertex3f(-15, -3.5, -0.1);
glTexCoord2d(1, 1); glVertex3f(15, -3.5, -0.1); //se elige donde poner la imagen de fondo. ponemos -0.1 en z para que est de fondo
glTexCoord2d(1, 0); glVertex3f(15, 20, -0.1);
glTexCoord2d(0, 0); glVertex3f(-15, 20, -0.1);
glEnd();
glEnable(GL_LIGHTING);
glDisable(GL_TEXTURE_2D);
}
//si el juego esta en modo "activo", es decir, en JUGVSMAQ o JUGVSMAQ se dibuja en la pantalla el espacio
else if (estado == JUGVSMAQ || estado == JUGVSJUG)
{
Juego.Dibuja();
}
//si el juego esta en REGLAS se facilitan por pantalla las reglas del juego
else if (estado == REGLAS) {
gluLookAt(0, 7.5, 30, // posicion del ojo
0.0, 7.5, 0.0, // hacia que punto mira (0,7.5,0)
0.0, 1.0, 0.0); // definimos hacia arriba (eje Y)
//Ponemos fondo a la pantalla de incicio)
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, ETSIDI::getTexture("imagenes/reglas.png").id);
//dibujo del plano donde est la foto
glDisable(GL_LIGHTING);
glBegin(GL_POLYGON);
glColor3f(1, 1, 1);
glTexCoord2d(0, 1); glVertex3f(-15, -3.5, -0.1);
glTexCoord2d(1, 1); glVertex3f(15, -3.5, -0.1); //se elige donde poner la imagen de fondo. ponemos -0.1 en z para que est de fondo
glTexCoord2d(1, 0); glVertex3f(15, 20, -0.1);
glTexCoord2d(0, 0); glVertex3f(-15, 20, -0.1);
glEnd();
glEnable(GL_LIGHTING);
glDisable(GL_TEXTURE_2D);
}
//si el juego esta en FINJ1 o FINJ2 significa que uno de los jugadores ha perdido, se imprime por pantalla y finaliza el juego
else if (estado == FINJ1)
{
gluLookAt(0, 7.5, 30, // posicion del ojo
0.0, 7.5, 0.0, // hacia que punto mira (0,7.5,0)
0.0, 1.0, 0.0); // definimos hacia arriba (eje Y)
//Ponemos fondo a la pantalla de incicio)
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, ETSIDI::getTexture("imagenes/menu3.png").id);
//dibujo del plano donde est la foto
glDisable(GL_LIGHTING);
glBegin(GL_POLYGON);
glColor3f(1, 1, 1);
glTexCoord2d(0, 1); glVertex3f(-15, -3.5, -0.1);
glTexCoord2d(1, 1); glVertex3f(15, -3.5, -0.1); //se elige donde poner la imagen de fondo. ponemos -0.1 en z para que est de fondo
glTexCoord2d(1, 0); glVertex3f(15, 20, -0.1);
glTexCoord2d(0, 0); glVertex3f(-15, 20, -0.1);
glEnd();
glEnable(GL_LIGHTING);
glDisable(GL_TEXTURE_2D);
ETSIDI::setTextColor(150, 75, 0); //r g b
ETSIDI::setFont("fuentes/Calibri.ttf", 60);
ETSIDI::printxy("Victoria J1! ", -7, 14);
ETSIDI::setTextColor(150, 75, 0); //r g b
ETSIDI::setFont("fuentes/Calibri.ttf", 30);
ETSIDI::printxy("Presione E para salir", -7, 10);
}
else if (estado == FINJ2)
{
gluLookAt(0, 7.5, 30, // posicion del ojo
0.0, 7.5, 0.0, // hacia que punto mira (0,7.5,0)
0.0, 1.0, 0.0); // definimos hacia arriba (eje Y)
//Ponemos fondo a la pantalla de incicio)
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, ETSIDI::getTexture("imagenes/menu3.png").id);
//dibujo del plano donde est la foto
glDisable(GL_LIGHTING);
glBegin(GL_POLYGON);
glColor3f(1, 1, 1);
glTexCoord2d(0, 1); glVertex3f(-15, -3.5, -0.1);
glTexCoord2d(1, 1); glVertex3f(15, -3.5, -0.1); //se elige donde poner la imagen de fondo. ponemos -0.1 en z para que est de fondo
glTexCoord2d(1, 0); glVertex3f(15, 20, -0.1);
glTexCoord2d(0, 0); glVertex3f(-15, 20, -0.1);
glEnd();
glEnable(GL_LIGHTING);
glDisable(GL_TEXTURE_2D);
ETSIDI::setTextColor(150, 75, 0); //r g b
ETSIDI::setFont("fuentes/Calibri.ttf", 60);
ETSIDI::printxy("Victoria J2! ", -7, 14);
ETSIDI::setTextColor(150, 75, 0); //r g b
ETSIDI::setFont("fuentes/Calibri.ttf", 30);
ETSIDI::printxy("Presione E para salir", -7, 10);
}
}
void Inicio::Raton(int button, int state, int x, int y)
{
Juego.Raton(button, state, x, y);
}
void Inicio::RotarOjo()
{
if (contador < 100 && (estado == JUGVSMAQ || estado == JUGVSJUG)) {
Juego.RotarOjo();
contador++;
}
else Juego.Para();
}
void Inicio::Mueve()
{
if (estado == JUGVSMAQ || estado == JUGVSJUG)
{
if ( Juego.GetContadorJ1() == 0)
{
estado = FINJ2;
}
if (Juego.GetContadorJ2() == 0)
{
estado = FINJ1;
}
}
}
| true |
fb0607e7fa8e670321b1be1411fd323360e8a37a
|
C++
|
alexyuehuang/OOP_Projects
|
/Studio8/Studio8/Header.h
|
UTF-8
| 514 | 2.90625 | 3 |
[] |
no_license
|
#include <iostream>
using namespace std;
class Rect {
private: int length=1; const int parameter=1;
public:
int width=1;
Rect() :length(0), width(0), parameter(0)
{}
// Rect( Rect &n) :length(n.getlength()), width(n.getwidth()), parameter(0)
//{}
int getlength() {
return length;
}
int getwidth() {
return width;
}
void changewidth(int a) {
width = a;
}
void changelength(int a) {
length = a;
}
/*void parameter(int a) {
parameter = a;
}*/
int getparameter() {
return parameter;
}
};
| true |
9810bcd7b25869238d3ef0b3182f3bb133887486
|
C++
|
aashish-2096/practice-check
|
/DS/tree/levelTraversal.cpp
|
UTF-8
| 2,500 | 3.71875 | 4 |
[] |
no_license
|
#include<bits/stdc++.h>
using namespace std;
class Node{
public:
int data;
Node* left;
Node* right;
Node(int data){
this->data = data;
this->left = nullptr;
this->right = nullptr;
}
};
class LevelOrderTraversal{
public:
Node *root;
LevelOrderTraversal(){
this->root = nullptr;
}
Node* createNode(int data){
Node *newNode = new Node(data);
return newNode;
}
void preOrderTraversal(Node* temp){
if(temp == nullptr){
return;
}
else{
cout<<temp->data<<" ";
preOrderTraversal(temp->left);
preOrderTraversal(temp->right);
}
}
int returnHeightOfTree(Node*temp){
int leftHeight,rightheight;
if(temp ==nullptr){
return -1;
}
else{
leftHeight = 1+returnHeightOfTree(temp->left);
rightheight = 1+returnHeightOfTree(temp->right);
return max(leftHeight,rightheight);
}
return 0;
}
int returnSizeOfTree(Node*temp){
if(temp == nullptr){
return 0;
}
else{
return 1+returnSizeOfTree(temp->left)+returnSizeOfTree(temp->right);
}
}
void levelOrderTraversal(Node *temp){
queue<Node*>node;
Node* diff = nullptr;
if(temp == nullptr){
return;
}
else{
node.push(temp);
while(!node.empty()){
diff = node.front();
node.pop();
cout<<diff->data<<" ";
if(diff->left != nullptr)
node.push(diff->left);
if(diff->right != nullptr)
node.push(diff->right);
}
}
}
};
int main(){
LevelOrderTraversal * tree = new LevelOrderTraversal();
tree->root = tree->createNode(5);
tree->root->left = tree->createNode(4);
tree->root->left->left = tree->createNode(2);
tree->root->left->right = tree->createNode(3);
tree->root->right = tree->createNode(7);
tree->root->right->left = tree->createNode(6);
tree->root->right->right = tree->createNode(8);
tree->root->right->right->right = tree->createNode(11);
cout<<"Level Order Traversal"<<endl;
//tree->preOrderTraversal(tree->root);
//tree->levelOrderTraversal(tree->root);
cout<<tree->returnHeightOfTree(tree->root)<<endl;
cout<<tree->returnSizeOfTree(tree->root);
return 0;
}
| true |
8d9813fd5dbf7db7e72ddbb5f234c9eccf192a1f
|
C++
|
meepzh/CIS563-FluidSolver
|
/src/geom/drawable.cpp
|
UTF-8
| 1,106 | 2.578125 | 3 |
[
"WTFPL"
] |
permissive
|
// Copyright 2016 Robert Zhou
//
// drawable.cpp
// MFluidSolver
#include "drawable.hpp"
Drawable::Drawable()
: vertexIndexArrBufferID(-1),
vertexColorArrBufferID(-1),
vertexPositionArrBufferID(-1) {
}
Drawable::~Drawable() {
if (vertexIndexArrBufferID != -1) glDeleteBuffers(1, &vertexIndexArrBufferID);
if (vertexColorArrBufferID != -1) glDeleteBuffers(1, &vertexColorArrBufferID);
if (vertexPositionArrBufferID != -1)
glDeleteBuffers(1, &vertexPositionArrBufferID);
}
bool Drawable::bindIndexBuffer() {
if (vertexIndexArrBufferID == -1) return false;
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vertexIndexArrBufferID);
return true;
}
bool Drawable::bindColorBuffer() {
if (vertexColorArrBufferID == -1) return false;
glBindBuffer(GL_ARRAY_BUFFER, vertexColorArrBufferID);
return true;
}
bool Drawable::bindPositionBuffer() {
if (vertexPositionArrBufferID == -1) return false;
glBindBuffer(GL_ARRAY_BUFFER, vertexPositionArrBufferID);
return true;
}
GLenum Drawable::drawMode() {
return GL_TRIANGLES;
}
GLenum Drawable::idxCount() {
return _idxCount;
}
| true |
ea74ee65a2d11687ffad228da8b1c676923431ae
|
C++
|
MishkaSimakov/CRayTracing
|
/include/Color.h
|
UTF-8
| 1,222 | 2.9375 | 3 |
[] |
no_license
|
#pragma once
#ifndef RAYTRACING_COLOR_H
#define RAYTRACING_COLOR_H
#include "Math/Vec3.h"
#include "SFML/Graphics.hpp"
class Color {
public:
double r, g, b;
Color(double _value) : r(_value), g(_value), b(_value) {};
Color(vec3 v) : r(v.x), g(v.y), b(v.z) {};
Color(double _r, double _g, double _b) : r(_r), g(_g), b(_b) {};
Color operator+(Color other) { return Color(r + other.r, g + other.g, b + other.b); }
Color operator*(Color other) { return Color(r * other.r, g * other.g, b * other.b); }
Color operator/(Color other) { return Color(r / other.r, g / other.g, b / other.b); }
Color corrected() {
// Color col = Color(r, g, b, a);
//
// float white = 20.0;
// col = col * white * 16.0;
// col = (col * (col / white / white + 1.0)) / (col + 1.0);
//
// return col;
// double gamma = 1;
// return Color(pow(r, gamma), pow(g, gamma), pow(b, gamma));
return *this;
}
sf::Color getSFMLColor() {
return sf::Color(
std::min(r * 255, 255.0),
std::min(g * 255, 255.0),
std::min(b * 255, 255.0),
255
);
}
};
#endif //RAYTRACING_COLOR_H
| true |
d8cf80ec392cf3c1697e99b10b80ef7c34a8479c
|
C++
|
JonathanXSG/MP_NN
|
/src/neural_network/feedForward.cpp
|
UTF-8
| 1,381 | 2.734375 | 3 |
[] |
no_license
|
#include "../../headers/NeuralNetwork.hpp"
void NeuralNetwork::feedForward() {
std::vector<double> *leftNeurons; // Matrix of neurons to the left
Matrix *leftWeights; // Matrix of weights between leftNeurons and next layer
for (unsigned i = 0; i < (this->topologySize - 1); i++) {
// If it's not the input layer, get the activated values
if (i != 0)
leftNeurons = this->getActivatedNeurons(i);
// If it's the input layer, get the non-activated values
else
leftNeurons = this->getNeurons(i);
leftWeights = this->getWeightMatrix(i);
fill(this->getNeurons(i + 1)->begin(),
this->getNeurons(i + 1)->end(),
this->bias);
// Here we are basically multiplying the Neurons from the previous layer
// to the weights that go to each right neuron, them sum them
// rightNeuron_x = Sum ( leftNeuron_y * weight_x-y )
// #pragma omp parallel for schedule(static, 1) collapse(2)
for (unsigned r = 0; r < leftWeights->getRows(); r++) {
for (unsigned c = 0; c < leftWeights->getColumns(); c++) {
this->getNeurons(i+1)->at(c) += (leftNeurons->at(r) * leftWeights->at(r, c));
}
}
this->layers.at(i + 1)->activate();
this->layers.at(i + 1)->derive();
}
}
| true |
918df9ebaa30544c5ddab8bdce98919a71b50161
|
C++
|
LyricZhao/DLMO
|
/pci-test.cpp
|
UTF-8
| 1,530 | 2.6875 | 3 |
[] |
no_license
|
#include <cuda_runtime.h>
#include <curand.h>
#include <iostream>
#include "timer.hpp"
#include "utils.hpp"
int main() {
auto bandwidth = [](size_t size, uint64_t time) {
double speed = static_cast<double>(size) / time * 1e9;
return speed / static_cast<double>(1u << 30u);
};
for (size_t size: {Unit::B(4), Unit::KiB(1), Unit::MiB(1), Unit::GiB(1), Unit::GiB(2), Unit::GiB(4)}) {
printf("Running test with %s ... \n", prettyBytes(size).c_str());
// Init
void *host_ptr, *device_ptr;
cudaMallocHost(&host_ptr, size, cudaHostAllocDefault);
cudaMalloc(&device_ptr, size);
curandGenerator_t generator;
curandCreateGeneratorHost(&generator, CURAND_RNG_PSEUDO_DEFAULT);
curandGenerateNormal(generator, static_cast<float*>(host_ptr), size / sizeof(float), 0, 0.1);
// Transfer
Timer timer;
cudaMemcpy(device_ptr, host_ptr, size, cudaMemcpyHostToDevice);
auto host2device_duration = timer.tik();
cudaMemcpy(host_ptr, device_ptr, size, cudaMemcpyDeviceToHost);
auto device2host_duration = timer.tik();
// Finish
cudaFreeHost(host_ptr);
cudaFree(device_ptr);
printf(" > Host to device: %s (%.3lf GiB/s)\n", prettyNanoseconds(host2device_duration).c_str(), bandwidth(size, host2device_duration));
printf(" > Device to host: %s (%.3lf GiB/s)\n", prettyNanoseconds(device2host_duration).c_str(), bandwidth(size, device2host_duration));
}
return 0;
}
| true |
c4fbe9248a80bae9f01f23f3c0f96fe8338d719e
|
C++
|
hereandnowlive/Opengl
|
/assignment 3/index.cpp
|
UTF-8
| 610 | 3.234375 | 3 |
[] |
no_license
|
#include "index.h"
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
index::index(){
//set values of the vector
this->x = 0;
this->y = 0;
this->z = 0;
}
//implementation of the normailze function
void index::normalize(index normal[], int i, int j,int indexsize){
norm = sqrt(pow((normal[i*indexsize + j].x),2.0) + pow((normal[i*indexsize + j].y),2.0) + pow((normal[i*indexsize + j].z),2.0));
normal[i*indexsize + j].x = normal[i*indexsize + j].x/norm;
normal[i*indexsize + j].y = normal[i*indexsize + j].y/norm;
normal[i*indexsize + j].z = normal[i*indexsize + j].z/norm;
}
| true |
6ad11660827c3bea4a24ccfa3ea98adf0c5959a3
|
C++
|
AcademySoftwareFoundation/openexr
|
/src/examples/generalInterfaceTiledExamples.cpp
|
UTF-8
| 3,391 | 2.578125 | 3 |
[
"BSD-3-Clause",
"LicenseRef-scancode-generic-cla"
] |
permissive
|
//
// SPDX-License-Identifier: BSD-3-Clause
// Copyright (c) Contributors to the OpenEXR Project.
//
//-----------------------------------------------------------------------------
//
// Code examples that show how class TiledInputFile and
// class TiledOutputFile can be used to read and write
// OpenEXR image files with an arbitrary set of channels.
//
//-----------------------------------------------------------------------------
#include <ImfArray.h>
#include <ImfChannelList.h>
#include <ImfMatrixAttribute.h>
#include <ImfStringAttribute.h>
#include <ImfTiledInputFile.h>
#include <ImfTiledOutputFile.h>
#include "drawImage.h"
#include <iostream>
#include "namespaceAlias.h"
using namespace IMF;
using namespace std;
using namespace IMATH_NAMESPACE;
void
writeTiled1 (
const char fileName[],
Array2D<GZ>& pixels,
int width,
int height,
int tileWidth,
int tileHeight)
{
Header header (width, height);
header.channels ().insert ("G", Channel (IMF::HALF));
header.channels ().insert ("Z", Channel (IMF::FLOAT));
header.setTileDescription (
TileDescription (tileWidth, tileHeight, ONE_LEVEL));
TiledOutputFile out (fileName, header);
FrameBuffer frameBuffer;
frameBuffer.insert (
"G", // name
Slice (
IMF::HALF, // type
(char*) &pixels[0][0].g, // base
sizeof (pixels[0][0]) * 1, // xStride
sizeof (pixels[0][0]) * width)); // yStride
frameBuffer.insert (
"Z", // name
Slice (
IMF::FLOAT, // type
(char*) &pixels[0][0].z, // base
sizeof (pixels[0][0]) * 1, // xStride
sizeof (pixels[0][0]) * width)); // yStride
out.setFrameBuffer (frameBuffer);
out.writeTiles (0, out.numXTiles () - 1, 0, out.numYTiles () - 1);
}
void
readTiled1 (const char fileName[], Array2D<GZ>& pixels, int& width, int& height)
{
TiledInputFile in (fileName);
Box2i dw = in.header ().dataWindow ();
width = dw.max.x - dw.min.x + 1;
height = dw.max.y - dw.min.y + 1;
int dx = dw.min.x;
int dy = dw.min.y;
pixels.resizeErase (height, width);
FrameBuffer frameBuffer;
frameBuffer.insert (
"G", // name
Slice (
IMF::HALF, // type
(char*) &pixels[-dy][-dx].g, // base
sizeof (pixels[0][0]) * 1, // xStride
sizeof (pixels[0][0]) * width)); // yStride
frameBuffer.insert (
"Z", // name
Slice (
IMF::FLOAT, // type
(char*) &pixels[-dy][-dx].z, // base
sizeof (pixels[0][0]) * 1, // xStride
sizeof (pixels[0][0]) * width)); // yStride
in.setFrameBuffer (frameBuffer);
in.readTiles (0, in.numXTiles () - 1, 0, in.numYTiles () - 1);
}
void
generalInterfaceTiledExamples ()
{
cout << "\nGZ (green, depth) tiled files\n" << endl;
cout << "drawing image" << endl;
int w = 800;
int h = 600;
Array2D<GZ> pixels (h, w);
drawImage6 (pixels, w, h);
cout << "writing file" << endl;
writeTiled1 ("tiledgz1.exr", pixels, w, h, 64, 64);
cout << "reading file" << endl;
readTiled1 ("tiledgz1.exr", pixels, w, h);
}
| true |
3f224083c4725127834d0fbbcfed6614d43f961a
|
C++
|
Hjvf01/battle_city
|
/src/controllers/user_controller.cpp
|
UTF-8
| 2,546 | 2.90625 | 3 |
[] |
no_license
|
#include "controllers.h"
UserController::UserController(
UserTank *_tank,
QQuickView *_view,
BoardController *_board
) : QObject() {
tank = _tank;
view = _view;
board = _board;
root = view->rootObject();
bullets_factory = new BulletFactory(view->engine());
initTank();
}
UserController::~UserController() {
delete tank;
delete bullets_factory;
for(auto bullet: bullets) delete bullet;
}
void UserController::changeTank(UserTank *_tank) {
tank = _tank;
initTank();
}
void UserController::initTank() {
tank->setParentItem(root);
tank->setParent(view);
connect(
tank, SIGNAL(moveNorth()),
this, SLOT(onMoveNorth())
);
connect(
tank, SIGNAL(moveEast()),
this, SLOT(onMoveEast())
);
connect(
tank, SIGNAL(moveSouth()),
this, SLOT(onMoveSouth())
);
connect(
tank, SIGNAL(moveWest()),
this, SLOT(onMoveWest())
);
connect(
tank, SIGNAL(shoot()),
this, SLOT(onShoot())
);
}
void UserController::onMoveEast() {
if(tank->getDirection() != Direction::East)
return tank->turnEast();
if(board->canMoveEast(tank))
tank->setX(tank->x() + tank->getStep());
}
void UserController::onMoveNorth() {
if(tank->getDirection() != Direction::North)
return tank->turnNorth();
if(board->canMoveNorth(tank))
tank->setY(tank->y() - tank->getStep());
}
void UserController::onMoveSouth() {
if(tank->getDirection() != Direction::South)
return tank->turnSouth();
if(board->canMoveSouth(tank))
tank->setY(tank->y() + tank->getStep());
}
void UserController::onMoveWest() {
if(tank->getDirection() != Direction::West)
return tank->turnWest();
if(board->canMoveWest(tank))
tank->setX(tank->x() - tank->getStep());
}
void UserController::onShoot() {
BulletController* b_contr = new BulletController(
bullets_factory->makeBullet(
tank->getDirection(),
tank->x(),
tank->y(),
tank->getSize()
),
board,
view,
true
);
bullets.append(b_contr);
connect(
b_contr, &BulletController::explode,
this, &UserController::onExplode
);
}
void UserController::onExplode(BulletController *bullet) {
Bullet* _bullet = bullet->getBullet();
board->destroy(_bullet->x(), _bullet->y(), _bullet->getDirection());
bullets.removeOne(bullet);
delete bullet;
}
| true |
950d3a728564f53e85ce8a806443ca17ba434e82
|
C++
|
rpdunn77/Kitty-Pirateer
|
/hdr/Game.h
|
UTF-8
| 2,867 | 3.078125 | 3 |
[] |
no_license
|
//Edited by: Keenan Longair.
//Last update: 8:30PM February 8th, 2016.
//Purpose: Prototyping of the main "GameBoard" and its interface. This is implemented
//as a singleton and thus can only have one instance. Use the Game::getInstance() function
//to gain access to the instance.
//Version: 0.6
#ifndef GAME_H_
#define GAME_H_
#include <stdlib.h>
#include <GL/glut.h> /* glut.h includes gl.h and glu.h */
class ImageLoader;//Gives access to the ImageLoader.
class Menu;//Gives access to the Menu.
#define MAX_OBJECTS 50//50 is Default for now, may be increased once # of objects has been
//determined.
class Game {
private:
//Contructor is private, if you want to get the instance use the public getInstance
//function by calling Game::getInstance().
Game() {
m_margine = 4;
m_width = 507*2;
m_height = 432*2;
};//Default Constructor.
Game(Game const&); //Don't Implement
void operator=(Game const&); //Don't implement
const static int c_interval = 1000 / 60;//60 frames per second, c_interval sets up
//the screens refresh rate and fps I believe.
//Window size:
int m_width;
int m_height;
int m_margine;
//Background texture:
GLuint m_backgroundTexture;
public:
//Insead of a constructor, use this static method to create an instance
//(or use the already created instance) of Game making this a singleton.
static Game& getInstance()
{
static Game instance;//Guaranteed to be destroyed.
//Instantiated on first use.
return instance;
};
static bool c_running;//Variable to tell update if the game is to be paused or not.
//The c_running variable is public, to allow other objects to alter this, in essence
//allowing events to pause the game if necessary.
//Functions for GL.
static void key(unsigned char key, int x, int y);//Key takes in the key commands
//used to call the control functions of the controllable character.
static void run();//Run is the computing loop which calls update.
static void idle();//Handles the delay between screen updates.
static void timer(int id);//Times and calls the update on the screen.
void update();//Update handles updating the display screen and calling update on each object.
void reshape(GLsizei newwidth, GLsizei newheight);//Reshapes the window as needed.
int LoadImage(char *filename);//Not sure what this does yet due to missing implementation.
//This function is currently left here in order to have it incase it is needed, but may be
//removed once its use is understood.
void init();//Set to be public incase any objects inheriting from this needs their init
//to be public aswell.
GLfloat frand();//Random number function. Here incase we need it.
};
#endif /* GAME_H_ */
| true |
69ff0ebc05a7ff615d93a4403750a00d7ebcbcf8
|
C++
|
daidai21/Leetcode
|
/Algorithms/C++/520-Detect_Capital.cpp
|
UTF-8
| 989 | 3.3125 | 3 |
[] |
no_license
|
// Runtime: 0 ms, faster than 100.00% of C++ online submissions for Detect Capital.
// Memory Usage: 8.2 MB, less than 50.00% of C++ online submissions for Detect Capital.
class Solution {
public:
bool detectCapitalUse(string word) {
if (word.size() == 1)
return true;
int upper_num = 0;
for (int i = 1; i < word.size(); ++i)
if (isupper(word[i]))
upper_num++;
return upper_num == 0 || (isupper(word[0]) && upper_num == word.size() - 1);
}
};
// Runtime: 8 ms, faster than 59.77% of C++ online submissions for Detect Capital.
// Memory Usage: 8.2 MB, less than 75.00% of C++ online submissions for Detect Capital.
class Solution {
public:
bool detectCapitalUse(string word) {
for (int i = 1; i < word.size(); ++i)
if (isupper(word[1]) != isupper(word[i]) || islower(word[0]) && isupper(word[i]))
return false;
return true;
}
};
| true |
e941efa470ff2047c21e9345b58f65c4966dd348
|
C++
|
asad-shuvo/ACM
|
/Online Judge/Leetcode/90. Subsets II.cpp
|
UTF-8
| 777 | 2.765625 | 3 |
[] |
no_license
|
// class Solution {
// public:
// vector<vector<int>> subsetsWithDup(vector<int>& nums) {
// }
// };
class Solution {
public:
vector<vector<int> >ans;
map<vector<int>,int>mp;
vector<int>tmp;
int mx;
void G(vector<int>v,int val,int indx){
if(v.size()==mx)return;
v.push_back(val);
sort(v.begin(),v.end());
if(mp[v]==0){
mp[v]=1;
ans.push_back(v);
}
for(int i=indx+1;i<mx;i++){
G(v,tmp[i],i);
}
}
vector<vector<int>> subsetsWithDup(vector<int>& nums) {
mx=nums.size();
tmp=nums;
vector<int>v;
ans.push_back(v);
for(int i=0;i<nums.size();i++)
G(v,nums[i],i);
return ans;
}
};
| true |
f8bcc97346fa8f8bef929032119cc674ef091eac
|
C++
|
2719896135/-
|
/NOIP-master/2007/escape/escape.cpp
|
UTF-8
| 698 | 3.203125 | 3 |
[] |
no_license
|
#include <stdio.h>
int FlashDistance (int curDist, int* magic);
int main ()
{
int magic, distance, time;
scanf ("%d", &magic);
scanf ("%d", &distance);
scanf ("%d", &time);
int flash = 0;
int run = 0;
for (int i = 1; i <= time; i ++) {
flash = FlashDistance (flash, &magic);
run += 17;
if (flash > run) {
run = flash;
}
if (run >= distance) {
printf ("Yes\n%d\n", i);
return 0;
}
}
printf ("No\n%d\n", run);
return 0;
}
int FlashDistance (int curDist, int* magic)
{
if (*magic >= 10) {
*magic -= 10;
curDist += 60;
return curDist;
}
*magic += 4;
return curDist;
}
| true |
af40065886883e01803a992ea80c60c502ee6f6a
|
C++
|
ellynhan/algorithm
|
/Tree/treeTraversal.cpp
|
UTF-8
| 1,594 | 3.28125 | 3 |
[] |
no_license
|
#include <iostream>
#include <queue>
using namespace std;
typedef struct Node{
char parent, left, right, me;
}node;
queue<char> preOrderAnswer;
queue<char> midOrderAnswer;
queue<char> postOrderAnswer;
node nodes[26];
void preOrder(node root){
preOrderAnswer.push(root.me);
if(root.left != '.'){
preOrder(nodes[root.left-'A']);
}
if(root.right!='.'){
preOrder(nodes[root.right-'A']);
}
return ;
}
void midOrder(node root){
if(root.left != '.'){
midOrder(nodes[root.left-'A']);
}
midOrderAnswer.push(root.me);
if(root.right!='.'){
midOrder(nodes[root.right-'A']);
}
return ;
}
void postOrder(node root){
if(root.left != '.'){
postOrder(nodes[root.left-'A']);
}
if(root.right!='.'){
postOrder(nodes[root.right-'A']);
}
postOrderAnswer.push(root.me);
return ;
}
int main(){
int visited[26]={0,};
int N;
char tmp;
cin >> N;
for(int i=0; i<N; i++){
char tmp;
cin >> tmp;
int index = tmp-'A';
nodes[index].me = tmp;
cin >> nodes[index].left >> nodes[index].right;
}
preOrder(nodes[0]);
midOrder(nodes[0]);
postOrder(nodes[0]);
while(!preOrderAnswer.empty()){
cout<<preOrderAnswer.front();
preOrderAnswer.pop();
}
cout<<endl;
while(!midOrderAnswer.empty()){
cout<<midOrderAnswer.front();
midOrderAnswer.pop();
}
cout<<endl;
while(!postOrderAnswer.empty()){
cout<<postOrderAnswer.front();
postOrderAnswer.pop();
}
}
| true |
b9d679b91bf080e45c8c437dacbad053621233f8
|
C++
|
Sookmyung-Algos/2021algos
|
/algos_assignment/3rd_grade/이가은_l2x3ge/1st_week/7576.cpp
|
UTF-8
| 1,065 | 2.671875 | 3 |
[] |
no_license
|
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
int M, N;
void bfs();
int v[1001][1001];
int time[1001][1001] = { 0, };
queue < pair<int, int>> q;
int dx[4] = { -1,1,0,0 };
int dy[4] = { 0,0,-1,1 };
int main() {
int max = 0;
cin >> M >> N;
for (int i = 0;i < N;i++) {
for (int j = 0;j < M;j++) {
cin >> v[i][j];
if (v[i][j] == 1) {
q.push(make_pair(i, j));
}
}
}
bfs();
for (int i = 0;i < N;i++) {
for (int j = 0;j < M;j++) {
if (v[i][j] == 0) {
cout << -1;
return 0;
}
if (max < time[i][j]) max = time[i][j];
}
}
cout << max;
}
void bfs() {
while (!q.empty()) {
int x = q.front().first;
int y = q.front().second;
q.pop();
for (int i = 0;i < 4;i++) {
int next_x = x + dx[i];
int next_y = y + dy[i];
if (next_x >= 0 && next_y >= 0 && next_x < N && next_y < M && (v[next_x][next_y]==0)) {
v[next_x][next_y] = 1;
q.push(make_pair(next_x, next_y));
//------토마토가 익는 시간 (레벨)----------
time[next_x][next_y] = time[x][y] + 1;
}
}
}
}
| true |
afe521d081dc8f1904111c6d4412f710d36b21f3
|
C++
|
DavidKopalaCU/CSCI2270
|
/BST/BST/BST.cpp
|
UTF-8
| 6,153 | 3.3125 | 3 |
[] |
no_license
|
//
// BST.cpp
// BST
//
// Created by David Kopala on 3/8/18.
// Copyright © 2018 davidkopala. All rights reserved.
//
#include "BST.hpp"
BST::BST()
{
root = nullptr;
height = -1;
}
BST::BST(int start)
{
root = new node(start, nullptr, nullptr, nullptr);
height = 0;
}
bool BST::priv_find(node *parent, int target)
{
if (parent == nullptr) {
return false;
} else if (parent->value == target) {
return true;
} else if (target < parent->value) {
return priv_find(parent->left, target);
} else {
return priv_find(parent->right, target);
}
}
bool BST::exists(int target)
{
return priv_find(root, target);
}
void BST::addValue(int value)
{
if (exists(value)) {
return;
}
if (root == nullptr) {
root = new node(value, nullptr, nullptr, nullptr);
return;
}
priv_addValue(root, value, 0);
}
void BST::priv_addValue(node *parent, int value, int depth)
{
if (value < parent->value) {
if (parent->left == nullptr) {
parent->left = new node(value, parent, nullptr, nullptr);
if (depth == height) {
height++;
}
return;
} else {
return priv_addValue(parent->left, value, ++depth);
}
} else {
if (parent->right == nullptr) {
parent->right = new node(value, parent, nullptr, nullptr);
if (depth == height) {
height++;
}
return;
} else {
return priv_addValue(parent->right, value, ++depth);
}
}
}
void BST::getLevel_recur(node *parent, int level, string *build)
{
if (level == 0) {
if (parent == nullptr) {
(*build) += "-,";
} else {
(*build) += to_string(parent->value) + ",";
}
return;
} else {
if (parent == nullptr) {
getLevel_recur(parent, level-1, build);
getLevel_recur(parent, level-1, build);
} else {
getLevel_recur(parent->left, level-1, build);
getLevel_recur(parent->right, level-1, build);
}
}
}
string *BST::getLevel(int level)
{
string *levelVals = new string[pow(2, level)];
string build;
getLevel_recur(root, level, &build);
stringstream s(build);
int index = 0;
while (!s.eof()) {
string word;
getline(s, word, ',');
if (word == "") {
continue;
}
levelVals[index++] = word;
}
return levelVals;
}
void BST::printTree()
{
int maxWidth = pow(2, height+2);
for (int i = 0; i <= height; i++) {
int spacing = (maxWidth / (pow(2, i) + 1)) - (1);
string *vals = getLevel(i);
for (int j = 0; j < pow(2, i); j++) {
if (j < (pow(2, i)/2)) {
cout<<left<<setw(spacing)<<" "<<setw(2)<<vals[j];
} else {
cout<<right<<setw(spacing)<<" "<<setw(2)<<vals[j];
}
}
cout<<endl;
}
}
void BST::priv_deleteValue(node *parent, int target) {
if (parent == nullptr) {
return;
} else if (parent->value != target) {
if (target < parent->value) {
return priv_deleteValue(parent->left, target);
} else {
return priv_deleteValue(parent->right, target);
}
} else {
//No children
if (parent->right == nullptr && parent->left == nullptr) {
if (parent->parent->left == parent) {
parent->parent->left = nullptr;
} else {
parent->parent->right = nullptr;
}
delete parent;
return;
} else if ((parent->right == nullptr) || (parent->left == nullptr)) { //One child
if (parent->parent->left == parent) {
if (parent->left != nullptr) {
parent->left->parent = parent->parent;
parent->parent->left = parent->left;
} else {
parent->right->parent = parent->parent;
parent->parent->left = parent->right;
}
} else {
if (parent->left != nullptr) {
parent->left->parent = parent->parent;
parent->parent->right = parent->left;
} else {
parent->right->parent = parent->parent;
parent->parent->right = parent->right;
}
}
delete parent;
return;
} else { //Two Children
if (parent == root) {
return;
} else if (parent->value < parent->parent->value) {
node *next = parent->right;
while (next->left != nullptr) {
next = next->left;
}
parent->parent->left = next;
if (next->right != nullptr) {
next->parent->left = next->right;
next->right->parent = next->parent;
} else {
next->parent->left = nullptr;
}
next->parent = parent->parent;
parent->parent->left = next;
next->left = parent->left;
next->right = parent->right;
} else {
node *next = parent->left;
while (next->right != nullptr) {
next = next->right;
}
parent->parent->right = next;
if (next->left != nullptr) {
next->parent->right = next->left;
next->left->parent = next->parent;
} else {
next->parent->right = nullptr;
}
next->parent = parent->parent;
parent->parent->right = next;
next->left = parent->left;
next->right = parent->right;
}
}
}
}
void BST::deleteValue(int target)
{
if (!exists(target)) {
return;
}
priv_deleteValue(root, target);
}
| true |
d8a89361525befad266337529d821d3a2a396a67
|
C++
|
redorav/hlslpp
|
/include/hlsl++_type_traits.h
|
UTF-8
| 2,256 | 2.75 | 3 |
[
"MIT"
] |
permissive
|
#pragma once
namespace hlslpp
{
template <bool Test, class T = void>
struct enable_if {};
template <class T>
struct enable_if<true, T>
{
typedef T type;
};
template <typename T> struct remove_cv { typedef T type; };
template <typename T> struct remove_cv<const T> { typedef T type; };
template <typename T> struct remove_cv<volatile T> { typedef T type; };
template <typename T> struct remove_cv<const volatile T> { typedef T type; };
template<typename T, T Value>
struct integral_constant { static const T value = Value; };
typedef integral_constant<bool, true> true_type;
typedef integral_constant<bool, false> false_type;
template<typename T> struct is_integral_helper : false_type {};
template<> struct is_integral_helper<bool> : true_type {};
template<> struct is_integral_helper<char> : true_type {};
template<> struct is_integral_helper<signed char> : true_type {};
template<> struct is_integral_helper<unsigned char> : true_type {};
template<> struct is_integral_helper<wchar_t> : true_type {};
template<> struct is_integral_helper<short> : true_type {};
template<> struct is_integral_helper<unsigned short> : true_type {};
template<> struct is_integral_helper<int> : true_type {};
template<> struct is_integral_helper<unsigned int> : true_type {};
template<> struct is_integral_helper<long> : true_type {};
template<> struct is_integral_helper<unsigned long> : true_type {};
template<> struct is_integral_helper<long long> : true_type {};
template<> struct is_integral_helper<unsigned long long> : true_type {};
template<typename T>
struct is_integral : is_integral_helper<typename remove_cv<T>::type> {};
template<typename T> struct is_floating_helper : false_type {};
template<> struct is_floating_helper<float> : true_type {};
template<> struct is_floating_helper<double> : true_type {};
template<> struct is_floating_helper<long double> : true_type {};
template<typename T>
struct is_floating_point : is_floating_helper<typename remove_cv<T>::type> {};
template<bool> struct concat;
template<> struct concat<false> : false_type {};
template<> struct concat<true> : true_type {};
template<class T>
struct is_arithmetic : concat<is_integral<T>::value || is_floating_point<T>::value> {};
}
| true |
ca8a548e8fb5fea4d21929df0612380c97987f6c
|
C++
|
knightzf/review
|
/leetcode/allPossibleFullBinaryTrees/q3.cpp
|
UTF-8
| 1,038 | 3.296875 | 3 |
[] |
no_license
|
#include "header.h"
class Solution {
public:
vector<TreeNode*> allPossibleFBT(int N) {
vector<TreeNode*> res;
if(N == 1)
{
TreeNode* node = new TreeNode(0);
res.push_back(node);
}
else
{
for(int i = 1; i < N - 1; i += 2)
{
vector<TreeNode*> leftV = allPossibleFBT(i);
vector<TreeNode*> rightV = allPossibleFBT(N - 1 - i);
for(int j = 0; j < leftV.size(); ++j)
{
for(int k = 0; k < rightV.size(); ++k)
{
TreeNode* node = new TreeNode(0);
node->left = leftV[j];
node->right = rightV[k];
res.push_back(node);
}
}
}
}
return res;
}
};
int main()
{
Solution s;
cout<<s.allPossibleFBT(2).size()<<endl;
}
| true |
fd491b68dad586d9e3329f4d0eaaf904df0bb885
|
C++
|
Rahul-111/Competitivecode
|
/Hashing/hashexaple.cpp
|
UTF-8
| 431 | 3.140625 | 3 |
[] |
no_license
|
#include<iostream>
#include<vector>
using namespace std;
vector <string > hashtable[100];
void insert(string s,int i)
{
hashtable[i].push_back(s);
}
void search(int n)
{
cout<<hashtable[n][0]<<"\n";
}
int main()
{
int n;
cin>>n;
while(n--)
{
int i;
cin>>i;
string s;
cin>>s;
insert(s,i);
}
int x;
cin>>x;
while(x--)
{
int t;
cin>>t;
search(t);
}
return 0;
}
| true |
be4ba5143b6ee9978e4d79f7a7754f36b7f6c043
|
C++
|
abalis3/forlorn-dryplace
|
/client/src/MenuTextBox.cpp
|
UTF-8
| 4,004 | 2.796875 | 3 |
[] |
no_license
|
#include "MenuTextBox.h"
#include "Util.h"
static const char BG_RECT_IMG_PATH[] = "MenuTextBox/background.png";
static const char MARVEL_FONT_PATH[] = "Fonts/Marvel-Regular.ttf";
static const int BASE_FONT_SIZE = 175;
static const float FONT_SIZE_SCALE = 0.8; /* pct of height of box for font height */
static const float FONT_SPACING_PCT = 0.05; /* pct of height of box for font spacing */
MenuTextBox::MenuTextBox(int maxChars)
{
/* Load necessary resources */
bgRectTexture = new raylib::Texture(Util::formResourcePath(BG_RECT_IMG_PATH));
bgRectTexture->GenMipmaps();
font = new raylib::Font(Util::formResourcePath(MARVEL_FONT_PATH), BASE_FONT_SIZE, nullptr, 95);
GenTextureMipmaps(&font->texture);
/* Initialize and alloc char array and set to empty string */
content = new char[maxChars + 1];
content[0] = '\0';
numChars = 0;
this->maxChars = maxChars;
enabled = true;
fontSize = BASE_FONT_SIZE;
fontSpacing = 0;
recalculateContentSize();
}
MenuTextBox::~MenuTextBox()
{
delete content;
delete bgRectTexture;
delete font;
}
void MenuTextBox::setSize(float width, float height)
{
/* Force the width to be at least as large as the height */
if (width >= height) {
dstRect.width = width;
} else {
dstRect.width = height;
}
dstRect.height = height;
fontSize = height * FONT_SIZE_SCALE;
fontSpacing = height * FONT_SPACING_PCT;
recalculateContentSize();
}
void MenuTextBox::setX(float xPos)
{
dstRect.x = xPos;
}
void MenuTextBox::setY(float yPos)
{
dstRect.y = yPos;
}
float MenuTextBox::getWidth()
{
return dstRect.width;
}
float MenuTextBox::getHeight()
{
return dstRect.height;
}
std::string MenuTextBox::getContent()
{
return std::string(content);
}
void MenuTextBox::setEnabled(bool enabled)
{
this->enabled = enabled;
}
void MenuTextBox::onKeyPressed(int key)
{
if (!enabled) {
return;
}
/* Handle presses of 0-9, A-Z, and Backspace */
if ((key >= '0' && key <= '9') || (key >= 'A' && key <= 'Z')) {
if (numChars < maxChars) {
content[numChars++] = (char) key;
content[numChars] = '\0';
}
} else if (key == KEY_BACKSPACE && numChars > 0) {
content[--numChars] = '\0';
}
recalculateContentSize();
}
void MenuTextBox::render(Renderer *renderer)
{
Color renderColor;
if (enabled) {
renderColor = Color {255, 255, 255, (unsigned char)(getDependentOpacity()*255)};
} else {
renderColor = Color{200, 200, 200, (unsigned char)(getDependentOpacity()*255)};
}
/* Draw left edge of bg rect */
renderer->drawTexture(bgRectTexture, 0, 0, bgRectTexture->height / 2, bgRectTexture->height,
dstRect.x, dstRect.y, dstRect.height / 2, dstRect.height, renderColor);
/* Draw middle segment of bg rect, stretched to fill space*/
renderer->drawTexture(bgRectTexture, bgRectTexture->height / 2, 0,
bgRectTexture->width - bgRectTexture->height, bgRectTexture->height,
dstRect.x + (dstRect.height / 2), dstRect.y, dstRect.width - dstRect.height,
dstRect.height, renderColor);
/* Draw right edge of bg rect */
renderer->drawTexture(bgRectTexture, bgRectTexture->width - (bgRectTexture->height / 2), 0,
bgRectTexture->height / 2, bgRectTexture->height,
dstRect.x + dstRect.width - (dstRect.height / 2), dstRect.y, dstRect.height / 2,
dstRect.height, renderColor);
renderer->setColor(renderColor);
renderer->drawText(*font, content, dstRect.x + ((dstRect.width - contentSize.x) / 2),
dstRect.y + ((dstRect.height - contentSize.y) / 2), fontSize, fontSpacing,
getDependentOpacity());
}
void MenuTextBox::recalculateContentSize()
{
if (numChars == 0) {
contentSize.x = 0;
contentSize.y = 0;
} else {
contentSize = font->MeasureText(content, fontSize, fontSpacing);
}
}
| true |
eed18c157a3cbbbf8ab5511652eb4b2019c2aab1
|
C++
|
tue-alga/CoordinatedSchematization
|
/include/SchematLib/MapSimplification/BboxFaceMerge.h
|
UTF-8
| 29,843 | 2.625 | 3 |
[
"Apache-2.0"
] |
permissive
|
#ifndef SCHEMATLIB_MAPSIMPLIFICATION_BBOXFACEMERGE_H
#define SCHEMATLIB_MAPSIMPLIFICATION_BBOXFACEMERGE_H
#include "FaceMergeStrategies.h"
#include <CGAL/ch_graham_andrew.h>
#include <CGAL/convex_hull_traits_2.h>
#include <CGAL/min_quadrilateral_2.h>
namespace SchematLib::MapSimplification::FaceMergeApproach
{
class BboxFaceMerge
{
using Traits = FaceMergeTraits;
// The factor above which we deem the effect minor when removing this face.
double m_faceSizeFactor = 2;
template<typename T>
static void apply_permutation(const std::vector<T>& source, std::vector<T>& target, const std::vector<std::size_t>& indexForLocation)
{
for (auto i : indexForLocation)
{
target.push_back(source[i]);
}
}
template<typename T, typename Compare, typename Other>
static void coordinated_sort(std::vector<T>& toSort, Compare&& compareFunc, std::vector<Other>& coordinatedOther)
{
// Fill indices
std::vector<std::size_t> is(toSort.size(), 0);
std::iota(is.begin(), is.end(), 0);
std::sort(is.begin(), is.end(), [&toSort, &compareFunc](auto i0, auto i1)
{
return compareFunc(toSort[i0], toSort[i1]);
});
std::vector<T> temp;
// Apply permutation
apply_permutation(toSort, temp, is);
std::vector<Other> temp2;
apply_permutation(coordinatedOther, temp2, is);
toSort = std::move(temp);
coordinatedOther = std::move(temp2);
}
class DidInsertVertex : public CGAL::Arr_observer<Traits::Arr>
{
bool m_didInsert = false;
std::optional< Vertex_handle> m_created;
public:
void clear()
{
m_didInsert = false;
m_created = {};
}
bool didInsert() const
{
return m_didInsert;
}
std::optional< Vertex_handle> created()const
{
return m_created;
}
void after_create_vertex(Vertex_handle vh) override
{
m_didInsert = true;
m_created = vh;
}
};
class SplitterObserver : public CGAL::Arr_observer<Traits::Arr>
{
Halfedge_handle startEdge;
Halfedge_handle endEdge;
Halfedge_handle cwDeleteEdge;
Halfedge_handle ccwDeleteEdge;
std::optional<Halfedge_handle> createdHalfEdge;
std::optional<Vertex_handle> splitV;
std::optional<std::size_t>splitId;
Vertex_handle cwDeleteTarget;
Vertex_handle ccwDeleteSrc;
bool splittingCw = false;
bool splittingCcw = false;
public:
SplitterObserver(Halfedge_handle startEdge,
Halfedge_handle endEdge,
Halfedge_handle cwDeleteEdge,
Halfedge_handle ccwDeleteEdge) : startEdge(startEdge), endEdge(endEdge), cwDeleteEdge(cwDeleteEdge), ccwDeleteEdge(ccwDeleteEdge)
{
cwDeleteTarget = cwDeleteEdge->target();
ccwDeleteSrc = ccwDeleteEdge->source();
}
std::map<std::size_t, std::pair<Halfedge_handle, Halfedge_handle>> splits;
void after_create_edge(Halfedge_handle he) override
{
createdHalfEdge = he;
}
Halfedge_handle deleteEdgeCw() const
{
return cwDeleteEdge;
}
Halfedge_handle deleteEdgeCcw() const
{
return ccwDeleteEdge;
}
std::optional<Halfedge_handle> halfEdgeCreated()const
{
return createdHalfEdge;
}
void after_create_vertex(Vertex_handle) override {}
void after_split_edge(Halfedge_handle he0, Halfedge_handle he1) override
{
splits[splitId.value()] = std::make_pair(he0, he1);
if (splittingCw)
{
std::cout << "[BboxMerge] CW edge was split\n";
splittingCw = false;
if (he0->target() == cwDeleteTarget || he0->source() == cwDeleteTarget)
{
cwDeleteEdge = he0->target() == cwDeleteTarget ? he0 : he0->twin();
}
else if (he1->target() == cwDeleteTarget || he1->source() == cwDeleteTarget)
{
cwDeleteEdge = he1->target() == cwDeleteTarget ? he1 : he1->twin();
}
else
{
throw std::runtime_error("DERP");
}
}
if (splittingCcw)
{
std::cout << "[BboxMerge] CCW edge was split\n";
splittingCcw = false;
if (he0->source() == ccwDeleteSrc || he0->target() == ccwDeleteSrc)
{
ccwDeleteEdge = he0->source() == ccwDeleteSrc ? he0 : he0->twin();
}
else if (he1->source() == ccwDeleteSrc || he1->target() == ccwDeleteSrc)
{
ccwDeleteEdge = he1->source() == ccwDeleteSrc ? he1 : he1->twin();
}
else
{
throw std::runtime_error("DERP");
}
}
}
void after_split_face(Face_handle, Face_handle, bool) override {}
void before_split_edge(Halfedge_handle he, Vertex_handle v, const X_monotone_curve_2&,
const X_monotone_curve_2&) override
{
splitId = he->data().id.value();
splitV = v;
if (he == cwDeleteEdge || he->twin() == cwDeleteEdge)
{
splittingCw = true;
}
else if (he == ccwDeleteEdge || he->twin() == ccwDeleteEdge)
{
splittingCcw = true;
}
}
void before_split_face(Face_handle, Halfedge_handle) override {}
};
bool m_verbose = false;
void compute_splitter(const std::vector<Traits::Point_2>& bbox, Traits::Segment_2& axisSegment, std::size_t& majorAxis, std::size_t& minorAxis)
{
auto l0 = Traits::approximate_length(bbox[0], bbox[1]);
auto l1 = Traits::approximate_length(bbox[1], bbox[2]);
majorAxis = l0 > l1 ? 0 : 1;
minorAxis = 1 - majorAxis;
auto dir = CGAL::midpoint(bbox[minorAxis + 2], bbox[minorAxis + 3]) - CGAL::midpoint(bbox[minorAxis], bbox[minorAxis + 1]);
// Segment along major axis through middle of box.
axisSegment = Traits::Make_segment_2()(
CGAL::midpoint(bbox[minorAxis], bbox[minorAxis + 1]) - dir,
CGAL::midpoint(bbox[minorAxis + 2], bbox[minorAxis + 3]) + dir
);
if (m_verbose) { std::cout << "Seg: " << axisSegment.left() << " " << axisSegment.right() << '\n'; }
}
template<typename Observer>
static void handleNewEdge(Traits::Halfedge_handle he, Observer& observer)
{
observer.handleNewEdge(he->data().id.value(), he->source()->data().id, he->target()->data().id);
}
template<typename Observer>
static void handleEdgeReplace(std::size_t e, Traits::Halfedge_handle he0, Traits::Halfedge_handle he1, Observer& observer)
{
observer.handleEdgeReplace(e, std::vector<std::size_t>{he0->data().id.value(), he1->data().id.value()});
}
static void printVert(Traits::Vertex_handle vert)
{
std::cout << "{" << vert->point().x() << "," << vert->point().y() << "}";
}
static void printEdge(Traits::Halfedge_handle edge)
{
printVert(edge->source());
std::cout << ',';
printVert(edge->target());
}
template<typename Observer>
Traits::Halfedge_handle insert_bbox_segment(Traits::Arr& arrangement, Traits::Halfedge_handle startHe, Traits::Halfedge_handle endHe,
const Traits::Point_2& intersectionStart, const Traits::Point_2& intersectionEnd, Observer& observer) const
{ //Construct
auto startVs = std::make_pair(startHe->source(), startHe->target());
auto endVs = std::make_pair(endHe->source(), endHe->target());
auto e0 = startHe->data().id.value();
auto e1 = endHe->data().id.value();
DidInsertVertex tracker;
tracker.attach(arrangement);
Traits::Vertex_handle v0, v1;
bool noRebuildE0 = false;
bool noRebuildE1 = false;
bool v0AlreadyExists = true;
{
auto pnt = Traits::reducedPrecision(intersectionStart);
if (Traits::approximate_length(pnt, startHe->source()->point()) < 1.0)
{
v0 = startHe->source();
noRebuildE0 = true;
}
else if (Traits::approximate_length(pnt, startHe->target()->point()) < 1.0)
{
v0 = startHe->target();
noRebuildE0 = true;
}
else
{
arrangement.remove_edge(startHe, false, false);
v0 = CGAL::insert_point(arrangement, Traits::reducedPrecision(intersectionStart));
v0AlreadyExists = !tracker.didInsert();
}
}
tracker.clear();
bool v1AlreadyExists = true;
{
auto pnt = Traits::reducedPrecision(intersectionEnd);
if (Traits::approximate_length(pnt, endHe->source()->point()) < 1.0)
{
v1 = endHe->source();
noRebuildE1 = true;
}
else if (Traits::approximate_length(pnt, endHe->target()->point()) < 1.0)
{
v1 = endHe->target();
noRebuildE1 = true;
}
else
{
arrangement.remove_edge(endHe, false, false);
v1 = CGAL::insert_point(arrangement, Traits::reducedPrecision(intersectionEnd));
v1AlreadyExists = !tracker.didInsert();
}
}
if (m_verbose) { std::cout << "[BboxMerge] V0: " << v0->point() << " exists:" << v0AlreadyExists << '\n'; }
if (m_verbose) { std::cout << "[BboxMerge] V1: " << v1->point() << " exists:" << v1AlreadyExists << '\n'; }
if (!v0AlreadyExists)observer.handleNewVertex(v0->data().id);
if (!v1AlreadyExists) observer.handleNewVertex(v1->data().id);
// reconstrut
if (v0AlreadyExists && !noRebuildE0)
{
auto newHe = arrangement.insert_at_vertices(Traits::Make_segment_2()(startVs.first->point(), startVs.second->point()), startVs.first, startVs.second);
handleNewEdge(newHe, observer);
observer.handleEdgeReplace(e0, std::vector<std::size_t>{newHe->data().id.value()});
}
else if (!v0AlreadyExists)
{
auto startHe0 = arrangement.insert_at_vertices(Traits::Make_segment_2()(startVs.first->point(), v0->point()), startVs.first, v0);
auto startHe1 = arrangement.insert_at_vertices(Traits::Make_segment_2()(v0->point(), startVs.second->point()), v0, startVs.second);
handleNewEdge(startHe0, observer);
handleNewEdge(startHe1, observer);
if (m_verbose)
{
std::cout << "\tStart he0:";
printEdge(startHe0);
std::cout << "\n";
std::cout << "\tStart he1:";
printEdge(startHe1);
std::cout << "\n";
}
handleEdgeReplace(e0, startHe0, startHe1, observer);
}
if (v1AlreadyExists && !noRebuildE1)
{
auto newHe = arrangement.insert_at_vertices(Traits::Make_segment_2()(endVs.first->point(), endVs.second->point()), endVs.first, endVs.second);
handleNewEdge(newHe, observer);
observer.handleEdgeReplace(e1, std::vector<std::size_t>{newHe->data().id.value()});
}
else if (!v1AlreadyExists)
{
auto endHe0 = arrangement.insert_at_vertices(Traits::Make_segment_2()(endVs.first->point(), v1->point()), endVs.first, v1);
auto endHe1 = arrangement.insert_at_vertices(Traits::Make_segment_2()(v1->point(), endVs.second->point()), v1, endVs.second);
handleNewEdge(endHe0, observer);
handleNewEdge(endHe1, observer);
if (m_verbose)
{
std::cout << "End he0:";
printEdge(endHe0);
std::cout << "\n";
std::cout << "End he1:";
printEdge(endHe1);
std::cout << "\n";
}
handleEdgeReplace(e1, endHe0, endHe1, observer);
}
// Add middle
auto middleEdge = arrangement.insert_at_vertices(Traits::Make_segment_2()(v0->point(), v1->point()), v0, v1);
if (middleEdge->source() != v0) throw std::runtime_error("TWISTED!");
handleNewEdge(middleEdge, observer);
if (m_verbose)
{
std::cout << "[BboxMerge] Middle edge: ";
printEdge(middleEdge);
std::cout << '\n';
}
if(m_verbose)
{
std::size_t leftComplexity = 0, rightComplexity = 0;
Traits::for_each_ccb_edge(middleEdge->face(), [&leftComplexity](auto face, auto&cmd)
{
++leftComplexity;
});
Traits::for_each_ccb_edge(middleEdge->twin()->face(), [&rightComplexity](auto face, auto&cmd)
{
++rightComplexity;
});
std::cout << "[bboxMerge] Left right face complexities: " << leftComplexity << " " << rightComplexity << '\n';
}
return middleEdge;
}
void find_edges_to_delete(Traits::Halfedge_handle middleEdge, std::vector<Traits::Halfedge_handle>& cwDelete,
std::vector<Traits::Halfedge_handle>& ccwDelete)
{
// CCW direction
{
std::vector<Traits::NT> cumulativeApproxLength;
{
auto curr = middleEdge->twin()->next();
while (curr != middleEdge->twin())
{
auto len = Traits::approximate_length(curr->source()->point(), curr->target()->point());
cumulativeApproxLength.push_back(len + (cumulativeApproxLength.empty() ? 0 : cumulativeApproxLength.back()));
curr = curr->next();
}
}
const auto totalLength = cumulativeApproxLength.back();
// Keep track of chain of degree-2 vertices, delete them all when applicable.
Traits::Halfedge_handle curr = middleEdge->twin()->next();
Traits::Halfedge_handle chainStart = curr;
std::size_t index = 0;
while (curr != middleEdge->twin())
{
if (cumulativeApproxLength[index] > totalLength*0.5)break;
curr = curr->next();
if (curr->source()->degree() > 2) chainStart = curr;
++index;
}
while( curr->target()->degree() <= 2)
{
curr = curr->next();
if (curr == middleEdge->twin()) throw std::runtime_error("Chain is invalid, central edge should have deg>2 vertices");
}
// Add edges before curr
for (; chainStart != curr; chainStart = chainStart->next())
{
ccwDelete.push_back(chainStart);
}
ccwDelete.push_back(curr);
}
// CW direction
{
std::vector<Traits::NT> cumulativeApproxLength;
{
auto curr = middleEdge->next();
while (curr != middleEdge)
{
auto len = Traits::approximate_length(curr->source()->point(), curr->target()->point());
cumulativeApproxLength.push_back(len + (cumulativeApproxLength.empty() ? 0 : cumulativeApproxLength.back()));
curr = curr->next();
}
}
const auto totalLength = cumulativeApproxLength.back();
Traits::Halfedge_handle curr = middleEdge->next();
Traits::Halfedge_handle chainStart = curr;
std::size_t index = 0;
while (curr != middleEdge)
{
if (cumulativeApproxLength[index] > totalLength*0.5)break;
curr = curr->next();
if (curr->source()->degree() > 2) chainStart = curr;
++index;
}
while (curr->target()->degree() <= 2)
{
curr = curr->next();
if (curr == middleEdge) throw std::runtime_error("Chain is invalid, central edge should have deg>2 vertices");
}
// Add edges before curr
for (; chainStart != curr; chainStart = chainStart->next())
{
cwDelete.push_back(chainStart);
}
cwDelete.push_back(curr);
}
}
template<typename Observer = EdgeTrackingObserver>
void notify_complement_reroute(const std::vector<Traits::Halfedge_handle>& chain, Observer& observer)
{
{
std::vector<std::size_t> rerouteEdges;
auto start = chain.back()->next();
if (chain.back()->face()->is_unbounded()) throw std::runtime_error("Face fucked up");
while (start != chain.front())
{
rerouteEdges.push_back(start->data().id.value());
start = start->next();
}
std::vector<std::size_t> deleteVertices;
std::vector<std::size_t> deletedIds;
for (auto el : chain)
{
if (el->source() != chain.front()->source())
{
deleteVertices.push_back(el->source()->data().id);
}
deletedIds.push_back(el->data().id.value());
}
// We move in the other direction actually, so revert the ids (with appropriate ID's).
SpecialEdgeIdFunctions::reverseCanonicalComplement(deletedIds);
observer.handleEdgeReroute(deletedIds, rerouteEdges);
// Delete intermediate vertices.
for (auto v : deleteVertices)observer.handleVertexDelete(v);
}
}
public:
// Flag that we are going to try to remap faces.
bool recomputeAfterMerge() const
{
return true;
}
void set_verbose(bool val)
{
m_verbose = val;
}
/**
* \brief
* \tparam Arrangement
* \tparam FaceIterator
* \tparam LookupStructure
* \tparam Observer
* \param arrangement The CGAL arrangement to use.
* \param face
* \param lookup The lookup structure to use. Should be attached to the arrangement!
* \param remappedFaces
* \param observer
*/
template<typename SelectPredicate, typename Observer = EdgeTrackingObserver>
void operator()(Traits::Arr& arrangement, Traits::Face_handle face, std::map<std::size_t, Traits::Face_handle>& remappedFaces, Observer& observer, const SelectPredicate& pred)
{
if (face->is_unbounded() || face->is_fictitious()) return;
// Expect clean interior!
using ListPolygon = std::vector<Traits::Point_2>;
// Get face points
std::vector<Traits::Point_2> points;
std::vector<Traits::Halfedge_handle> hes;
std::vector<std::size_t> degrees;
std::size_t maxDegree = 0;
Traits::for_each_ccb_edge(face, [&points, &hes, °rees, &maxDegree](auto he, auto& cmd)
{
points.push_back(he->source()->point());
hes.push_back(he);
degrees.push_back(he->source()->degree());
maxDegree = std::max<std::size_t>(maxDegree, he->source()->degree());
});
if (maxDegree == 2)
{
throw std::runtime_error("Invalid face, disconnected!");
}
{ // Check if we only have 1 >degree 2 vertex
std::size_t above2Count = 0;
std::size_t index = 0;
std::size_t highDegEl = 0;
for (auto deg : degrees)
{
if (deg > 2) {
above2Count++;
highDegEl = index;
}
++index;
}
if (above2Count == 1)
{
std::cout << "[BboxMerge] Collapsing face with single high degree vert \n";
// collapse to element
auto targetVert = hes[highDegEl]->source();
for (auto e : hes)
{
observer.handleEdgeCollapse(e->data().id.value(), targetVert->data().id);
if (e->source() != targetVert) observer.handleVertexMerge(e->source()->data().id, targetVert->data().id);
arrangement.remove_edge(e);
}
return;
}
}
if (m_verbose)
{
std::cout << "[BboxMerge] Point count: " << points.size() << '\n';
for (auto el : points)
{
std::cout << el;
std::cout << '\n';
}
}
//Compue CH
ListPolygon CH;
using QuadTraits = CGAL::Min_quadrilateral_default_traits_2<Traits::Kernel>;
auto endIt = CGAL::ch_graham_andrew(points.begin(), points.end(), std::back_inserter(CH), CGAL::Convex_hull_traits_2<Traits::ArrTraits>{});
if(m_verbose)
{
std::cout << "[BboxMerge] CH count: " << CH.size() << '\n';
for (auto el : CH)
{
std::cout << el;
std::cout << '\n';
}
}
// Compute BBOX
ListPolygon bbox;
QuadTraits traits;
auto bboxEnd = CGAL::min_rectangle_2(CH.begin(), CH.end(), std::back_inserter(bbox), traits);
if(m_verbose)
{
std::cout << "[BboxMerge] bbox count: " << bbox.size() << '\n';
for (auto el : bbox)
{
std::cout << el;
std::cout << '\n';
}
}
if (bbox.size() == 4)
{
bbox.push_back(bbox[0]);
}
for (auto& el : bbox)
{
el = Traits::reducedPrecision(el);
}
// Get major axis.
Traits::Segment_2 axisSegment;
std::size_t majorAxis, minorAxis;
compute_splitter(bbox, axisSegment, majorAxis, minorAxis);
std::vector<Traits::Point_2> intersections;
std::vector<std::size_t> intersectionEdgeIndices;
// Determine cuts through polygon //Note: special case if intersectin full segments!
for (std::size_t i = 0; i < points.size(); ++i)
{
auto next = (i + 1) % points.size();
auto polySeg = Traits::Make_segment_2()(points[i], points[next]);
using Pnt = std::pair<Traits::ArrTraits::Point_2, Traits::ArrTraits::Multiplicity>;
using Seg = Traits::ArrTraits::X_monotone_curve_2;
typedef boost::variant < Pnt, Seg> Intersection_result;
std::vector<Intersection_result> localIntersections;
Traits::ArrTraits::Intersect_2 intersector = Traits::ArrTraits{}.intersect_2_object();
intersector(axisSegment, polySeg, std::back_inserter(localIntersections));
if (localIntersections.empty()) continue;
for (const auto& inters : localIntersections)
{
if (const auto* pnt = boost::get<Pnt>(&inters))
{
intersections.push_back(pnt->first);
intersectionEdgeIndices.push_back(i);
}
else if (const auto*seg = boost::get<Seg>(&inters))
{
intersections.push_back(seg->left());
intersections.push_back(seg->right());
intersectionEdgeIndices.push_back(i);
intersectionEdgeIndices.push_back(i);
}
else
{
throw std::runtime_error("No clue what this is");
}
}
}
// Find edges to delete
std::size_t edgeStart, edgeEnd;
Traits::Point_2 intersectionStart, intersectionEnd;
if (intersections.size() <= 1)
{
//err
throw std::runtime_error("Expected at least 2 intersections");
}
else if (intersections.size() == 2)
{
//"Easy"
edgeStart = intersectionEdgeIndices[0];
intersectionStart = intersections[0];
edgeEnd = intersectionEdgeIndices[1];
intersectionEnd = intersections[1];
}
else
{
std::cout << "Selecting largest cut\n";
Traits::ArrTraits::Line_2 line(bbox[minorAxis], bbox[minorAxis + 1]);
Traits::ArrTraits::Compare_signed_distance_to_line_2 comparer;
coordinated_sort(intersections, [&line, &comparer](const auto& pnt0, const auto& pnt1)
{
return comparer(line, pnt0, pnt1);
}, intersectionEdgeIndices);
// Determine inside/outside.
std::vector<CGAL::Bounded_side> midpointSides;
// Pick largest
Traits::NT maxLen = 0;
std::optional<std::size_t> maxLenIndex;
for (std::size_t i = 0; i < intersections.size() - 1; ++i)
{
auto insideness = CGAL::bounded_side_2(points.begin(), points.end(), CGAL::midpoint(intersections[i], intersections[i + 1]), Traits::ArrTraits{});;
// If point is on boundary (i.e. segment intersection) or outside, this is not an interior segment
if (insideness == CGAL::ON_BOUNDARY || insideness == CGAL::ON_UNBOUNDED_SIDE) continue;
auto approxLen = Traits::approximate_length(intersections[i], intersections[i + 1]);
if (maxLen < approxLen)
{
maxLen = approxLen;
maxLenIndex = i;
}
}
if (!maxLenIndex.has_value()) throw std::runtime_error("All length zero segs?!?!");
intersectionStart = intersections[maxLenIndex.value()];
intersectionEnd = intersections[maxLenIndex.value() + 1];
edgeStart = intersectionEdgeIndices[maxLenIndex.value()];
edgeEnd = intersectionEdgeIndices[maxLenIndex.value() + 1];
}
if(m_verbose)
{
std::cout << "[BboxMerge] Start and end edges: " << edgeStart << ',' << edgeEnd << '\n';
std::cout << "[BboxMerge] Total size: " << points.size() << '\n';
}
Traits::Halfedge_handle middleEdge = insert_bbox_segment(arrangement, hes[edgeStart], hes[edgeEnd],
intersectionStart, intersectionEnd, observer);
std::vector<Traits::Halfedge_handle> ccwDeleteHes, cwDeleteHes;
find_edges_to_delete(middleEdge, cwDeleteHes, ccwDeleteHes);
// Reroute by the 'complement' of the edges in the face
notify_complement_reroute(cwDeleteHes, observer);
notify_complement_reroute(ccwDeleteHes, observer);
// Delete the edges in the arrangement
for (auto el : ccwDeleteHes) arrangement.remove_edge(el);
for (auto el : cwDeleteHes) arrangement.remove_edge(el);
}
};
}
#endif
| true |
a91a05f0b62cbccf903cf77d0d1f05d7066fa1de
|
C++
|
orazdow/SoundLib
|
/expr/lexer.cpp
|
UTF-8
| 5,843 | 3.109375 | 3 |
[] |
no_license
|
#include "lexer.h"
/************* buffer ******************/
void alloc_buff(InputBuff* b, long len){
b->input = (char*)calloc(len, 1);
b->tokens = (char*)calloc(len, 1);
b->temp = (char*)calloc(VAR_LEN, 1);
b->len = len;
}
void realloc_buff(InputBuff* b, long len){
b->input = (char*)realloc(b->input, len);
b->tokens = (char*)realloc(b->tokens, len);
b->len = len;
}
void clear_buff(InputBuff* b){
memset(b->input, 0, b->len);
memset(b->tokens, 0, b->len);
memset(b->temp, 0, VAR_LEN);
}
void free_buff(InputBuff*b){
free(b->input); free(b->tokens); free(b->temp);
}
/*********** checks ***************/
bool isLetter(char c){
return ((c >= 65 && c <= 90) || (c >= 97 && c <= 122)) || c == '_';
}
bool isNumber(char c){
return (c >= 48 && c <= 57);
}
bool isSeperator(char c){
return (c == '(' || c == ')' || c == ';'); // handle ',' '[' ']' '{' '}'
}
bool isOperator(char c){
switch(c){
case '-' : return true;
case '+' : return true;
case '*' : return true;
case '/' : return true;
case '=' : return true;
case '>' : return true;
case '<' : return true;
}
return false;
}
bool doubleOp(char a, char b){ //handle **, == , ++ -- >= <=
if(a == '-' && b == '>'){
return true;
}
return false;
}
/*************** Lexer *****************/
Lexer::Lexer(const long _len){
alloc_buff(&buffer, _len ? _len : BUFF_LEN);
operatorMap = {
{ "+", {10, false, W_OP_ADD, OP_ADD} },
{ "-", {10, false, W_OP_SUB, OP_SUB} },
{ "*", {20, false, W_OP_MULT, OP_MULT} },
{ "/", {20, false, W_OP_DIV, OP_DIV} },
{ "-u", {30, true, W_OP_USUB, NULL} },
{ "(", {50, false, W_OP_LP, NULL} },
{ ")", {50, false, W_OP_RP, NULL} }
};
}
Lexer::~Lexer(){
free_buff(&buffer);
}
void Lexer::dump(Lexer::ScanMode type){
this->mode = DUMP;
this->lastMode = type;
}
bool Lexer::load(const char str[]){
clear_buff(&buffer);
long in_len = strlen(str);
if(in_len > buffer.len){
int factor = ceil(in_len/(float)buffer.len);
realloc_buff(&buffer, buffer.len*factor);
printf("increasing buffer %ux to %u\n", factor, buffer.len);
}
strcpy(buffer.input, str);
sourcebuff = buffer.input;
tokenbuff = buffer.tokens;
temp = buffer.temp;
return true;
}
void Lexer::printLexemes(bool info){
for(int i = 0; i < lexemes.size(); i++){
printf("%s ", lexemes[i].str);
if(info){
IWORD w = lexemes[i];
switch(w.type){
case NUL :
printf("null \n");
break;
case OP :
printf("op %u %u % u\n", w.value.op.type, w.value.op.precedence, w.value.op.rightAssoc);
break;
case IVAL :
printf("int %i\n", w.value.i);
break;
case UVAL : //not imp
printf("uint %i\n", w.value.i);
break;
case FVAL :
printf("float %f\n", w.value.f);
break;
case STR :
printf("string %s\n", w.value.s);
case IDENT : //not imp
break;
}
}
}
printf("\n");
}
/* tokenize buffer into lexems: */
bool Lexer::scan(){
char* p = sourcebuff;
if(!p) return false;
long buff_i = 0;
long len = buffer.len-1;
mode = ScanMode::BEGIN;
int i = 0;
char* tok = tokenbuff;
bool dot = false;
bool hold = false;
while(*p != '\0' || hold){
char c = *p;
switch(mode)
{
case ScanMode::BEGIN :
if(c == ' '){
p++;
}
else if(isLetter(c) || isNumber(c) || isOperator(c) || isSeperator(c)){ // add '"' string handling
temp[i] = c;
INC(i);
p++;
if(isLetter(c))
mode = ScanMode::ALPHATOK;
else if(isNumber(c))
mode = ScanMode::NUMTOK;
else if(isOperator(c))
mode = ScanMode::OPERATOR;
else if(isSeperator(c))
dump(OPERATOR);
}
else{ mode = ScanMode::UNEXPECTED; }
if(*p == '\0'){
hold = true;
dump(mode);
}
break;
case ScanMode::ALPHATOK :
if(isLetter(c) || isNumber(c)){
temp[i] = c;
INC(i);
p++;
}
else if(isOperator(c) || isSeperator(c) || c == ' '){
dump(ALPHATOK);
}
else{
mode = ScanMode::UNEXPECTED;
break;
}
if(*p == '\0'){
hold = true;
dump(mode);
}
break;
case ScanMode::NUMTOK :
if(isNumber(c) || (c == '.' && !dot)){
temp[i] = c;
INC(i);
p++;
if(c == '.'){ dot = true; }
}
else if(isOperator(c) || isSeperator(c) || c == ' '){
dump(NUMTOK);
}
else{ dot = false; mode = ScanMode::UNEXPECTED; break; }
if(*p == '\0'){
hold = true;
dump(mode);
}
break;
case ScanMode::OPERATOR :
if(isLetter(c) || isNumber(c) || isSeperator(c) || c == ' '){
dump(OPERATOR);
}
else if(isOperator(c)){
if(doubleOp(*(p-1), c)){
temp[i] = c;
INC(i);
p++;
}
dump(OPERATOR);
}
else{
mode = ScanMode::UNEXPECTED;
break;
}
if(*p == '\0'){
hold = true;
dump(mode);
}
break;
case ScanMode::UNEXPECTED :
printf("UNEXPECTED TOKEN: %c\n", c);
return false;
break;
case ScanMode::DUMP :
/* merge tokens or check for syntax errors here.. */
temp[i] = '\0';
strcpy(tok, temp);
// tokens.push_back(tok);
lexemes.push_back(makeLexeme(tok, lastMode, dot));
tok += (i+1);
i = 0;
mode = ScanMode::BEGIN;
hold = false;
dot = false;
break;
}
if(buff_i++ > len) return false;
}
return true;
}
IWORD Lexer::makeLexeme(char* str, Lexer::ScanMode mode, bool dot){
IWORD rtn;
switch(mode){
case ScanMode::ALPHATOK :
rtn.type = WTYPE::STR;
rtn.value.s = str;
break;
case ScanMode::NUMTOK :
if(dot){
rtn.type = WTYPE::FVAL;
rtn.value.f = atof(str);
}else{
rtn.type = WTYPE::IVAL;
rtn.value.f = atoi(str);
}
break;
case ScanMode::OPERATOR :
rtn.type = WTYPE::OP;
rtn.value.op = operatorMap[str];
break;
}
rtn.str = str;
return rtn;
}
| true |
0d5792b30e2250394149e71f07cc3dde59d5f895
|
C++
|
necula/engine
|
/src/Resources/Shader.h
|
UTF-8
| 814 | 2.578125 | 3 |
[] |
no_license
|
#ifndef SHADER_H
#define SHADER_H
#include "../Common/Include/esUtil.h"
#include <stdlib.h>
#include <cstdio>
#include <iostream>
#include <vector>
#include <string>
using namespace std;
typedef struct
{
char* uniformName;
int length;
float* values;
} uniform;
class CShader
{
public:
CShader(char *vertexShaderLocation, char *fragmentShaderLocation);
CShader(char *name, char *vertexShaderLocation, char *fragmentShaderLocation);
void addUniform(char* uniformName, int length, string values);
void addState(char* state);
GLint getProgram();
uniform getUniform(int i);
char* getName();
int getNumberOfUniforms();
int getNumberOfStates();
int getState(int i);
private:
GLint load(char*, char*);
GLint m_program;
char *m_name;
vector<uniform> m_uniforms;
vector<int> m_states;
};
#endif
| true |
e627b738cfc5dd49564941cc0fdc9edf058f4f0d
|
C++
|
Limitless-Rasul-Power/E-Commerce
|
/E-Commerce App/Client_Menu.h
|
UTF-8
| 6,077 | 2.90625 | 3 |
[
"MIT"
] |
permissive
|
#pragma once
#include "DataBase.h"
namespace Client = ECommerce::Client;
void Client::Menu(App::DataBase* const& database)
{
std::string full_name;
std::cout << "Full Name: ";
getline(std::cin, full_name);
bool is_client_exist = false;
for (int i = 0; i < database->Get_database_notes()->Get_item_count(); i++)
{
if (full_name == database->Get_database_notes()->At(i)->Get_guest_name())
{
is_client_exist = true;
break;
}
}
App::Notification* note{};
App::Client* client{};
if (is_client_exist)
{
note = new App::Notification("Database Client Visit!", full_name);
}
else
{
client = new App::Client(full_name);
note = new App::Notification("New Client Visit", client->Get_full_name());
database->Get_database_clients()->Add(client);
}
database->Get_database_notes()->Add(note);
short choice{};
int index = -1;
while (true)
{
for (int i = 0; i < database->Get_database_products()->Get_item_count(); i++)
{
std::cout << "\n\n" << '#' << i + 1 << ", Product Short Information\n\n";
std::cout << "Product ID: " << database->Get_database_products()->At(i)->Get_product()->Get_id() << '\n';
std::cout << "Product Name: " << database->Get_database_products()->At(i)->Get_product()->Get_name() << "\n\n";
}
std::cout << "\n\n1)Buy with ID\n2)Show More Information with ID\nEnter: ";
std::cin >> choice;
index = -1;
if (choice == 1)
{
std::cout << "DataBase has this IDs\n\n";
for (unsigned int i = 0U; i < database->Get_database_products()->Get_item_count(); i++)
{
std::cout << "ID = " << database->Get_database_products()->At(i)->Get_product()->Get_id() << '\n';
}
std::cout << "\nEnter Product id which you want to buy: ";
std::cin >> choice;
for (unsigned int i = 0U; i < database->Get_database_products()->Get_item_count(); i++)
{
if (choice == database->Get_database_products()->At(i)->Get_product()->Get_id())
{
index = i;
break;
}
}
if (index == -1)
throw InvalidArgumentException("Wrong ID entered!", 77, "Client_Menu.h");
if (is_client_exist)
note = new App::Notification("DataBase Client wants to buy product!", full_name);
else
note = new App::Notification("New Client wants to buy product!", client->Get_full_name());
database->Get_database_notes()->Add(note);
break;
}
else if (choice == 2)
{
std::cout << "DataBase has this IDs\n\n";
for (int i = 0; i < database->Get_database_products()->Get_item_count(); i++)
{
std::cout << "ID = " << database->Get_database_products()->At(i)->Get_product()->Get_id() << '\n';
}
std::cout << "\nEnter ID: ";
std::cin >> choice;
bool is_id_exist = false;
for (int i = 0; i < database->Get_database_products()->Get_item_count(); i++)
{
if (choice == database->Get_database_products()->At(i)->Get_product()->Get_id())
{
is_id_exist = true;
index = i;
break;
}
}
if (is_id_exist)
{
database->Get_database_products()->At(index)->Show();
if (is_client_exist)
note = new App::Notification("Database Client wants to show more information!", full_name);
else
note = new App::Notification("New Client wants to show more information!", client->Get_full_name());
database->Get_database_notes()->Add(note);
std::cout << '\n';
system("pause");
}
else
std::cout << "Wrong ID!\n";
}
else
{
if (is_client_exist)
note = new App::Notification("Database client didn't buy anything and press exit button!", full_name);
else
note = new App::Notification("New Client didn't buy anything and press exit button!", client->Get_full_name());
database->Get_database_notes()->Add(note);
return;
}
}
int amount{};
std::cout << "\n\nWe have " << database->Get_database_products()->At(index)->Get_amount() << " amounts\n";
std::cout << "How many amount do you want to buy: ";
std::cin >> amount;
while (amount <= 0 || amount > database->Get_database_products()->At(index)->Get_amount())
{
std::cout << "\nInvalid Amount entered please enter again: ";
std::cin >> amount;
}
int option{};
std::cout << "\n\nDo you want to buy " << amount << " amounts of " << database->Get_database_products()->At(index)->Get_product()->Get_name() \
<< " ?\n1)Yes(press Y)\n2)No(press N)\nEnter: ";
std::cin >> option;
while (option < 0 || option > 2)
{
std::cout << "\n\nDo you want to buy " << amount << " amounts of " << database->Get_database_products()->At(index)->Get_product()->Get_name() \
<< " ?\n1)Yes(press Y)\n2)No(press N)\nEnter: ";
std::cin >> option;
}
if (option == 1)
{
std::cout << "\n\nSuccessfully bought, thank you for choosing us\n";
if (amount == database->Get_database_products()->At(index)->Get_amount())
{
if (is_client_exist)
note = new App::Notification("Database client buy last product!", full_name);
else
note = new App::Notification("New client buy last product!", client->Get_full_name());
database->Get_database_products()->Delete_by_id(database->Get_database_products()->At(index)->Get_product()->Get_id());
}
else
{
if (!is_client_exist)
note = new App::Notification("Database client buys X amount(s) of product!", full_name);
else
note = new App::Notification("New client buys X amount(s) of product!", client->Get_full_name());
database->Get_database_products()->At(index)->Set_amount(database->Get_database_products()->At(index)->Get_amount() - amount);
}
}
else
{
if (is_client_exist)
note = new App::Notification("Database client comes to last operation and didn't buy!", full_name);
else
note = new App::Notification("New client comes to last operation and didn't buy!", client->Get_full_name());
std::cout << "\n\nProduct didn't buy, Thank you for visiting!\n";
}
database->Get_database_notes()->Add(note);
}
| true |
4cf1dbae2c0e2ad7f6aeb6934b6ec02a47f5d645
|
C++
|
VigneshKumarKK/Data-Structure-training
|
/.vscode/tree/Binary_Search_tree/binary_srch_tree_delete.cpp
|
UTF-8
| 3,415 | 4 | 4 |
[] |
no_license
|
#include <iostream>
#include <stdlib.h>
using namespace std;
struct node
{
int data;
struct node *left;
struct node *right;
};
struct node* createNode(int newdata)
{
struct node* newnode;
newnode = (struct node*)malloc(sizeof(struct node));
newnode->data = newdata;
newnode->left = NULL;
newnode->right = NULL;
return newnode;
}
void inorder(struct node* root)
{
if (root != NULL)
{
inorder(root->left);
cout << root->data <<" ,";
inorder(root->right);
}
}
void preorder(struct node* root)
{
if (root != NULL)
{
cout << root->data <<" ,";
inorder(root->left);
inorder(root->right);
}
}
void postorder(struct node* root)
{
if (root != NULL)
{
inorder(root->left);
inorder(root->right);
cout << root->data <<" ,";
}
}
struct node* insert(struct node* node, int data)
{
if (node == NULL)
return createNode(data);
else if (data < node->data)
node->left = insert(node->left, data);
else if (data > node->data)
node->right = insert(node->right, data);
return node;
}
struct node* minNode(struct node* current)
{
while (current->left != NULL)
current = current->left;
return current;
}
struct node* deleteNode(struct node* root, int data)
{
if (root == NULL)
return root;
else if (data < root->data)
root->left = deleteNode(root->left, data);
else if (data > root->data)
root->right = deleteNode(root->right, data);
else
{
if (root->left == NULL)
{
struct node* temp ;
temp = root->right;
free(root);
return temp;
}
else if (root->right == NULL)
{
struct node* temp;
temp = root->left;
free(root);
return temp;
}
struct node* temp;
temp = minNode(root->right);
root->data = temp->data;
root->right = deleteNode(root->right, temp->data);
}
return root;
}
int main()
{
struct node* root = NULL;
int maindata=0;
bool flag=0;
while(1)
{
cout << "Enter a number into binary tree or press -1 to exit ::::::: ";
cin >> maindata;
if(flag!=0 && maindata!=-1)
{
insert(root, maindata);
}
else if(flag==0)
{
root = insert(root, maindata);
flag=1;
}
else if(maindata==-1)
{
break;
}
}
//print before delete
cout<<"\n=========BEFORE DELETE FUNCTION TAKE PLACE=============\n\n";
cout <<"\n\nINORDER DISPLAY OF BINARY TREE\n";
inorder(root);
cout <<"\n\n\nPREORDER DISPLAY OF BINARY TREE\n";
preorder(root);
cout <<"\n\n\nPOSTORDER DISPLAY OF BINARY TREE\n";
postorder(root);
cout<< "\n\n";
while(1)
{
cout << "Enter a number to delete in binary tree or press -1 to exit ::::::: ";
cin >> maindata;
if(maindata!=-1)
{
root = deleteNode(root, maindata);
cout <<"\n\nAfter deletion of "<<maindata <<" from binary tree, inorder traverse looks \n";
inorder(root);
}
else
{
break;
}
}
//print after delete
cout<<"\n=========AFTER DELETE FUNCTION TAKE PLACE=============\n\n";
cout <<"\n\nINORDER DISPLAY OF BINARY TREE\n";
inorder(root);
cout <<"\n\n\nPREORDER DISPLAY OF BINARY TREE\n";
preorder(root);
cout <<"\n\n\nPOSTORDER DISPLAY OF BINARY TREE\n";
postorder(root);
cout<< "\n\n";
return 1;
}
| true |
a35f4ed24724ad955c9babb4135359104ca08074
|
C++
|
lcglcglcg/code
|
/cpp_code/the_big_three/03多态/person.h
|
UTF-8
| 310 | 3.015625 | 3 |
[] |
no_license
|
class person
{
public:
person(const char *name, int age);
~person();
virtual void display()const;
protected:
char *name;
int age;
};
class student:public person
{
public:
student(const char *name, int age, int score);
~student();
virtual void display()const;
protected:
int score;
};
| true |
bdd02d69b2ce088652f2507c95d8f85a080f6bc0
|
C++
|
BekjanJuma/Competitive-Programming
|
/acm.timus.ru-old-solutions/p1087.cpp
|
UTF-8
| 653 | 2.625 | 3 |
[] |
no_license
|
#include <iostream>
#include <cstdio>
#include <cstdlib>
using namespace std;
int compare (const void * a, const void * b)
{
return ( *(int*)a - *(int*)b );
}
int main()
{
int A[10010];
int n, m, k[60];
cin >> n >> m;
for( int i=0; i<m; i++ )
cin >> k[i];
qsort( k, m, sizeof(int), compare);
for( int i=0; i<=(n+2); i++ )
A[i] = -1;
A[k[0]] = 2;
for( int i=0; i<m; i++ )
A[k[i]+1] = 1;
for( int i=0; i<=(n+1); i++ )
{
if(A[i] == -1)
{
for( int j=0; j<m; j++ )
{
if( i>k[j] )
{
if( A[i-k[j]] == 2 )
A[i] = 1;
}
}
if( A[i] == -1 )
A[i] = 2;
}
}
cout << A[n] << endl;
return 0;
}
| true |
95152ff4fb02f944ff1ebc5912d36cb59bef68d5
|
C++
|
jiujiangluck/PAT-Advanced-Level-Practise
|
/New Version/A1129.cpp
|
UTF-8
| 1,091 | 2.578125 | 3 |
[] |
no_license
|
#include<iostream>
#include<string>
#include<vector>
#include<unordered_map>
#include<set>
#include<stack>
#include<queue>
#include<cctype>
#include<climits>
#include<algorithm>
#include<cmath>
#define _CRT_SECURE_NO_WARNINGS
#define inf INT_MAX
using namespace std;
typedef pair<int, int> pp;
vector<int> fre;
int n, mn;
struct cmp {
int x, d;
bool operator <(const cmp &a) const { return d != a.d ? d < a.d : x > a.x; }
};
priority_queue<cmp> q;
vector<cmp> getAns() {
vector<cmp> v;
while (!q.empty() && v.size() < mn) {
cmp k = q.top(); q.pop();
if (fre[k.x] > k.d) continue;
v.push_back(k);
}
for (auto it : v) {
q.push(it);
}
return v;
}
int main() {
ios::sync_with_stdio(false);
cin >> n >> mn;
fre.resize(n + 1,0);
for (int i = 0; i < n; i++) {
int temp;
cin >> temp;
if (i > 0) {
cout << temp << ":";
vector<cmp> v = getAns();
for (int j = 0; j < mn && j < v.size(); j++) {
cout << " " << v[j].x;
}
cout << endl;
}
fre[temp]++;
q.push({ temp, fre[temp] });
}
system("pause");
return 0;
}
| true |
1436c5ad712714a0888a537ca38f9fa87491acf8
|
C++
|
bbathe/Arduino
|
/contester-fpad-esp32/contester-fpad-esp32.ino
|
UTF-8
| 3,718 | 2.890625 | 3 |
[
"MIT"
] |
permissive
|
#include "esp_sleep.h"
#include <BleKeyboard.h>
/*
keypad mapping
keypad # -> character to send
3x4 keypad
01 02 03
04 05 06
07 08 09
10 11 12
*/
#define KEYPAD_KEY_COUNT 12
uint8_t keyLookup[KEYPAD_KEY_COUNT] = {
// 1st (top) row [01 02 03]
KEY_F1,
KEY_F2,
KEY_F3,
// 2nd row [04 05 06]
KEY_F4,
KEY_F5,
KEY_F6,
// 3rd row [07 08 09]
KEY_F7,
KEY_F8,
KEY_F9,
// 4th (bottom) row [10 11 12]
//KEY_F10,
//KEY_F11,
//KEY_F12,
KEY_F3,
KEY_F2,
KEY_F4,
};
// bluetooth connection
BleKeyboard bleKeyboard("contester-fpad", "bbathe", 100);
// GPIO pins
#define KEYPAD_PIN 34
#define ACTIVITY_PIN 32
// used to remove noise from key readings (bounces & "riding the keys")
unsigned long sumLevel = 0;
unsigned long countLevel = 0;
void setup() {
Serial.begin(115200);
// make sure 12-bit resolution
analogReadResolution(12);
// set pins
pinMode(KEYPAD_PIN, INPUT);
pinMode(ACTIVITY_PIN, OUTPUT);
// start bluetooth keyboard to send keystrokes to computer
bleKeyboard.begin();
}
void loop() {
// wait until bluetooth connection is good
if ( bleKeyboard.isConnected() ) {
digitalWrite(ACTIVITY_PIN, HIGH);
// get key press from keypad
int pinLevel = analogRead(KEYPAD_PIN);
// if there is no key pressed, check if transition just happened to trigger "key up"
if ( pinLevel == 0 ) {
// throw out weird readings
if ( (countLevel > 1000) && (countLevel < 200000) ) {
// "key up"
int key = translateToKey(sumLevel / countLevel);
if ( key > 0 ) {
char kd[16];
sprintf(kd, "0x%02X", key);
Serial.println(kd);
// send character and show activity
digitalWrite(ACTIVITY_PIN, LOW);
bleKeyboard.write(key);
delay(50);
digitalWrite(ACTIVITY_PIN, HIGH);
}
}
// reset key reading
sumLevel = 0;
countLevel = 0;
} else {
// for calculating what key is pressed
sumLevel += pinLevel;
countLevel++;
}
} else {
// show some activity so we don't look dead
digitalWrite(ACTIVITY_PIN, HIGH);
delay(50);
digitalWrite(ACTIVITY_PIN, LOW);
delay(3000);
}
}
// take an analog pinLevel and return the character to send
uint8_t translateToKey(int pinLevel) {
if ( pinLevel >= 1706 ) {
if ( pinLevel <= 1786 ) {
// 1746 avg
return keyLookup[11];
} else if ( pinLevel >= 1800 && pinLevel <= 1880 ) {
// 1840 avg
return keyLookup[10];
} else if ( pinLevel >= 1904 && pinLevel <= 1984 ) {
// 1944 avg
return keyLookup[9];
} else if ( pinLevel >= 2022 && pinLevel <= 2102 ) {
// 2062 avg
return keyLookup[8];
} else if ( pinLevel >= 2150 && pinLevel <= 2230 ) {
// 2190 avg
return keyLookup[7];
} else if ( pinLevel >= 2296 && pinLevel <= 2376 ) {
// 2336 avg
return keyLookup[6];
} else if ( pinLevel >= 2459 && pinLevel <= 2539 ) {
// 2499 avg
return keyLookup[5];
} else if ( pinLevel >= 2655 && pinLevel <= 2735 ) {
// 2695 avg
return keyLookup[4];
} else if ( pinLevel >= 2889 && pinLevel <= 2969 ) {
// 2929 avg
return keyLookup[3];
} else if ( pinLevel >= 3209 && pinLevel <= 3289 ) {
// 3249 avg
return keyLookup[2];
} else if ( pinLevel >= 3702 && pinLevel <= 3782 ) {
// 3742 avg
return keyLookup[1];
} else if ( pinLevel >= 4054 ) {
// 4094 avg
return keyLookup[0];
}
}
return 0;
}
| true |
a072d953b1f2731a45a62d6f1736ba4a6b03c578
|
C++
|
thulium-lab/thulium-main
|
/PyLab/remote_programs/arduino/arduino_shutter_WM_v0.1/arduino_shutter_WM_v0.1.ino
|
UTF-8
| 5,819 | 2.5625 | 3 |
[] |
no_license
|
// Developed by Artem Golovizin, LPI (FIAN). Based on arduino_shutters_v2.2.,
// Controlls shutters based on simple stepper motors in a logic way: 0 - only bias coil is on, 1 - both coils are on.
// Tipical resistences are 50-200 Ohm, the larger difference between bias and TTL resistence the larger rotation, tipical 10 degrees.
// Commands look like 'WMShutters c_i s_i c_j s_j!' where c_i,j - is a channel number (0 - on the main board), s_i,j - is a channel state, '!' in the end of line indicates command end.
#include "ctype.h"
const double second_coefficient = 1.014; // coeffitien reflects arduino time for 1s interval 0.988 - for second arduino
int available_ports[] = {A0, 12, 13, 11, 10, 9, 8, 7, 6, 5, 4, 3, A1, A2, A3, A4, A5};
const int ports_number = 17;
const int trig_pin = 2; // pin for triggering arduino on start of time sequence
// variables
int i = 0;
int k = 0;
int j = 0;
int int_arr[34]; // int array for handling channel:state for each beam shutter at specific time edge
int int_arr_current_length = 0; // current length of channels and states for beam shutters which are to write
// variables
char w[50];
String ws;
const byte n_words = 50; // maximum nuber of words in recieved messege
unsigned long last_time = 10; // last time when edge (beam shutters states) was changed
unsigned long last_trigger_time = 0; // last time when triggered
unsigned long t;
int words_number = 0; // number of words in last recieved command
int n_sequences; // number of sequencies t_ch1_s1_ch2_s2..._ where at time t channels' states chi changes ti si
String words[n_words]; // array of string to read from serial port to
String edge_sequence[n_words]; // array of strings to save sequences of beam shutters
int edge_delay=0; // delay of next edge (where any beam shutter state changes) from previous one in ms
int current_edge=0; // serial number of currently set edge (state)
bool handled ; // artifact from previous version (not used now); if serial input command is handled
bool interrupted = false; // if interruption from trigger occured this flag rises, when interruption is handled it crears
bool sequence_finished=false; // rises when beam shutter sequence is finished, after that programm waits when next trigger comes
// 0 for no unnesessery data to serial, 1 - for the most needed, 2 - for debugging pulse_scheme, 3 - for debugging WavelenghtMeter, 10 - for all
int debug=1;
int counter = 0;
int input_size;
String full, tail;
char b;
int first_space;
String msg;
String channel_string;
void setup() {
Serial.begin(9600); // boud rate
// attachInterrupt(0,interrupt_handler,RISING); // connect trigger on pin 2 to interrupt with handler function interrupt_handler, edge is rising
for (i = 0; i < ports_number; i++) {
pinMode(available_ports[i], OUTPUT); // configure output shutter pins
}
}
// interrupt (trigger) handler; rises flag 'interrupted' to then stat SMTH (i.e. writing to beam shutter channels)
//void interrupt_handler(){
// t = millis();
// msg = "interrupt t=" + String(t);
// if (t - last_trigger_time > 10){ // it is not a noise -- somewhy this part is needed
// last_time = t; // write down time when trigger arrived (sequence is started)
// last_trigger_time = t;
// current_edge = 0;
// interrupted=true; // rise flag
// msg += " good";
// }
// else {
// msg += " bad";
// }
// if (debug == 2 or debug == 10){
// Serial.println(msg);
// }
// if (debug == 1){
// Serial.print("i");
// }
//}
void loop() {
// if (interrupted){ // if interruption occured (trigger came) this flag is rised
// interrupted=false; // clear flag
// DO SMTH
// }
// chech if smth has been sent in serial port and call handler
if (Serial.available()){
data_input_handler();
}
}
// function that parses input commands
void data_input_handler() {
i = get_string_array(); // reads input and separates words
if (i == -1){
if (debug > 0 ){
Serial.println("Bad");
}
return;
}
handled = false; // dedicated
if ( (words[0]).equals("*IDN") ) { // identification
Serial.println("WMArduinoUnoShutters");
}
if ( (words[0]).equals("debug") ) { // set debug mode
if (words_number == 2){
debug = words[1].toInt();
Serial.println("Debug state updated");
}
else {
Serial.println("incorrect command");
}
}
if ( (words[0]).equals("WMShutters") ) { // set state of wavelength meter shutters
if( (words_number-1)%2 ) { // check if input more or less correct
if (debug > 0 ){
Serial.println("Bad WMShutters command");
}
return;
}
for (int i = 1; i < words_number; i+=2)
{
if (debug ==3 or debug==10 ){
Serial.print(words[i].toInt());
Serial.print(" ");
Serial.println(words[i+1].toInt());
}
digitalWrite(available_ports[words[i].toInt()], words[i+1].toInt());
}
if (debug == 2 ){
Serial.println("WS Ok");
}
if (debug == 1 ){
Serial.print(".");
}
}
}
int get_string_array()
{
// detachInterrupt(0); // it was an idea that some problems are due to the interrupt, but they are not
// it is nessesery to set strings to "", otherwise smth doesn't work
full = "";
for (int i = 0; i < n_words; i++) {
words[i] = "";
}
k=0;
i=30000; // numbers to try read serial input
while (i>0){
b=char(Serial.read());
if (b == '!' or b=='?'){
break;
}
else if (b ==' '){
k++;
}
else if (b>=0){
words[k]+=b;
}
i--;
}
// Serial.println(i);
if (debug == 10){
Serial.print("Trying read");
for (int i = 0; i < n_words; i++) {
Serial.print(words[i]);
}
Serial.println("");
}
words_number = k+1;
// attachInterrupt(0,interrupt_handler,RISING);
return 0;
}
| true |
75939e34a3405c47f3b7e9cceee4d002cbfa7691
|
C++
|
namanworld/LeetCode-Solutions-Time-Complexity-Optimized-
|
/1504. Count Submatrices With All Ones.cpp
|
UTF-8
| 758 | 2.53125 | 3 |
[] |
no_license
|
class Solution {
public:
int numSubmat(vector<vector<int>>& mat) {
int n = mat.size(), m = mat[0].size();
vector<vector<int> > arr(n, vector<int>(m, 0));
for(int i=0; i<n; i++){
int c = 0;
for(int j=m-1; j>=0; j--){
if(mat[i][j]) c++;
else c=0;
arr[i][j] = c;
}
}
int count = 0;
for(int i=0; i<n; i++){
for(int j=0; j<m; j++){
int c = INT_MAX;
for(int k=i; k<n; k++){
if(arr[k][j]<c){
c = arr[k][j];
}
count+=c;
}
}
}
return count;
}
};
| true |
5932680022d1619e2ad79f8ada7d5a60c0e92cae
|
C++
|
Song2012/C---Primer-exercise
|
/Ex4.18.cpp
|
WINDOWS-1256
| 687 | 2.546875 | 3 |
[] |
no_license
|
/*
* =====================================================================================
*
* Filename: Ex4.18.cpp
*
* Description:
*
* Version: 1.0
* Created: 2012/3/12 һ 0:21:03
* Revision: none
* Compiler: gcc
*
* Author: Python (),
* Company:
*
* =====================================================================================
*/
#include <iostream>
using namespace std;
int main(void) {
int a[] ={1,1,1,1,1};
for(int *pbegin = a , *pend = a+5 ; pbegin != pend ; pbegin++) {
*pbegin = 0;
}
cout<<"a:";
for(int i = 0;i != 5;i++) {
cout<<a[i]<<" ";
}
cout<<endl;
return 0;
}
| true |
f40005bcc095f93ef7979844969e2d9005f311f4
|
C++
|
vsapiens/Orientada_Objetos
|
/Orientada_Objetos/Video/Materia.h
|
UTF-8
| 774 | 3.21875 | 3 |
[] |
no_license
|
//
// Materia.h
// Orientada_Objetos
//
// Created by Erick González on 2/25/18.
// Copyright © 2018 Erick González. All rights reserved.
//
#ifndef Materia_h
#define Materia_h
class Materia
{
public:
//Constructor Default
Materia();
//Constructor con parametros
Materia(int idMateria, string nombre){this->idMateria = idMateria;this->nombre = nombre;}
//Metodos de Acceso
int getIdMateria(){return idMateria;}
string getNombre(){return nombre;}
//Metodos de Modificacion
void setIdMateria(int idMateria){this->idMateria = idMateria;}
void setNombre(string nombre){this->nombre = nombre;}
private:
int idMateria;
string nombre;
};
Materia::Materia()
{
idMateria = 0;
nombre = "-";
}
#endif /* Materia_h */
| true |
6c1595b1e10e44cb76a414fa7519c1ea8ad386c7
|
C++
|
milon/UVa
|
/Volume-9/UVa_913.cpp
|
UTF-8
| 245 | 2.515625 | 3 |
[] |
no_license
|
//UVa Problem-913(Joana and the Odd Number)
//Accepted
//Running time: 0.008 sec
#include<iostream>
using namespace std;
int main(){
long long n,a;
while(cin>>n){
a=(1+n)*(n/2+1)/2;
a=a*2-1;
a=a*3-6;
cout<<a<<endl;
}
return 0;
}
| true |
98e4ce6fb9325a35878cfa306c203304d3c076d9
|
C++
|
PaigeG/Comp-Sci-2-2018
|
/main9.cpp
|
UTF-8
| 1,114 | 3.421875 | 3 |
[] |
no_license
|
//Paige Gadapee
//Drive Code for Lab 9
//April 10, 2018
#include "lab9.h"
#include "savings.h"
#include "checking.h"
#include <iostream>
using namespace std;
int main()
{
//variables
double interest, amount, number;
cout << "Normal account : " << endl;
Account origin(50.0);
origin.getBalance();
origin.display();
cout << "After adding 12.50 to your accout :" << endl;
origin.credit(12.5);
origin.display();
cout << "After crediting 6.25 to your account : " << endl;
origin.debit(6.25);
origin.display();
cout << "Savings Account : " << endl;
SavingsAccount save(300.0, .10);
save.display();
interest = save.calculateInterest();
save.credit(interest);
cout << "With interest ";
save.display();
cout << "Checking Account :" << endl;
CheckingAccount spend(500.0, 2.25);
spend.display();
cout << "Enter an amount to add to your account : ";
cin >> amount;
spend.credit(amount);
spend.display();
cout << "Enter an amount to subtract from your account : ";
cin >> number;
spend.debit(number);
spend.display();
return(0);
}
| true |
cb12af7a8b0f785e90e958cd021ce8fae8a67356
|
C++
|
danielvallejo237/Advanced-Programming
|
/Uhunt_problems/Mathematics/UVA_10056_withp.cpp
|
UTF-8
| 547 | 2.5625 | 3 |
[] |
no_license
|
#include <bits/stdc++.h>
using namespace std;
double EPS=1e-9;
double prob(double p, double sujeto,int players)
{
return p*pow((1-p),sujeto-1)/(1.0-pow((1-p), players));
}
int main()
{
int testcases;
cin>>testcases;
while(testcases--)
{
double p;
int players;
int sujeto;
cin>>players>>p>>sujeto;
if(p<EPS)
{
printf ("0.0000\n");
continue;
}
double proba=prob(p,sujeto,players);
printf("%.4lf\n", proba);
}
return 0;
}
| true |
ec8887bef2a966a6c19fc2a23958c97121ffcb32
|
C++
|
yanmt311/MT_1
|
/其他/Test/Test/Student.h
|
GB18030
| 629 | 2.96875 | 3 |
[] |
no_license
|
#ifndef STUDENT_H_INCLUDED
#define STUDENT_H_INCLUDED
class Student
{
private:
char Name[20]; //ѧ
double Chinese; //ijɼ
double Math; //ѧɼ
public:
double Average(); //ƽɼ
double Sum(); //ܷ
void Show(); //ӡϢ
//أβбͬأ
void SetStudentdent(char*, double);//Ϊijɼ
void SetStudentdent(char*, double, double);//Ϊijɼѧɼ
};
#endif // STUDENT_H_INCLUDED
| true |
b89a6b7321ed5abb0a145a7d4b6fa389965850b6
|
C++
|
Rescon/MI206
|
/TP1/TP1_MI206/include/Image.hh
|
ISO-8859-2
| 6,029 | 2.65625 | 3 |
[] |
no_license
|
#ifndef _IMAGE_
#define _IMAGE_
#define NMAX 21
/************************************************************/
/* definitions de types */
/************************************************************/
template <class T> class Info;
struct Vecteur;
class Noyau;
class FIFO;
template <class T> class Image;
typedef int BOOL;
/************************************************************/
/* variables globales et leurs procdures */
/************************************************************/
static int BORD; // 0 : bords nuls; 1 : bords geodesiques;
// 2 : bords wrappes (image torique);
int ChangeBord(int val);
/************************************************************/
/* classe Info */
/************************************************************/
template <class T> class PixLC {
public:
PixLC();
~PixLC();
void InsereApres(T* pix);
void InsereAvant(T * pix);
private:
T * pix;
char * NomOperation;
PixLC<T> * Suivant, *Precedent;
friend class Info<T>;
};
template <class T> class Info {
private :
T* pix;
PixLC<T> * PixListe; //element courant de la liste
int S;
Info<T>* Precedent;
Info<T> * Suivant;
public :
Info<T>();
Info<T>(int taille);
Info<T>(int t,T* im);
Info<T>(const Info<T>& ii);
~Info();
Info<T>& operator=(const Info<T>& ii);
void Info_decale(const int& i);
T operator[](const int& i) const;
T index(const int& i) const;
T* ref() const;
void Ecrit_info(const int& i,const T& z);
void Empile(char * NomOperation);
bool DepileAvant();
bool DepileArriere();
const char * DerniereOperation();
};
/************************************************************/
/* structure Vecteur */
/************************************************************/
struct Vecteur {
int x;
int y;
Vecteur();
Vecteur(int i, int j);
Vecteur(const Vecteur& v);
~Vecteur();
Vecteur& operator=(const Vecteur& v);
Vecteur operator+(const Vecteur& v);
Vecteur& operator+=(const Vecteur& v);
int operator*(const Vecteur& v);
Vecteur operator-();
Vecteur rot90();
Vecteur rot270();
int operator==(const Vecteur& t);
};
/************************************************************/
/* classe Noyau */
/************************************************************/
class Noyau {
public :
int debx,finx; /* Position en x */
int deby,finy; /* Position en y */
int val[NMAX][NMAX]; /* Valeurs */
Noyau();
~Noyau();
int KX0();
int KX1();
int KY0();
int KY1();
Noyau& operator= (const Noyau& k);
Noyau Noyau_transpose ();
Noyau& Noyau_efface ();
Noyau& Noyau_setmasque(int tab[NMAX][NMAX]);
// Somme et multiplication par un scalaire
Noyau operator+ (const Noyau& p);
Noyau operator* (const int x);
};
/************************************************************/
/* classe FIFO */
/************************************************************/
class FIFO {
private :
int first; /* Dbut de liste */
int last; /* Fin de liste */
int size; /* Taille admise */
int *listx; /* Liste des x */
int *listy; /* Liste des y */
public :
FIFO();
FIFO(int taille);
~FIFO();
FIFO& operator=(const FIFO& ff);
FIFO& FIFO_delete ();
FIFO& FIFO_alloc(int taille);
FIFO& FIFO_free();
FIFO& FIFO_add (int x,int y);
FIFO& FIFO_reinit ();
void FIFO_get(int& x,int& y);
int FIFO_empty() const;
};
/************************************************************/
/* classe Image */
/************************************************************/
template<class T> class Image {
private :
int W,L; /* Dimensions Statiques */
Info<T> I; /* Information totale */
public :
Image();
Image(const int& i,const int& j);
Image(const Image<int>& pp);
~Image();
int* PI();
int PW();
int PL();
int X (int i,int j) const;
Image<int>& operator= (const Image<int>& p);
Image<int> Image_translat(const Vecteur& v) const;
Image<int> Nord() const;
Image<int> Sud() const;
Image<int> Ouest() const;
Image<int> Est() const;
Image<int> NE() const;
Image<int> SE() const;
Image<int> NW() const;
Image<int> SW() const;
Image<int>& Image_efface ();
int* Image_hist ();
/* Operations booleennes */
Image<BOOL> operator& (const Image<BOOL>& p) const;
Image<BOOL> operator| (const Image<BOOL>& p) const;
Image<BOOL> operator! () const;
Image<BOOL> operator^ (const Image<BOOL>& p) const;
Image<BOOL> operator- (const Image<BOOL>& p) const;
Image<BOOL> operator== (const Image<BOOL>& p) const;
Image<BOOL> operator<= (const Image<BOOL>& p) const;
Image<BOOL> operator>= (const Image<BOOL>& p) const;
// Operations de base sur les niveaux de gris
Image<BOOL> Image_seuil (const int s);
Image<int> operator+ (const Image<int>& p);
Image<int> Image_superpose (const Image<BOOL>& p,const int nb,const int coul);
Image<int> Image_diff(const Image<int>& p);
// Ecriture sous differents formats
int Imagetopgm (char *nom) const;
int Image_compte_pixel () const;
//gestion de la pile des modifications (operations undo et redo)
void Empile(char * NomOperation); /*empile l'image actuelle dans la pile arriere, efface la pile avant*/
bool DepileArriere(); /*undo:remplace l'image actuelle par la premiere de la pile ariere, empile l'image actuelle dans la pile avant*/
bool DepileAvant(); /*redo:remplace l'image actuelle par la premiere de la pile avant, empile l'image actuelle dans la pile arriere*/
const char * DerniereOperation(); /*renvoit le nom de la derniere operation effectuee*/
};
#endif
| true |
68b57dee5ba1db1087af1a2ad71544df8c0708db
|
C++
|
lock19960613/SCL
|
/Daily/CPP/Leetcode847-访问所有节点的最短路径.h
|
UTF-8
| 918 | 2.8125 | 3 |
[] |
no_license
|
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
int shortestPathLength(vector<vector<int>>& graph) {
typedef pair<int,int> PII;
int n = graph.size(),INF = 1e9;
vector<vector<int>> dp(1<<n,vector<int>(n,INF));
queue<PII> q;
for(int i = 0;i < n;i++){
dp[1 << i][i] = 0;
q.push({1 << i,i});
}
while(q.size()){
auto t = q.front();
q.pop();
for(auto node:graph[t.second]){
int a = t.first | 1 << node,b = node;
if(dp[a][b] > dp[t.first][t.second] + 1){
dp[a][b] = dp[t.first][t.second] + 1;
q.push({a,b});
}
}
}
int res = INF;
for(int i = 0;i < n;i++){
res = min(res,dp[(1 << n) - 1][i]);
}
return res;
}
};
| true |
62b0438214bacc34046f82fafe459e7323e8bd3a
|
C++
|
BOISSARD/WifiBot
|
/outputmanager.h
|
UTF-8
| 625 | 2.640625 | 3 |
[] |
no_license
|
#ifndef OUTPUTMANAGER_H
#define OUTPUTMANAGER_H
#include <QTextStream>
#include <iostream>
#include "direction.h"
#include "connexionmanager.h"
using namespace std;
class OutputManager
{
public:
OutputManager();
~OutputManager();
void setConnexionManager(ConnexionManager* connexion);
virtual void moveRobot(Direction direction, float speed) = 0;
virtual void moveCamera(Direction direction, float speed) = 0;
ConnexionManager* getConnexion(){
return connexion;
}
protected:
ConnexionManager* connexion;
};
#endif // OUTPUTMANAGER_H
| true |
935b7cbecf5f799f10e88ffd12df704b56ec7fcd
|
C++
|
Riateche/ridual
|
/src/Directory_watcher.cpp
|
UTF-8
| 1,201 | 2.625 | 3 |
[
"MIT",
"CC-BY-4.0",
"CC-BY-3.0"
] |
permissive
|
#include "Directory_watcher.h"
#include <QDir>
#include <QDebug>
#include "Core.h"
#include "File_system_engine.h"
Directory_watcher::Directory_watcher(Core *c) :
QObject(0)
, Core_ally(c)
{
connect(&watcher, SIGNAL(directoryChanged(QString)), this, SIGNAL(directory_changed(QString)));
fs = core->get_file_system_engine();
}
void Directory_watcher::add(QString path) {
//qDebug() << "Directory_watcher::add" << path;
if (counter.contains(path)) {
counter[path]++;
//qDebug() << "already added";
} else {
//qDebug() << "adding";
counter[path] = 1;
QString real_path = fs->get_real_file_name(path);
if (!real_path.isEmpty() && QDir(real_path).exists() && QDir(real_path).isReadable()) {
real_paths[path] = real_path;
watcher.addPath(real_path);
}
}
}
void Directory_watcher::remove(QString path) {
//qDebug() << "Directory_watcher::remove" << path;
counter[path]--;
if (counter[path] == 0) {
//qDebug() << "removing";
counter.remove(path);
real_paths.remove(path);
watcher.removePath(path);
}
}
void Directory_watcher::slot_directory_changed(QString real_path) {
emit directory_changed(real_paths.key(real_path));
}
| true |
1729ffe3d5ca3f40c55e3546bbcc55a9ddd0194d
|
C++
|
felixguendling/cista
|
/include/cista/memory_holder.h
|
UTF-8
| 969 | 2.734375 | 3 |
[
"MIT"
] |
permissive
|
#pragma once
#include <variant>
#include "cista/buffer.h"
#include "cista/containers/unique_ptr.h"
#include "cista/mmap.h"
#include "cista/targets/buf.h"
namespace cista {
using memory_holder = std::variant<buf<mmap>, buffer, byte_buf>;
template <typename T>
struct wrapped {
wrapped(memory_holder mem, T* el) : mem_{std::move(mem)}, el_{el} {
el_.self_allocated_ = false;
}
explicit wrapped(raw::unique_ptr<T> el) : el_{std::move(el)} {}
T* get() const noexcept { return el_.get(); }
T* operator->() noexcept { return el_.get(); }
T const* operator->() const noexcept { return el_.get(); }
T& operator*() noexcept { return *el_; }
T const& operator*() const noexcept { return *el_; }
memory_holder mem_;
raw::unique_ptr<T> el_;
};
template <typename T>
wrapped(memory_holder, T*) -> wrapped<T>;
template <typename T>
wrapped(memory_holder, raw::unique_ptr<T>) -> wrapped<T>;
} // namespace cista
| true |
b5e0484e1f122a10ac19c2a6eda1b7b675b9cf45
|
C++
|
BusHero/robotino_api2
|
/common/lib/rec/robotino3/serialio/tag/HwVersion.h
|
UTF-8
| 1,608 | 2.53125 | 3 |
[] |
no_license
|
#ifndef _REC_ROBOTINO3_SERIALIO_TAG_HWVERSION_H_
#define _REC_ROBOTINO3_SERIALIO_TAG_HWVERSION_H_
#include "rec/robotino3/serialio/Tag.h"
#include "rec/robotino3/serialio/tag/HwVersionFwd.h"
namespace rec
{
namespace robotino3
{
namespace serialio
{
namespace tag
{
class HwVersion : public rec::robotino3::serialio::Tag
{
public:
static HwVersionPointer create()
{
return HwVersionPointer( new HwVersion );
}
QString print() const
{
return "HW_VERSION: " + _versionStr;
}
static HwVersionPointer decode( QIODevice* buffer )
{
unsigned char ch = 0;
if( buffer->getChar( (char*)&ch ) )
{
if( 0 == ch )
{
throw rec::robotino3::serialio::TagException( QString( "HwVersion length=%1 not allowed" ).arg( (quint32)ch ) );
}
QByteArray ba = buffer->read( ch );
if( ba.size() != ch )
{
throw rec::robotino3::serialio::TagException( QString( "HwVersion length=%1 but only %2 bytes left in body" ).arg( (quint32)ch ).arg( ba.size() ) );
}
HwVersionPointer hwVersion = create();
hwVersion->_versionStr = QString( ba );
return hwVersion;
}
else
{
throw rec::robotino3::serialio::TagException( QString( "Error getting length of HwVersion tag" ) );
}
}
QString versionStr() const
{
return _versionStr;
}
private:
HwVersion()
: Tag( TAG_HW_VERSION )
{
}
QString _versionStr;
};
}
}
}
}
#endif //_REC_ROBOTINO3_SERIALIO_TAG_HWVERSION_H_
| true |
219f03534deb66c4896053bcbfdc7fc6f78d332a
|
C++
|
ntran273/traveltips
|
/src/gui/fbpastpost.cpp
|
UTF-8
| 7,037 | 2.59375 | 3 |
[] |
no_license
|
/*Copyright 2017 Paul Salvador Inventado
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef FBPASTPOST
#define FBPASTPOST
#include "fbpastpost.h"
#include <iostream>
/** ViewController for the Login top level window **/
LoginController::LoginController(GladeAppManager* gapManager, std::string windowName, bool isTopLevel):ViewController(gapManager, windowName, isTopLevel){
// Sets the size and position of the window
window->set_title("FB Past Post");
window->set_default_size(400, 300);
window->set_position(Gtk::WIN_POS_CENTER_ALWAYS);
// Assigns login() as handler for clicking on the login button
Gtk::Button* pButton = nullptr;
builder->get_widget("btn_fblogin", pButton);
pButton->signal_clicked().connect( sigc::mem_fun(*this, &LoginController::login) );
FbManager* mgr = FB::getManager();
mgr->addConnectionListener(this);
}
void LoginController::login(){
// Switch to the posts_window
FbManager* mgr = FB::getManager();
mgr->login(gapManager->getGtkApplication()->get_id());
}
void LoginController::loginSuccess(){
gapManager->showView("posts_window");
}
bool LoginController::clickClose(GdkEventAny* evt){
// Exit the GUI
gapManager->exit();
return false;
}
/** ViewController for the Posts window **/
PostController::PostController(GladeAppManager* gapManager, std::string windowName, bool isTopLevel):ViewController(gapManager, windowName, isTopLevel){
// Sets the size and position of the window
window->set_title("Posts");
window->set_default_size(800, 600);
window->set_position(Gtk::WIN_POS_CENTER_ALWAYS);
// Associates the post_box Box in the Glade file to a pointer for later use
posts_container = nullptr;
builder->get_widget("post_box", posts_container);
// Associates the post_box Box in the Glade file to a pointer for later use
remembered_posts_container = nullptr;
builder->get_widget("remember_post_box", remembered_posts_container);
// Assigns refresh() as handler for clicking on the refresh button
Gtk::Button* pRefresh = nullptr;
builder->get_widget("btn_refresh", pRefresh);
pRefresh->signal_clicked().connect( sigc::mem_fun(*this, &PostController::refresh) );
// Assigns remember_refresh() as handler for clicking on the remembered post refresh button
Gtk::Button* pRemRefresh = nullptr;
builder->get_widget("btn_rem_refresh", pRemRefresh);
pRemRefresh->signal_clicked().connect( sigc::mem_fun(*this, &PostController::rememberedRefresh) );
}
void PostController::refresh(){
// Place holder to API call that will create Post objects for each Facebook post retrieved.
// Each post is sent to addPost so it is shown on the GUI
FbManager* mgr = FB::getManager();
std::vector<Post*> results = mgr->getPosts();
for(Post* p : results){
addPost(p);
}
}
void PostController::rememberedRefresh(){
// Place holder to API call that will create Post objects for each Facebook post retrieved.
// Each post is sent to addPost so it is shown on the GUI
//remembered_posts_container
std::vector<Post*> posts = PostLoader::getPosts();
for(auto post: rememberedPosts){
remembered_posts_container->remove(*(post.second));
}
rememberedPosts.clear();
for(Post* p : posts){
addRememberedPost(p);
}
}
void PostController::addPost(Post* post){
if(posts.count(post->getId())==0){ // add post if has not been added yet
// Creates a PostWidget object associated with a Post. All values of the Post are used for the display
PostWidget* p = Gtk::manage(new PostWidget(post));
// Stores the PostWidget object for reference
posts[post->getId()] = p;
// Adds the PostWidget object into the post_box designed in the Glade file
posts_container->add(*p);
}
}
void PostController::addRememberedPost(Post* post){
if(rememberedPosts.count(post->getId())==0){ // add post if has not been added yet
// Creates a PostWidget object associated with a Post. All values of the Post are used for the display
PostWidget* p = Gtk::manage(new PostWidget(post));
// Stores the PostWidget object for reference
rememberedPosts[post->getId()] = p;
// Adds the PostWidget object into the post_box designed in the Glade file
remembered_posts_container->add(*p);
}
}
bool PostController::clickClose(GdkEventAny* evt){
// Switch the view to the login window when the x button is clicked
gapManager->showView("start_window");
return false;
}
/** Widget to represent Facebook posts **/
//PostWidget::PostWidget(std::string id, std::string titleText, std::string imageLoc, std::string messageText){
PostWidget::PostWidget(Post* p){
post = p;
// Create widgets that will be added into a Box widget.
remember_label = new Gtk::Label("Remember");
remember = new Gtk::Switch(); // on/off switch
remember->set_active(p->isRemembered());
remember->property_active().signal_changed().connect(sigc::mem_fun(*this, &PostWidget::toggleSwitch));
title_separator = new Gtk::Separator(Gtk::ORIENTATION_VERTICAL);
title = new Gtk::Label(p->getTitle(), Gtk::ALIGN_START);
// Creates another (horizontal) box that contains the title label and switch
remember_container = new Gtk::HBox();
// Add the switch and label into the box
remember_container->pack_start(*remember_label, false, false, 5);
remember_container->pack_start(*remember, false, false, 5);
remember_container->pack_start(*title_separator, false, false, 5);
remember_container->pack_start(*title, true, true, 5);
// Creates other widgets
timestamp = new Gtk::Label(p->getTimestamp(), Gtk::ALIGN_START);
message = new Gtk::Label(p->getMessage(), Gtk::ALIGN_START);
// Add all widgets into the main Box
pack_start(*remember_container, true, true);
pack_start(*timestamp, true, true, 5);
if(!p->getImage().empty()){
image = new Gtk::Image(p->getImage());
image->set_halign(Gtk::ALIGN_START);
pack_start(*image, true, true, 5);
}
pack_start(*message, true, true, 5);
post_separator = new Gtk::Separator(Gtk::ORIENTATION_HORIZONTAL);
pack_start(*post_separator, true, true, 5);
// Tell GTK to refresh the GUI so as to show all added components
show_all();
}
// getters and setters
std::string PostWidget::getId(){
return id;
}
std::string PostWidget::getTitle(){
return title->get_text();
}
std::string PostWidget::getImage(){
//retrieve image here
return "";
}
std::string PostWidget::getMessage(){
return message->get_text();
}
Post* PostWidget::getPost(){
return post;
}
void PostWidget::toggleSwitch(){
if(!remember->get_active()){
post->setRemembered(false);
post->remove();
}else if(remember->get_active()){
post->setRemembered(true);
post->save();
}
}
#endif
| true |
c7d04efdf4e56a867dc302fadc3c1af9244094d8
|
C++
|
selvabharathis/Arduino-Coding
|
/pir_sensor-led/pir_sensor-led.ino
|
UTF-8
| 638 | 2.59375 | 3 |
[] |
no_license
|
// S.Selvabharathi B.Tech IT Rajalakshmi Engineering College
// vcc->3v to 5v , gnd->gnd ,out->analog pin of microcontroller
//NOTE: pir has sensitivity adjustment,duration adjestment and trigger(non-repeating and repeating) if trigger is in repeat mode the led will blink on and off , so becarefull with all the constrains.
int led = D6;
int pir=D7;
int state=0;
void setup() {
pinMode(pir, INPUT);
pinMode(led, OUTPUT);
}
void loop(){
state = digitalRead(pir);
delay(1000);
if(state == HIGH)
{
digitalWrite (led, HIGH);
}
if(state == LOW)
{
digitalWrite (led, LOW);
}
}
| true |
c930977edb21c1344455bd5aa9f5eac93966be54
|
C++
|
RicoJia/Accelerated-C-
|
/Acc_C++_chap8/8_6.cpp
|
UTF-8
| 630 | 2.96875 | 3 |
[] |
no_license
|
//
// Created by rico on 7/19/19.
//
#include "8_6.h"
#include <iostream>
using std::cout;
using std::endl;
#include <map>
using std::map;
#include <utility>
using std::pair;
#include <string>
using std::string;
#include <list>
using std::list;
#include <algorithm>
using std::copy;
#include <iterator>
using std::back_inserter;
void test_8_6()
{
map<int,string> m = {{1,"hola"},{2,"amigo"}};
list<pair<int,string> > l;
copy(m.begin(),m.end(),back_inserter(l));
for(auto i = l.begin();i!=l.end();++i)
cout<<i->first<<" "<<i->second<<endl; //注意,这是正确print Map的方式。
}
| true |
0eb7d66178f7a18bbfecf9e58c7471ff074050d4
|
C++
|
WhiZTiM/coliru
|
/Archive2/cd/07b4abe3e4aa35/main.cpp
|
UTF-8
| 544 | 2.6875 | 3 |
[] |
no_license
|
struct Traits {
template <typename T>
struct Foo {
typedef typename T::bar* type;
};
};
template <typename T>
class Bar
{
typedef int bar;
// need to make T::Foo<Bar> a friend somehow?
using my_friend=typename T::template Foo<Bar>;
friend my_friend;
typedef typename T::template Foo<Bar>::type type; // won't compile because bar is private...
// suppose I cannot make bar public.
type val;
};
int main() {
Bar<Traits> b;
}
| true |
d31eb49c265b7679594eedf5e9590d47ce2bd16f
|
C++
|
LizaBelova/GGRPG
|
/elemental.cpp
|
UTF-8
| 2,736 | 3.109375 | 3 |
[] |
no_license
|
#include "elemental.h"
elemental::elemental()
{
set_name("Elemental");
set_hp(100);
set_max_hp(100);
set_def(130);
set_atk(85);
set_max_atk(85);
set_mana(0);
for(int i=0;i<8;i++){
status[i]=false;
status_cont[i]=0;
}
}
elemental::~elemental()
{
}
void elemental::skill1(vector<Creature *> heroes, vector<Creature *>)
{
int damage;
int target;
int count=0;
int agr=0;
cout<<"Elemental uses Firestorm"<<endl;
while(count<2){
target=rand()%heroes.size();
damage=20+rand()%31;
for(int i=0;i<heroes.size();i++){
if(heroes[i]->get_name()=="Knight" && heroes[i]->get_status(1) && agr==0) {target=i; agr++; break;}
}
if(heroes[target]->get_name()=="Knight" && heroes[target]->get_status(0)==true){
cout<<"But Knight raise the shield"<<endl;
heroes[target]->set_status_cont(0,-1);
if(heroes[target]->get_status_cont(0)==0) heroes[target]->set_status(0,false);
return;
}
if(heroes[target]->get_def()>0){
heroes[target]->set_hp(-damage/2);
heroes[target]->set_def(-damage/2);
cout<<heroes[target]->get_name()<<" get "<<damage<<" damage,"<<damage/2<<" to HP and DEF"<<endl;
if(heroes[target]->get_def()<0) heroes[target]->set_def(abs(heroes[target]->get_def()));
}
else {
heroes[target]->set_hp(-damage);
cout<<heroes[target]->get_name()<<" get "<<damage<<" damage to HP"<<endl;
}
heroes[target]->set_status(5,true);
heroes[target]->set_status_cont(5,3-heroes[target]->get_status_cont(5));
if(heroes[target]->get_hp()<1){
heroes[target]->set_hp(abs(heroes[target]->get_hp()));
heroes[target]->set_status(2,true);
}
count++;
}
}
void elemental::skill2(vector<Creature *> heroes, vector<Creature *>)
{
int target=rand()%heroes.size();
for(int i=0;i<heroes.size();i++){
if(heroes[i]->get_name()=="Knight" && heroes[i]->get_status(1)) {target=i; break;}
}
if(heroes[target]->get_name()=="Knight" && heroes[target]->get_status(0)==true){
cout<<"Elemental uses Frostbalt, But Knight raise the shield"<<endl;
heroes[target]->set_status_cont(0,-1);
if(heroes[target]->get_status_cont(0)==0) heroes[target]->set_status(0,false);
return;
}
cout<<"Elemental uses Frostbolt on "<<heroes[target]->get_name()<<" and imposes Freeze"<<endl;
heroes[target]->set_status(7,true);
heroes[target]->set_status_cont(7,1-heroes[target]->get_status_cont(7));
}
| true |
9fbeb01d2537ac90848c3104a6e7fe02cdd4113b
|
C++
|
codebaard/GLSLPathTracer
|
/glPathTracer/include/Framebuffer.h
|
UTF-8
| 1,666 | 2.625 | 3 |
[] |
no_license
|
/*
The purpose for this class is handle the framebuffer state and data within openGL.
Every Instance represents a single framebuffer with a arbitrary settings and purposes.
written by Julius Neudecker
v0.1 30.07.2020 - created.
v0.2 31.07.2020 - Added Functionality for fetching Compute Shader Buffer
*/
#ifndef FRAMEBUFFER_H
#define FRAMEBUFFER_H
#include <glfwHandler.h>
#include <jLog.h>
#include <Shader.h>
#define RENDERBUFFER_SIZE_WIDTH 512
#define RENDERBUFFER_SIZE_HEIGHT 512
class Framebuffer {
public:
//set default values since the framebuffer is normally intended to render texture output.
Framebuffer(unsigned int width, unsigned int height, unsigned int bufferType = GL_FRAMEBUFFER, unsigned int attachmentUnit = GL_COLOR_ATTACHMENT0);
void EnableRenderToTexture();
void DisableRenderToTexture(); //Disable after Rendering!
void ShowRenderedTexture();
void SetShaderProgram(std::string cwd, const char* vertexShader, const char* fragmentShader);
void InitImageTexture();
void ActivateImageTexture();
void FetchTexture();
~Framebuffer();
private:
void _attachTexture();
void _initQuadArray();
unsigned int _FBO;
unsigned int _RBO;
unsigned int _bufferType;
unsigned int _attachmentUnit;
unsigned int _targetTextureID;
unsigned int _computeImageTextureID;
unsigned int _width;
unsigned int _height;
Shader* _renderer;
//for rendering fullscreen quad
unsigned int _quadVAO, _quadVBO;
float _quadVertexArray[24] = {
// positions // texCoords
-1.0f, 1.0f, 0.0f, 1.0f,
-1.0f, -1.0f, 0.0f, 0.0f,
1.0f, -1.0f, 1.0f, 0.0f,
-1.0f, 1.0f, 0.0f, 1.0f,
1.0f, -1.0f, 1.0f, 0.0f,
1.0f, 1.0f, 1.0f, 1.0f
};
};
#endif
| true |
1253f83be6cef36d2f3070e0b290d225bdc97258
|
C++
|
Merisho/comprog
|
/algotester/anniversary-7/c.cpp
|
UTF-8
| 789 | 2.625 | 3 |
[] |
no_license
|
#include <bits/stdc++.h>
using namespace std;
vector<vector<int>> g;
vector<bool> v;
int dfs(int x) {
v[x] = true;
int k = 1;
for (int i = 0; i < g[x].size(); ++i) {
int to = g[x][i];
if (!v[to]) {
k += dfs(to);
}
}
return k;
}
int main() {
int n, m;
cin >> n >> m;
v = vector<bool>(n, false);
g = vector<vector<int>>(n);
for (int i = 0; i < m; ++i) {
int a, b;
cin >> a >> b;
g[a - 1].push_back(b - 1);
g[b - 1].push_back(a - 1);
}
vector<int> c(n + 1, 0);
for (int i = 0; i < n; ++i) {
if (!v[i]) {
int k = dfs(i);
++c[k];
}
}
int s = 0;
for (int i = 1; i <= n; ++i) {
s += c[i];
int r = c[i];
for (int j = i + 1; j < n; ++j) {
if (c[j] == 0) {
continue;
}
r *= c[j];
}
s += r;
}
cout << s;
return 0;
}
| true |
0769a148714917f7ae1811f62d067cf9d83a32ce
|
C++
|
SubhamGupta007/Dynamic-Programming
|
/Kushagra Shekhawat/Day 6/29. Page Faults in LRU.cpp
|
UTF-8
| 2,054 | 3.1875 | 3 |
[] |
no_license
|
#include<bits/stdc++.h>
using namespace std;
int PageFaults(int pages[],int N,int C);
void pushPageBack(deque<int> &dq,
unordered_map<int,int> &ump,int page);
void RemovePageAndAddNew(deque<int> &dq,
unordered_map<int,int> &ump,int page);
int main()
{
int T;
cin>>T;
while(T--){
int N,C;
cin>>N;
int pages[N];
for(int i=0;i<N;i++)
cin>>pages[i];
cin>>C;
cout<<PageFaults(pages,N,C)<<endl;
}
return 0;
}
int PageFaults(int pages[],int N,int C){
deque<int>dq;
unordered_map<int,int>ump;
int capacity = C,i=0;
int pageFault=0;
for(i=0;capacity>0 and i<N;i++){
if(ump.find(pages[i])==ump.end()){
dq.push_back(pages[i]);
ump[pages[i]] = dq.size();
pageFault++;
capacity--;
}else{
pushPageBack(dq,ump,pages[i]);
}
}
//cout<<"pageFault:"<<pageFault<<endl;
for(;i<N;i++){
if(ump.find(pages[i])==ump.end()){
RemovePageAndAddNew(dq,ump,pages[i]);
pageFault++;
//cout<<"RemovePageAndAddNew :"<<dq.front()<<" and "<<pages[i]<<endl;
}else{
//cout<<"PushPageBack, pageNo:"<<pages[i]<<endl;
pushPageBack(dq,ump,pages[i]);
}
}
return pageFault;
}
void pushPageBack(deque<int> &dq,
unordered_map<int,int> &ump,int page){
int position = ump[page];
for(auto it = dq.begin();it!=dq.end();++it)
if(--position == 0){
auto tempit = it;
while(tempit!=dq.end()){
ump[*tempit] = ump[*tempit]-1;
++tempit;
}
dq.erase(it);
ump.erase(page);
break;
}
dq.push_back(page);
ump[page]=dq.size();
}
void RemovePageAndAddNew(deque<int> &dq,
unordered_map<int,int> &ump,int page){
int removePage = dq.front();
for(auto it=dq.begin();it!=dq.end();++it){
ump[*it] = ump[*it]-1;
}
dq.pop_front();
ump.erase(removePage);
dq.push_back(page);
ump[page] = dq.size();
}
| true |
7607215bf78264dd795ee6957e5fa15868653c55
|
C++
|
MaximumEndurance/Algo-17
|
/Practise/3-Jul-Prac/LCA_in_BT.cpp
|
UTF-8
| 895 | 3.515625 | 4 |
[] |
no_license
|
#include "tree.h"
bool search(Node* root, int val) {
if(!root) return 0;
if(root->data == val)
return 1;
return (search(root->left, val) || search(root->right, val));
}
Node* LCA_in_BT(Node* root, Node* n1, Node* n2) {
if(!root) return NULL;
bool onLeft1 = search(root->left, n1->data);
bool onRight1 = search(root->right, n2->data);
bool onLeft2 = search(root->left, n2->data);
bool onRight2 = search(root->right, n1->data);
if((onLeft1 && onRight1) || (onLeft2 && onRight2)) {
return root;
}
if(onLeft1 && onLeft2) {
return LCA_in_BT(root->left, n1, n2);
}
if(onRight1 && onRight2) {
return LCA_in_BT(root->right, n1, n2);
}
return root;
}
int main() {
Node* root = takeInput();
print(root);
int data1; int data2;
cin >>data1 >>data2;
Node* n1 =new Node(data1);
Node* n2 = new Node(data2);
Node* ans = LCA_in_BT(root, n1, n2);
cout<<ans->data<<endl;
}
| true |
0dc6657cfb3940dfec49d320fce59373d9bde342
|
C++
|
tanmaythaakur/fs_elite
|
/Elite_2.0/ABDValue.cpp
|
UTF-8
| 2,182 | 3.6875 | 4 |
[] |
no_license
|
/*
Sumanth has an idea to calculate the ABD value of a string.
An ABD value is defined as the absolute diffrence between
the most occurance count of a charcter and the least occurance count
of another character in the given string.
Sumanth is given a string S,
He wants to find out, the sum of ABD values of all the substrings of S,
where ABD > 0.
Your task is to help Sumanth to find total ABD value of substrings of S.
Input Format:
-------------
A String S
Output Format:
--------------
Print an integer, sum of ABD of all the strings of S
Sample Input-1:
---------------
abbcc
Sample Output-1:
----------------
5
Explanation:
------------
The substrings with non-zero ABD are as follows:
Substring and ABD value -> "abb"-1,"abbc"-1,"abbcc"-1,"bbc"-1,"bcc"-1
The total sum of ABD is, 5
Sample Input-2:
---------------
abcbabc
Sample Output-2:
----------------
15
Explanation:
------------
The substrings with non-zero ABD are as follows:
substring and ABD value -> "abcb"-1,"abcba"-1,"abcbab"-2,"abcbabc"-1,"bcbabc"-2
"bcbab"-2, "bcba"-1, "bcb"-1, "cbab"-1,"cbabc"-1,"bab"-1, "babc"-1.
The total sum of ABD is, 15
*/
#include <bits/stdc++.h>
using namespace std;
void print(vector<int> &arr)
{
int sz = arr.size();
cout << "[";
for (int i = 0; i < sz; i++)
{
cout << arr[i];
if (i != sz - 1)
cout << ", ";
}
cout << "]\n";
}
int main()
{
string str;
cin >> str;
int n = str.size();
unordered_map<char, int> mp;
int abd = 0;
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j <= n; j++)
{
string substring = str.substr(i, j - i);
mp.clear();
// cout << substring << endl;
for (char ch : substring)
mp[ch]++;
int maxi = INT_MIN, mini = INT_MAX;
for (auto x : mp)
{
maxi = max(maxi, x.second);
mini = min(mini, x.second);
}
abd += maxi - mini;
// cout << maxi << " " << mini << endl;
// cout << "******************" << endl;
}
}
cout << abd << endl;
return 0;
}
| true |
c5fbe66d193df87d13ee3354f766d25f993b125f
|
C++
|
AmgCoder/DSA-CP
|
/Array/Nuts and Bolts Problem/solution.cpp
|
UTF-8
| 2,148 | 4.28125 | 4 |
[
"MIT"
] |
permissive
|
// C++ program to solve nut and bolt
// problem using Quick Sort.
#include <iostream>
using namespace std;
// Method to print the array
void printArray(char arr[])
{
for(int i = 0; i < 6; i++)
{
cout << " " << arr[i];
}
cout << "\n";
}
// Similar to standard partition method.
// Here we pass the pivot element too
// instead of choosing it inside the method.
int partition(char arr[], int low,
int high, char pivot)
{
int i = low;
char temp1, temp2;
for(int j = low; j < high; j++)
{
if (arr[j] < pivot)
{
temp1 = arr[i];
arr[i] = arr[j];
arr[j] = temp1;
i++;
}
else if(arr[j] == pivot)
{
temp1 = arr[j];
arr[j] = arr[high];
arr[high] = temp1;
j--;
}
}
temp2 = arr[i];
arr[i] = arr[high];
arr[high] = temp2;
// Return the partition index of
// an array based on the pivot
// element of other array.
return i;
}
// Function which works just like quick sort
void matchPairs(char nuts[], char bolts[],
int low, int high)
{
if (low < high)
{
// Choose last character of bolts
// array for nuts partition.
int pivot = partition(nuts, low,
high, bolts[high]);
// Now using the partition of nuts
// choose that for bolts partition.
partition(bolts, low, high, nuts[pivot]);
// Recur for [low...pivot-1] &
// [pivot+1...high] for nuts and
// bolts array.
matchPairs(nuts, bolts, low, pivot - 1);
matchPairs(nuts, bolts, pivot + 1, high);
}
}
// Driver code
int main()
{
// Nuts and bolts are represented
// as array of characters
char nuts[] = {'@', '#', '$', '%', '^', '&'};
char bolts[] = {'$', '%', '&', '^', '@', '#'};
// Method based on quick sort which
// matches nuts and bolts
matchPairs(nuts, bolts, 0, 5);
cout <<"Matched nuts and bolts are : \n";
printArray(nuts);
printArray(bolts);
}
| true |
7f31ecbac666bcfcf80aca2bf3301d8e7b6289eb
|
C++
|
Mahmoudnaoum/Banker
|
/banker.cpp
|
UTF-8
| 7,252 | 2.9375 | 3 |
[] |
no_license
|
#include <iostream>
#include <vector>
#include <algorithm>
#include <conio.h>
using namespace std;
void safety_state_fun(vector< vector<int> >allocation, vector< vector<int> >max, vector<int> available);
void request_state_fun(vector< vector<int> >allocation, vector< vector<int> >max, vector<int> available);
int main()
{
cout << "Enter The Allocation matrix" << endl;
vector< vector<int> > allocation
{
{0, 0, 0, 0},
{0, 0, 0, 0},
{0, 0, 0, 0},
{0, 0, 0, 0},
{0, 0, 0, 0}
};
int input;
for (size_t i = 0; i < 5; i++)
{
for (size_t j = 0; j < 4; j++)
{
cin >> input;
allocation[i][j] = input;
}
}
cout << "Enter The Max matrix" << endl;
vector< vector<int> > max
{
{0, 0, 0, 0},
{0, 0, 0, 0},
{0, 0, 0, 0},
{0, 0, 0, 0},
{0, 0, 0, 0}
};
for (size_t i = 0; i < 5; i++)
{
for (size_t j = 0; j < 4; j++)
{
cin >> input;
max[i][j] = input;
}
}
cout << "Enter The Available matrix" << endl;
vector<int> available{ 0, 0, 0, 0 };
for (size_t i = 0; i < 4; i++)
{
cin >> input;
available[i] = input;
}
char state;
cout << "Please enter S for safe state or R for the request state" << endl;
cin >> state;
if (state == 'S')
{
safety_state_fun(allocation, max, available);
}
else if (state == 'R')
{
request_state_fun(allocation, max, available);
}
return 0;
}
void safety_state_fun(vector< vector<int> >allocation, vector< vector<int> >max, vector<int> available)
{
vector< vector<int> > need
{
{0, 0, 0, 0},
{0, 0, 0, 0},
{0, 0, 0, 0},
{0, 0, 0, 0},
{0, 0, 0, 0}
};
for (int i = 0; i < allocation.size(); i++)
{
for (int j = 0; j < allocation[i].size(); j++)
{
need[i][j] = max[i][j] - allocation[i][j];
}
}
// Print NEED MATRIX
cout << "Need Matrix" << endl;
for (int i = 0; i < allocation.size(); i++)
{
for (int j = 0; j < allocation[i].size(); j++)
{
cout << need[i][j] << " ";
}
cout << endl;
}
// -----------------
vector<int> sequence;
int i_ = 0;
vector<int>::iterator it;
bool lte;
int process_no = allocation.size();
int data_no = allocation[0].size();
for (int i = 0; i < 5; i++)
{
while (sequence.size() < process_no)
{
lte = true;
it = find(sequence.begin(), sequence.end(), i_);
for (int i = 0; i < available.size(); i++)
{
if (need[i_][i] > available[i])
{
lte = false;
break;
}
}
if (lte && it == sequence.end())
{
sequence.push_back(i_);
for (int i = 0; i < data_no; i++)
{
available[i] = available[i] + allocation[i_][i];
}
}
i_ = (i_ + 1) % process_no;
}
}
// Print Safe State
if (sequence.size() < process_no)
{
cout << "No";
}
else
{
cout << "Yes , Safe state <";
for (int i = 0; i < sequence.size(); i++)
{
if (i != sequence.size() - 1)
{
cout << "P" << sequence[i] << ", ";
}
else
{
cout << "P" << sequence[i] << ">";
}
}
}
_getch();
}
void request_state_fun(vector< vector<int> >allocation, vector< vector<int> >max, vector<int> available)
{
vector< vector<int> > need
{
{0, 0, 0, 0},
{0, 0, 0, 0},
{0, 0, 0, 0},
{0, 0, 0, 0},
{0, 0, 0, 0}
};
for (int i = 0; i < allocation.size(); i++)
{
for (int j = 0; j < allocation[i].size(); j++)
{
need[i][j] = max[i][j] - allocation[i][j];
}
}
// Print NEED MATRIX
cout << "Need Matrix" << endl;
for (int i = 0; i < allocation.size(); i++)
{
for (int j = 0; j < allocation[i].size(); j++)
{
cout << need[i][j] << " ";
}
cout << endl;
}
// -----------------
int immediate_no;
bool im_granted = true;
cout << "Enter the process no" << endl;
cin >> immediate_no;
cout << "Enter the instances" << endl;
int inputtt;
vector<int> request{ 0 , 0 , 0 , 0 };
for (size_t i = 0; i < 4; i++)
{
cin >> inputtt;
request[i] = inputtt;
}
for (int i = 0; i < request.size(); i++)
{
if (need[immediate_no][i] < request[i])
{
cout << "NO it cant be granted";
im_granted = false;
break;
}
if (request[i] > available[i])
{
cout << "Wait";
im_granted = false;
break;
}
}
if (im_granted)
{
for (int i = 0; i < request.size(); i++)
{
available[i] = available[i] - request[i];
need[immediate_no][i] = need[immediate_no][i] - request[i];
allocation[immediate_no][i] = allocation[immediate_no][i] + request[i];
}
}
vector<int> sequence;
int i_ = 0;
vector<int>::iterator it;
bool lte;
int process_no = allocation.size();
int data_no = allocation[0].size();
for (int i = 0; i < 5; i++)
{
while (sequence.size() < process_no)
{
lte = true;
it = find(sequence.begin(), sequence.end(), i_);
for (int i = 0; i < available.size(); i++)
{
if (need[i_][i] > available[i])
{
lte = false;
break;
}
}
if (lte && it == sequence.end())
{
sequence.push_back(i_);
for (int i = 0; i < data_no; i++)
{
available[i] = available[i] + allocation[i_][i];
}
}
i_ = (i_ + 1) % process_no;
}
}
// Print Safe State
if (sequence.size() < process_no)
{
cout << "No request can't be granted with safe state";
}
else
{
cout << "Yes request can be granted with safe state, Safe state <";
for (int i = 0; i < sequence.size(); i++)
{
if (sequence[i] != immediate_no)
{
if (i != sequence.size() - 1)
{
cout << "P" << sequence[i] << ", ";
}
else
{
cout << "P" << sequence[i] << ">";
}
}
else
{
if (i != sequence.size() - 1)
{
cout << "P" << sequence[i] << "req" << ", ";
}
else
{
cout << "P" << sequence[i] << "req" << ">";
}
}
}
}
_getch() ;
}
| true |
85c55ad0c2d23abf23dd50b1f1e2f77ce58773e4
|
C++
|
a1mond/password-manager
|
/User/User.cpp
|
UTF-8
| 915 | 3.296875 | 3 |
[] |
no_license
|
#include <vector>
#include <string>
#include <iostream>
#include "User.h"
using namespace std;
User::User(const string& l, const string& p) {
login = l;
pass = p;
}
void User::printPasswords() {
if (!getPasswords().empty()) {
for (const auto &elem : passwords) {
cout << " " << elem.first << ": " << elem.second << endl;
}
} else {
cout << "No records were found" << endl;
}
}
void User::addPassword(const string &app, const string& p) {
passwords.try_emplace(app, p);
}
bool User::checkPass(const string& p) {
return !pass.compare(p);
}
const string& User::getLogin() const {
return login;
}
const string& User::getPass() const {
return pass;
}
const map<string, string>& User::getPasswords() const {
return passwords;
}
| true |
3f79c4dcec258086537a4180aee83e96825d25a8
|
C++
|
TangGSen/OpenglStudyV1
|
/openglstudyv2/src/main/cpp/SkyBox.cpp
|
UTF-8
| 4,888 | 2.859375 | 3 |
[] |
no_license
|
//
// Created by Administrator on 2017/10/15.
//
#include "SkyBox.h"
void SkyBox::init(const char *imageDir){
vertexBuffer =new VertexBuffer[6];
sShader = new SShader[6];
initFront(imageDir);
initBack( imageDir);
initLeft(imageDir);
initRight(imageDir);
initTop(imageDir);
initBottom(imageDir);
};
void SkyBox::initFront(const char*imageDir){
sShader[0].init("Res/skybox.vs","Res/skybox.fs");
char temp[256] ;
memset(temp,0,256);
strcpy(temp,imageDir);
strcat(temp,"front.bmp");
sShader[0].setTexture("U_Texture",temp);
vertexBuffer[0].setSize(4);
vertexBuffer[0].setPosition(0,-0.5f,-0.5f,-0.5f);
vertexBuffer[0].setPosition(1,0.5f,-0.5f,-0.5f);
vertexBuffer[0].setPosition(2,-0.5f,0.5f,-0.5f);
vertexBuffer[0].setPosition(3,0.5f,0.5f,-0.5f);
vertexBuffer[0].setTexcoord(0,0.0,0.0);
vertexBuffer[0].setTexcoord(1,1.0f,0.0);
vertexBuffer[0].setTexcoord(2,0.0,1.0f);
vertexBuffer[0].setTexcoord(3,1.0f,1.0f);
};
void SkyBox::initBack(const char*imageDir){
sShader[1].init("Res/skybox.vs","Res/skybox.fs");
char temp[256] ;
memset(temp,0,256);
strcpy(temp,imageDir);
strcat(temp,"back.bmp");
sShader[1].setTexture("U_Texture",temp);
vertexBuffer[1].setSize(4);
vertexBuffer[1].setPosition(0,0.5f,-0.5f,0.5f);
vertexBuffer[1].setPosition(1,-0.5f,-0.5f,0.5f);
vertexBuffer[1].setPosition(2,-0.5f,0.5f,0.5f);
vertexBuffer[1].setPosition(3,0.5f,0.5f,0.5f);
vertexBuffer[1].setTexcoord(0,0.0,0.0);
vertexBuffer[1].setTexcoord(1,1.0f,0.0);
vertexBuffer[1].setTexcoord(2,0.0,1.0f);
vertexBuffer[1].setTexcoord(3,1.0f,1.0f);
};
void SkyBox::initLeft(const char*imageDir){
sShader[2].init("Res/skybox.vs","Res/skybox.fs");
char temp[256] ;
memset(temp,0,256);
strcpy(temp,imageDir);
strcat(temp,"left.bmp");
sShader[2].setTexture("U_Texture",temp);
vertexBuffer[2].setSize(4);
vertexBuffer[2].setPosition(0,-0.5f,-0.5f,0.5f);
vertexBuffer[2].setPosition(1,-0.5f,-0.5f,-0.5f);
vertexBuffer[2].setPosition(2,-0.5f,0.5f,0.5f);
vertexBuffer[2].setPosition(3,-0.5f,0.5f,-0.5f);
vertexBuffer[2].setTexcoord(0,0.0,0.0);
vertexBuffer[2].setTexcoord(1,1.0f,0.0);
vertexBuffer[2].setTexcoord(2,0.0,1.0f);
vertexBuffer[2].setTexcoord(3,1.0f,1.0f);
};
void SkyBox::initRight(const char*imageDir){
sShader[3].init("Res/skybox.vs","Res/skybox.fs");
char temp[256] ;
memset(temp,0,256);
strcpy(temp,imageDir);
strcat(temp,"right.bmp");
sShader[1].setTexture("U_Texture",temp);
vertexBuffer[3].setSize(4);
vertexBuffer[3].setPosition(0,0.5f,-0.5f,-0.5f);
vertexBuffer[3].setPosition(1,0.5f,-0.5f,0.5f);
vertexBuffer[3].setPosition(2,0.5f,0.5f,-0.5f);
vertexBuffer[3].setPosition(3,0.5f,0.5f,0.5f);
vertexBuffer[3].setTexcoord(0,0.0,0.0);
vertexBuffer[3].setTexcoord(1,1.0f,0.0);
vertexBuffer[3].setTexcoord(2,0.0,1.0f);
vertexBuffer[3].setTexcoord(3,1.0f,1.0f);
};
void SkyBox::initTop(const char*imageDir){
sShader[4].init("Res/skybox.vs","Res/skybox.fs");
char temp[256] ;
memset(temp,0,256);
strcpy(temp,imageDir);
strcat(temp,"top.bmp");
sShader[4].setTexture("U_Texture",temp);
vertexBuffer[4].setSize(4);
vertexBuffer[4].setPosition(0,-0.5f,0.5f,-0.5f);
vertexBuffer[4].setPosition(1,0.5f,0.5f,-0.5f);
vertexBuffer[4].setPosition(2,-0.5f,0.5f,0.5f);
vertexBuffer[4].setPosition(3,0.5f,0.5f,0.5f);
vertexBuffer[4].setTexcoord(0,0.0,0.0);
vertexBuffer[4].setTexcoord(1,1.0f,0.0);
vertexBuffer[4].setTexcoord(2,0.0,1.0f);
vertexBuffer[4].setTexcoord(3,1.0f,1.0f);
};
void SkyBox::initBottom(const char*imageDir){
sShader[5].init("Res/skybox.vs","Res/skybox.fs");
char temp[256] ;
memset(temp,0,256);
strcpy(temp,imageDir);
strcat(temp,"bottom.bmp");
sShader[5].setTexture("U_Texture",temp);
vertexBuffer[5].setSize(4);
vertexBuffer[5].setPosition(0,-0.5f,-0.5f,0.5f);
vertexBuffer[5].setPosition(1,0.5f,-0.5f,0.5f);
vertexBuffer[5].setPosition(2,-0.5f,-0.5f,-0.5f);
vertexBuffer[5].setPosition(3,0.5f,-0.5f,-0.5f);
vertexBuffer[5].setTexcoord(0,0.0,0.0);
vertexBuffer[5].setTexcoord(1,1.0f,0.0);
vertexBuffer[5].setTexcoord(2,0.0,1.0f);
vertexBuffer[5].setTexcoord(3,1.0f,1.0f);
};
void SkyBox::draw(glm::mat4 &ViewMatrix, glm::mat4 &ProjctionMatrix, float x, float y, float z) {
//需要禁用深度测试
glDisable(GL_DEPTH_TEST);
//这样确保,天空盒子是跟摄像机跑的
mModelMatrix = glm::translate(x,y,z);
for (int i = 0; i < 6; ++i) {
vertexBuffer[i].bind();
sShader[i].bind(glm::value_ptr(mModelMatrix),glm::value_ptr(ViewMatrix),glm::value_ptr(ProjctionMatrix));
glDrawArrays(GL_TRIANGLE_STRIP,0,4);
vertexBuffer[i].unBind();
}
}
| true |
fc3834e7cb8128474d5e87042ef68070bbbf06ba
|
C++
|
Micha70/E3DC-Control-Display
|
/framebuffer.h
|
UTF-8
| 5,905 | 2.71875 | 3 |
[] |
no_license
|
/*
Copyright (C) 2017, Richard e Collins.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
#ifndef __FRAME_BUFFER_H__
#define __FRAME_BUFFER_H__
#include <stdint.h>
#include <linux/fb.h>
namespace FBIO{ // Using a namespace to try to prevent name clashes as my class name is kind of obvious. :)
///////////////////////////////////////////////////////////////////////////////////////////////////////////
class FrameBuffer
{
public:
/*
Creates and opens a FrameBuffer object.
If the OS does not support the frame buffer driver or there is some other error,
this function will return NULL.
Set pVerbose to true to get debugging information as the object is created.
*/
static FrameBuffer* Open(bool pVerbose = false);
~FrameBuffer();
/*
Returns the width of the frame buffer.
*/
int GetWidth()const{return mWidth;}
/*
Returns the height of the frame buffer.
*/
int GetHeight()const{return mHeight;}
/*
Writes a single pixel with the passed red, green and blue values. 0 -> 255, 0 being off 255 being full on.
*/
void WritePixel(int pX,int pY,uint8_t pRed,uint8_t pGreen,uint8_t pBlue);
/*
Clears the entrie screen.
*/
void ClearScreen(uint8_t pRed,uint8_t pGreen,uint8_t pBlue);
/*
Expects source to be 24bit, three 8 bit bytes in R G B order.
IE pSourcePixels[0] is red, pSourcePixels[1] is green and pSourcePixels[2] is blue.
Renders the image to pX,pY without scaling. Most basic blit.
*/
void BlitRGB24(const uint8_t* pSourcePixels,int pX,int pY,int pSourceWidth,int pSourceHeight);
/*
Expects source to be 24bit, three 8 bit bytes in R G B order.
IE pSourcePixels[0] is red, pSourcePixels[1] is green and pSourcePixels[2] is blue.
Renders the image to pX,pY from pSourceX,pSourceY in the source without scaling.
pSourceStride is the byte size of one scan line in the source data.
Allows sub rect render of the source image.
*/
void BlitRGB24(const uint8_t* pSourcePixels,int pX,int pY,int pWidth,int pHeight,int pSourceX,int pSourceY,int pSourceStride);
/*
Draws a horizontal line.
*/
void DrawLineH(int pFromX,int pFromY,int pToX,uint8_t pRed,uint8_t pGreen,uint8_t pBlue);
/*
Draws a vertical line.
*/
void DrawLineV(int pFromX,int pFromY,int pToY,uint8_t pRed,uint8_t pGreen,uint8_t pBlue);
/*
Draws an arbitrary line.
Will take a short cut if the line is horizontal or vertical.
*/
void DrawLine(int pFromX,int pFromY,int pToX,int pToY,uint8_t pRed,uint8_t pGreen,uint8_t pBlue);
/*
Draws a circle using the Midpoint algorithm.
https://en.wikipedia.org/wiki/Midpoint_circle_algorithm
*/
void DrawCircle(int pCenterX,int pCenterY,int pRadius,uint8_t pRed,uint8_t pGreen,uint8_t pBlue,bool pFilled = false);
/*
Draws a rectangle with the passed in RGB values either filled or not.
*/
void DrawRectangle(int pFromX,int pFromY,int pToX,int pToY,uint8_t pRed,uint8_t pGreen,uint8_t pBlue,bool pFilled = false);
/*
Converts from HSV to RGB.
Very handy for creating colour palettes.
See:- (thanks David H)
https://stackoverflow.com/questions/3018313/algorithm-to-convert-rgb-to-hsv-and-hsv-to-rgb-in-range-0-255-for-both
*/
void HSV2RGB(float H,float S, float V,uint8_t &rRed,uint8_t &rGreen, uint8_t &rBlue)const;
private:
FrameBuffer(int pFile,uint8_t* pFrameBuffer,struct fb_fix_screeninfo pFixInfo,struct fb_var_screeninfo pScreenInfo,bool pVerbose);
/*
Draws an arbitrary line.
Using Bresenham's line algorithm
https://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm
*/
void DrawLineBresenham(int pFromX,int pFromY,int pToX,int pToY,uint8_t pRed,uint8_t pGreen,uint8_t pBlue);
const int mWidth,mHeight;
const int mStride;// Num bytes between each line.
const int mPixelSize; // The byte count of each pixel. So to move in the x by one pixel.
const int mFrameBufferFile;
const int mFrameBufferSize;
const bool mVerbose;
const struct fb_var_screeninfo mVaribleScreenInfo;
uint8_t* mFrameBuffer;
const int mXOffset;
const int mYOffset;
};
class Font
{
public:
Font(int pPixelSize = 1);
~Font();
int GetCharWidth()const{return 8*mPixelSize;}
int GetCharHeight()const{return 13*mPixelSize;}
// These render the passed in colour, does not change the pen colour.
void DrawChar(FrameBuffer* pDest,int pX,int pY,uint8_t pRed,uint8_t pGreen,uint8_t pBlue,int pChar)const;
void Print(FrameBuffer* pDest,int pX,int pY,uint8_t pRed,uint8_t pGreen,uint8_t pBlue,const char* pText)const;
void Printf(FrameBuffer* pDest,int pX,int pY,uint8_t pRed,uint8_t pGreen,uint8_t pBlue,const char* pFmt,...)const;
// These use current pen. Just a way to reduce the number of args you need to use for a property that does not change that much.
void Print(FrameBuffer* pDest,int pX,int pY,const char* pText)const;
void Printf(FrameBuffer* pDest,int pX,int pY,const char* pFmt,...)const;
void SetPenColour(uint8_t pRed,uint8_t pGreen,uint8_t pBlue);
void SetPixelSize(int pPixelSize);
private:
int mPixelSize;
struct
{
uint8_t r,g,b;
}mPenColour;
};
///////////////////////////////////////////////////////////////////////////////////////////////////////////
};//namespace FBIO
#endif //__FRAME_BUFFER_H__
| true |
ef09795080b067389a5a160ce1c58b487c092f6b
|
C++
|
MultivacX/leetcode2020
|
/algorithms/medium/1262. Greatest Sum Divisible by Three.h
|
UTF-8
| 2,638 | 3.453125 | 3 |
[
"MIT"
] |
permissive
|
// 1262. Greatest Sum Divisible by Three
// Runtime: 48 ms, faster than 90.75% of C++ online submissions for Greatest Sum Divisible by Three.
// Memory Usage: 11.6 MB, less than 100.00% of C++ online submissions for Greatest Sum Divisible by Three.
class Solution {
public:
int maxSumDivThree(vector<int>& nums) {
/*
if sum % 3 == 1, sum -= min(A + B, C), when A % 3 == 2, B % 3 == 2, and C % 3 == 1
if sum % 3 == 2, sum -= min(A + B, C), when A % 3 == 1, B % 3 == 1, and C % 3 == 2
*/
int sum = 0;
int left1 = 0;
int left2 = 0;
for (int i : nums) {
sum += i;
if (i % 3 == 1) {
if (left1 == 0) {
left1 = i;
} else {
left2 = left2 == 0 ? left1 + i : min(left2, left1 + i);
left1 = min(left1, i);
}
} else if (i % 3 == 2) {
if (left2 == 0) {
left2 = i;
} else {
left1 = left1 == 0 ? left2 + i : min(left1, left2 + i);
left2 = min(left2, i);
}
}
}
if (sum % 3 == 1) sum -= left1;
else if (sum % 3 == 2) sum -= left2;
return sum % 3 == 0 ? sum : 0;
}
// ERROR: 36 / 40 test cases passed.
// [2,19,6,16,5,10,7,4,11,6]
/*int maxSumDivThree(vector<int>& nums) {
int sum = 0;
vector<int> _1;
vector<int> _2;
for (int i : nums) {
int x = i % 3;
if (x == 0) sum += i;
else if (x == 1) _1.push_back(i);
else _2.push_back(i);
}
sort(_1.begin(), _1.end());
sort(_2.begin(), _2.end());
int i = _1.size() - 1;
int j = _2.size() - 1;
while (i >= 0 && j >= 0) {
int _111 = i >= 2 ? (_1[i] + _1[i - 1] + _1[i - 2]) : 0;
int _222 = j >= 2 ? (_2[j] + _2[j - 1] + _2[j - 2]) : 0;
int _12 = _1[i] + _2[j];
if (_12 >= _111 + _222) {
sum += _12;
--i;
--j;
} else {
if (_111 > 0) {
sum += _111;
i -= 3;
}
if (_222 > 0) {
sum += _222;
j -= 3;
}
}
}
while (i >= 2) {
sum += _1[i] + _1[i - 1] + _1[i - 2];
i -= 3;
}
while (j >= 2) {
sum += _2[j] + _2[j - 1] + _2[j - 2];
j -= 3;
}
return sum;
}*/
};
| true |
5cd7aa8b91e0f3faae174b277ecbb2b1a71819fe
|
C++
|
VanzaA/Jueces-online
|
/Resoluciones/TheDepartmentofRedundancyDepartment.cpp
|
UTF-8
| 574 | 2.75 | 3 |
[
"MIT"
] |
permissive
|
// https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=425
#include <iostream>
#include <map>
#include <queue>
using namespace std;
int main(int argc, char *argv[]){
map<int, int> mapa;
queue<int> cola;
int n;
while (cin >> n){
if(mapa.find(n) != mapa.end()){
mapa[n]++;
}else{
mapa[n]=1;
cola.push(n);
}
}
while(cola.size()){
cout << cola.front() << " " << mapa[cola.front()] << endl;
cola.pop();
}
return 0;
}
| true |
4d52cbbe2c560047e8d9645b502b69072c4dc26c
|
C++
|
karikera/ken
|
/KR3/data/map.cpp
|
UTF-8
| 914 | 2.640625 | 3 |
[] |
no_license
|
#include "stdafx.h"
#include "map.h"
using namespace kr;
size_t std::hash<kr::_pri_::MapKeyData>::operator ()(const kr::_pri_::MapKeyData& key) const noexcept
{
return kr::mem::hash(key.m_buffer, key.m_size);
}
bool _pri_::MapKeyData::operator ==(const MapKeyData& other) const noexcept
{
if (m_size != other.m_size) return false;
return memcmp(m_buffer, other.m_buffer, m_size) == 0;
}
bool _pri_::MapKeyData::operator !=(const MapKeyData& other) const noexcept
{
if (m_size != other.m_size) return true;
return memcmp(m_buffer, other.m_buffer, m_size) != 0;
}
_pri_::MapKey::~MapKey() noexcept
{
krfree((void*)m_buffer);
}
_pri_::MapKey::MapKey(MapKey&& _move) noexcept
{
m_buffer = _move.m_buffer;
m_size = _move.m_size;
_move.m_buffer = nullptr;
}
_pri_::MapKeyStatic::operator const _pri_::MapKey& () const noexcept
{
return *static_cast<const MapKey*>(static_cast<const MapKeyData*>(this));
}
| true |
2d6dccd303ca69b8be29571d1b4994c2765bce29
|
C++
|
msk-repo01/genetic_algo
|
/src/examples/n_queen/nqueen_ga.h
|
UTF-8
| 2,993 | 3.234375 | 3 |
[
"MIT"
] |
permissive
|
/*
* nqueen_ga.h
* A simple Genetic Algorithm for N-QUEEN problem
*
* Created on: Dec 24, 2016
* Author: S.Khan
*/
#ifndef NQUEEN_GA_H_
#define NQUEEN_GA_H_
# include "ga.h"
using namespace std;
using namespace ga;
/**
* A SIMPLE GENETIC ALGORITHM FOR N-QUEEN PROBLEM (nqueen_genetic_algo)
* ====================================================================
* REPRESENTATION - A vector of integers from 0 to N_QUEEN_NUM - 1 (each integer
* occurring only once). An integer represents the row number(0-based) and the
* position of this integer in the vector represents the column number(0-based)
* of a queen.
* Note - rows and column numbers are 0-based
* Example for N = 4 : a vector {2, 0, 3, 1} would mean :
* First queen is in 2nd row , 0th column
* Second queen is in 0th row, 1st column
* Third queen is in 3rd row , 3rd column
* Fourth queen is in 1st row, 4th column
*
* vector {2, 0, 3, 1} is shown below :
*
* | | x | | |
* | | | | x |
* | x | | | |
* | | | x | |
*
*
* CONSTRUCTOR - set the value of N in N-Queen problem.
* The default value is set to 100.
*
*/
class nqueen_genetic_algo : public simple_ga<vector<int>>
{
public :
explicit nqueen_genetic_algo(int n_queen_number)
{
if(n_queen_number < 4) // show error message and set to default
{
cerr<<"error invalid value of N : "<<n_queen_number<<
" (solutions may not exist for N < 4 in N-queen problem)"<<endl<<
"keeping default value of N : "<<N_QUEEN_NUM<<endl;
}
else
{
N_QUEEN_NUM = n_queen_number;
// reset crossover point distribution
_uniform_distribution_crossover_pt =
uniform_int_distribution<int>(1, N_QUEEN_NUM - 1);
}
}
protected:
vector<int> getRandomIndiv() override;
double getFitness(const vector<int> & indiv) override;
void displayIndiv(const vector<int> & indiv) override;
vector<int> crossOver(const crossoverParents & crossover_parents) override;
void mutate(vector<int> &indiv) override;
bool shouldStop() override;
private:
/**
* value of N for N-Queen problem
*/
int N_QUEEN_NUM = 100;
// shuffle random engine
mt19937 random_engine_shuffle;
// allele mutation random engine
mt19937 random_engine_allele_mutation;
// crossover point 1 random engine
mt19937 random_engine_crossover_pt1 {1};
// generate uniformly distribution values
// for float value between 0 and 1
uniform_real_distribution<float> _uniform_float_distribution {0.0, 1.0};
// for double value between 0 and 1
uniform_real_distribution<double> _uniform_double_distribution {0.0, 1.0};
// for integer value between 1 and NQUEEN_NUM - 1
uniform_int_distribution<int> _uniform_distribution_crossover_pt {1, N_QUEEN_NUM - 1};
vector<int> getConflictingPositions(const vector<int> & indiv);
vector<int> onePointOrderCrossover(const crossoverParents & crossoverParents);
};
#endif /* NQUEEN_GA_H_ */
| true |
d5e173b51631dd23383ee87192e2550d01739a25
|
C++
|
dieram3/competitive-programming-library
|
/include/cpl/graph/hopcroft_karp_maximum_matching.hpp
|
UTF-8
| 3,241 | 2.84375 | 3 |
[
"BSL-1.0"
] |
permissive
|
// Copyright Diego Ramirez 2015
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef CPL_GRAPH_HOPCROFT_KARP_MAXIMUM_MATCHING_HPP
#define CPL_GRAPH_HOPCROFT_KARP_MAXIMUM_MATCHING_HPP
#include <cstddef> // size_t
#include <cstdint> // SIZE_MAX
#include <functional> // function
#include <queue> // queue
#include <vector> // vector
namespace cpl {
/// \brief Finds the maximum cardinality matching in an undirected bipartite
/// graph.
///
/// \param g The target graph.
///
/// Finds the maximum cardinality matching in the given graph. It is the maximum
/// number of edges in an edge subset, such that no two edges share a common
/// endpoint.
///
/// \returns The maximum cardinality matching.
///
/// \pre The graph \p g must be bipartite.
///
/// \par Complexity
/// <tt>O(E * sqrt(V))</tt>.
///
template <typename Graph>
std::size_t hopcroft_karp_maximum_matching(const Graph& g) {
// Note: pair_of can be used to query the selected pairs.
const size_t num_vertices = g.num_vertices();
const size_t nil = num_vertices; // The null vertex
std::vector<size_t> pair_of(num_vertices, nil);
std::vector<size_t> dist(num_vertices + 1);
std::vector<size_t> set_a, set_b;
auto separate_vertices = [&] {
std::vector<signed char> color(num_vertices);
std::function<void(size_t)> dfs_visit;
dfs_visit = [&](const size_t u) {
color[u] == 1 ? set_a.push_back(u) : set_b.push_back(u);
for (const auto e : g.out_edges(u)) {
const size_t v = (u == g.source(e)) ? g.target(e) : g.source(e);
if (color[v])
continue;
color[v] = -color[u];
dfs_visit(v);
}
};
for (size_t v = 0; v < num_vertices; ++v) {
if (color[v] != 0)
continue;
color[v] = 1;
dfs_visit(v);
}
};
auto bfs = [&] {
std::queue<size_t> q;
for (const size_t a : set_a) {
if (pair_of[a] == nil) {
dist[a] = 0;
q.push(a);
} else
dist[a] = SIZE_MAX;
}
dist[nil] = SIZE_MAX;
while (!q.empty()) {
const size_t a = q.front();
q.pop();
if (dist[a] >= dist[nil])
continue;
for (const auto e : g.out_edges(a)) {
const size_t b = (a == g.source(e)) ? g.target(e) : g.source(e);
if (dist[pair_of[b]] != SIZE_MAX)
continue;
dist[pair_of[b]] = dist[a] + 1;
q.push(pair_of[b]);
}
}
return dist[nil] != SIZE_MAX;
};
std::function<bool(size_t)> dfs = [&](const size_t a) {
if (a == nil)
return true;
for (const auto e : g.out_edges(a)) {
const auto b = (a == g.source(e)) ? g.target(e) : g.source(e);
if (dist[pair_of[b]] != dist[a] + 1)
continue;
if (!dfs(pair_of[b]))
continue;
pair_of[b] = a;
pair_of[a] = b;
return true;
}
dist[a] = SIZE_MAX;
return false;
};
separate_vertices();
size_t num_matching = 0;
while (bfs()) {
for (const size_t a : set_a)
if (pair_of[a] == nil && dfs(a))
++num_matching;
}
return num_matching;
}
} // end namespace cpl
#endif // Header guard
| true |
e887f3f453c2227cfdc80710b99764520cd30e8f
|
C++
|
asonnino/hello-enclave
|
/App/App.cpp
|
UTF-8
| 2,091 | 2.84375 | 3 |
[
"Unlicense"
] |
permissive
|
#include <stdio.h>
#include <iostream>
#include "Enclave_u.h"
#include "sgx_urts.h"
#include "sgx_utils/sgx_utils.h"
/* Global EID shared by multiple threads */
sgx_enclave_id_t global_eid = 0;
// OCall implementations
void ocall_print(const char* str) {
printf("%s\n", str);
}
int main(int argc, char const *argv[]) {
if (initialize_enclave(&global_eid, "enclave.token", "enclave.signed.so") < 0) {
std::cout << "Fail to initialize enclave." << std::endl;
return 1;
}
int ptr;
sgx_status_t status = generate_random_number(global_eid, &ptr);
std::cout << status << std::endl;
if (status != SGX_SUCCESS) {
std::cout << "noob" << std::endl;
}
printf("Random number: %d\n", ptr);
// Perform a simple addition in the enclave
int a = ptr;
int b = 100;
status = ecall_add(global_eid, &ptr, a, b);
if (status != SGX_SUCCESS) {
std::cout << "Enclave addition failed :(" << std::endl;
return 1;
}
std::cout << "Enclave addition success! " << a << " + " << b << " = " << ptr << std::endl;
// Seal the random number
size_t sealed_size = sizeof(sgx_sealed_data_t) + sizeof(ptr);
uint8_t* sealed_data = (uint8_t*)malloc(sealed_size);
sgx_status_t ecall_status;
status = seal(global_eid, &ecall_status,
(uint8_t*)&ptr, sizeof(ptr),
(sgx_sealed_data_t*)sealed_data, sealed_size);
if (!is_ecall_successful(status, "Sealing failed :(", ecall_status)) {
return 1;
}
int unsealed;
status = unseal(global_eid, &ecall_status,
(sgx_sealed_data_t*)sealed_data, sealed_size,
(uint8_t*)&unsealed, sizeof(unsealed));
if (!is_ecall_successful(status, "Unsealing failed :(", ecall_status)) {
return 1;
}
std::cout << "Seal round trip success! Receive back " << unsealed << std::endl;
// Destroy enclave
status = sgx_destroy_enclave(global_eid);
if(status != SGX_SUCCESS) {
std::cout << "Fail to destroy enclave.\n" << std::endl;
return 1;
}
return 0;
}
| true |
103bf1baebd1745f5d0c47447b156ac0d2848abd
|
C++
|
Saki-Zhang/LeetCode
|
/isValidSudoku.cpp
|
UTF-8
| 991 | 3.046875 | 3 |
[] |
no_license
|
// 36. Valid Sudoku
// https://leetcode.com/problems/valid-sudoku/
class Solution {
public:
bool isValidSudoku(vector<vector<char>>& board) {
unordered_set<char> rows[9];
unordered_set<char> cols[9];
unordered_set<char> boxes[9];
for(int i = 0;i < 9;i ++) {
for(int j = 0;j < 9;j ++) {
if(board[i][j] == '.') {
continue;
}
int r = i;
int c = j;
int b = r / 3 * 3 + c / 3;
if(rows[r].find(board[i][j]) != rows[r].end() || cols[c].find(board[i][j]) != cols[c].end() || boxes[b].find(board[i][j]) != boxes[b].end()) {
return false;
}
rows[r].insert(board[i][j]);
cols[c].insert(board[i][j]);
boxes[b].insert(board[i][j]);
}
}
return true;
}
};
| true |
2be427a4a2a8ce13ae454d04481d7a29dbea4caa
|
C++
|
Mistah-Skipp/Prog-2
|
/Prob 2 &4/checkingActImp.cpp
|
UTF-8
| 1,314 | 2.78125 | 3 |
[] |
no_license
|
//checkingActImp
#include <iostream>
#include "checkingAct.h"
#include "bankAccount.h"
//Service Charge
void checking::setServiceCharge(double charge) {
srvChrg = charge;
}
double checking::getServiceCharge() const {
return srvChrg;
}
//Minimum Balance
void checking::setMinBalance(double minBal) {
minimum = minBal;
}
double checking::getMinBalance() const {
return minimum;
}
//Deposit Withdraw
void checking::withdraw(double balChange) { //withdraw also used for writing check
bankAccount::setBalance(bankAccount::getBalance() - balChange);
if (bankAccount::getBalance() < checking::getMinBalance()) {
//checks if enough $$ in account, if not its charged with service fee
std::cout << "Acct Overdrawn...Charging balance\n";
bankAccount::setBalance(bankAccount::getBalance() - checking::getServiceCharge());
}
}
void checking::deposit(double balChange){
bankAccount::setBalance(bankAccount::getBalance() + balChange);
}
void checking::postInterest() {
bankAccount::setBalance((bankAccount::getIntRate() * bankAccount::getBalance()) + bankAccount::getBalance());
}
checking::checking(double charge, double rate, double minBal, double intBal, double balChange) {
srvChrg = charge;
bankAccount::setIntRate(rate);
minimum = minBal;
bankAccount::setBalance(intBal);
change = balChange;
}
| true |
da1887ecabc8a0077c037d5df9fbfa44685b71ff
|
C++
|
andrewduong77/cse1325
|
/Lecture Code/Lecture 4 code/class_example.cpp
|
UTF-8
| 1,705 | 4.09375 | 4 |
[] |
no_license
|
#include <iostream>
using namespace std;
class Date {
public:
Date(int y, int m, int d)
{
year = y;
month = m;
day = d;
}
void add_day(int num)
{
day += num;
}
void add_day();
int get_year();
int get_month();
int get_day();
void set_month(int m);
string to_string();
// Date operator+(Date date_two);
private:
int year, month, day;
};
int Date::get_year() {
return year;
}
int Date::get_month() {
return month;
}
int Date::get_day() {
return day;
}
void Date::set_month(int m)
{
if (m > 0 && m < 13)
month = m;
else
cout << "Not a valid month" << endl;
}
void Date::add_day()
{
day++;
}
string Date::to_string()
{
return std::to_string(year) + " " + std::to_string(month) + " " + std::to_string(day); // Using std:: because we are in Date's scope. It is trying to access the Date's to_string method, which doesn't work. So you have to go to std's scope
}
//Date Date::operator+ (const Date& date_two)
//{
// year += date_two.get_year();
// month += date_two.get_month();
// day += date_two.get_day();
//}
int main () {
Date date { 2018, 1, 29 };
//date.year = 1111; Not working due to private Variable
//cout << date.year;
cout << date.get_year() << endl;
date.set_month(26);
cout << date.get_month() << endl;
date.add_day(2);
cout << date.get_day() << endl;
date.add_day();
cout << date.get_day() << endl;
cout << date.to_string() << endl;
//Date date_two { 0, 0, 1};
//date = date + date_two;
//cout << date.to_string() << endl;
return 0;
}
| true |
7f892cbe79dcb54857aad44031ac9bff8165ae5a
|
C++
|
NeymarL/SeedCup2016
|
/loop.cpp
|
UTF-8
| 4,095 | 3.15625 | 3 |
[] |
no_license
|
/**
* 处理循环结构代码
*/
#include "headers.h"
/**
* 处理循环结构
*/
void do_loop()
{
string expression = "";
string expression1 = "";
string expression2 = "";
string expression3 = "";
Code* blockbegin = IP;
Code* blockend = match_bracket();
if (IP->code.find("for") == 0) {
//处理for循环头部
int numofline = 1;
for (; numofline<4; IP++, numofline++) {
expression = cutexpr(numofline);
if (numofline == 1) {
expression1 = expression;
}
else if (numofline == 2) {
expression2 = expression;
}
else if (numofline == 3) {
expression3 = expression;
}
}
if (expression2 == "") {
expression2 = "1";
}
}
else if (IP->code.find("while") == 0) {
//处理while循环头部
expression2 = cutexpr(1);
IP++;
}
else if (IP->code.find("do") == 0) {
IP++;
Code *tmpIP = IP;
GVS.push_table(); // 新建变量表
do_block();
if (IP->code.find("break") != -1) {
IP = blockend;
return;
}
IP++;
expression2 = cutexpr(1);
IP = tmpIP;
}
Code* tmpIP = IP;
if (expression1 != "") {
handle_expression(expression1);
}
IP = blockend + 1;
for (; output(blockbegin), if_continue(expression2);) {
IP = tmpIP;
GVS.push_table();
do_block();
if (IP->code.find("break") != -1) {
IP = blockend;
return;
}
if (expression3 != "") {
handle_expression(expression3);
}
}
}
/**
* 剪切循环判断中的表达式
* @param numofline [description]
* @return [description]
*/
string cutexpr(int numofline)
{
bool in_para = false;
int i = 0;
string expression;
for (; IP->code[i] != ')' && IP->code[i] != ';'; i++) {
//截取表达式
if (numofline==1) {
if (IP->code[i] == '(' && in_para == false) {
in_para = true;
}
else if (in_para) {
expression += IP->code[i];
}
}
else if (numofline > 1) {
expression += IP->code[i];
}
}
trim(expression);
if(expression.find("printf") == 0) {
expression = expression + ")";
}
return expression;
}
/**
* 判断是不是比较表达式
* @param exrpression [description]
* @return [description]
*/
bool is_compare_exp(string exrpression)
{
if (exrpression.find(">") == -1 &&
exrpression.find("<") == -1 &&
exrpression.find("==") == -1 &&
exrpression.find("!=") == -1) {
return false;
}
else {
return true;
}
}
/**
* 判断循环是否要继续
* @param expression [description]
* @return [description]
*/
int if_continue(string expression)
{
vector<string> list;
string former_exp = "";
string value_exp = "";
int i = 0;
int res = 0;
int is_printf = 0;
if (expression.find("printf") == 0) {
is_printf = 1;
}
if (is_printf == 0) {
list = split(expression, ",");
}
if (list.size() > 1) {
for (; i < list.size() - 2; i++) {
former_exp += list[i];
former_exp+=",";
}
former_exp += list[i];
value_exp = list[list.size() - 1];
handle_expression(former_exp);
}
else{
value_exp = expression;
}
if (is_printf == 0 && is_compare_exp(value_exp)) {
res = handle_compare(value_exp);
}
else {
if (is_printf == 1) {
res = do_printf(value_exp);
}
else {
res = handle_expression(value_exp);
}
}
return res;
}
/**
* 输出循环头
* @param blockbegin [description]
*/
void output(Code* blockbegin)
{
Code* tmpIP = NULL;
tmpIP = IP;
IP = blockbegin;
do_output();
IP = tmpIP;
}
| true |
b4cad28d4931a69f77820f030a53cc70004dad21
|
C++
|
DanielKrawisz/data
|
/include/data/net/websocket.hpp
|
UTF-8
| 3,459 | 2.5625 | 3 |
[] |
no_license
|
// Copyright (c) 2022-2023 Daniel Krawisz
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef DATA_NET_WEBSOCKET
#define DATA_NET_WEBSOCKET
#include <data/net/URL.hpp>
#include <data/net/HTTP.hpp>
#include <data/net/asio/session.hpp>
namespace data::net::websocket {
// open a websocket connection.
void open (
asio::io_context &,
const URL &,
HTTP::SSL *,
asio::error_handler error_handler,
close_handler,
interaction<string_view, const string &>);
void open_secure (
asio::io_context &,
const URL &,
HTTP::SSL &,
asio::error_handler error_handler,
close_handler,
interaction<string_view, const string &>);
void open_insecure (
asio::io_context &,
const URL &,
asio::error_handler error_handler,
close_handler,
interaction<string_view, const string &>);
}
#include <boost/beast/websocket.hpp>
#include <iostream>
#include <memory>
#include <string>
#include <thread>
namespace data::net::websocket {
namespace beast = boost::beast;
namespace websocket = beast::websocket;
namespace net = boost::asio;
using tcp = net::ip::tcp;
class WebSocketSession : public std::enable_shared_from_this<WebSocketSession> {
public:
explicit WebSocketSession (tcp::socket socket) : ws_ (std::move (socket)) {}
void run() {
ws_.async_accept (beast::bind_front_handler(&WebSocketSession::on_accept, shared_from_this()));
}
private:
void on_accept (beast::error_code ec) {
if (ec) {
std::cerr << "Accept error: " << ec.message () << std::endl;
return;
}
read ();
}
void read () {
ws_.async_read (buffer_, beast::bind_front_handler (&WebSocketSession::on_read, shared_from_this ()));
}
void on_read (beast::error_code ec, std::size_t bytes_transferred) {
if (ec) {
std::cerr << "Read error: " << ec.message () << std::endl;
return;
}
ws_.text (ws_.got_text ());
ws_.async_write (buffer_.data (), beast::bind_front_handler (&WebSocketSession::on_write, shared_from_this ()));
buffer_.consume (bytes_transferred);
}
void on_write (beast::error_code ec, std::size_t) {
if (ec) {
std::cerr << "Write error: " << ec.message() << std::endl;
return;
}
read ();
}
websocket::stream<tcp::socket> ws_;
beast::flat_buffer buffer_;
};
/*
void accept_connection (tcp::acceptor &acceptor) {
acceptor.async_accept([&] (beast::error_code ec, tcp::socket socket) {
if (!ec) std::make_shared<WebSocketSession> (std::move (socket))->run ();
accept_connection (acceptor);
});
}
int main () {
const auto address = net::ip::make_address("127.0.0.1");
const auto port = static_cast<unsigned short>(8080);
net::io_context ioc;
tcp::acceptor acceptor {ioc, {address, port}};
std::cout << "WebSocket server listening on " << address << ":" << port << std::endl;
accept_connection (acceptor);
ioc.run ();
return 0;
}*/
}
#endif
| true |
d57610380a4d1f06006222004dba089e6638fc0f
|
C++
|
bielprze/JiMP2
|
/Roz 15/15_16.cpp
|
UTF-8
| 570 | 3.484375 | 3 |
[] |
no_license
|
//: C15:VirtualsInDestructors.cpp
// Virtual calls inside destructors
#include <iostream>
using namespace std;
class Base {
public:
virtual ~Base() {
cout << "Base1()\n";
f();
}
virtual void f() { cout << "Base::f()\n"; }
};
class Derived : public Base {
public:
~Derived() { cout << "~Derived()\n"; }
void f() { cout << "Derived::f()\n"; }
};
class C : public Derived {
public:
void f() { cout<< "klasa C"<<endl;}
~C(){cout << "~C()\n"; }
};
int main() {
Derived *d = new C;
delete d;
} ///:~
| true |
263db73cb08812d2cd76a26422f9088dde70f6f3
|
C++
|
peter9378/acmicpc_stepbystep
|
/using_string/2675.cpp
|
UHC
| 458 | 3.140625 | 3 |
[] |
no_license
|
/**
* baekjoon_stepbystep
* No. 2675 ڿ ݺ
* @author peter9378
* @date 2018.02.12
*/
#include <iostream>
#include <cstring>
#include <string>
using namespace std;
int main()
{
int test_case;
cin >> test_case;
for (int T = 0; T < test_case; T++)
{
int R;
string S, result = "";
cin >> R >> S;
for (int i = 0; i < S.length(); i++)
{
for (int j = 0; j < R; j++)
result += S[i];
}
cout << result << endl;
}
return 0;
}
| true |
9aa0f76b9a4ddc78a83362a306f453442d2ae2f4
|
C++
|
efficient/cicada-exp-sigmod2017-ermia
|
/dbcore/sm-log-offset.h
|
UTF-8
| 3,633 | 3.046875 | 3 |
[
"MIT"
] |
permissive
|
// -*- mode:c++ -*-
#ifndef __SM_LOG_OFFSET_H
#define __SM_LOG_OFFSET_H
#include "sm-log-file.h"
/* The LSN generator of the log.
When allocating a log block, a thread must acquire an LSN offset
and then map it to a corresponding location on disk as a separate
step. The benefit is that the monotonic part of LSN generation (the
expensive part) simplifies to a single atomic add, thus easing a
notorious global contention point (the move to O(1) log record per
transaction also helps a lot there). The downside is the
introduction of race conditions when mapping those offsets to
segments, in particular at segment boundaries. Whenever a thread
acquires an LSN offset that is partly or fully past-end of the last
segment, it must install a new segment, in a race with all other
threads that find themselves in the same situation.
*/
struct sm_log_offset_mgr : sm_log_file_mgr {
struct segment_assignment {
// segment of this log block
segment_id *sid;
// LSN of the next log block
LSN next_lsn;
// allocation big enough for the requested log block?
bool full_size;
};
using sm_log_file_mgr::sm_log_file_mgr;
/* Convert an LSN into the fat_ptr that can be used to access the
log record at that LSN. Normally the LSN should point to the
payload section of a record. If [is_ext] is true, the returned
pointer has ASI_EXT rather than ASI_LOG.
*/
fat_ptr lsn2ptr(LSN lsn, bool is_ext);
/* Convert a fat_ptr into the LSN it corresponds to.
Throw illegal_argument if the pointer does not correspond to
any LSN.
*/
LSN ptr2lsn(fat_ptr ptr);
/* Retrieve the segment descriptor that corresponds to
[mod_segnum]. The latter is a segment number modulo
NUM_LOG_SEGMENTS, as if returned by LSN::segment.
The caller is responsible to ensure that the segment exists and
is the correct one. The latter should not be too difficult to
achieve, given that the log never contains more than
NUM_LOG_SEGMENTS segments.
*/
segment_id *get_segment(uint32_t mod_segnum);
/* Retrieve the segment descriptor that corresponds to the given
[lsn_offset]. If the offset is not part of any segment, return
NULL instead. This function should only be called for offsets
that have already been assigned a segment.
*/
segment_id *get_offset_segment(uint64_t lsn_offset);
/* Assign a segment to the given range of LSN offsets, hopefully
yielding a full LSN.
There are three possible outcomes:
1. LSN assignment is successful (the common case). Return
{sid,next_lsn,true}, where [sid] is the segment the LSN
belongs to and [next_lsn] is the LSN that follows (possibly
in a different segment).
2. LSN assignment succeeded, but the requested block runs past
the end of the segment. Return {sid,next_lsn,false}, where
[sid] is the segment the LSN belongs to, and [next_lsn] is
the first LSN of the next segment. The caller must "close"
the segment with a skip record, and can then retry.
3. The given LSN offset does not correspond to any physical
location in the log. Return {NULL,INVALID_LSN,false}. The
caller should discard this LSN offset and request a new one.
*/
segment_assignment assign_segment(uint64_t lsn_begin, uint64_t lsn_end);
/* Install a new segment.
*/
segment_id *_install_segment(segment_id *sid, uint64_t lsn_offset);
};
#endif
| true |
f56e94ed33ea6d10e097a10244fa48a3ff8219c1
|
C++
|
DanB91/GBEmuOld
|
/src/Emulator/opcodes_inline.h
|
UTF-8
| 5,862 | 3.09375 | 3 |
[] |
no_license
|
#ifndef OPCODES_INLINE_H
#define OPCODES_INLINE_H
#include "CPU.h"
using namespace GBEmu;
inline void CPU::setFlag(Flag flag){
F |= static_cast<byte>(flag);
}
inline void CPU::clearFlag(Flag flag){
F &= ~static_cast<byte>(flag);
}
inline bool CPU::isFlagSet(Flag flag){
return (F & static_cast<byte>(flag)) != 0;
}
//loads 16 bit immediate
inline void CPU::load16BitImmediate(byte &destHigh, byte &destLow){
destHigh = mmu->readByte(PC + 2);
destLow = mmu->readByte(PC + 1);
}
//increment 16 bit value
inline void CPU::increment16Bit(byte &high, byte &low){
word w = wordFromBytes(high, low);
w++;
high = highByte(w);
low = lowByte(w);
}
//decrement 16 bit values
inline void CPU::decrement16Bit(byte &high, byte &low){
word w = wordFromBytes(high, low);
w--;
high = highByte(w);
low = lowByte(w);
}
//incrememnt 8 bit values
inline void CPU::increment8Bit(byte &value){
value++;
if(value == 0)
setFlag(Flag::Z);
else
clearFlag(Flag::Z);
clearFlag(Flag::N);
if((value & 0xF) == 0)
setFlag(Flag::H);
}
//decrement 8 bit value
inline void CPU::decrement8Bit(byte &value){
value--;
if(value == 0)
setFlag(Flag::Z);
else
clearFlag(Flag::Z);
setFlag(Flag::N);
if((value & 0xF) == 0xF)
setFlag(Flag::H);
}
inline void CPU::rotateLeft(byte &value){
if(value & 0x80)
setFlag(Flag::C);
else
clearFlag(Flag::C);
value = (value << 1) | ((value >> 7) & 1);
clearFlag(Flag::N);
clearFlag(Flag::H);
clearFlag(Flag::Z);
}
inline void CPU::rotateRight(byte &value)
{
if(value & 1){
setFlag(Flag::C);
} else{
clearFlag(Flag::C);
}
value = (value >> 1) | ((value << 7) & 0x80);
clearFlag(Flag::N);
clearFlag(Flag::H);
clearFlag(Flag::Z);
}
inline void CPU::rotateLeftThroughCarry(byte &value)
{
byte temp = (value << 1) | ((F & static_cast<byte>(Flag::C)) ? 1 : 0);
if(value & 0x80)
setFlag(Flag::C);
else
clearFlag(Flag::C);
value = temp;
clearFlag(Flag::N);
clearFlag(Flag::H);
clearFlag(Flag::Z);
}
inline void CPU::rotateRightThroughCarry(byte &value)
{
byte temp = ((F & static_cast<byte>(Flag::C)) ? 0x80 : 0) | (value >> 1) ;
if(value & 0x1)
setFlag(Flag::C);
else
clearFlag(Flag::C);
value = temp;
clearFlag(Flag::N);
clearFlag(Flag::H);
clearFlag(Flag::Z);
}
inline void CPU::addToHL(word addend){
int result = getHL() + addend;
clearFlag(Flag::N);
//carry from 15th bit
if(result & 0x10000){
setFlag(Flag::C);
}
//carry from 11th bit
if((getHL() ^ addend ^ (result & 0xFFFF)) & 0x1000){
setFlag(Flag::H);
}
H = highByte(result);
L = lowByte(result);
}
inline void CPU::jumpIfClear8Bit(Flag flag, byte value){
if(!isFlagSet(flag)){
PC += static_cast<int8_t>(value);
performedAction = true;
} else{
performedAction = false;
}
}
inline void CPU::decimalAdjust(byte &value)
{
unsigned result = static_cast<unsigned>(value);
if(!isFlagSet(Flag::N)){ //if addition was used
if(isFlagSet(Flag::H) || (result & 0xF) > 9){ //adjust low nibble
result += 0x6;
}
if(isFlagSet((Flag::C)) || (result & 0xF0) > 0x90){ //adjust high nibble
result += 0x60;
}
} else{ //subtraction used
if(isFlagSet(Flag::H)){
result = (result - 6) & 0xFF;
}
if(isFlagSet(Flag::C)){
result -= 0x60;
}
}
if(result & 0x100){
setFlag(Flag::C);
}
clearFlag(Flag::H);
if((result & 0xFF) == 0){
setFlag(Flag::Z);
} else{
clearFlag(Flag::Z);
}
value = result;
}
inline void CPU::jumpIfSet8Bit(Flag flag, byte value){
if(isFlagSet(flag)){
PC += static_cast<int8_t>(value);
performedAction = true;
} else{
performedAction = false;
}
}
inline void CPU::complement(byte &value){
value = ~value;
setFlag(Flag::N);
setFlag(Flag::H);
}
inline void CPU::addToA(byte value)
{
int result = A + value;
if((result & 0xFF) == 0){
setFlag(Flag::Z);
} else {
clearFlag(Flag::Z);
}
if(result & 0x100){
setFlag(Flag::C);
} else {
clearFlag(Flag::C);
}
if((A ^ value ^ (result & 0xFF)) & 0x10){
setFlag(Flag::H);
} else{
clearFlag(Flag::H);
}
clearFlag(Flag::N);
A = static_cast<byte>(result);
}
inline void CPU::subtractFromA(byte value)
{
int result = A - value;
if((result & 0xFF) == 0){
setFlag(Flag::Z);
} else {
clearFlag(Flag::Z);
}
if(result < 0){
setFlag(Flag::C);
} else{
clearFlag(Flag::C);
}
if((A ^ value ^ (result & 0xFF)) & 0x10){
setFlag(Flag::H);
} else{
clearFlag(Flag::H);
}
setFlag(Flag::N);
A = static_cast<byte>(result);
}
inline void CPU::andToA(byte value){
A &= value;
if(A == 0){
setFlag(Flag::Z);
} else{
clearFlag(Flag::Z);
}
clearFlag(Flag::C);
clearFlag(Flag::N);
setFlag(Flag::H);
}
inline void CPU::xorToA(byte value)
{
A ^= value;
if(A == 0){
setFlag(Flag::Z);
} else{
clearFlag(Flag::Z);
}
clearFlag(Flag::C);
clearFlag(Flag::N);
clearFlag(Flag::H);
}
inline void CPU::orToA(byte value)
{
A |= value;
if(A == 0){
setFlag(Flag::Z);
} else{
clearFlag(Flag::Z);
}
clearFlag(Flag::C);
clearFlag(Flag::N);
clearFlag(Flag::H);
}
inline void CPU::compareToA(byte value)
{
byte tempA = A;
subtractFromA(value);
A = tempA;
}
#endif // OPCODES_INLINE_H
| true |
2a9f0fbbb45c9c9cf1be9d488aaf98f7a76611c8
|
C++
|
robinhoode/ILoveYouTron
|
/src/TriangulatedCylinder.h
|
UTF-8
| 876 | 2.609375 | 3 |
[] |
no_license
|
#ifndef _TRIANGULATED_CYLINDER
#define _TRIANGULATED_CYLINDER
#include "ofMath.h"
#include "ofMain.h"
#include "ofConstants.h"
#include "ThreeDShape.h"
class TriangulatedCylinder : ThreeDShape {
public:
double angleY, angleZ, angleStep;
double standardShapeHeight, shapeHeight, levelShape;
double iterationSize, levelScale;
TriangulatedCylinder() {
setup();
levelScale = 1500;
iterationSize = 2;
}
TriangulatedCylinder(double l, double i) {
setup();
levelScale = l;
iterationSize = i;
}
void setup();
void draw();
void drawVertices(double shapeHeight, double scalar);
void drawWireframe(double shapeHeight, double scalar);
void drawTexture(double shapeHeight, double scalar);
/*
void doRotation() {
angleY += PI/128;
rotateY(angleY);
angleZ += PI/243;
rotateZ(angleZ);
}
*/
};
#endif
| true |
d37c147583421bb5107d49d66799739c28b44134
|
C++
|
adityanjr/code-DS-ALGO
|
/HackerBlocks/Divide and Conquer/Help rahul to search/main.cpp
|
UTF-8
| 733 | 2.984375 | 3 |
[
"MIT"
] |
permissive
|
#include<bits/stdc++.h>
using namespace std;
#define ll long long int
ll binarysearch(ll arr[], ll start, ll end, ll search){
if(start<=end){
ll mid = start + (end-start)/2;
if(arr[mid]==search)
return mid;
if(arr[mid]<=arr[end]){
if(search>arr[mid] && search<=arr[end])
return binarysearch(arr,mid+1,end,search);
else
return binarysearch(arr,start,mid-1,search);
}
else{
if(search<arr[mid] && search>=arr[start])
return binarysearch(arr,start,mid-1,search);
else
return binarysearch(arr,mid+1,end,search);
}
}
}
int main() {
ll n;
ll search;
cin>>n;
ll arr[n];
for(int i=0;i<n;i++){
cin>>arr[i];
}
cin>>search;
cout<<binarysearch(arr,0,n-1,search);
return 0;
}
| true |
46ee80e6d9ae5305b060f77a6540ec9342d3145f
|
C++
|
JJYDXFS/Compiler_exp
|
/exp2/NFA.h
|
GB18030
| 1,385 | 3.3125 | 3 |
[] |
no_license
|
#pragma once
#include <iostream>
// н㱣һάбУͨ±
typedef int NType;
typedef char InfoType;
typedef struct NFA { // NFA
int start; // ʼ
int end; //
}NFA;
class Edge //
{
public:
int NodeIndex; // յ±
Edge *nextedge; // һڱ
InfoType info; // תȡַ
Edge() {
NodeIndex = 0;
nextedge = NULL;
info = '\0';
}
Edge(const Edge &E) { // 캯ѲҪʱ
NodeIndex = E.NodeIndex;
nextedge = E.nextedge;
info = E.info;
}
/*~Edge() {
if (nextedge != NULL) {
delete[]nextedge;
nextedge = NULL;
}
}*/
};
class NFANode // ״̬
{
public:
NType data; // Ϣʱûõ
Edge *firstedge; // һڱ
NFANode() {
data = '\0';
firstedge = NULL;
}
NFANode(const NFANode &N) { // 캯
data = N.data;
firstedge = N.firstedge;
}
/*~NFANode() {
if (firstedge != NULL) {
delete[]firstedge;
firstedge = NULL;
}
}*/
};
// ݽṹ ṹ
//typedef struct Edge {
// int NodeIndex; // յ±
// struct Edge *nextedge; // һڱ
// InfoType info; // תȡַ
//}Edge;
//typedef struct NFANode {
// NType data; // Ϣʱûõ
// Edge *firstedge; // һڱ
//}NFANode;
| true |
5b07b20763e2f1c669a3dbe1e1b393bde21b2709
|
C++
|
CaoHoaiTan/HCMUTE
|
/Kỹ thuật lập trình - Programming Techniques/C5/DayConTang.cpp
|
UTF-8
| 733 | 2.671875 | 3 |
[] |
no_license
|
#include <stdio.h>
#define SIZE 100
#define oo 100000
void nhap(int A[], int &n);
void QHD(int A[], int n, int L[], int T[]);
void TruyVet(int A[], int n, int L[], int T[]);
int main(){
int A[SIZE]={0}, L[SIZE]={0}, T[SIZE]={0}, n;
nhap(A,n);
QHD(A,n,L,T);
printf("%d\n",L[0]);
TruyVet(A,n,L,T);
return 0;
}
void nhap(int A[], int &n){
scanf("%d",&n);
for (int i=1;i<=n;i++)
scanf("%d",&A[i]);
}
void QHD(int A[], int n, int L[], int T[]){
L[n]=1; A[0]= -oo;
for (int i=n-1;i>=0;i--){
int j,jmax=i;
for (j=i+1;j<=n;j++)
if (A[j]>A[i] && L[j]>L[jmax]) jmax=j;
L[i]=L[jmax]+1;
T[i]=jmax;
}
}
void TruyVet(int A[], int n, int L[], int T[]){
int i=T[0];
while (i<n){
printf("%d ",A[i]);
i=T[i];
}
}
| true |
262bea37997af3706cd749bc6a117fecf824a1fa
|
C++
|
verto4599/LeetCode
|
/Array/1431. Kids With the Greatest Number of Candies.cpp
|
UTF-8
| 466 | 2.90625 | 3 |
[] |
no_license
|
vector<bool> kidsWithCandies(vector<int>& candies, int extraCandies) {
int maxCandies=-1;
vector<bool> check;
for(int i=0;i<candies.size();i++)
maxCandies=max(maxCandies,candies[i]);
for(int i=0;i<candies.size();i++){
if(candies[i] + extraCandies >= maxCandies )
check.push_back(true);
else
check.push_back(false);
}
return check;
}
| true |
a4591c7019790f79f83d4f9665d315dd659baa04
|
C++
|
Siddharth-Babbar/Pepcoding
|
/PepcodingSept_19/Lec_008/Matrix1.cpp
|
UTF-8
| 645 | 3.328125 | 3 |
[] |
no_license
|
#include<iostream>
#include<vector>
using namespace std;
void input(vector<vector<int>> & arr)
{
for(int i=0; i<arr.size();i++)
{
for(int j=0;j<arr[0].size();j++)
{
cin>>arr[i][j];
}
}
}
void display(vector<vector<int>> & arr)
{
for(vector<int> ar:arr)
{
for(int ele: ar)
{
cout<<ele<<" ";
}
cout<<endl;
}
}
int main(int args,char** argv)
{
int n,m;
cout<<"Plese enter the numbers:"<<endl;
cin>>n>>m;
vector<vector<int>> arr(n,vector<int> (m,10));
input(arr);
display(arr);
return 0;
}
| true |
4b978d1602a6e5dbb0f4e219057ea2d9fde155bb
|
C++
|
nithish642k/binary-tree
|
/40)check if given tree is height balanced.cpp
|
UTF-8
| 1,090 | 3.421875 | 3 |
[] |
no_license
|
/* Number of nodes on the longest path between any two leaf nodes */
#include<bits/stdc++.h>
using namespace std;
struct Node
{
int data;
struct Node *left,*right;
Node(int data)
{
this->data=data;
left=right=NULL;
}
};
int check(struct Node *node)
{
if(node==NULL)
return 0;
if(node->left==NULL&&node->right==NULL)
return 1;
int leftHeight=check(node->left);
int rightHeight=check(node->right);
if(leftHeight==-1||rightHeight==-1||abs(leftHeight-rightHeight)>1)
return -1;
return max(leftHeight,rightHeight)+1;
}
int main()
{
/*
struct Node *root=new Node(2);
root->left=new Node(7);
root->right=new Node(5);
root->left->left=new Node(2);
root->left->right=new Node(6);
root->left->left->left=new Node(5);
*/
struct Node *root=new Node(2);
root->left=new Node(7);
root->right=new Node(5);
root->left->left=new Node(2);
root->left->right=new Node(6);
root->right->left=new Node(3);
root->left->left->left=new Node(5);
cout<<"Balanced:"<<(check(root)!=-1);
return 0;
}
| true |
8a89e99a641d57ab65b88c2114bc81bb119c17c4
|
C++
|
Minhan93/Financial-Computing-With-C-
|
/HW5/HW5_1c.cpp
|
UTF-8
| 2,167 | 2.875 | 3 |
[] |
no_license
|
//
// main.cpp
// hw5
//
// Created by Li M on 15/10/5.
// Copyright (c) 2015年 Li M. All rights reserved.
//
#include<cstdlib>
#include<ctime>
#include<stdio.h>
#include<math.h>
#include<iostream>
using namespace std;
int main()
{
srand( static_cast<unsigned int>(time(NULL)));
const double T=1,S0=100,r=0.05,sigma=0.2,K=100;
const int N=10000;
//const double pi=3.14159265358979323846264338328;
double u1,u2,u3;
double y;
double z[N];
for (int i=0;i<N;)
{
u1=rand()/(static_cast<double>(RAND_MAX)+1);
u2=rand()/(static_cast<double>(RAND_MAX)+1);
u3=rand()/(static_cast<double>(RAND_MAX)+1);
y=-log(u1);
if(u2<=exp(-pow(y-1,2)/2))
{
if(u3<0.5)
z[i]=fabs(y);
else
z[i]=-fabs(y);
i++;
}
}
double S[N];
double C[N];
double sum=0;//double p=0;
for(int i=0;i<N;i++)
{
S[i]=S0*exp((r-pow(sigma,2)/2)*T+sigma*pow(T,1/2)*z[i]);
if(S[i]>K)
{C[i]=exp(-r*T)*(S[i]-K);
// p++;
}
else
C[i]=0;
sum+=C[i];
//cout<<" "<<C[i];
}
sum=sum/N;
cout<<"the price of option from accept-reject method is:"<<sum<<endl;
//Marsaglia method below
double u4,u5;
double Z[N];
for(int i=0;i<N;)
{
u4=rand()/(static_cast<double>(RAND_MAX)+1)*2-1;
u5=rand()/(static_cast<double>(RAND_MAX)+1)*2-1;
double s=pow(u4,2)+pow(u5,2);
if(s<1)
{
Z[i]=u4*sqrt(-2*log(s)/s);
i++;
}
}
double S2[N];
double C2[N];
double sum2=0;
for(int i=0;i<N;i++)
{
S2[i]=S0*exp((r-pow(sigma,2)/2)*T+sigma*sqrt(T)*Z[i]);
if(S2[i]>K)
{
C2[i]=exp(-r*T)*(S2[i]-K);
}
else
C2[i]=0;
sum2+=C2[i];
//cout<<" "<<C2[i];
}
sum2=sum2/N;//cout<<"m="<<m;cout<<"p="<<p;
cout<<"the price of option from Marsaglia method is:"<<sum2<<endl;
}
| true |
7442d0445e57ad20bc00bb04b4f46ffb9c5a39d0
|
C++
|
anshishazhudeou/uwaterlooCourses
|
/2019Winter/cs349/02.gui/examples/xlib/null.min.cpp
|
UTF-8
| 628 | 3.28125 | 3 |
[] |
no_license
|
/*
CS 349 Code Examples: X Windows and XLib
null Creates and destroys a display (a good first test to see
if X Windows is working).
- - - - - - - - - - - - - - - - - - - - - -
See associated makefile for compiling instructions
*/
#include <cstdlib>
#include <iostream>
#include <X11/Xlib.h> // main Xlib header
Display* display;
int main() {
display = XOpenDisplay(""); // open display (using DISPLAY env var)
if (display == NULL) {
std::cout << "error\n";
exit (-1);
} else {
std::cout << "success!: ";
XCloseDisplay(display); // close display
}
}
| true |
26d6d428a1e12ae344825ca31e6028a2e9321be7
|
C++
|
SeyoungJeon/Algorithmus2
|
/BaekJoon/Project1/17136.cpp
|
UHC
| 1,491 | 3.234375 | 3 |
[] |
no_license
|
#include <iostream>
using namespace std;
int map[10][10];
int color[5] = { 5,5,5,5,5 };
int ans = 101,result;
void func(int row, int col) {
// 1~10 Ȯ
if (col == 10) {
func(row+1, 0);
return;
}
// Ȯ
if (row == 10) {
// ּҵǴ
if (result < ans) {
ans = result;
}
return;
}
// ̸ ʿ䰡 ĭ
if (map[row][col] == 0) {
func(row, col + 1);
return;
}
// 1~5ĭ Ŀ
for (int i = 1; i <= 5; i++) {
// 5 Ҵ, Ѿ
if (color[i - 1] == 0 || row + i > 10 || col + i > 10)
continue;
bool possible = true;
for (int k = 0; k < i; k++) {
for (int l = 0; l < i; l++) {
if (map[row+k][col+l] == 0){
possible = false;
break;
}
}
if (!possible)
break;
}
if (!possible)
continue;
for (int k = 0; k < i; k++) {
for (int l = 0; l < i; l++) {
map[row + k][col + l] = 0;
}
}
color[i - 1]--;
result++;
func(row, col + i);
for (int k = 0; k < i; k++) {
for (int l = 0; l < i; l++) {
map[row + k][col + l] = 1;
}
}
color[i - 1]++;
result--;
}
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
cin >> map[i][j];
}
}
func(0, 0);
if (ans == 101) {
cout << -1 << '\n';
}
else {
cout << ans << '\n';
}
return 0;
}
| true |
038dd7257474a63f865afa61dfe8b1943db779ed
|
C++
|
atyuwen/string_dictionary
|
/src/libcsd_test.cpp
|
UTF-8
| 3,253 | 2.734375 | 3 |
[
"MIT"
] |
permissive
|
#define _CRT_SECURE_NO_WARNINGS
#include "libcsd_test.h"
#include <iostream>
#include <memory>
#include <StringDictionary.h>
#include <iterators/IteratorDictStringPlain.h>
void test_libcsd(const std::vector<std::string>& strs)
{
std::vector<std::string> sorted_strs = strs;
std::sort(sorted_strs.begin(), sorted_strs.end());
std::vector<char> chars;
for (const std::string& str : sorted_strs)
{
chars.insert(chars.end(), str.begin(), str.end());
chars.emplace_back('\0');
}
// HASHHF
{
IteratorDictStringPlain* it = new IteratorDictStringPlain((uchar*)(&chars[0]), chars.size());
std::unique_ptr<StringDictionary> dict{ new StringDictionaryHASHHF(it, chars.size(), 10) };
// delete it
std::cout << "CSD HASHHF - " << dict->getSize() << " bytes\n";
}
// HASHUFFDAC
{
IteratorDictStringPlain* it = new IteratorDictStringPlain((uchar*)(&chars[0]), chars.size());
std::unique_ptr<StringDictionary> dict{ new StringDictionaryHASHUFFDAC(it, chars.size(), 10) };
// delete it
std::cout << "CSD HASHUFFDAC - " << dict->getSize() << " bytes\n";
}
// PFC
{
IteratorDictStringPlain* it = new IteratorDictStringPlain((uchar*)(&chars[0]), chars.size());
std::unique_ptr<StringDictionary> dict{ new StringDictionaryPFC(it, 100) };
// delete it
std::cout << "CSD PFC - " << dict->getSize() << " bytes\n";
}
// RPFC
{
IteratorDictStringPlain* it = new IteratorDictStringPlain((uchar*)(&chars[0]), chars.size());
std::unique_ptr<StringDictionary> dict{ new StringDictionaryRPFC(it, 100) };
// delete it
std::cout << "CSD RPFC - " << dict->getSize() << " bytes\n";
}
// HTFC
{
IteratorDictStringPlain* it = new IteratorDictStringPlain((uchar*)(&chars[0]), chars.size());
std::unique_ptr<StringDictionary> dict{ new StringDictionaryHTFC(it, 100) };
// delete it
std::cout << "CSD HTFC - " << dict->getSize() << " bytes\n";
}
// HHTFC
{
IteratorDictStringPlain* it = new IteratorDictStringPlain((uchar*)(&chars[0]), chars.size());
std::unique_ptr<StringDictionary> dict{ new StringDictionaryHHTFC(it, 100) };
// delete it
std::cout << "CSD HHTFC - " << dict->getSize() << " bytes\n";
}
// RPHTFC
{
IteratorDictStringPlain* it = new IteratorDictStringPlain((uchar*)(&chars[0]), chars.size());
std::unique_ptr<StringDictionary> dict{ new StringDictionaryRPHTFC(it, 100) };
// delete it
std::cout << "CSD RPHTFC - " << dict->getSize() << " bytes\n";
}
// RPDAC
{
IteratorDictStringPlain* it = new IteratorDictStringPlain((uchar*)(&chars[0]), chars.size());
std::unique_ptr<StringDictionary> dict{ new StringDictionaryRPDAC(it) };
// delete it
std::cout << "CSD RPDAC - " << dict->getSize() << " bytes\n";
}
// FMINDEX
{
IteratorDictStringPlain* it = new IteratorDictStringPlain((uchar*)(&chars[0]), chars.size());
std::unique_ptr<StringDictionary> dict{ new StringDictionaryFMINDEX(it, false, 4, 0) };
// delete it
std::cout << "CSD FMINDEX - " << dict->getSize() << " bytes\n";
}
// DXBW
{
//IteratorDictStringPlain* it = new IteratorDictStringPlain((uchar*)(&chars[0]), chars.size());
//std::unique_ptr<StringDictionary> dict{ new StringDictionaryXBW(it) };
//// delete it
//std::cout << "CSD DXBW - " << dict->getSize() << " bytes\n";
}
}
| true |
04aee2c73340c7b11587f586f0226de8b972bfd6
|
C++
|
BryanCaceresChacon/Practica-de-Laboratorio3
|
/Ejercicio2/Ejercicio2/Ejercicio2.cpp
|
UTF-8
| 595 | 3.234375 | 3 |
[] |
no_license
|
// Ejercicio2.cpp : Este archivo contiene la función "main". La ejecución del programa comienza y termina ahí.
//
#include <iostream>
using namespace std;
//EJERCICIO2
int main()
{
int cont = 0;
int n = 0;
cout << "Ingrese un numero:";
cin >> n;
for (int i = 1; i <= n; i++) {
if (i % 2 == 0) {
for (int j = (i / 2); j >= 1; j--) {
if (i % j == 0) {
cont = cont + j;
}
}
if (cont == i)
cout << cont << " ";
}
cont = 0;
}
}
| true |
dd737833bae1e12d8c82c7a705cd1d80cefe8821
|
C++
|
Alcaro/russian-malware
|
/arlib/string.h
|
UTF-8
| 26,918 | 2.734375 | 3 |
[] |
no_license
|
#pragma once
#include "global.h"
#include "array.h"
#include "hash.h"
#include <string.h>
// define my own ctype, because table lookup is faster than libc call that probably ends up in a table lookup anyways,
// and so I can define weird whitespace (\f\v) to not space (several Arlib modules require that, better centralize it)
// this means they don't obey locale, but all modern locales use UTF-8, for which isctype() has no useful answer
// locale shouldn't be in libc anyways; localization is complex enough to belong in a separate library that updates faster than libc,
// and its global-state-based design interacts badly with libraries, logging, threading, text-based formats like JSON, etc
#ifdef _WIN32
#include <ctype.h> // include this one before windows.h does, the defines below confuse it
#endif
#define iscntrl my_iscntrl // define them all away, then don't bother implementing the ones I don't use
#define isprint my_isprint
#define isspace my_isspace
#define isblank my_isblank
#define isgraph my_isgraph
#define ispunct my_ispunct
#define isalnum my_isalnum
#define isalpha my_isalpha
#define isupper my_isupper
#define islower my_islower
#define isdigit my_isdigit
#define isxdigit my_isxdigit
#define tolower my_tolower
#define toupper my_toupper
extern const uint8_t char_props[256];
// bit meanings:
// 0x80 - space (\t\n\r ) - contrary to libc isspace, \f\v are not considered space
// 0x40 - digit (0-9)
// 0x20 - letter (A-Za-z) - tolower/toupper needs 0x20 to be letter,
// 0x10 - unused and 0x80 is cheaper to test on some platforms, so it goes to the most common test (space)
// 0x08 - unused other bit assignments are arbitrary
// 0x04 - lowercase (a-z) also contrary to libc, these functions handle byte values only;
// 0x02 - uppercase (A-Z) EOF is not a valid input (EOF feels like a poor design)
// 0x01 - hex digit (0-9A-Fa-f)
static inline bool isspace(uint8_t c) { return char_props[c] & 0x80; }
static inline bool isdigit(uint8_t c) { return char_props[c] & 0x40; }
static inline bool isalpha(uint8_t c) { return char_props[c] & 0x20; }
static inline bool islower(uint8_t c) { return char_props[c] & 0x04; }
static inline bool isupper(uint8_t c) { return char_props[c] & 0x02; }
static inline bool isalnum(uint8_t c) { return char_props[c] & 0x60; }
static inline bool isxdigit(uint8_t c) { return char_props[c] & 0x01; }
static inline uint8_t tolower(uint8_t c) { return c|(char_props[c]&0x20); }
static inline uint8_t toupper(uint8_t c) { return c&~(char_props[c]&0x20); }
// A string is a mutable byte sequence. It usually represents UTF-8 text, but can be arbitrary binary data, including NULs.
// All string functions taking or returning a char* assume/guarantee NUL termination. Anything using uint8_t* does not.
// cstring is an immutable sequence of bytes that does not own its storage; it usually points to a string constant, or part of a string.
// In most contexts, it's called stringview, but I feel that's too long.
// Long ago, cstring was just a typedef to 'const string&', hence its name.
// The child classes put various constraints on their contents that the parent does not; they do not obey the Liskov substitution principle.
// Any attempt to turn a string into cstring&, then call operator= or otherwise mutate it, is object slicing and undefined behavior.
class cstring;
class cstrnul;
class string;
#define OBJ_SIZE 16 // maximum 120, or the inline length overflows
// (127 would fit, but that requires an extra alignment byte, which throws the sizeof assert)
// minimum 16 on 64bit, 12 on 32bit
// most strings are short, so let's keep it small; 16 for all
#define MAX_INLINE (OBJ_SIZE-1) // macros instead of static const to make gdb not print them every time
class cstring {
friend class string;
friend class cstrnul;
friend bool operator==(const cstring& left, const cstring& right);
friend inline bool operator==(const cstring& left, const char * right);
static uint32_t max_inline() { return MAX_INLINE; }
union {
struct {
uint8_t m_inline[MAX_INLINE+1];
// last byte is how many bytes are unused by the raw string data
// if all bytes are used, there are zero unused bytes - which also serves as the NUL
// if not inlined, it's -1
};
struct {
uint8_t* m_data;
uint32_t m_len; // always > MAX_INLINE, if not inlined; some of the operator== demand that
bool m_nul; // whether the string is properly terminated (always true for string, possibly false for cstring)
// 2 unused bytes here
uint8_t m_reserved; // reserve space for the last byte of the inline data; never ever access this
};
};
uint8_t& m_inline_len_w() { return m_inline[MAX_INLINE]; }
int8_t m_inline_len() const { return m_inline[MAX_INLINE]; }
forceinline bool inlined() const
{
static_assert(sizeof(cstring)==OBJ_SIZE);
return m_inline_len() >= 0;
}
forceinline uint8_t len_if_inline() const
{
static_assert((MAX_INLINE & (MAX_INLINE+1)) == 0); // this xor trick only works for power of two minus 1
return MAX_INLINE^m_inline_len();
}
forceinline const uint8_t * ptr() const
{
if (inlined()) return m_inline;
else return m_data;
}
forceinline arrayvieww<uint8_t> bytes_raw() const
{
if (inlined())
return arrayvieww<uint8_t>((uint8_t*)m_inline, len_if_inline());
else
return arrayvieww<uint8_t>(m_data, m_len);
}
public:
forceinline uint32_t length() const
{
if (inlined()) return len_if_inline();
else return m_len;
}
forceinline arrayview<uint8_t> bytes() const { return bytes_raw(); }
//If this is true, bytes()[bytes().size()] is '\0'. If false, it's undefined behavior.
//this[this->length()] is always '\0', even if this is false.
forceinline bool bytes_hasterm() const
{
return (inlined() || m_nul);
}
private:
forceinline void init_empty()
{
m_inline_len_w() = MAX_INLINE;
m_inline[0] = '\0';
}
void init_from_nocopy(const char * str)
{
init_from_nocopy((uint8_t*)str, strlen(str), true);
}
void init_from_nocopy(const uint8_t * str, size_t len, bool has_nul = false)
{
if (len <= MAX_INLINE)
{
for (uint32_t i=0;i<len;i++) m_inline[i] = str[i]; // memcpy's constant overhead is huge if len is unknown
m_inline[len] = '\0';
m_inline_len_w() = MAX_INLINE-len;
}
else
{
if (len > 0xFFFFFFFF) abort();
m_inline_len_w() = -1;
m_data = (uint8_t*)str;
m_len = len;
m_nul = has_nul;
}
}
void init_from_nocopy(arrayview<uint8_t> data, bool has_nul = false) { init_from_nocopy(data.ptr(), data.size(), has_nul); }
void init_from_nocopy(const cstring& other) { *this = other; }
// TODO: make some of these ctors constexpr, so gcc can optimize them into the data section (Clang already does)
// partial or no initialization is c++20 only, so not until then
// may need removing the union and memcpying things to/from a struct
class noinit {};
cstring(noinit) {}
public:
cstring() { init_empty(); }
cstring(const cstring& other) = default;
cstring(const char * str) { init_from_nocopy(str); }
cstring(const char8_t * str) { init_from_nocopy((char*)str); }
cstring(arrayview<uint8_t> bytes) { init_from_nocopy(bytes); }
cstring(arrayview<char> chars) { init_from_nocopy(chars.reinterpret<uint8_t>()); }
cstring(nullptr_t) { init_empty(); }
// If has_nul, then bytes[bytes.size()] is zero. (Undefined behavior does not count as zero.)
cstring(arrayview<uint8_t> bytes, bool has_nul) { init_from_nocopy(bytes, has_nul); }
cstring& operator=(const cstring& other) = default;
cstring& operator=(const char * str) { init_from_nocopy(str); return *this; }
cstring& operator=(const char8_t * str) { init_from_nocopy((char*)str); return *this; }
cstring& operator=(nullptr_t) { init_empty(); return *this; }
explicit operator bool() const { return length() != 0; }
forceinline uint8_t operator[](ssize_t index) const { return ptr()[index]; }
//~0 means end of the string, ~1 is last character
//don't try to make -1 the last character, it breaks str.substr(x, ~0)
//this shorthand exists only for substr()
int32_t realpos(int32_t pos) const
{
if (pos >= 0) return pos;
else return length()-~pos;
}
cstring substr(int32_t start, int32_t end) const
{
start = realpos(start);
end = realpos(end);
return cstring(arrayview<uint8_t>(ptr()+start, end-start), (bytes_hasterm() && (uint32_t)end == length()));
}
bool contains(cstring other) const
{
return memmem(this->ptr(), this->length(), other.ptr(), other.length()) != NULL;
}
size_t indexof(cstring other, size_t start = 0) const; // Returns -1 if not found.
size_t lastindexof(cstring other) const;
bool startswith(cstring other) const;
bool endswith(cstring other) const;
size_t iindexof(cstring other, size_t start = 0) const;
size_t ilastindexof(cstring other) const;
bool icontains(cstring other) const;
bool istartswith(cstring other) const;
bool iendswith(cstring other) const;
bool iequals(cstring other) const;
string replace(cstring in, cstring out) const;
//crsplitwi - cstring-returning backwards-counting split on word boundaries, inclusive
//cstring-returning - obvious
//backwards-counting - splits at the rightmost opportunity, "a b c d".rsplit<1>(" ") is ["a b c", "d"]
//word boundary - isspace()
//inclusive - the boundary string is included in the output, "a\nb\n".spliti("\n") is ["a\n", "b\n"]
//all subsets of splitting options are supported
array<cstring> csplit(cstring sep, size_t limit) const;
template<size_t limit = SIZE_MAX>
array<cstring> csplit(cstring sep) const { return csplit(sep, limit); }
array<cstring> crsplit(cstring sep, size_t limit) const;
template<size_t limit>
array<cstring> crsplit(cstring sep) const { return crsplit(sep, limit); }
array<string> split(cstring sep, size_t limit) const { return csplit(sep, limit).cast<string>(); }
template<size_t limit = SIZE_MAX>
array<string> split(cstring sep) const { return split(sep, limit); }
array<string> rsplit(cstring sep, size_t limit) const { return crsplit(sep, limit).cast<string>(); }
template<size_t limit>
array<string> rsplit(cstring sep) const { return rsplit(sep, limit); }
array<cstring> cspliti(cstring sep, size_t limit) const;
template<size_t limit = SIZE_MAX>
array<cstring> cspliti(cstring sep) const { return cspliti(sep, limit); }
array<cstring> crspliti(cstring sep, size_t limit) const;
template<size_t limit>
array<cstring> crspliti(cstring sep) const { return crspliti(sep, limit); }
array<string> spliti(cstring sep, size_t limit) const { return cspliti(sep, limit).cast<string>(); }
template<size_t limit = SIZE_MAX>
array<string> spliti(cstring sep) const { return spliti(sep, limit); }
array<string> rspliti(cstring sep, size_t limit) const { return crspliti(sep, limit).cast<string>(); }
template<size_t limit>
array<string> rspliti(cstring sep) const { return rspliti(sep, limit); }
private:
// Input: Three pointers, start <= at <= end. The found match must be within the incoming at..end.
// Output: Set at/end.
array<cstring> csplit(bool(*find)(const uint8_t * start, const uint8_t * & at, const uint8_t * & end), size_t limit) const;
public:
template<typename T>
std::enable_if_t<sizeof(T::match(nullptr,nullptr,nullptr))!=0, array<cstring>>
csplit(T regex, size_t limit) const
{
return csplit([](const uint8_t * start, const uint8_t * & at, const uint8_t * & end)->bool {
auto cap = T::match((char*)start, (char*)at, (char*)end);
if (!cap) return false;
at = (uint8_t*)cap[0].start;
end = (uint8_t*)cap[0].end;
return true;
}, limit);
}
template<size_t limit = SIZE_MAX, typename T>
std::enable_if_t<sizeof(T::match(nullptr,nullptr,nullptr))!=0, array<cstring>>
csplit(T regex) const { return csplit(regex, limit); }
template<typename T>
std::enable_if_t<sizeof(T::match(nullptr,nullptr,nullptr))!=0, array<string>>
split(T regex, size_t limit) const
{
return csplit(regex, limit).template cast<string>();
}
template<size_t limit = SIZE_MAX, typename T>
std::enable_if_t<sizeof(T::match(nullptr,nullptr,nullptr))!=0, array<string>>
split(T regex) const { return split(regex, limit); }
inline string upper() const; // Only considers ASCII, will not change ø. Will capitalize a decomposed ñ, but not a precomposed one.
inline string lower() const;
cstring trim() const; // Deletes whitespace at start and end. Does not do anything to consecutive whitespace in the middle.
bool contains_nul() const;
bool isutf8() const; // NUL is considered valid UTF-8. Modified UTF-8, CESU-8, WTF-8, etc are not.
// The index is updated to point to the next codepoint. Initialize it to zero; stop when it equals the string's length.
// If invalid UTF-8, or descynchronized index, returns U+DC80 through U+DCFF; callers are welcome to treat this as an error.
uint32_t codepoint_at(uint32_t& index) const;
//Whether the string matches a glob pattern. ? in 'pat' matches any byte (not utf8 codepoint), * matches zero or more bytes.
//NUL bytes are treated as any other byte, in both strings.
bool matches_glob(cstring pat) const __attribute__((pure)) { return matches_glob(pat, false); }
// Case insensitive. Considers ASCII only, øØ are considered nonequal.
bool matches_globi(cstring pat) const __attribute__((pure)) { return matches_glob(pat, true); }
private:
bool matches_glob(cstring pat, bool case_insensitive) const __attribute__((pure));
public:
string leftPad (size_t len, uint8_t ch = ' ') const;
size_t hash() const { return ::hash(ptr(), length()); }
private:
class c_string {
char* ptr;
bool do_free;
public:
c_string(arrayview<uint8_t> data, bool has_term)
{
if (has_term)
{
ptr = (char*)data.ptr();
do_free = false;
}
else
{
ptr = (char*)xmalloc(data.size()+1);
memcpy(ptr, data.ptr(), data.size());
ptr[data.size()] = '\0';
do_free = true;
}
}
operator const char *() const { return ptr; }
const char * c_str() const { return ptr; }
inline operator cstrnul() const;
~c_string() { if (do_free) free(ptr); }
};
public:
//no operator const char *, a cstring doesn't necessarily have a NUL terminator
c_string c_str() const { return c_string(bytes(), bytes_hasterm()); }
};
// Like cstring, but guaranteed to have a nul terminator.
class cstrnul : public cstring {
friend class cstring;
friend class string;
forceinline const char * ptr_withnul() const { return (char*)ptr(); }
class has_nul {};
cstrnul(noinit) : cstring(noinit()) {}
cstrnul(arrayview<uint8_t> bytes, has_nul) : cstring(noinit()) { init_from_nocopy(bytes, true); }
public:
cstrnul() { init_empty(); }
cstrnul(const cstrnul& other) = default;
cstrnul(const char * str) { init_from_nocopy(str); }
cstrnul(nullptr_t) { init_empty(); }
cstrnul& operator=(const cstring& other) = delete;
cstrnul& operator=(const cstrnul& other) = default;
cstrnul& operator=(const char * str) { init_from_nocopy(str); return *this; }
cstrnul& operator=(nullptr_t) { init_empty(); return *this; }
explicit operator bool() const { return length() != 0; }
operator const char * () const { return ptr_withnul(); }
cstrnul substr_nul(int32_t start) const
{
start = realpos(start);
return cstrnul(arrayview<uint8_t>(ptr()+start, length()-start), has_nul());
}
};
class string : public cstrnul {
friend class cstring;
friend class cstrnul;
static size_t bytes_for(size_t len) { return bitround(len+1); }
forceinline uint8_t * ptr() { return (uint8_t*)cstring::ptr(); }
forceinline const uint8_t * ptr() const { return cstring::ptr(); }
void resize(size_t newlen);
void init_from(const char * str)
{
//if (!str) str = "";
init_from((uint8_t*)str, strlen(str));
}
forceinline void init_from(const uint8_t * str, size_t len)
{
if (__builtin_constant_p(len))
{
if (len <= MAX_INLINE)
{
memcpy(m_inline, str, len);
m_inline[len] = '\0';
m_inline_len_w() = max_inline()-len;
}
else init_from_large(str, len);
}
else init_from_outline(str, len);
}
forceinline void init_from(arrayview<uint8_t> data) { init_from(data.ptr(), data.size()); }
void init_from_outline(const uint8_t * str, size_t len);
void init_from_large(const uint8_t * str, size_t len);
void init_from(const cstring& other);
void init_from(string&& other)
{
memcpy((void*)this, (void*)&other, sizeof(*this));
other.init_empty();
}
void reinit_from(const char * str)
{
if (!str) str = "";
reinit_from(arrayview<uint8_t>((uint8_t*)str, strlen(str)));
}
void reinit_from(arrayview<uint8_t> data);
void reinit_from(cstring other)
{
reinit_from(other.bytes());
}
void reinit_from(string&& other)
{
deinit();
memcpy((void*)this, (void*)&other, sizeof(*this));
other.init_empty();
}
void deinit()
{
if (!inlined()) free(m_data);
}
void append(arrayview<uint8_t> newdat);
void append(uint8_t newch)
{
uint32_t oldlength = length();
resize(oldlength + 1);
ptr()[oldlength] = newch;
}
public:
//Resizes the string to a suitable size, then allows the caller to fill it in. Initial contents are undefined.
arrayvieww<uint8_t> construct(size_t len)
{
resize(len);
return bytes();
}
string& operator+=(const char * right)
{
append(arrayview<uint8_t>((uint8_t*)right, strlen(right)));
return *this;
}
string& operator+=(cstring right)
{
append(right.bytes());
return *this;
}
string& operator+=(char right)
{
append((uint8_t)right);
return *this;
}
string& operator+=(uint8_t right)
{
append(right);
return *this;
}
// for other integer types, fail (short/long/etc will be ambiguous)
string& operator+=(int right) = delete;
string& operator+=(unsigned right) = delete;
string() : cstrnul(noinit()) { init_empty(); }
string(const string& other) : cstrnul(noinit()) { init_from(other); }
string(string&& other) : cstrnul(noinit()) { init_from(std::move(other)); }
forceinline string(cstring other) : cstrnul(noinit()) { init_from(other); }
forceinline string(arrayview<uint8_t> bytes) : cstrnul(noinit()) { init_from(bytes); }
forceinline string(arrayview<char> chars) : cstrnul(noinit()) { init_from(chars.reinterpret<uint8_t>()); }
forceinline string(const char * str) : cstrnul(noinit()) { init_from(str); }
forceinline string(const char8_t * str) : cstrnul(noinit()) { init_from((char*)str); }
string(array<uint8_t>&& bytes);
forceinline string(nullptr_t) = delete;
forceinline string& operator=(const string& other) { reinit_from(other); return *this; }
forceinline string& operator=(const cstring& other) { reinit_from(other); return *this; }
forceinline string& operator=(string&& other) { reinit_from(std::move(other)); return *this; }
forceinline string& operator=(const char * str) { reinit_from(str); return *this; }
forceinline string& operator=(const char8_t * str) { reinit_from((char*)str); return *this; }
forceinline string& operator=(nullptr_t) { deinit(); init_empty(); return *this; }
~string() { deinit(); }
explicit operator bool() const { return length() != 0; }
operator const char * () const { return ptr_withnul(); }
//Reading the NUL terminator is fine. Writing the terminator, or poking beyond the NUL, is undefined behavior.
forceinline uint8_t& operator[](int index) { return ptr()[index]; }
forceinline uint8_t operator[](int index) const { return ptr()[index]; }
forceinline arrayview<uint8_t> bytes() const { return bytes_raw(); }
forceinline arrayvieww<uint8_t> bytes() { return bytes_raw(); }
//Takes ownership of the given pointer. Will free() it when done.
static string create_usurp(char * str);
static string create_usurp(array<uint8_t>&& in) { return string(std::move(in)); }
//Returns a string containing a single NUL.
static cstring nul() { return arrayview<uint8_t>((uint8_t*)"", 1); }
//Returns U+FFFD for UTF16-reserved codepoints and other forbidden codepoints. 0 yields a NUL byte.
static string codepoint(uint32_t cp);
// Returns number of bytes written. Buffer must be at least 4 bytes. Does not NUL terminate.
// May write garbage between out+return and out+4.
static size_t codepoint(uint8_t* out, uint32_t cp);
string upper() const & { return string(*this).upper(); }
string upper() && // Only considers ASCII, will not change ø. Will capitalize a decomposed ñ, but not a precomposed one.
{
bytesw by = this->bytes();
for (size_t i=0;i<by.size();i++) by[i] = toupper(by[i]);
return std::move(*this);
}
string lower() const & { return string(*this).lower(); }
string lower() &&
{
bytesw by = this->bytes();
for (size_t i=0;i<by.size();i++) by[i] = tolower(by[i]);
return std::move(*this);
}
//3-way comparison. If a comes first, return value is negative; if equal, zero; if b comes first, positive.
//Comparison is bytewise. End goes before NUL, so the empty string comes before everything else.
//The return value is not guaranteed to be in [-1..1]. It's not even guaranteed to fit in anything smaller than int.
static int compare3(cstring a, cstring b);
//Like the above, but case insensitive (treat every letter as uppercase). Considers ASCII only, øØ are considered nonequal.
//If the strings are case-insensitively equal, uppercase goes first.
static int icompare3(cstring a, cstring b);
static bool less(cstring a, cstring b) { return compare3(a, b) < 0; }
static bool iless(cstring a, cstring b) { return icompare3(a, b) < 0; }
//Natural comparison; "8" < "10". Other than that, same as above.
//Exact rules:
// Strings are compared component by component. A component is either a digit sequence, or a non-digit. 8 < 10, 2 = 02
// - and . are not part of the digit sequence. -1 < -2, 1.2 < 1.03
// If the strings are otherwise equal, repeat the comparison, but with 2 < 02. If still equal, repeat case sensitively (if applicable).
// Digits (0x30-0x39) belong after $ (0x24), but before @ (0x40).
//Correct sorting is a$ a1 a2 a02 a2a a2a1 a02a2 a2a3 a2b a02b A3A A3a a3A a3a A03A A03a a03A a03a a10 a11 aa a@
//It's named snat... instead of nat... because case sensitive natural comparison is probably a mistake; it shouldn't be the default.
static int snatcompare3(cstring a, cstring b) { return string::natcompare3(a, b, false); }
static int inatcompare3(cstring a, cstring b) { return string::natcompare3(a, b, true); }
static bool snatless(cstring a, cstring b) { return snatcompare3(a, b) < 0; }
static bool inatless(cstring a, cstring b) { return inatcompare3(a, b) < 0; }
private:
static int natcompare3(cstring a, cstring b, bool case_insensitive);
public:
};
cstring::c_string::operator cstrnul() const { return ptr; }
inline string cstring::upper() const { return string(*this).lower(); }
inline string cstring::lower() const { return string(*this).lower(); }
// TODO: I need a potentially-owning string class
// cstring never owns memory, string always does, new one has a flag for whether it does
// it's like a generalized cstring::c_str()
// will be immutable after creation, like cstring
// will be used for json/bml parsers, and most likely a lot more
// need to find a good name for it first
// also need to check how much time SSO saves once that class exists
#undef OBJ_SIZE
#undef MAX_INLINE
// using cstring rather than const cstring& is cleaner, but makes GCC 7 emit slightly worse code
// TODO: check if that's still true for GCC > 7
#if __GNUC__ == 7
// TODO: delete friend declaration when deleting this
template<size_t N> inline bool operator==(const cstring& left, char (&right)[N]) { return operator==(left, (const char*)right); }
template<size_t N> inline bool operator==(const cstring& left, const char (&right)[N])
{
#if defined(__GNUC__) && !defined(__clang__) && __GNUC__ >= 8 && __GNUC__ <= 10 && __cplusplus >= 201103
// https://gcc.gnu.org/bugzilla/show_bug.cgi?id=91212
return operator==(left, (const char*)right);
#else
if (N-1 <= cstring::max_inline())
return ((uint8_t)left.m_inline_len() == cstring::max_inline()-(N-1) && memeq(left.m_inline, right, N-1));
else
return (!left.inlined() && left.m_len == N-1 && memeq(left.m_data, right, N-1));
#endif
}
template<typename T, typename Ttest = std::enable_if_t<std::is_same_v<T,const char*> || std::is_same_v<T,char*>>>
inline bool operator==(const cstring& left, T right) { return left.bytes() == arrayview<uint8_t>((uint8_t*)right, strlen(right)); }
#else
forceinline bool operator==(const cstring& left, const char * right)
{
size_t len = strlen(right);
if (__builtin_constant_p(len))
{
if (len <= cstring::max_inline())
return ((uint8_t)left.m_inline_len() == (cstring::max_inline()^len) && memeq(left.m_inline, right, len));
else
return (!left.inlined() && left.m_len == len && memeq(left.m_data, right, len));
}
else return left.bytes() == arrayview<uint8_t>((uint8_t*)right, len);
}
#endif
inline bool operator==(const char * left, const cstring& right) { return operator==(right, left); }
#ifdef __SSE2__
bool operator==(const cstring& left, const cstring& right);
#else
inline bool operator==(const cstring& left, const cstring& right)
{
return left.bytes() == right.bytes();
}
#endif
inline bool operator!=(const cstring& left, const char * right ) { return !operator==(left, right); }
inline bool operator!=(const cstring& left, const cstring& right) { return !operator==(left, right); }
inline bool operator!=(const char * left, const cstring& right) { return !operator==(left, right); }
bool operator<(cstring left, const char * right) = delete;
bool operator<(cstring left, cstring right ) = delete;
bool operator<(const char * left, cstring right ) = delete;
inline string operator+(cstring left, cstring right ) { string ret = left; ret += right; return ret; }
inline string operator+(cstring left, const char * right) { string ret = left; ret += right; return ret; }
inline string operator+(string&& left, cstring right ) { left += right; return left; }
inline string operator+(string&& left, const char * right) { left += right; return left; }
inline string operator+(const char * left, cstring right ) { string ret = left; ret += right; return ret; }
inline string operator+(string&& left, char right) = delete;
inline string operator+(cstring left, char right) = delete;
inline string operator+(char left, cstring right) = delete;
//Checks if needle is one of the 'separator'-separated words in the haystack. The needle may not contain 'separator' or be empty.
//For example, haystack "GL_EXT_FOO GL_EXT_BAR GL_EXT_QUUX" (with space as separator) contains needles
// 'GL_EXT_FOO', 'GL_EXT_BAR' and 'GL_EXT_QUUX', but not 'GL_EXT_QUU'.
bool strtoken(const char * haystack, const char * needle, char separator);
template<typename T>
cstring arrayview<T>::get_or(size_t n, const char * def) const
{
if (n < count) return items[n];
else return def;
};
| true |
7a27bf00d9916bb14e671acce9b3f68d395ae74a
|
C++
|
velazqua/competitive-programming
|
/online-judges/UVa/10650/10650.cpp
|
UTF-8
| 2,083 | 2.609375 | 3 |
[] |
no_license
|
/* Alex Velazquez
* Start: Sun Mar 11 19:29:02 EDT 2012
* End :
*/
#include <algorithm>
#include <bitset>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <deque>
#include <functional>
#include <iomanip>
#include <iostream>
#include <list>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <sstream>
#include <utility>
#include <vector>
#define FOR(I,A,B) for(int I= (A); I<(B); ++I)
#define REP(I,N) FOR(I,0,N)
#define ALL(A) (A).begin(), (A).end()
typedef long long int LL;
using namespace std;
typedef pair<int,int> ii;
typedef vector<ii> vii;
typedef vector<int> vi;
bool isPrime( int N )
{
if( N%2 == 0 ) return false;
for( int i=3; i*i<=N; ++i )
if( N%i == 0 )
return false;
return true;
}
int main ()
{
vector<int> primes;
primes.push_back( 2 );
for( int i=3; i<=32000; ++i )
if( isPrime( i ) )
primes.push_back( i );
vector<vector<int> > DPrimes;
int size = primes.size();
// find determinate primes
bool skip = false;
REP( i, size-2 )
{
if( skip )
{
skip = false;
continue;
}
int d = primes[i+1]-primes[i];
int c = primes[i+1];
FOR( j, i+2, size )
{
if( primes[j]-c == d )
{
c = primes[j];
}
else
{
if( c != primes[i+1] ) // found it
{
vector<int> T;
for( int k=i; k<=j-1; ++k )
T.push_back( primes[k] );
DPrimes.push_back( T );
if( T.size() == 4 ) skip = true;
}
break;
}
}
}
int x, y;
while( cin >> x >> y )
{
int a = min(x,y);
int b = max(x,y);
int size = DPrimes.size();
REP( i, size )
{
if( DPrimes[i][0] < a ) continue;
if( DPrimes[i][0] > b ) break;
if( DPrimes[i].size() == 3 )
{
if( DPrimes[i][2] <= b )
cout << DPrimes[i][0] << " " << DPrimes[i][1] << " " << DPrimes[i][2] << endl;
}
else
{
if( DPrimes[i][3] <= b )
{
//cout << DPrimes[i][1] << " " << DPrimes[i][2] << " " << DPrimes[i][3] << endl;
cout << DPrimes[i][0] << " " << DPrimes[i][1] << " " << DPrimes[i][2] << " " << DPrimes[i][3] << endl;
}
}
}
}
}
| true |
4ab8dbc5631830b0d29c6ebfefce2163a3a76c0f
|
C++
|
alexweav/BackpropFramework
|
/spike/Main.cpp
|
UTF-8
| 2,805 | 2.78125 | 3 |
[
"MIT"
] |
permissive
|
#include <iostream>
#include "Core/ExecutionContext.h"
#include "Core/IDifferentiableExecutor.h"
#include "Operations/Arithmetic.h"
#include "Operations/Value.h"
#include "Evaluation/LazyEvaluator.h"
#include "Utils/Dictionary.h"
#include "Data/Datatypes.h"
#include "Data/Initializers/Ones.h"
#include "Data/Initializers/Constant.h"
#include "Optimizers/GradientDescentOptimizer.h"
class TestExecutor: public IExecutor {
public:
DataObject operator() (const ExecutionContext& context) const {
return Scalar(100);
}
};
class TestNode: public Node {
public:
TestNode(void): Node({}) {
std::shared_ptr<TestExecutor> executor1(new TestExecutor());
std::shared_ptr<TestExecutor> executor2(new TestExecutor());
RegisterExecutor(executor1);
RegisterExecutor(executor2);
}
DataObject Forward(const ExecutionContext& context) const { }
};
int main(int argc, char** argv) {
//LazyEvaluator ev;
auto input = Input();
auto c1 = Constant(1.0);
std::cout << "not borked" << std::endl;
/*Variables vars;
std::cout << ev.EvaluateGraph(input, vars)[input->Channels(0)].ToScalar() << std::endl;
input->RegisterNewDefaultValue(Scalar(3.0));
vars[input] = Scalar(5.0);
std::cout << ev.EvaluateGraph(input, vars)[input->Channels(0)].ToScalar() << std::endl << std::endl;
auto x = std::shared_ptr<Variable>(new Variable(3.0));
ChannelDictionary res = ev.EvaluateGraph(x);
std::cout << res[x->Channels(0)] << std::endl;
auto c3 = Value(3.0);
auto c4 = Value(4.0);
res = ev.EvaluateGraph({c3, c4});
std::cout << res[c3->Channels(0)] << std::endl;
std::cout << res[c4->Channels(0)] << std::endl;
auto seven = c3 + c4;
res = ev.EvaluateGraph(seven);
std::cout << res[seven->Channels(0)] << std::endl;
auto x_squared = x * x;
LegacyEvaluator eval;
std::cout << ev.EvaluateGraph(x_squared)[x_squared->Channels(0)] << std::endl;
GradientDescentOptimizer optimizer(0.25);
int i;
auto grads = eval.BackwardEvaluate(x_squared, vars);
for (i = 0; i < 10; i++) {
grads = eval.BackwardEvaluate(x_squared, vars);
std::cout << "grad: " << grads[x->Channels(0)] << std::endl;
x->Update(optimizer, grads[x->Channels(0)]);
std::cout << eval.EvaluateGraph(x_squared)[x_squared->Channels(0)] << std::endl;
}
std::cout << std::endl;
auto y = Var();
auto z = Var();
auto inter1 = y * c3;
auto out1 = inter1 + z;
auto out2 = inter1 - z;
vars[y] = Scalar(2.0);
vars[z] = Scalar(1.0);
auto results = ev.EvaluateGraph({out1, out2}, vars);
std::cout << "out1: " << results[out1->Channels(0)] << std::endl;
std::cout << "out2: " << results[out2->Channels(0)] << std::endl;
return 0;*/
}
| true |
c4e18b9b722f9857bff90251b5d676db430e6307
|
C++
|
maxbader/transitbuddy
|
/transitbuddy_human_publisher/include/mpedplus/CellDefinition.h
|
UTF-8
| 1,005 | 2.734375 | 3 |
[
"BSD-2-Clause"
] |
permissive
|
#pragma once
#include <string>
#include <vector>
using namespace std;
namespace mped {
class CellDefinition {
private:
long id;
long rows;
long columns;
double width;
double height;
vector<double> origin;
public:
__declspec(dllexport) CellDefinition();
__declspec(dllexport) ~CellDefinition(void);
__declspec(dllexport) long getId();
__declspec(dllexport) void setId( const long& id);
__declspec(dllexport) long getRows();
__declspec(dllexport) void setRows( const long& rows);
__declspec(dllexport) long getColumns();
__declspec(dllexport) void setColumns( const long& columns);
__declspec(dllexport) double getWidth();
__declspec(dllexport) void setWidth( const double& width);
__declspec(dllexport) double getHeight();
__declspec(dllexport) void setHeight( const double& height);
__declspec(dllexport) vector<double> getOrigin();
__declspec(dllexport) void setOrigin( const vector<double>& origin);
};
}
| true |
ec1f474709276c90fe4df629bb0906fd94ccb9da
|
C++
|
dreamsComeTrue/agaLang
|
/include/agaASTFunctionCall.h
|
UTF-8
| 1,276 | 2.84375 | 3 |
[] |
no_license
|
#ifndef _AGA_ASTFUNCTIONCALL_H_
#define _AGA_ASTFUNCTIONCALL_H_
#include <vector>
#include "agaASTNode.h"
namespace aga
{
class agaASTFunctionCall : public agaASTNode
{
public:
agaASTFunctionCall (std::shared_ptr<agaASTNode> &parentNode) : agaASTNode (FunctionCallNode, parentNode) {}
void AddParameter (std::shared_ptr<agaASTNode> node) { m_Parameters.push_back (node); }
const std::vector<std::shared_ptr<agaASTNode>> &GetParameters () { return m_Parameters; }
void SetName (const std::string &name) { m_Name = name; }
const std::string &GetName () const { return m_Name; }
virtual llvm::Value *Evaluate (agaCodeGenerator *codeGenerator);
virtual void SemanticCheck (std::shared_ptr<agaSemanticAnalyzer> analyzer) {}
virtual const std::string ToString ()
{
std::string result = "[ " + m_Name;
for (const std::shared_ptr<agaASTNode> ¶m : m_Parameters)
{
result += " " + param->ToString ();
}
result += " ]";
return result;
}
private:
std::string m_Name;
std::vector<std::shared_ptr<agaASTNode>> m_Parameters;
};
}
#endif // _AGA_ASTFUNCTIONCALL_H_
| true |
c272ca93b1caccbd6f6216e450516e76faf28664
|
C++
|
TMRGZ/Practicas-Fundamentos-de-la-Programacion-UMA
|
/Apuntes/Recursividad/RecursividadParejas.cpp
|
UTF-8
| 396 | 3.328125 | 3 |
[] |
no_license
|
#include<iostream>
using namespace std;
unsigned parejas (unsigned n){
unsigned res;
if(n<=2){
res = 1;
}else{
res = parejas(n-1)+parejas(n-2);
}
return res;
}
int main(){
unsigned n, resultado;
cout << "introduce: ";
cin >> n;
resultado = parejas (n);
cout << "Resultado: " << resultado;
return 0;
}
| true |
05bae5006127352df91e9b78d5d435591762c205
|
C++
|
Amere/CompetetiveProgramming-Problems-Library
|
/Dhaka 2015 Asia Regionals/cOUNTINGwEEKend.cpp
|
UTF-8
| 1,716 | 2.625 | 3 |
[] |
no_license
|
#include <map>
#include <set>
#include <iostream>
#include <algorithm>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <cmath>
#include <cstdio>
#include <vector>
#include <queue>
#include <stack>
#include <sstream>
#include <fstream>
#include <iomanip>
#include <bitset>
using namespace std;
int INF = 2000000000;
int mon(string m){
if (m=="JAN") {
return 31;
}
if (m=="FEB") {
return 28;
}
if (m=="MAR") {
return 31;
}
if (m=="APR") {
return 30;
}
if (m=="MAY") {
return 31;
}
if (m=="JUN") {
return 30;
}
if (m=="JUL") {
return 31;
}
if (m=="AUG") {
return 31;
}
if (m=="SEP") {
return 30;
}
if (m=="OCT") {
return 31;
}
if (m=="NOV") {
return 30;
}
if (m=="DEC") {
return 31;
}
return 0;
}
int day(string d){
if (d=="MON") {
return 1;
}
if (d=="TUE") {
return 2;
}
if (d=="WED") {
return 3;
}
if (d=="THU") {
return 4;
}
if (d=="FRI") {
return 5;
}
if (d=="SAT") {
return 6;
}
if (d=="SUN") {
return 7;
}
return 0;
}
int main() {
ios_base::sync_with_stdio(0);cin.tie(0);
int t;
cin>>t;
while (t--) {
string d,m;
cin>>m>>d;
int mo = mon(m);
int da = day(d);
int count = 0;
for (int i=0,j=da; i<mo; i++) {
if (j==8) {
j=1;
}
if (j==5 || j== 6) {
count++;
}
j++;
}
cout<<count<<endl;
}
return 0;
}
| true |
b1f37890f074341308b6ad0f1c1e383d9bb44170
|
C++
|
SignorMercurio/Gluttonous-Snake
|
/Snake.cpp
|
UTF-8
| 5,452 | 2.75 | 3 |
[] |
no_license
|
#include <bits/stdc++.h>
#include <windows.h>
#include <conio.h>
#define N 28
#define UP 72
#define DOWN 80
#define LEFT 75
#define RIGHT 77
using namespace std;
typedef struct{int x, y;}point;
point snake[400], food, next_head;//next_head pos of head
char game_map[N][N];
int head, tail;
int lv, len, interval;
char dir;
void gotoxy(int x, int y)//prevent blinking
{
HANDLE hConsoleOutput;
COORD dwCursorPosition;
dwCursorPosition.X = x;
dwCursorPosition.Y = y;
hConsoleOutput = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleCursorPosition(hConsoleOutput, dwCursorPosition);
}
inline void update(char game_map[][N], int lv, int len, int interval)
{
gotoxy(0, 0);
int i, j;
printf("\n");
for (i = 0; i < N; ++i){
printf("\t\t");
for (j = 0; j < N; ++j)
printf("%c ", game_map[i][j]);
switch(i){
case 0: printf("\tLevel: %d", lv); break;
case 4: printf("\tLength: %d", len); break;
case 8: printf("\tInterval: %3d ms", interval); break;
case 18: printf("\tPress Space to Pause");
}
printf("\n");
}
}
inline void rand_food()
{
srand(int(time(0)));
do{
food.x = rand() % 20 + 1;
food.y = rand() % 20 + 1;
}while (game_map[food.x][food.y] != ' ');
game_map[food.x][food.y] = '$';
}
inline void init()
{
int i, j;
for (i = 1; i <= N-2; ++i)
for (j = 1; j <= N-2; ++j)
game_map[i][j] = ' ';
for (i = 0; i <= N-1; ++i)
game_map[0][i] = game_map[N-1][i] = game_map[i][0] = game_map[i][N-1] = '#';
game_map[1][1] = game_map[1][2] = game_map[1][3] = game_map[1][4] = '@';
game_map[1][5] = 'Q';
head = 4; tail = 0;
snake[head].x = 1; snake[head].y = 5;
snake[tail].x = 1; snake[tail].y = 1;
snake[1].x = 1; snake[1].y = 2;
snake[2].x = 1; snake[2].y = 3;
snake[3].x = 1; snake[3].y = 4;
rand_food();
lv = 0; len = 5; interval = 400;
dir = RIGHT;
puts("\n\n\n\n\n\n\n\n\n\n\n\t\t\t\t\t\tPress Any Key");
getch();
update(game_map, lv, len, interval);
}
inline int mov()
{
bool timeover = true;
double start = (double)clock() / CLOCKS_PER_SEC; //get total time
char tmp;
here:
//wait for 1s
while ((timeover = ((double)clock() / CLOCKS_PER_SEC - start <= interval / 1000.0)) && !_kbhit());
if (timeover){
char c = getch();
if (c == ' ') {
printf("Game Paused");
while (getch() != ' ');
system("cls");
update(game_map, lv, len, interval);
}
else if ((c != UP && c != DOWN && c != LEFT && c != RIGHT) ||
(dir == UP && c == DOWN) || (dir == DOWN && c == UP) ||
(dir == LEFT && c == RIGHT) || (dir == RIGHT && c == LEFT))
goto here;
else
dir = c;
}
switch (dir){
case UP:
next_head.x = snake[head].x - 1; next_head.y = snake[head].y;
break;
case DOWN:
next_head.x = snake[head].x + 1; next_head.y = snake[head].y;
break;
case LEFT:
next_head.x = snake[head].x; next_head.y = snake[head].y - 1;
break;
case RIGHT:
next_head.x = snake[head].x; next_head.y = snake[head].y + 1;
break;
}
if ((!next_head.x || next_head.x == N-1 || !next_head.y || next_head.y == N-1) || //hit the wall
(game_map[next_head.x][next_head.y] != ' ' && !(next_head.x == food.x && next_head.y == food.y))){ //hit itself
puts("Game Over!\nReplay? y/n");
while (tolower(tmp = getchar()) != 'y' && tolower(tmp) != 'n');
if (tmp == 'y') return 2;
else return 0;
}
if (len == 100){
puts("Congratulations!\nReplay? y/n");
while (tolower(tmp = getchar()) != 'y' && tolower(tmp) != 'n');
if (tmp == 'y') return 2;
else return 0;
}
return 1;
}
inline void eating()
{
++len;
int grade = len / 5 - 1;
if (grade != lv){
lv = grade;
if (interval > 50)
interval = 400 - lv * 50;
}
game_map[next_head.x][next_head.y] = 'Q'; //change head pos
game_map[snake[head].x][snake[head].y] = '@'; //head becomes body
head = (head + 1) % 400;
snake[head].x = next_head.x;
snake[head].y = next_head.y; //change head pos
rand_food();
update(game_map, lv, len, interval);
}
inline void not_eating()
{
game_map[snake[tail].x][snake[tail].y] = ' '; //tail becomes ' '
tail = (tail + 1) % 400;
game_map[next_head.x][next_head.y] = 'Q';
game_map[snake[head].x][snake[head].y] = '@';
head = (head + 1) % 400;
snake[head].x = next_head.x;
snake[head].y = next_head.y;
update(game_map, lv, len, interval);
}
int main()
{
SetConsoleTitle("Snake");
system("color 3E");
there:
init();
while (1)
switch(mov()){
case 1:
if (next_head.x == food.x && next_head.y == food.y) eating();
else not_eating();
break;
case 2: system("cls"); goto there; break;
default: return 0;
}
return 0;
}
| true |
f222a56b5cd95ecc7cc553efd81743c81448c315
|
C++
|
Digital-Monk/OpenTESArena
|
/OpenTESArena/src/World/LevelInstance.cpp
|
UTF-8
| 3,297 | 2.71875 | 3 |
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
#include "LevelInstance.h"
#include "components/debug/Debug.h"
void LevelInstance::init()
{
this->changedVoxels.clear();
this->voxelInsts.clear();
}
Int3 LevelInstance::makeVoxelCoord(WEInt x, int y, SNInt z)
{
return Int3(x, y, z);
}
LevelInstance::ChangedVoxel *LevelInstance::findVoxel(WEInt x, int y, SNInt z)
{
const Int3 voxelCoord = LevelInstance::makeVoxelCoord(x, y, z);
for (ChangedVoxel &changedVoxel : this->changedVoxels)
{
if (changedVoxel.first == voxelCoord)
{
return &changedVoxel;
}
}
return nullptr;
}
const LevelInstance::ChangedVoxel *LevelInstance::findVoxel(WEInt x, int y, SNInt z) const
{
const Int3 voxelCoord = LevelInstance::makeVoxelCoord(x, y, z);
for (const ChangedVoxel &changedVoxel : this->changedVoxels)
{
if (changedVoxel.first == voxelCoord)
{
return &changedVoxel;
}
}
return nullptr;
}
int LevelInstance::getChangedVoxelCount() const
{
return static_cast<int>(this->changedVoxels.size());
}
const LevelInstance::ChangedVoxel &LevelInstance::getChangedVoxel(int index) const
{
DebugAssertIndex(this->changedVoxels, index);
return this->changedVoxels[index];
}
const VoxelDefinition &LevelInstance::getVoxelDef(LevelDefinition::VoxelID id,
const LevelDefinition &levelDef) const
{
const int baseVoxelDefCount = levelDef.getVoxelDefCount();
const bool useBaseVoxelDefs = id < baseVoxelDefCount;
if (useBaseVoxelDefs)
{
return levelDef.getVoxelDef(id);
}
else
{
const int index = static_cast<int>(id) - baseVoxelDefCount;
DebugAssertIndex(this->voxelDefAdditions, index);
return this->voxelDefAdditions[index];
}
}
int LevelInstance::getVoxelInstanceCount() const
{
return static_cast<int>(this->voxelInsts.size());
}
VoxelInstance &LevelInstance::getVoxelInstance(int index)
{
DebugAssertIndex(this->voxelInsts, index);
return this->voxelInsts[index];
}
LevelDefinition::VoxelID LevelInstance::getVoxel(WEInt x, int y, SNInt z,
const LevelDefinition &levelDef) const
{
const ChangedVoxel *changedVoxel = this->findVoxel(x, y, z);
return (changedVoxel != nullptr) ? changedVoxel->second : levelDef.getVoxel(x, y, z);
}
void LevelInstance::setChangedVoxel(WEInt x, int y, SNInt z, LevelDefinition::VoxelID voxelID)
{
ChangedVoxel *changedVoxel = this->findVoxel(x, y, z);
if (changedVoxel != nullptr)
{
changedVoxel->second = voxelID;
}
else
{
const Int3 voxelCoord = LevelInstance::makeVoxelCoord(x, y, z);
this->changedVoxels.push_back(std::make_pair(voxelCoord, voxelID));
}
}
LevelDefinition::VoxelID LevelInstance::addVoxelDef(const VoxelDefinition &voxelDef)
{
this->voxelDefAdditions.push_back(voxelDef);
return static_cast<LevelDefinition::VoxelID>(this->voxelDefAdditions.size() - 1);
}
void LevelInstance::update(double dt)
{
// @todo: reverse iterate over voxel instances, removing ones that are finished doing
// their animation, etc.. See LevelData::updateFadingVoxels() for reference.
// @todo: when updating adjacent chasms, add new voxel definitions to the level definition
// if necessary. It's okay to mutate the level def because new chasm permutations aren't
// really "instance data" -- they belong in the level def in the first place.
/*for (VoxelInstance &voxelInst : this->voxelInsts)
{
voxelInst.update(dt);
}*/
DebugNotImplemented();
}
| true |