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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
da248a918585678883dd3c8f3b72a0b58675ebd1 | C++ | ardiprasetia/dw | /3.cpp | UTF-8 | 1,370 | 3.09375 | 3 | [] | no_license | #include <iostream>
using namespace std;
void bentukPersegi (int panjang_persegi){
int i,j;
double r = 2.0;
cout << "Hasil bentuk persegi dari panjang persegi (bilangan ganjil), " << panjang_persegi << " adalah : ";
//cin >> panjang_persegi;
cout << endl;
if (panjang_persegi % 2 == 1){
for(i=1;i<=panjang_persegi;i++) {
for(j=1;j<=panjang_persegi;j++) {
if (j == panjang_persegi/r + 0.5 ){
cout << "* ";
}
else if(i == panjang_persegi/r + 0.5 ){
cout << "* ";
}
else if (j == panjang_persegi and i == panjang_persegi){
cout << "* ";
}
else if (j == panjang_persegi and i == 1){
cout << "* ";
}
else if (j == 1 and i == panjang_persegi){
cout << "* ";
}
else if (j == 1 and i == 1){
cout << "* ";
}
else{
cout << "= ";
}
}
cout << endl;
}
}
else{
cout << "Input Bilangan Ganjil dengan benar! \n\n";
}
}
int main()
{
cout << "## Program C++ Bentuk Persegi dari Bintang(*) dan sama dengan(=) ##" << endl;
cout << "=======================================================" << endl;
cout << endl;
bentukPersegi(7);
return 0;
} | true |
0379ae690e64d9ead2028cbada23e65c4c341560 | C++ | agus7803/Lab0 | /Tarea0/prog4-p4gr36/hpp/Sistema.hpp | UTF-8 | 1,457 | 2.5625 | 3 | [] | no_license | #ifndef SISTEMA_HPP
#define SISTEMA_HPP
#include <string>
#include <iostream>
#include "partida.hpp"
#include "videojuego.hpp"
#include "jugador.hpp"
#include "dataType/dtJugador.hpp"
#include "dataType/dtPartida.hpp"
#include "dataType/dtVideojuego.hpp"
using namespace std;
class Sistema {
private:
jugador** array_jugadores;
int tope_Jugadores;
videojuego** array_videojuegos;
int tope_Videojuegos;
partida** array_partidas;
int tope_Partidas;
public:
//Contructores
Sistema();
Sistema(jugador** array_jugadores, int tope_Jugadores, videojuego** array_videojuegos, int tope_Videojuegos, partida** array_partidas, int tope_Partidas);
//Get
int getTopeJugadores();
int getTopeJuegos();
int getTopePartidas();
//Seters
void setTopeJugadores(int tope_Jugadores);
void setTopeJuegos(int tope_Videojuegos);
void setTopePartidas(int tope_Partidas);
//operaciones
void agregarJugador(string nickname, int edad, string contrasenia);
void agregarVideojuego(string nombre, tipoJuego genero);
dtJugador** obtenerJugadores(int& cantJugadores);
dtVideojuego** obtenerVideojuegos(int& cantVideojuegos);
dtPartida** obtenerPartidas(string videojuego, int& cantPartidas);
void iniciarPartida(string nickname, string videojuego, dtPartida* datos);
//Destructor
~Sistema();
};
#endif | true |
7ad1c4c48422d202d7310907355a946534a558c4 | C++ | saks1209am/C-Programs | /Datatypes/main.cpp | UTF-8 | 222 | 2.859375 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
char grade= 'A';
string phrase="Giraffe Academy";
bool isMale=true;
int age=50;
double gpa=2.3;
cout<< grade <<endl;
return 0;
}
| true |
2576faaed45128587fcc27589c8829fe0037f795 | C++ | r1cebank/coding-challenge | /Helvetic Coding Contest 2016/collective-mindsets/medium.cpp | UTF-8 | 1,274 | 3.125 | 3 | [
"MIT"
] | permissive | /*
* Helvetic Coding Contest 2016, 690A1
* Status: submitted
* A1. Collective Mindsets (medium)
* Way to go! Heidi now knows how many brains there must be for her to get one. But throwing herself in the midst of a clutch of hungry zombies is quite a risky endeavor. Hence Heidi wonders: what is the smallest number of brains that must be in the chest for her to get out at all (possibly empty-handed, but alive)? *
* The brain dinner night will evolve just as in the previous subtask: the same crowd is present, the N - 1 zombies have the exact same mindset as before and Heidi is to make the first proposal, which must be accepted by at least half of the attendees for her to survive. *
* Input
* The only line of input contains one integer: N, the number of attendees (1 ≤ N ≤ 109). *
* Output
* Output one integer: the smallest number of brains in the chest which allows Heidi to merely survive.
*/
#include <iostream>
using namespace std;
int main() {
int N;
cin >> N;
if (N % 2) {
cout << N / 2 << endl;
} else {
int powerOfTwo = 1;
while (powerOfTwo <= N) {
powerOfTwo = powerOfTwo * 2;
};
cout << (N - powerOfTwo / 2) / 2 << endl;
}
return 0;
}
| true |
eba3970fec73af681a57df5b8b1c1887fa077513 | C++ | wheder/jeskynepokladu | /mi-paa/batoh_bb/overkill_tfull.cpp | UTF-8 | 3,256 | 2.6875 | 3 | [] | no_license | #include <iostream>
#include <cstdio>
#include <sstream>
#include <cstring>
#include <fstream>
#include <exception>
#include <cctype>
#include <iomanip>
#include <time.h>
#include <sys/time.h>
#include <stdlib.h>
using namespace std;
int * C = NULL;
int * M = NULL;
int pocet = 0;
int max_hmotnost = 0;
bool * max_arr = NULL;
int max_sum = 0;
int id = 0;
struct timeval t_start;
struct timeval t_konec;
double t1 = 0;
double t2 = 0;
double stavy = 0;
int spocitej(bool * temp_arr, int new_index , int M_so_far, int C_so_far) {
stavy++;
M_so_far += M[new_index];
C_so_far += C[new_index];
// if (M_so_far > max_hmotnost) return -1.0;
temp_arr[new_index] = true;
if (M_so_far <= max_hmotnost && C_so_far > max_sum) {
max_sum = C_so_far;
for (int g =0; g<pocet; g++) max_arr[g]=temp_arr[g];
}
int index = new_index+1;
while (index < pocet) {
int max = spocitej(temp_arr, index, M_so_far, C_so_far);
if (M_so_far <= max_hmotnost && max > max_sum) {
max_sum = max;
for (int g =0; g<pocet; g++) max_arr[g]=temp_arr[g];
}
index++;
}
temp_arr[new_index] = false;
if (M_so_far > max_hmotnost) {
return -1;
}
else return C_so_far;
}
int main(int argc, char *argv[])
{
int instances_count = 0;
if (argc != 3) {
cout << "usage: " <<argv[0]<< " <inputfile> <instances>" << endl;
return 1;
}
instances_count = atoi(argv[2]);
ifstream inf;
inf.open( argv[1], ios::in );
if ( !inf.good () ) {
cerr << "Chyba cteni z '" << argv[1] << "'." << endl;
return 2;
}
else {
//cout << "Oteviram soubor '" << argv[1] << "' ke cteni." << endl;
}
for (int inst=0; inst < instances_count; ++inst) {
pocet = 0;
max_hmotnost = 0;
max_sum = 0;
id = 0;
inf>>id;
if (!inf.good()) return 7;
inf>>pocet;
if (!inf.good()) return 6;
inf>>max_hmotnost;
if (!inf.good()) return 5;
C = new int[pocet]; // cost
M = new int[pocet]; // objem
for ( int i=0 ; i<pocet ; i++ ) {
inf>>M[i];
if (!inf.good()) return 4;
inf>>C[i];
if (!inf.good()) return 3;
}
max_arr = new bool[pocet];
for (int d = 0; d< pocet; ++d) max_arr[d] = false;
gettimeofday(&t_start, NULL);
for (int f=0;f<pocet;f++) {
bool * temp_arr = new bool[pocet];
for (int bb = 0; bb < pocet; ++bb) temp_arr[bb] = false;
spocitej(temp_arr, f , 0, 0);
delete [] temp_arr;
}
gettimeofday(&t_konec, NULL);
t1=t_start.tv_sec+(t_start.tv_usec/1000000.0);
t2=t_konec.tv_sec+(t_konec.tv_usec/1000000.0);
printf("%d %d %d ",id, pocet, max_sum);
for ( int q = 0; q< pocet; q++) {
printf(" %d", (int)max_arr[q]);
}
printf(" --- %.12f", t2-t1);
printf(" %f", stavy);
delete [] C;
delete [] M;
delete [] max_arr;
printf("\n");
}
inf.close();
}
| true |
41af2a2f79008a07b60456c3ec95b89b927f667f | C++ | XingGaoY/computer_graphics | /光线追踪/SphereTex.h | UTF-8 | 949 | 2.5625 | 3 | [] | no_license | //CLASS_TextureSphere
#ifndef _TEXSPHERE
#define _TEXSPHERE 1
#define M_PI 3.14159265358979323846
#include "Surface.h"
#include "Ray.h"
class TexSphere:public Surface
{
public:
Vector3 centre;
float radii;
TexSphere():Surface(){};
TexSphere(Vector3 centre1,float radii1,Vector3 DR,Vector3 SR,Vector3 AR,int RSP,Vector3 DT,Vector3 ST,int TSR,Vector3 IR,Vector3 IT,bool Trancparent,Texture* tex);
TexSphere(const TexSphere& sphere){*this = sphere;}
void Setoutnorm(hitrecord& rec);
bool Gethitpoint(const Ray& ray,float tmin,float tmax,hitrecord& record)const;
bool Shadowhit(const Ray& ray,float tmin,float tmax)const;
};
inline TexSphere::TexSphere( Vector3 centre1, float radii1, Vector3 DR, Vector3 SRC, Vector3 AR,int RSP,
Vector3 DT, Vector3 ST, int TSP, Vector3 IR, Vector3 IT, bool transparent,Texture* tex):Surface(transparent, DR, SRC, AR, RSP, DT, ST, TSP, IR, IT,tex)
{
centre = centre1;
radii = radii1;
}
#endif | true |
29b407f7a0ff7127fa68c4c7bbf555223335d81a | C++ | avinashw50w/ds_algo | /Dynamic programming/DP on trees/directi2.cpp | UTF-8 | 1,184 | 3.59375 | 4 | [] | no_license | /*A tree is given in which each edge is having some weight associated with it and you are given a number K.
So starting from root in K-steps how much maximum weight you can collect.
You can traverse in any direction either from parent to child or child to parent.
You can visit a node multiple times.
Eg:
O
5/ \ 6
O O
24/ 1/ \11
For K=1, ans=6
For K=2, ans=29 etc..*/
#include <bits/stdc++.h>
using namespace std;
#define MAX_N 50
int root;
int weight[MAX_N]; // weight of each node
vector <int> g[MAX_N]; // adjacency list
int dp[MAX_N][MAX_N]; // initialized with -1
int solve(int u, int jumps) {
if (jumps == 0)
return weight[u];
if (dp[u][jumps] == -1) {
dp[u][jumps] = weight[u];
for (int v : g[u])
dp[u][jumps] = max(dp[u][jumps], weight[u] + solve(v, jumps - 1));
}
return dp[u][jumps];
}
void add(int x, int y) {
g[x].push_back(y);
g[y].push_back(x);
}
int main() {
add(0, 1); add(0, 2); add(1, 3); add(2, 4); add(2, 5);
weight[0] = 0;
weight[1] = 5;
weight[2] = 6;
weight[3] = 8;
weight[4] = 10;
weight[5] = 11;
memset(dp, -1, sizeof(dp));
cout << solve(0, 3);
} | true |
6d2f859f53f79a4575f185876de689b02141505a | C++ | MaapleWaafles/PhysicsEngine2D | /dependencies/Matrix4.h | UTF-8 | 1,677 | 3.421875 | 3 | [] | no_license | #pragma once
//Included Vector4 to use its properties
#include "Vector4.h"
class Matrix4
{
public:
// Creating a union to allocate one large amount of memory
union {
//Struct is held within the union axis array of 4 x points, 4 y points, 4 z points and 4 w points
struct
{
//axis array holding the points
float axis[16];
};
//Vector4 Type axis array holding 3D Points
Vector4 axisV4[4];
};
//Matrix4 Constructor
Matrix4();
//Matrix4 Copy Constructor Holding the x, y and z positions to be passed into
Matrix4(float ax, float ay, float az, float aw, float bx, float by, float bz, float bw, float cx, float cy, float cz, float cw, float dx, float dy, float dz, float dw);
//Matrix4 Copy Constructor that references back of Matrix4 type
Matrix4(const Matrix4& other);
//Matrix4 Deconstructor
~Matrix4();
//Matrix4 Functions that holds the identity Matrix, Transformation Matrix, Transpose of the Matrix, Matrix by Matrix Function and Vector4 = Vector4 Type
Matrix4 Identity();
Matrix4 Transpose();
Matrix4& operator = (const Matrix4& m_matrix);
Matrix4 operator *(const Matrix4& a_matrix) const;
Vector4 operator *(const Vector4& a_vector) const;
//Matrix4 Operators for Finding the index within an array and an explicit operator which uses constructor with single parameter
//setRotate Functions for X, Y and Z and Rotate for X, Y and Z
Vector4& operator [] (int index);
explicit operator float* ();
void setRotateX(float radians);
void setRotateY(float radians);
void setRotateZ(float radians);
void rotateX(float radians);
void rotateY(float radians);
void rotateZ(float radians);
};
| true |
92086f7ab5301900b3aecbfbad0db61a51165354 | C++ | Austin-M1/2500-MTRN | /Assignment 2 V3.0/RectPrism.cpp | UTF-8 | 2,184 | 2.625 | 3 | [] | no_license | #ifdef __APPLE__
#include <OpenGL/gl.h>
#elif defined(WIN32)
#include <Windows.h>
#include <GL/gl.h>
#include <GL/glut.h>
#else
#include <GL/glut.h>
#endif
#include "Shape.hpp"
#include "RectPrism.hpp"
RectPrism::RectPrism(double x_length, double y_length, double z_length)
{
X_length = x_length;
Y_length = y_length;
Z_length = z_length;
}
void RectPrism::draw()
{
glPushMatrix();
setColorInGL();
positionInGL();
// Draw Rect prism top face
glBegin(GL_QUADS);
glVertex3f(X_length / 2.0, Y_length, Z_length / 2.0);
glVertex3f(X_length / 2.0, Y_length, -Z_length / 2.0);
glVertex3f(-X_length / 2.0, Y_length, -Z_length / 2.0);
glVertex3f(-X_length / 2.0, Y_length, Z_length / 2.0);
glEnd();
//Draw Rect prism bottom face
glBegin(GL_QUADS);
glVertex3f(X_length / 2.0, 0.0, Z_length / 2.0);
glVertex3f(X_length / 2.0, 0.0, -Z_length / 2.0);
glVertex3f(-X_length / 2.0, 0.0, -Z_length / 2.0);
glVertex3f(-X_length / 2.0, 0.0, Z_length / 2.0);
glEnd();
//Draw Rect prism back face
glBegin(GL_QUADS);
glVertex3f(X_length / 2.0, Y_length, Z_length / 2.0);
glVertex3f(X_length / 2.0, Y_length, -Z_length / 2.0);
glVertex3f(X_length / 2.0, 0.0, -Z_length / 2.0);
glVertex3f(X_length / 2.0, 0.0, Z_length / 2.0);
glEnd();
//Draw Rect prism front face
glBegin(GL_QUADS);
glVertex3f(-X_length / 2.0, Y_length, Z_length / 2.0);
glVertex3f(-X_length / 2.0, Y_length, -Z_length / 2.0);
glVertex3f(-X_length / 2.0, 0.0, -Z_length / 2.0);
glVertex3f(-X_length / 2.0, 0.0, Z_length / 2.0);
glEnd();
//Draw Rect prism left face
glBegin(GL_QUADS);
glVertex3f(X_length / 2.0, Y_length, Z_length / 2.0);
glVertex3f(X_length / 2.0, 0.0, Z_length / 2.0);
glVertex3f(-X_length / 2.0, 0.0, Z_length / 2.0);
glVertex3f(-X_length / 2.0, Y_length, Z_length / 2.0);
glEnd();
//Draw Rect prism right face
glBegin(GL_QUADS);
glVertex3f(X_length / 2.0, Y_length, -Z_length / 2.0);
glVertex3f(X_length / 2.0, 0.0, -Z_length / 2.0);
glVertex3f(-X_length / 2.0, 0.0, -Z_length / 2.0);
glVertex3f(-X_length / 2.0, Y_length, -Z_length / 2.0);
glEnd();
glPopMatrix();
glFlush();
}
| true |
61a1f5df55996366fdfe6ad287adcffdc69d0985 | C++ | ragebiswas/algorepo | /practice/mergesort.cpp | UTF-8 | 1,252 | 3.46875 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <cassert>
#include <algorithm>
using namespace std;
void print(int i)
{
cout<<i<<" ";
}
void merge(vector<int>& v, int l, int m, int r)
{
vector<int> buf1(v.begin() + l, v.begin() + m + 1);
vector<int> buf2(v.begin() + m + 1, v.begin() + r + 1);
int buf1ptr = 0, buf2ptr = 0;
int p = l;
while(buf1ptr < buf1.size() && buf2ptr < buf2.size())
{
if(buf1[buf1ptr] < buf2[buf2ptr])
{
v[p++] = buf1[buf1ptr++];
}
else
{
v[p++] = buf2[buf2ptr++];
}
}
if(buf1ptr < buf1.size())
{
while(buf1ptr < buf1.size())
{
v[p++] = buf1[buf1ptr++];
}
}
if(buf2ptr < buf2.size())
{
while(buf2ptr < buf2.size())
{
v[p++] = buf2[buf2ptr++];
}
}
}
void mergesort(vector<int>& v, int l, int r)
{
if(l >= r)
return;
int m = (l+r)/2;
mergesort(v, l, m);
mergesort(v, m+1, r);
merge(v, l, m, r);
}
int main()
{
int arr[] = { 3, 2, 1, 0, 9, 8, 3, 4, 12, -2 };
vector<int> v(arr, arr+10);
cout<<"Sorting: ";
for_each(v.begin(), v.end(), print);
cout<<endl;
mergesort(v, 0, v.size()-1);
cout<<"Sorted : ";
for_each(v.begin(), v.end(), print);
cout<<endl;
return 0;
}
| true |
8f4680aae7221c53a0e4eafe2007eb57c2344cc2 | C++ | DrStrangelove42/DreamOfaRidiculousMan | /Source/Characters/Monsters/Skeleton.h | UTF-8 | 448 | 2.765625 | 3 | [
"MIT"
] | permissive | #ifndef SKELETON_H
#define SKELETON_H
#include "../Monster.h"
/// <summary>
/// A Skeleton is a type of Monster. These will always have the same characteristics.
/// </summary>
class Skeleton : public Monster
{
protected:
public:
/// <summary>
///
/// </summary>
/// <param name="renderer"></param>
/// <param name="p"></param>
/// <param name="r"></param>
Skeleton(RenderContext& renderer, Player& p, Room* r);
~Skeleton();
};
#endif
| true |
de1fcdf7c0b7fda9be13d2074c5b8479ba1022ee | C++ | frankxiaoq/praticeMethod | /algPratice/main.cpp | UTF-8 | 400 | 2.78125 | 3 | [] | no_license | #include "SortMethod.h"
#include "PraticeMethod.h"
int main(int argc, char **argv)
{
int arr[] = {-1, 3 -4, 1, 6};
int arr_sum = maxSumSubArr3(arr, 5);
cout << arr_sum << endl;
int aa(0);
int *pta = &aa;
int &rfa = aa;
double bb(0.0);
double *ptb = &bb;
double &rfb = bb;
cout << sizeof(pta) << " " << sizeof(ptb) << endl;
cout << sizeof(rfa) << " " << sizeof(rfb) << endl;
return 0;
} | true |
192bf45c43aa03b9c2fd62306b45d649b14e2596 | C++ | PythonCodes1/Competitive-programming | /LeetCode/May LeetCode Challenge/C++/9 - Valid Perfect Square.cpp | UTF-8 | 524 | 3.015625 | 3 | [] | no_license | class Solution {
public:
bool isPerfectSquare(int num) {
int ld = num%10;
if(ld == 2 || ld == 3 || ld == 7 || ld == 8)
return false;
int l = 1;
int r = num;
while(l <= r){
long long int mid = l + (r-l)/2;
long long int sq = mid*mid;
if(sq == num)
return true;
else if (sq < num)
l = mid + 1;
else
r = mid - 1;
}
return false;
}
};
| true |
c64f396f761e998072daa3654dff7fb242f6f2f5 | C++ | kunalmittal51/cppcodes | /codechef_long/april_long.cpp | UTF-8 | 743 | 3.15625 | 3 | [] | no_license | #include<iostream>
#include<vector>
using namespace std;
int min (int i , int j)
{
if ( i < j)
{
return i;
}
else return j;
}
int main()
{
int n;
cin>>n;
vector<int>c;
vector<int>t;
for ( int i = 0 ; i < n ; i++)
{
int j ;
cin>>j;
c.push_back(j);
}
for ( int i = 0 ; i < n ; i++)
{
int j ;
cin>>j;
t.push_back(j);
}
int min1 = 10000000;
int min2 = 10000000;
int min3 = 10000000;
for ( int i = 0 ; i < n ; i++)
{
if ( t[i] == 1 && min1 > c[i])
{
min1 = c[i];
}
else if ( t[i] == 2 && min2 > c[i])
{
min2 = c[i];
}
else if ( t[i] == 3 && min3 > c[i])
{
min3 = c[i];
}
}
int ans = min(min1+min2,min3);
cout<<ans<<endl;
return 0;
}
| true |
ce79931a677a3542e5bd240750a91dac4fd2ab0b | C++ | enrondata/microsoft-pst-sdk | /sourceCode/fairport/branch/ankopp/pstsdk/util/util.h | UTF-8 | 12,777 | 2.59375 | 3 | [
"Apache-2.0"
] | permissive | //! \file
//! \brief General utility functions and classes
//! \author Terry Mahaffey
//!
//! This is where any generalized utility classes and functions go which
//! are not directly related to MS-PST in some fashion. It is my hope that
//! this file stay as small as possible.
//! \ingroup util
#ifndef PSTSDK_UTIL_UTIL_H
#define PSTSDK_UTIL_UTIL_H
#include <cstdio>
#include <time.h>
#include <memory>
#include <vector>
#include <cassert>
#include <boost/utility.hpp>
#include "pstsdk/util/errors.h"
#include "pstsdk/util/primitives.h"
// Compile with _SINGLE_THREADED defined if running on non-windows platform and
// link time dependency on boost not preferred. But this will make pst library not thread safe.
// #define _SINGLE_THREADED
#if defined (_WIN32)
#define _WINDOWS_PLATFORM
#endif
#if defined (_WINDOWS_PLATFORM)
#include <Windows.h>
typedef CRITICAL_SECTION windows_cs;
#elif !defined (_SINGLE_THREADED)
#include <boost/thread/locks.hpp>
#include <boost/thread/recursive_mutex.hpp>
typedef boost::recursive_mutex boost_mutex;
#endif
namespace pstsdk
{
//! \brief A generic class to read and write to a file
//!
//! This was necessary to get around the 32 bit limit (4GB) file size
//! limitation in ANSI C++. I needed to use compiler specific work arounds,
//! and that logic is centralized here.
//! \ingroup util
class file : private boost::noncopyable
{
public:
//! \brief Construct a file object from the given filename
//! \throw runtime_error if an error occurs opening the file
//! \param[in] filename The file to open
file(const std::wstring& filename);
//! \brief Close the file
~file();
//! \brief Read from the file
//! \throw out_of_range if the requested location or location+size is past EOF
//! \param[in,out] buffer The buffer to store the data in. The size of this vector is the amount of data to read.
//! \param[in] offset The location on disk to read the data from.
//! \returns The amount of data read
size_t read(std::vector<byte>& buffer, ulonglong offset) const;
//! \cond write_api
//! \brief Write to the file
//! \throw out_of_range if the requested location or location+size is past EOF
//! \param[in] buffer The data to write. The size of this vector is the amount of data to write.
//! \param[in] offset The location on disk to read the data from.
//! \returns The amount of data written
size_t write(const std::vector<byte>& buffer, ulonglong offset);
private:
std::wstring m_filename; //!< The filename used to open this file
FILE * m_pfile; //!< The file pointer
};
//! \brief Class to abstact platform specific mutex variable types
class lock_var : boost::noncopyable
{
public:
#if defined (_WINDOWS_PLATFORM)
windows_cs win_cs;
lock_var(const lock_var&) { }
lock_var() { win_cs.DebugInfo = NULL; }
#elif !defined (_SINGLE_THREADED)
boost_mutex bst_mutex;
lock_var() { }
lock_var(const lock_var&) { }
#endif
};
//! \brief Global lock variable for thread safety
static lock_var g_lock_var;
//! \brief A generic class to manage thread safety
class thread_lock
{
public:
//! \brief C'tor global lock
thread_lock(bool make_scoped = true);
//! \brief C'tor local lock
thread_lock(pstsdk::lock_var* plck_var, bool make_scoped = true);
//! \brief D'tor
~thread_lock();
//! \brief Waits to get ownership of thread
void aquire_lock();
//! \brief Releases ownership of thread. When using non scoped lock,
//! user is responsible for explicitly releasing aquired lock.
void release_lock();
//! \brief Initializes mutex/critical section
void initialize_lock();
private:
lock_var* m_plock_var;
bool is_scoped;
#if defined (_WINDOWS_PLATFORM)
bool is_owner;
#elif !defined (_SINGLE_THREADED)
boost::unique_lock<boost_mutex> m_bstlock;
#endif
};
//! \endcond
//! \brief Convert from a filetime to time_t
//!
//! FILETIME is a Win32 date/time type representing the number of 100 ns
//! intervals since Jan 1st, 1601. This function converts it to a standard
//! time_t.
//! \param[in] filetime The time to convert from
//! \returns filetime, as a time_t.
//! \ingroup util
time_t filetime_to_time_t(ulonglong filetime);
//! \brief Convert from a time_t to filetime
//!
//! FILETIME is a Win32 date/time type representing the number of 100 ns
//! intervals since Jan 1st, 1601. This function converts to it from a
//! standard time_t.
//! \param[in] time The time to convert from
//! \returns time, as a filetime.
//! \ingroup util
ulonglong time_t_to_filetime(time_t time);
//! \brief Convert from a VT_DATE to a time_t
//!
//! VT_DATE is an OLE date/time type where the integer part is the date and
//! the fraction part is the time. This function converts it to a standard
//! time_t
//! \param[in] vt_time The time to convert from
//! \returns vt_time, as a time_t
//! \ingroup util
time_t vt_date_to_time_t(double vt_time);
//! \brief Convert from a time_t to a VT_DATE
//!
//! VT_DATE is an OLE date/time type where the integer part is the date and
//! the fraction part is the time. This function converts to it from a
//! standard time_t.
//! \param[in] time The time to convert from
//! \returns time, as a VT_DATE
//! \ingroup util
double time_t_to_vt_date(time_t time);
//! \brief Test to see if the specified bit in the buffer is set
//! \param[in] pbytes The buffer to check
//! \param[in] bit Which bit to test
//! \returns true if the specified bit is set, false if not
//! \ingroup util
bool test_bit(const byte* pbytes, ulong bit);
//! \brief Convert an array of bytes to a std::wstring
//! \param[in] bytes The bytes to convert
//! \returns A std::wstring
//! \ingroup util
std::wstring bytes_to_wstring(const std::vector<byte> &bytes);
//! \brief Convert a std::wstring to an array of bytes
//! \param[in] wstr The std::wstring to convert
//! \returns An array of bytes
//! \ingroup util
std::vector<byte> wstring_to_bytes(const std::wstring &wstr);
} // end pstsdk namespace
//! \cond write_api
inline pstsdk::thread_lock::thread_lock(bool make_scoped) : m_plock_var(&g_lock_var), is_scoped(make_scoped)
{
initialize_lock();
}
inline pstsdk::thread_lock::thread_lock(pstsdk::lock_var* plck_var, bool make_scoped) : m_plock_var(plck_var), is_scoped(make_scoped)
{
initialize_lock();
}
inline void pstsdk::thread_lock::initialize_lock()
{
#if defined (_WINDOWS_PLATFORM)
is_owner = false;
if(m_plock_var->win_cs.DebugInfo == NULL)
InitializeCriticalSection(&m_plock_var->win_cs);
#elif !defined (_SINGLE_THREADED)
m_bstlock = boost::unique_lock<boost_mutex>(m_plock_var->bst_mutex, boost::defer_lock);
#endif
}
inline pstsdk::thread_lock::~thread_lock()
{
#if defined (_WINDOWS_PLATFORM)
if(is_owner && is_scoped)
LeaveCriticalSection(&m_plock_var->win_cs);
#elif !defined (_SINGLE_THREADED)
if(m_bstlock.owns_lock() && is_scoped)
m_bstlock.unlock();
#endif
}
inline void pstsdk::thread_lock::aquire_lock()
{
#if defined (_WINDOWS_PLATFORM)
EnterCriticalSection(&m_plock_var->win_cs);
is_owner = true;
#elif !defined (_SINGLE_THREADED)
if(!m_bstlock.owns_lock())
m_bstlock.lock();
#endif
}
inline void pstsdk::thread_lock::release_lock()
{
#if defined (_WINDOWS_PLATFORM)
if(is_owner || !is_scoped)
{
is_owner = false;
LeaveCriticalSection(&m_plock_var->win_cs);
}
#elif !defined (_SINGLE_THREADED)
if(m_bstlock.owns_lock() || !is_scoped)
m_bstlock.unlock();
#endif
}
//! \endcond
inline pstsdk::file::file(const std::wstring& filename)
: m_filename(filename)
{
const char* mode = "r+b";
#ifdef _MSC_VER
errno_t err = fopen_s(&m_pfile, std::string(filename.begin(), filename.end()).c_str(), mode);
if(err != 0)
m_pfile = NULL;
#else
m_pfile = fopen(std::string(filename.begin(), filename.end()).c_str(), mode);
#endif
if(m_pfile == NULL)
throw std::runtime_error("fopen failed");
}
inline pstsdk::file::~file()
{
fflush(m_pfile);
fclose(m_pfile);
}
inline size_t pstsdk::file::read(std::vector<byte>& buffer, ulonglong offset) const
{
#ifdef _MSC_VER
if(_fseeki64(m_pfile, offset, SEEK_SET) != 0)
#else
if(fseek(m_pfile, offset, SEEK_SET) != 0)
#endif
{
throw std::out_of_range("fseek failed");
}
size_t read = fread(&buffer[0], 1, buffer.size(), m_pfile);
if(read != buffer.size())
throw std::out_of_range("fread failed");
return read;
}
//! \cond write_api
inline size_t pstsdk::file::write(const std::vector<byte>& buffer, ulonglong offset)
{
#ifdef _MSC_VER
if(_fseeki64(m_pfile, offset, SEEK_SET) != 0)
#else
if(fseek(m_pfile, offset, SEEK_SET) != 0)
#endif
{
throw std::out_of_range("fseek failed");
}
size_t write = fwrite(&buffer[0], 1, buffer.size(), m_pfile);
if(write != buffer.size())
throw std::out_of_range("fwrite failed");
return write;
}
//! \endcond
inline time_t pstsdk::filetime_to_time_t(ulonglong filetime)
{
const ulonglong jan1970 = 116444736000000000ULL;
return (filetime - jan1970) / 10000000;
}
inline pstsdk::ulonglong pstsdk::time_t_to_filetime(time_t time)
{
const ulonglong jan1970 = 116444736000000000ULL;
return (time * 10000000) + jan1970;
}
inline time_t pstsdk::vt_date_to_time_t(double)
{
throw not_implemented("vt_date_to_time_t");
}
inline double pstsdk::time_t_to_vt_date(time_t)
{
throw not_implemented("vt_date_to_time_t");
}
inline bool pstsdk::test_bit(const byte* pbytes, ulong bit)
{
return (*(pbytes + (bit >> 3)) & (0x80 >> (bit & 7))) != 0;
}
#if defined(_WIN32) || defined(__MINGW32__)
// We know that std::wstring is always UCS-2LE on Windows.
inline std::wstring pstsdk::bytes_to_wstring(const std::vector<byte> &bytes)
{
if(bytes.size() == 0)
return std::wstring();
return std::wstring(reinterpret_cast<const wchar_t *>(&bytes[0]), bytes.size()/sizeof(wchar_t));
}
inline std::vector<pstsdk::byte> pstsdk::wstring_to_bytes(const std::wstring &wstr)
{
if(wstr.size() == 0)
return std::vector<byte>();
const byte *begin = reinterpret_cast<const byte *>(&wstr[0]);
return std::vector<byte>(begin, begin + wstr.size()*sizeof(wchar_t));
}
#else // !(defined(_WIN32) || defined(__MINGW32__))
// We're going to have to do this the hard way, since we don't know how
// big wchar_t really is, or what encoding it uses.
#include <iconv.h>
inline std::wstring pstsdk::bytes_to_wstring(const std::vector<byte> &bytes)
{
if(bytes.size() == 0)
return std::wstring();
// Up to one wchar_t for every 2 bytes, if there are no surrogate pairs.
if(bytes.size() % 2 != 0)
throw std::runtime_error("Cannot interpret odd number of bytes as UTF-16LE");
std::wstring out(bytes.size() / 2, L'\0');
iconv_t cd(::iconv_open("WCHAR_T", "UTF-16LE"));
if(cd == (iconv_t)(-1)) {
perror("bytes_to_wstring");
throw std::runtime_error("Unable to convert from UTF-16LE to wstring");
}
const char *inbuf = reinterpret_cast<const char *>(&bytes[0]);
size_t inbytesleft = bytes.size();
char *outbuf = reinterpret_cast<char *>(&out[0]);
size_t outbytesleft = out.size() * sizeof(wchar_t);
size_t result = ::iconv(cd, const_cast<char **>(&inbuf), &inbytesleft, &outbuf, &outbytesleft);
::iconv_close(cd);
if(result == (size_t)(-1) || inbytesleft > 0 || outbytesleft % sizeof(wchar_t) != 0)
throw std::runtime_error("Failed to convert from UTF-16LE to wstring");
out.resize(out.size() - (outbytesleft / sizeof(wchar_t)));
return out;
}
inline std::vector<pstsdk::byte> pstsdk::wstring_to_bytes(const std::wstring &wstr)
{
if(wstr.size() == 0)
return std::vector<byte>();
// Up to 4 bytes per character if all codepoints are surrogate pairs.
std::vector<byte> out(wstr.size() * 4);
iconv_t cd(::iconv_open("UTF-16LE", "WCHAR_T"));
if(cd == (iconv_t)(-1)) {
perror("wstring_to_bytes");
throw std::runtime_error("Unable to convert from wstring to UTF-16LE");
}
const char *inbuf = reinterpret_cast<const char *>(&wstr[0]);
size_t inbytesleft = wstr.size() * sizeof(wchar_t);
char *outbuf = reinterpret_cast<char *>(&out[0]);
size_t outbytesleft = out.size();
size_t result = ::iconv(cd, const_cast<char **>(&inbuf), &inbytesleft, &outbuf, &outbytesleft);
::iconv_close(cd);
if(result == (size_t)(-1) || inbytesleft > 0)
throw std::runtime_error("Failed to convert from wstring to UTF-16LE");
out.resize(out.size() - outbytesleft);
return out;
}
#endif // !(defined(_WIN32) || defined(__MINGW32__))
#endif
| true |
9cdc7082073b98af880a92312b2501bca1e23fb5 | C++ | atompacman/Xerof | /src/civ/human/RangeOfSight.cpp | UTF-8 | 5,007 | 3.015625 | 3 | [] | no_license | #include <iosfwd>
#include <FatalErrorDialog.h>
#include <RangeOfSight.h>
const std::string ERR_MSG("Invalid range of sight model file format: ");
//= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = //
// CONSTRUCTOR/DESTRUCTOR //
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - //
RangeOfSight::RangeOfSight(std::ifstream& i_ROSFile) :
m_StraigthWin(i_ROSFile),
m_DiagonalWin(i_ROSFile)
{}
RangeOfSight::Window::Window(std::ifstream& io_File) :
Array2D<bool>(),
m_ULCorner(),
m_LRCorner()
{
std::string line;
// Skip comments and blank lines
while (io_File.peek() != '.') {
getline(io_File, line);
}
// Save position before reading
unsigned int pos(io_File.tellg());
// Read model size
findWindowCorners(io_File);
// Resize 2D boolean array
clearAndResize(toCoord(m_LRCorner - m_ULCorner));
// Return to beginning of model
io_File.seekg(pos);
// Read model
readWindow(io_File);
}
void RangeOfSight::Window::findWindowCorners(std::ifstream& io_File)
{
SCoord center(0, 0);
SCoord dim(0, 0);
std::string line;
while (io_File.peek() != '#' && !io_File.eof()) {
getline(io_File, line);
if (line.empty()) {
break;
}
if (line.length() % 2 == 0) {
FatalErrorDialog(ERR_MSG + "pair number of characters in a line");
}
unsigned int len((line.length() + 1) * 0.5);
if (dim.x == 0) {
dim.x = len;
}
else if (dim.x != len) {
FatalErrorDialog(ERR_MSG + "inconsitant line lengths");
}
int pos(line.find('^'));
if (pos != -1) {
center = SCoord((pos + 1) * 0.5, dim.y);
}
else {
pos = line.find('7');
if (pos != -1) {
center = SCoord((pos + 1) * 0.5, dim.y);
}
}
++dim.y;
}
if (center == SCoord(0, 0)) {
FatalErrorDialog(ERR_MSG + "no character position indicator");
}
m_ULCorner = center * -1;
m_LRCorner = m_ULCorner + dim;
}
void RangeOfSight::Window::readWindow(std::ifstream& io_File)
{
char c(0);
for (unsigned int y(0); y < m_Dim.y; ++y) {
for (unsigned int x(0); x < m_Dim.x; ++x) {
io_File >> c;
switch (c) {
case '.':
operator()(x,y) = false;
break;
case 'X': case '^': case '7':
operator()(x, y) = true;
break;
case '\n': case '\r': case '\0':
continue;
default:
FatalErrorDialog(ERR_MSG + "invalid character");
}
}
}
io_File.read(&c, 1);
}
//= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = //
// IS VISIBLE //
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - //
bool RangeOfSight::isVisible(SCoord i_Coord, Direction i_Direction) const
{
// Rotate coordinate according to direction
assertNonCenterDir(i_Direction);
i_Coord = rotateCoord(i_Coord, i_Direction % 4);
// Select appropriate window
const Window& win(isDiagonal(i_Direction) ? m_DiagonalWin : m_StraigthWin);
// De-center coordinate
Coord decentered(toCoord(i_Coord - win.m_ULCorner));
// Check if rotated coord is within window range
if (!(decentered < win.dimensions())) {
return false;
}
return win(decentered);
}
//= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = //
// GETTERS //
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - //
SCoord RangeOfSight::getWindowULCorner(Direction i_Direction) const
{
// Select appropriate window
assertNonCenterDir(i_Direction);
const Window& win(isDiagonal(i_Direction) ? m_DiagonalWin : m_StraigthWin);
switch (i_Direction % 4) {
case UP : return win.m_ULCorner;
case RIGHT: return SCoord(-win.m_LRCorner.y + 1, win.m_ULCorner.x );
case DOWN : return SCoord(-win.m_LRCorner.x + 1,-win.m_LRCorner.y + 1);
case LEFT : return SCoord( win.m_ULCorner.y ,-win.m_LRCorner.x + 1);
default : return SCoord();
}
}
SCoord RangeOfSight::getWindowLRCorner(Direction i_Direction) const
{
// Select appropriate window
assertNonCenterDir(i_Direction);
const Window& win(isDiagonal(i_Direction) ? m_DiagonalWin : m_StraigthWin);
switch (i_Direction % 4) {
case UP : return win.m_LRCorner;
case RIGHT: return SCoord(-win.m_ULCorner.y + 1, win.m_LRCorner.x );
case DOWN : return SCoord(-win.m_ULCorner.x + 1,-win.m_ULCorner.y + 1);
case LEFT : return SCoord( win.m_LRCorner.y ,-win.m_ULCorner.x + 1);
default : return SCoord();
}
}
| true |
2d5292cb6c93e72c56d87c82da06a2e126c6a70c | C++ | benjamincarman/cpp-nfold-ILP | /nfold.cc | UTF-8 | 21,882 | 2.921875 | 3 | [] | no_license | /*******************************************************************************
*
* File: nfold.cc
*
* Author: Benjamin Carman
*
* Date: June 4, 2019
*
* Description: An implementation file of the NFold class which allows for the
* the creation of an ILP instance with the n-fold form. This class
* verifies the ILP's structure and can solve it by finding
* augmenting steps using Gurobi to solve auxillary programs until
* an optimum solution is reached. See documentation, README, and
* paper by Altmanová, Knop, and Koutecký for more information.
*
******************************************************************************/
#include "nfold.h"
#include "gurobi_c++.h"
#include <cstdlib>
#include <iostream>
#include <string>
#include <vector>
#include <cmath>
#include <algorithm>
using namespace std;
NFold::NFold(GRBEnv *e, unsigned int gc)
{
env = e;
solved = false;
safelyInstantiated = false;
initial = std::nullopt;
graverComplexity = gc;
}
NFold::NFold(GRBEnv *e, unsigned int n1, std::vector<int> objective1, std::vector<int> lowerBound1,
std::vector<int> upperBound1, std::vector<std::vector<int> > topMatrix1,
std::vector<std::vector<int> > diagMatrix1, std::vector<int> b1,
unsigned int gc, std::optional<std::vector<int> > initial1)
{
env = e;
n = n1;
r = topMatrix1.size();
s = diagMatrix1.size();
t = topMatrix1[0].size();
objective = objective1;
lowerBound = lowerBound1;
upperBound = upperBound1;
topMatrix = topMatrix1;
diagMatrix = diagMatrix1;
b = b1;
currentSolution.resize(n * t);
string error = checkDataValidity();
if (error != "")
{
cout << error << endl;
exit(-2);
}
buildConstraintMatrix();
graverComplexity = gc;
if (initial1 == std::nullopt)
{
cout << "No initial solution provided." << endl;
//Commence finding initial solution here
findInitialFeasibleSolution();
if (initial == std::nullopt)
{
cout << "No feasible solution for this instance exists." << endl;
exit(-2);
}
}
else
{
initial = initial1.value();
}
//Check validity of initial solution
error = checkInitialSolution();
if (error != "")
{
cout << error << endl;
exit(-2);
}
solved = false;
//Error checks pass, object is safely instantiated
safelyInstantiated = true;
}
void NFold::setGraverComplexity(unsigned int gc)
{
if (gc >= 2)
{
solved = false;
graverComplexity = gc;
}
else
{
cout << "Error: Invalid graver complexity." << endl;
exit (-2);
}
}
int NFold::getOptimizedObjectiveValue() const
{
if (solved)
{
return innerProduct(objective, currentSolution);
}
else
{
cout << "Cannnot get optimized objective value. Instance not solved." << endl;
exit(-2);
}
}
vector<int> NFold::getOptimizedSolution() const
{
if (solved)
{
return currentSolution;
}
else
{
cout << "Cannot get optimized solution. Instance not solved." << endl;
exit(-2);
}
}
void NFold::inputState(istream &ins)
{
solved = false;
//Input matrix dimension values
ins >> n;
ins >> r;
ins >> s;
ins >> t;
//Size all vectors/matrices accordingly
objective.resize(n * t);
lowerBound.resize(n * t);
upperBound.resize(n * t);
topMatrix.resize(r);
for (size_t i = 0; i < r; i++)
{
topMatrix[i].resize(t);
}
diagMatrix.resize(s);
for (size_t i = 0; i < s; i++)
{
diagMatrix[i].resize(t);
}
b.resize(r + (n * s));
//Input vector/matrix values
for (size_t i = 0; i < n * t; i++)
{
ins >> objective[i];
}
for (size_t i = 0; i < n * t; i++)
{
ins >> lowerBound[i];
}
for (size_t i = 0; i < n * t; i++)
{
ins >> upperBound[i];
}
for (size_t i = 0; i < r; i++)
{
for (size_t j = 0; j < t; j++)
{
ins >> topMatrix[i][j];
}
}
for (size_t i = 0; i < s; i++)
{
for (size_t j = 0; j < t; j++)
{
ins >> diagMatrix[i][j];
}
}
for (size_t i = 0; i < r + (n * s); i++)
{
ins >> b[i];
}
if (ins.eof())
{
cout << "Error: Input file does not contain enough input data. NFold not instantiated." << endl;
exit(-2);
}
//Call error check function
string error = checkDataValidity();
if (error != "")
{
cout << error << endl;
exit(-2);
}
buildConstraintMatrix();
vector<int> initialInput;
initialInput.resize(n * t);
for (size_t i = 0; i < n * t; i++)
{
ins >> initialInput[i];
}
if (!ins.eof())
{
initial = initialInput;
}
else
{
cout << "No initial solution provided." << endl;
//Commence finding initial solution here
findInitialFeasibleSolution();
if (initial == std::nullopt)
{
cout << "No feasible solution for this instance exists." << endl;
exit(-2);
}
}
//Check validity of initial solution
error = checkInitialSolution();
if (error != "")
{
cout << error << endl;
exit(-2);
}
//At this point, all is safely instantiated
safelyInstantiated = true;
}
void NFold::buildConstraintMatrix()
{
constraintMatrix.resize(r + n * s);
for (size_t i = 0; i < r; i++)
{
constraintMatrix[i].resize(n * t);
for (size_t j = 0; j < n; j++)
{
for (size_t k = 0; k < t; k++)
{
constraintMatrix[i][j * t + k] = 1.0 * topMatrix[i][k];
}
}
}
for (size_t i = r; i < r + n * s; i++)
{
constraintMatrix[i].resize(n * t);
for (size_t j = 0; j < n; j++)
{
if ((i - r) / s == j)
{
for (size_t k = 0; k < t; k++)
{
constraintMatrix[i][j * t + k] = 1.0 * diagMatrix[(i - r) % s][k];
}
}
else
{
for (size_t k = 0; k < t; k++)
{
constraintMatrix[i][j * t + k] = 0.0;
}
}
}
}
}
void NFold::outputState(std::ostream &outs) const
{
outs << "n: " << n << endl
<< "r: " << r << endl
<< "s: " << s << endl
<< "t: " << t << endl;
outs << endl << "Objective:" << endl;
writeVector(objective, outs);
outs << endl << "Lower Bound:" << endl;
writeVector(lowerBound, outs);
outs << endl << "Upper Bound:" << endl;
writeVector(upperBound, outs);
outs << endl << "Top Matrix:" << endl;
writeMatrix(topMatrix, outs);
outs << endl << "Diagonal Matrix:" << endl;
writeMatrix(diagMatrix, outs);
outs << endl << "An Matrix:" << endl;
writeMatrix(constraintMatrix, outs);
outs << endl << "RHS (b): " << endl;
writeVector(b, outs);
outs << endl << "Solution: " << endl;
writeVector(currentSolution, outs);
outs << endl << "Objective Value: " << innerProduct(objective, currentSolution) << endl;
}
string NFold::checkDataValidity() const
{
//Check sizes of each vector and matrix
if (objective.size() != n * t)
{
return "Instantiation Error: Objective vector is not of size (n * t)";
}
if (lowerBound.size() != n * t)
{
return "Instantiation Error: Lower Bound vector is not of size (n * t)";
}
if (upperBound.size() != n * t)
{
return "Instantiation Error: Upper Bound vector is not of size (n * t)";
}
if (topMatrix.size() != r)
{
return "Instantiation Error: Top matrix does not have r rows.";
}
for (size_t i = 0; i < r; i++)
{
if (topMatrix[i].size() != t)
{
return "Instantiation Error: Top matrix does not have t columns.";
}
}
if (diagMatrix.size() != s)
{
return "Instantiation Error: Diagonal matrix does not have s rows.";
}
for (size_t i = 0; i < s; i++)
{
if (diagMatrix[i].size() != t)
{
return "Instantiation Error: Diagonal matrix does not have t columns.";
}
}
if (b.size() != r + n * s)
{
return "Instantiation Error: RHS vector is not of size (r + n * s)";
}
//Check that lower <= upper
for (size_t i = 0; i < n * t; i++)
{
if (lowerBound[i] > upperBound[i])
{
return "Instantiation Error: Lower bounds must be less than or equal to upper bounds.";
}
}
return "";
}
string NFold::checkInitialSolution() const
{
if (initial == std::nullopt)
{
return "Initial Solution Instantiation Error: No initial solution provided.";
}
vector<int> inSol = initial.value();
if (inSol.size() != n * t)
{
return "Initial Solution Instantiation Error: Initial solution is not of size (n * t).";
}
for (size_t i = 0; i < n * t; i++)
{
if (inSol[i] < lowerBound[i] || inSol[i] > upperBound[i])
{
return "Initial Solution Instantiation Error: Initial solution is not within upper and lower bounds.";
}
}
//Check feasibility of initial solution
vector<int> crossProduct;
crossProduct.resize(r + n * s);
//Create inSol vector of doubles to work with constraint matrix
vector<double> inSolDouble;
inSolDouble.resize(n * t);
for (size_t i = 0; i < n * t; i++)
{
inSolDouble[i] = 1.0 * inSol[i];
}
//Calculate cross product
for (size_t i = 0; i < r + n * s; i++)
{
int prod = int(innerProduct(constraintMatrix[i], inSolDouble));
crossProduct[i] = prod;
}
if (crossProduct != b)
{
return "Initial Solution Instantiation Error: Provided initial solution is infeasible.";
}
//No error found, return empty string
return "";
}
bool NFold::solve()
{
if (initial == std::nullopt)
{
cout << "No initial solution. Unable to solve." << endl;
solved = false;
return false;
}
if (solved == true)
{
cout << "Instance already solved." << endl;
return true;
}
currentSolution = initial.value();
cout << "Begin solve with GC: " << graverComplexity << endl;
bool done = false;
//Keep obtaining and adding best steps until step of 0 found
while (!done)
{
cout << "Current solution is: " << endl << "<";
for (size_t i = 0; i < n * t - 1; i++)
{
cout << currentSolution[i] << ", ";
}
cout << currentSolution[n * t - 1] << ">" << endl;
vector<int> graverBestStep = findGraverBestStep();
//If returns a zero step or a step in wrong direction
if (innerProduct(objective, graverBestStep) > -1)
{
done = true;
}
else //Good step. Add to current solution and continue
{
cout << "Graver best step found:" << endl << "<";
for (size_t i = 0; i < n * t - 1; i++)
{
cout << graverBestStep[i] << ", ";
}
cout << graverBestStep[n * t - 1] << ">" << endl;
for (size_t i = 0; i < n * t; i++)
{
currentSolution[i] += graverBestStep[i];
}
}
}
solved = true;
return true;
}
vector<int> NFold::findGraverBestStep()
{
//Find infinite norm of u - l
int infNorm = 0;
for (size_t i = 0; i < (n * t); i++)
{
int absDifference = abs(upperBound[i] - lowerBound[i]);
if (absDifference > infNorm)
{
infNorm = absDifference;
}
}
int upperLimit = int(floor(log2(infNorm)));
int lambda = 1;
vector<int> bestStep(n * t, 0);
int bestObjectiveValue = 0;
for (size_t i = 0; i < upperLimit; i++)
{
vector<int> goodStep = findGoodStep(lambda);
cout << "Good Step Found: " << endl << "<";
for (size_t i = 0; i < n * t - 1; i++)
{
cout << goodStep[i] << ", ";
}
cout << goodStep[n * t - 1] << ">" << endl;
if (innerProduct(objective, goodStep) > -1)
{
cout << "No good step found with lambda: " << lambda << endl;
break;
}
int exhaustedLambda = INT_MAX;
for (size_t i = 0; i < n * t; i++)
{
if (goodStep[i] != 0)
{
double lowerFeasibleStepLength = (1.0 *(lowerBound[i] - currentSolution[i]))/goodStep[i];
double upperFeasibleStepLength = (1.0 *(upperBound[i] - currentSolution[i]))/goodStep[i];
int bestFeasibleStepLength = int(floor(max(lowerFeasibleStepLength, upperFeasibleStepLength)));
if (exhaustedLambda > bestFeasibleStepLength)
{
exhaustedLambda = bestFeasibleStepLength;
}
}
}
//Just in case
if (exhaustedLambda == INT_MAX || exhaustedLambda < lambda)
{
exhaustedLambda = lambda;
}
for (size_t i = 0; i < n * t; i++)
{
goodStep[i] *= exhaustedLambda;
}
int currentObjectiveValue = innerProduct(objective, goodStep);
if (exhaustedLambda != lambda)
{
cout << "Lambda changed! Exhausted Lambda: " << exhaustedLambda << endl;
}
cout << "Objective value for lambda = " << exhaustedLambda << ", is: " << currentObjectiveValue << endl;
if (currentObjectiveValue < bestObjectiveValue)
{
bestObjectiveValue = currentObjectiveValue;
bestStep = goodStep;
}
//Exhaust the lamda and see if it is better step than ones seen so far
lambda *= 2; //TODO: Maybe generalize this to other c-apx values
}
return bestStep;
}
vector<int> NFold::findGoodStep(int lambda)
{
cout << "Finding good step with lambda: " << lambda << endl;
try {
//Create set Gamma and solve ILP for each
GRBModel model = GRBModel(*env);
model.set(GRB_IntParam_LogToConsole, 0);
//Create bounds for solution. Use double type to match addVars() requirements
//graverComplexity * lambda from Altmanova implementation. Need to address theory
double *lb = new double [n * t];
for (size_t i = 0; i < (n * t); i++)
{
lb[i] = ceil(max(-1.0 * graverComplexity * lambda, 1.0 * (lowerBound[i] - currentSolution[i]) / lambda));
}
double *ub = new double [n * t];
for (size_t i = 0; i < (n * t); i++)
{
ub[i] = floor(min(1.0 * graverComplexity * lambda, 1.0 * (upperBound[i] - currentSolution[i]) / lambda));
}
double *obj = new double [n * t];
for (size_t i = 0; i < (n * t); i++)
{
obj[i] = 1.0 * objective[i];
}
char *vTypesInt = new char [n * t];
for (size_t i = 0; i < (n * t); i++)
{
vTypesInt[i] = GRB_INTEGER;
}
GRBVar *h = model.addVars(lb, ub, obj, vTypesInt, NULL, (n * t));
//Add constraints from constraint matrix
for (size_t i = 0; i < r + n * s; i++)
{
GRBLinExpr constraint;
constraint.addTerms(&constraintMatrix[i][0], h, n * t);
model.addConstr(constraint, GRB_EQUAL, 0);//1.0 * b[i]);
}
//Add constraints for l1 norm less than graver complexity and minimize
double *lbZero = new double [n * t];
double *ubInfinity = new double [n * t];
double *arrayOnes = new double [n * t]; //For graverConstraint below
for (size_t i = 0; i < n * t; i++)
{
lbZero[i] = 0;
ubInfinity[i] = GRB_INFINITY;
arrayOnes[i] = 1;
}
GRBVar *positive = model.addVars(lbZero, ubInfinity, 0, vTypesInt, NULL, (n * t));
GRBVar *negative = model.addVars(lbZero, ubInfinity, 0, vTypesInt, NULL, (n * t));
for (size_t i = 0; i < n * t; i++)
{
model.addConstr(positive[i] - negative[i], GRB_EQUAL, h[i]);
}
GRBLinExpr graverConstraint;
graverConstraint.addTerms(arrayOnes, positive, n * t);
graverConstraint.addTerms(arrayOnes, negative, n * t);
delete[] lb;
delete[] ub;
delete[] obj;
delete[] lbZero;
delete[] ubInfinity;
delete[] vTypesInt;
delete[] arrayOnes;
model.addConstr(graverConstraint, GRB_LESS_EQUAL, graverComplexity);
model.set(GRB_IntAttr_ModelSense, GRB_MINIMIZE);
model.optimize();
vector<int> zeros(n * t, 0);
if (model.get(GRB_IntAttr_Status) == GRB_OPTIMAL)
{
double objectiveValue = model.get(GRB_DoubleAttr_ObjVal);
//cout << "Objective value: " << objectiveValue << endl;
if (objectiveValue > -1)
{
return zeros; //Step found is non-improving.
}
else
{
vector<int> goodStep;
goodStep.resize(n * t);
for (size_t i = 0; i < n * t; i++)
{
goodStep[i] = int(h[i].get(GRB_DoubleAttr_X));
}
return goodStep;
}
}
//Infeasible
return zeros;
}
catch(GRBException e)
{
cout << "Error in findGoodStep() with error code: " << e.getErrorCode() << endl;
cout << "Error Message: " << e.getMessage() << endl;
cout << "Exiting program..." << endl;
exit(-1);
}
catch(...)
{
cout << "Exception during optimization in findGoodStep()" << endl;
cout << "Exiting program..." << endl;
exit(-1);
}
}
void NFold::findInitialFeasibleSolution()
{
cout << "Trying to find initial feasible solution." << endl;
vector<int> iObjective;
vector<int> iLowerBound;
vector<int> iUpperBound;
vector<vector<int> > iTopMatrix(r, vector<int>(2 * (r + s) + t, 0));
vector<vector<int> > iDiagMatrix(s, vector<int>(2 * (r + s) + t, 0));
vector<int> iInitial;
//Set sizes of vectors
iObjective.resize(n * (2 * (r + s) + t));
iLowerBound.resize(n * (2 * (r + s) + t));
iUpperBound.resize(n * (2 * (r + s) + t));
iInitial.resize(n * (2 * (r + s) + t));
size_t newBrickSize = t + 2 * (r + s);
//Initialize objective
for (size_t brick = 0; brick < n; brick++)
{
for (size_t i = 0; i < t; i++)
{
iObjective[brick * newBrickSize + i] = 0;
}
for (size_t i = t; i < newBrickSize; i++)
{
iObjective[brick * newBrickSize + i] = 1;
}
}
//Initialize lower bound
for (size_t brick = 0; brick < n; brick++)
{
for (size_t i = 0; i < t; i++)
{
iLowerBound[brick * newBrickSize + i] = lowerBound[i];
}
for (size_t i = t; i < newBrickSize; i++)
{
iLowerBound[brick * newBrickSize + i] = 0;
}
}
//Get bMax value for upper bound
int bMax = 0;
for (size_t i = 0; i < r + n * s; i++)
{
if (abs(b[i]) > bMax)
{
bMax = abs(b[i]);
}
}
//Initialize upper bound
for (size_t brick = 0; brick < n; brick++)
{
for (size_t i = 0; i < t; i++)
{
iUpperBound[brick * newBrickSize + i] = upperBound[i];
}
for (size_t i = t; i < newBrickSize; i++)
{
iUpperBound[brick * newBrickSize + i] = bMax;
}
}
//Initialize top matrix
for (size_t i = 0; i < r; i++)
{
for (size_t j = 0; j < t; j++)
{
iTopMatrix[i][j] = topMatrix[i][j];
}
iTopMatrix[i][i + t] = 1;
iTopMatrix[i][i + t + r] = -1;
}
//Initialize the diagonal matrix
for (size_t i = 0; i < s; i++)
{
for (size_t j = 0; j < t; j++)
{
iDiagMatrix[i][j] = diagMatrix[i][j];
}
iDiagMatrix[i][i + t + r + r] = 1;
iDiagMatrix[i][i + t + r + r + s] = -1;
}
//Iniitialize the initial solution for this subproblem
size_t index = 0;
for (size_t i = 0; i < t; i++)
{
if (lowerBound[i] != INT_MIN)
{
iInitial[i] = lowerBound[i];
}
else if (upperBound[i] != INT_MIN)
{
iInitial[i] = upperBound[i];
}
else
{
iInitial[i] = 0;
}
}
index = t;
for (size_t i = 0; i < r; i++)
{
if (b[i] >= 0)
{
iInitial[i + index] = b[i];
iInitial[i + index + r] = 0;
}
else
{
iInitial[i + index] = 0;
iInitial[i + index + r] = -1 * b[i];
}
}
index = t + 2 * r;
for (size_t i = 0; i < s; i++)
{
if (b[i + r] >= 0)
{
iInitial[i + index] = b[i + r];
iInitial[i + index + s] = 0;
}
else
{
iInitial[i + index] = 0;
iInitial[i + index + s] = -1 * b[i + r];
}
}
index = newBrickSize;
//Fill in the rest
for (size_t sSection = 1; sSection < n; sSection++)
{
for (size_t i = 0; i < 2 * r + t; i++)
{
iInitial[i + index] = 0;
}
index += 2 * r + t;
for (size_t i = 0; i < s; i++)
{
if (b[r + sSection * s] >= 0)
{
iInitial[i + index] = b[r + sSection * s];
iInitial[i + index + s] = 0;
}
else
{
iInitial[i + index] = 0;
iInitial[i + index + s] = -1 * b[r + sSection * s];
}
}
index += 2 * s;
}
//Create instance
NFold auxILP(env, n, iObjective, iLowerBound, iUpperBound,
iTopMatrix, iDiagMatrix, b, graverComplexity, iInitial);
auxILP.solve();
auxILP.outputState(cout);
//Check solution of auxILP
vector<int> auxSolution = auxILP.getOptimizedSolution();
bool valid = true;
for (size_t brick = 0; brick < n; brick++)
{
for (size_t i = t; i < newBrickSize; i++)
{
if (auxSolution[brick * newBrickSize + i] != 0)
{
valid = false;
break;
}
}
if (!valid)
{
break;
}
}
if (!valid)
{
initial = std::nullopt;
}
else
{
vector<int> finalSolution;
finalSolution.resize(n * t);
for (size_t brick = 0; brick < n; brick++)
{
for (size_t i = 0; i < t; i++)
{
finalSolution[brick * t + i] = auxSolution[brick * newBrickSize + i];
}
}
cout << "Initial Feasible Solution Found: " << endl;
auxILP.writeVector(finalSolution, cout);
initial = finalSolution;
}
}
template <class T>
T NFold::innerProduct(const std::vector<T> &v1, const std::vector<T> &v2) const
{
if (v1.size() != v2.size())
{
cout << "Error in call to innerProduct. Vector sizes do not match." << endl;
exit(-1);
}
T prod = 0;
for (size_t i = 0; i < v1.size(); i++)
{
prod += v1[i] * v2[i];
}
return prod;
}
template <class T>
void NFold::writeVector(const std::vector<T> &v, std::ostream &outs) const
{
outs << "<";
for (size_t i = 0; i < v.size() - 1; i++)
{
outs << v[i] << ", ";
}
outs << v[v.size() - 1] << ">" << endl;
}
template <class T>
void NFold::writeMatrix(const std::vector<std::vector<T> > &m, std::ostream &outs) const
{
outs << "[ ";
for (size_t i = 0; i < m.size(); i++)
{
if (i != 0) outs << " ";
outs << "[";
for (size_t j = 0; j < m[i].size() - 1; j++)
{
outs << m[i][j] << ", ";
}
outs << m[i][m[i].size() - 1];
if (i != m.size() - 1) {outs << "]," << endl;}
else {outs << "] ]" << endl;}
}
}
| true |
97c7f744bda82160a11a839df883e70c7ee33612 | C++ | Tatane/DrumPart | /partition.h | UTF-8 | 506 | 2.6875 | 3 | [] | no_license | #ifndef PARTITION_H
#define PARTITION_H
#include <list>
#include <memory>
#include "measure.h"
using namespace std;
class Partition
{
public:
using MeasuresContainer = list<unique_ptr<Measure>>;
Partition();
void play();
int getTempo() const {return tempo; }
Measure & insertMeasure(int position, unique_ptr<Measure> measure = nullptr);
const MeasuresContainer & getMeasures() const;
private:
MeasuresContainer measures;
int tempo = 100;
};
#endif // PARTITION_H
| true |
9ca58fd4848bd4825568ca3d5e6a88be2c81bf7e | C++ | mecha-rm/GDW_Y2-PJT-repos | /GDW_Y2 - CNZ/src/CSV.h | UTF-8 | 571 | 3.21875 | 3 | [] | no_license | // class used for construction of level map
#pragma once
#include <string>
#include <vector>
#include <iterator>
#include <iostream>
#include <fstream>
#include <sstream>
// Basically we're reconstructing the CSV into an object.
class CSV
{
public:
// constructor
CSV() = default;
// constructor
CSV(std::string csvPath);
// get row
std::string GetRow(int num, int num2);
std::vector<std::string> const& operator[](std::size_t index) const;
// size of CSV
std::size_t Size() const;
private:
// rows[y][x]
std::vector<std::vector<std::string>> rows;
}; | true |
7b003f97413db97e1ce635d51f3f4868fdfc04bd | C++ | vgb0332/HomeForC- | /project2/main.cpp | UHC | 3,546 | 2.859375 | 3 | [] | no_license | /*
* main.cpp
*
* Created on: Mar 30, 2012
* Author: cskim
*/
#include <iostream>
#include "String.h"
using namespace std;
#include "PhoneContactList.h"
#include "PhoneContactMap.h"
#include "CPhoneContact.h"
/********************* 5 ߰ **********************/
string nameData[] = {"Park SH", "Kang JH", "Kim KS", "Lee YH", "Kang SH",
"Bae JM", "Lee DI", "Lee BH", "Jang WH", "Chun WY",
"Kim JH", "Jung MW", "Jung YS", "Choi EJ", "Hong JM"};
int numberData[] = {5023, 5002, 5008, 5067, 5038,
5381, 5125, 5165, 5684, 5752,
1111, 2222, 3333, 4444, 5555};
String emailData[] = {
"parksh@email.com", "kangjh@email.com", "kimks@email.com", "leeyh@email.com", "kangsh@email.com",
"baejm@email.com", "leedi@email.com", "leebh@email.com", "jangwh@email.com", "chunwy@email.com",
"kimjh@email.com", "jungmw@email.com", "jungys@email.com", "choiej@email.com", "hongjm@email.com"};
PhoneContactList pbList;
PhoneContactMap pbMap;
PhoneContactVector pbVector;
int incount = 15;
void testPhoneBook(PhoneContact* pb, String pbType){
cout << "***Test "+pbType+"PhoneBook***" << endl;
// Create PhoneBook made of vector and array
for (int i=0; i < incount; i++){
if (!pb->insert(nameData[i]+"-"+"L", numberData[i], emailData[i])){
cout << "***Error in Insert***" + nameData[i]+"-"+pbType[0]<< endl;
};
}
cout << "***List All "+pbType+" PhoneBook" << endl;
pb->listAll();
cout << endl << " /////// ERROR TESTS ////////" << endl;
//ߺ ̸ insert update ٽ
if (!pb->update(string("Jung MW-")+pbType[0], 4321, "UPDATED@email.com **EDITED**")){
cout << "***Error in Update --" + string("Jung MW-")+pbType[0] + " ***"<< endl;
};
//Ʈ ߰ -- insert(ߺ)
if (!pb->insert(string("Hong JM-")+pbType[0], 5555, "ADD TEST@email.com")){
cout << "***Error in Insert --" + string("Hong JM-")+pbType[0] + " ***"<< endl;
};
//Ʈ ߰ -- remove(ߺ)
if (!pb->remove(string("REMOVE TEST-")+pbType[0])){
cout << "***Error in Remove --" + string("REMOVE TEST-")+pbType[0] + " ***"<< endl;
};
//Ʈ ߰ -- update( ̸)
if (!pb->update(string("UPDATE TEST-")+pbType[0], 0000, "UPDATE TEST@email.com **TEST**")){
cout << "***Error in Update --" + string("UPDATE TEST-")+pbType[0] + " ***"<< endl;
};
cout << endl;
//findName(string email) Ʈ
cout << "Finding Name by Email(hongjm@email.com) - " << pb->findName("hongjm@email.com") << endl;
//findName(int number) Ʈ
cout << "Finding Name by Number(4444) - " << pb->findName(4444) << endl;
//findName Ʈ
cout << "Finding Name Error test - " << pb->findName(112345) << endl;
cout << endl << "***List All Updated Entry" << endl;
pb->listAll();
}
void testPhoneBookList(PhoneContact* pb){
string pbType = "List";
cout << "***Test "+pbType+"PhoneBook***" << endl;
// Create PhoneBook made of vector and array
for (int i=0; i < incount; i++){
if (!pb->insert(nameData[i]+"-"+pbType[0], numberData[i], emailData[i])){
cout << "***Error in Insert***" + nameData[i]+"-"+pbType[0]<< endl;
};
}
cout << "***List All "+pbType+" PhoneBook" << endl;
pb->listAll();
/* project-4 Ʈ
*
* 1. operator+=, [] Ʈ
* 2. Big3 Ʈ
* 3.
*
*/
cout << endl << "***List All Updated Entry" << endl;
pb->listAll();
}
int main ()
{
/*
PhoneContact* pBooks[] = { &pbList , &pbMap , &pbVector };
string pbTypes[] = { "List", "Map", "Vector" };
for (int i=0; i<3; ++i){
testPhoneBook(pBooks[i], pbTypes[i]);
cout << endl;
}
*/
testPhoneBookList(&pbList);
return 0;
}
| true |
55e9e63c08b9535ec0b4d70df9d91f0c0fcd1da7 | C++ | lmc110/GameOfLife | /life.h | UTF-8 | 730 | 2.90625 | 3 | [] | no_license | /****************************************************
This program reads an input file and adds the data
to a dynamically allocated grid. The grid consists of
live and dead cells. Once grid is populated with cells,
it is displayed to the screen. Each cell is then checked
for live neighbors and the rules are applied to it.
The next generation of cells are added to a new grid
and displayed to the screen.
*****************************************************/
#ifndef LIFE_H
#define LIFE_H
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
//function prototypes
void populateWorld (string fileName);
void showWorld();
void iterateGeneration();
#endif /* LIFE_H */
| true |
ad23bfc72a77939143d44635e86e5751a2c31d75 | C++ | skygaofei/Code | /Luogu/P3385 【模板】负环.cpp | UTF-8 | 1,665 | 2.53125 | 3 | [
"Apache-2.0"
] | permissive | //
// SPFA.cpp
// CSP RP++
//
// Created by skygao on 2019/11/15.
// Copyright © 2019 skygao. All rights reserved.
//
#include <stdio.h>
#include <queue>
#include <cstdlib>
#include <cstring>
#include <string>
#include <algorithm>
#include <iostream>
#include <vector>
#define maxn 2005
using namespace std;
int n,m;
vector<int> son[maxn],v[maxn];
bool vis[maxn];
int dis[maxn],cnt[maxn];
inline void addedge(int x,int y,int z)
{
son[x].push_back(y);
v[x].push_back(z);
}
inline bool SPFA(int S)
{
for(int i=1;i<=n;++i)
vis[i]=false,dis[i]=2147483647,cnt[i]=0;
queue<int> q;
q.push(S);
vis[S]=true;dis[S]=0;
while(!q.empty())
{
int rt=q.front();q.pop();vis[rt]=false;
if(cnt[rt]>=n)
return true;
for(int i=0;i<son[rt].size();++i)
{
int to=son[rt][i];
if(dis[to]>dis[rt]+v[rt][i])
{
dis[to]=dis[rt]+v[rt][i];
if(!vis[to])
{
q.push(to);
vis[to]=true;
cnt[to]++;
if(cnt[to]>=n)
return true;
}
}
}
}
return false;
}
int main()
{
int t,x,y,z;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&n,&m);
for(int i=1;i<=m;++i)
{
scanf("%d%d%d",&x,&y,&z);
if(z<0)
addedge(x,y,z);
else
addedge(x,y,z),addedge(y,x,z);
}
puts(SPFA(1)?"YE5":"N0");
for(int i=1;i<=n;++i)
son[i].clear(),v[i].clear();
}
return 0;
}
| true |
6e960242c5d9980df37df1a29db4f17a5092fd33 | C++ | ShawnDordeJay/Benchmark_Primzahlen_2 | /Benchmark_Primzahlen_2/Config.h | UTF-8 | 224 | 2.515625 | 3 | [] | no_license | #pragma once
class Config
{
public:
~Config();
static Config *getInstance(int N, int howmanyvalues);
int getN();
int getHowManyValues();
private:
Config();
static Config *INSTANCE;
int N;
int howmanyvalues;
};
| true |
c2f12a0d1431ea7111f19d6aab31458af245c9c9 | C++ | worden-lee/bikh-on-network | /cascade.h | UTF-8 | 21,529 | 2.578125 | 3 | [] | no_license | #include "networks.h"
#include "CSVController.h"
#include "BoostDotDisplay.h"
#include "CascadeParameters.h"
#include <boost/random/bernoulli_distribution.hpp>
using namespace std;
// classes for doing the Bikhchandani and related update rules
// abstract base class for an object to update states of nodes on network,
// one at a time
template<typename network_t, typename params_t>
class update_rule
{
};
// base class for several variants on the Bikh. process with
// local interactions
template<typename network_t, typename params_t, typename rng_t>
class bikh_on_network_update_rule : public update_rule<network_t, params_t>
{
public:
typedef class node_state {
public:
// these two are the actual state
bool decided;
bool adopted;
// the rest is extra record-keeping
bool cascaded;
bool flipped;
bool signal;
int neighbors_decided;
int neighbors_adopted;
double time_of_decision;
node_state() : decided(false), adopted(false), cascaded(false),
flipped(false), signal(false),
neighbors_decided(0), neighbors_adopted(0),
time_of_decision(0) {}
} node_state_t;
typedef class state_container : public vector<node_state_t> {
public:
state_container(int n) : vector<node_state_t>(n) {}
unsigned n_adopting(void) {
unsigned n = 0;
for (typename vector<node_state_t>::iterator
it = this->begin(); it != this->end(); ++it) {
if (it->decided && it->adopted) {
++n;
}
}
return n;
}
unsigned n_cascading(void) {
unsigned n = 0;
for (typename vector<node_state_t>::iterator
it = this->begin(); it != this->end(); ++it) {
if (it->decided && it->cascaded) {
++n;
}
}
return n;
}
unsigned n_decided(void) {
unsigned n = 0;
for (typename vector<node_state_t>::iterator
it = this->begin(); it != this->end(); ++it) {
if (it->decided) {
++n;
}
}
return n;
}
} state_container_t;
typedef typename boost::graph_traits<network_t>::vertex_descriptor
vertex_index_t;
double p;
rng_t &rng;
bikh_on_network_update_rule(double _p, rng_t &_rng) :
p(_p), rng(_rng)
{}
void update(vertex_index_t i, double t,
network_t &n, params_t ¶ms, state_container_t &state) {
boost::bernoulli_distribution<> d(p);
boost::variate_generator< rng_t&, boost::bernoulli_distribution<> >
choose_signal(rng, d);
state[i].signal = choose_signal();
this->figure_out_update(i, state[i].signal, n, params, state);
state[i].decided = true;
state[i].time_of_decision = t;
}
// this is the actual update operation, which is implemented by subclasses
virtual void figure_out_update(vertex_index_t i, bool signal,
network_t &n, params_t ¶ms, state_container_t &state) {
state[i].adopted = false;
}
// used by multiple subclasses for sorting
class compare_times {
public:
const state_container_t &state;
compare_times(const state_container_t&s) : state(s) {}
bool operator()(const vertex_index_t &a, const vertex_index_t &b) {
return state[a].time_of_decision < state[b].time_of_decision;
}
};
};
// The counting rule is a simple majority approximation:
// count all the others' actions together with your signal, and go with
// either adoption or rejection according to which is the majority.
// This is a pluralistic ignorance rule, because this is what you would
// get if you incorrectly assume all other players' actions match their
// private signals.
template<typename network_t, typename params_t, typename rng_t>
class counting_update_rule :
public bikh_on_network_update_rule<network_t,params_t,rng_t> {
public:
typedef typename
bikh_on_network_update_rule<network_t,params_t,rng_t>::state_container_t
state_container_t;
typedef typename
bikh_on_network_update_rule<network_t,params_t,rng_t>::vertex_index_t
vertex_index_t;
counting_update_rule(double p, rng_t &__rng) :
bikh_on_network_update_rule<network_t,params_t,rng_t>(p,__rng)
{}
virtual void figure_out_update(vertex_index_t i, bool signal,
network_t &n, params_t ¶ms, state_container_t &state) {
typename graph_traits<network_t>::out_edge_iterator ei,eend;
unsigned n_decided = 0, n_adopted = 0;
for (tie(ei,eend) = out_edges(i,n); ei != eend; ++ei) {
vertex_index_t j = target(*ei,n);
if (state[j].decided) {
++n_decided;
if (state[j].adopted)
++n_adopted;
}
}
int n_up = n_adopted, n_down = n_decided - n_adopted;
++(signal ? n_up : n_down);
if (n_up > n_down) {
state[i].adopted = true;
if (n_adopted > n_decided - n_adopted + 1) {
// would adopt with down signal
state[i].cascaded = true;
}
}
else if (n_up < n_down) {
state[i].adopted = false;
if (n_adopted + 1 < n_decided - n_adopted) {
// would reject with up signal
state[i].cascaded = true;
}
} else {
state[i].adopted = bernoulli_distribution<>(0.5)(this->rng);
//cout << "coin flip: " << state[i].adopted << "\n";
state[i].flipped = true;
}
state[i].neighbors_adopted = n_adopted;
state[i].neighbors_decided = n_decided;
//cout << n_up << " of " << total_n << ": "
// << (state[i].adopted ? "adopted" : "rejected")
// << (state[i].cascaded? ", cascaded" : "")
// << (state[i].flipped? ", flipped": "") << "\n";
}
};
#if 0 // to log messages
#define LOG_OUT cout
#else // or not to log messages
#include "boost/iostreams/stream.hpp"
#include "boost/iostreams/device/null.hpp"
boost::iostreams::stream< boost::iostreams::null_sink > null_ostream( ( boost::iostreams::null_sink() ) );
#define LOG_OUT null_ostream
#endif
int n_inferences, n_memoized;
// This is the Bikhchandani et al model, extended to consider
// possibly-local interactions.
// Each player uses Bayesian inference to infer likelihood that the true
// signal is positive, taking into account other players' actions and their
// own private signal. In a partly-connected network, each player takes into
// account only the other players they are connected to. When interpreting
// another player's action, they take into account that that person only saw
// the people they're connected to. But they can't take into account people
// they themselves can't see, so they proceed as if the neighbors' neighborhood
// is limited to the intersection of the neighbor's true neighborhood with
// their own neighborhood.
// This leads to a combinatorial explosion, because the likelihood
// calculation has to be done over and over for many different subsets of each
// player's neighborhood.
template<typename network_t, typename params_t, typename rng_t>
class bikh_log_odds_update_rule :
public bikh_on_network_update_rule<network_t,params_t,rng_t> {
public:
typedef typename
bikh_on_network_update_rule<network_t,params_t,rng_t>::state_container_t
state_container_t;
typedef typename
bikh_on_network_update_rule<network_t,params_t,rng_t>::vertex_index_t
vertex_index_t;
typedef typename
bikh_on_network_update_rule<network_t,params_t,rng_t>::compare_times
compare_times;
float rho, sigma;
map<vertex_index_t,float> *memoize_sum_of_influences_p;
bikh_log_odds_update_rule(double p, rng_t &__rng) :
bikh_on_network_update_rule<network_t,params_t,rng_t>(p,__rng),
rho( log(p/(1-p)) ), sigma( log((1+p)/(2-p)) ),
memoize_sum_of_influences_p(NULL) {}
// Given someone on the network, we figure out what they'll do
// by looking at each of their neighbors, and reconstructing what
// each of them did in relation to what their neighbors did...
// So we need to figure out who a neighbor's neighbors are. And not
// just who their neighbors actually are, that would be too easy, but
// who this person thinks that person's neighbors are, which is the
// intersection of the two people's neighborhoods.
// The caller expects this to return only:
// nodes connected to n1
// which took action before n1 did
// n1: the person whose neighborhood we want
// all_neighbors: restricted to this universe
// n: the network
// n1_neighbors: container where answer will be returned
virtual void construct_neighbors_neighbors( vertex_index_t n1,
set<vertex_index_t> &all_neighbors,
network_t &n,
set<vertex_index_t> &n1_neighbors,
state_container_t &state,
string indent) {
LOG_OUT << indent << " construct neighbors of " << n1 << ':';
for ( typename set<vertex_index_t>::iterator n2i = all_neighbors.begin();
n2i != all_neighbors.end(); ++n2i ) {
vertex_index_t n2 = *n2i;
typename boost::graph_traits<network_t>::edge_descriptor e;
bool edge_exists;
tie(e, edge_exists) = edge(n1,n2,n);
if (edge_exists && state[n2].decided &&
state[n2].time_of_decision < state[n1].time_of_decision) {
n1_neighbors.insert(n2);
LOG_OUT << ' ' << n2;
} else {
LOG_OUT << " (" << n2 << ')';
}
}
LOG_OUT << endl;
}
// sum_of_influences is called recursively. Given the neighbors
// of a given node, we reconstruct what influenced those neighbors
// and what we can infer about each of their signals. Return the
// sum of log odds expressing the likelihood that the true signal
// is positive, given that information.
virtual float sum_of_influences(set<vertex_index_t>&neighbors,
vertex_index_t n0,
network_t &n, params_t ¶ms,
state_container_t &state, string indent = "") {
// in order, try to infer their signal from what they were looking at
float total_log_odds = 0;
if (memoize_sum_of_influences_p && memoize_sum_of_influences_p->count(n0) > 0) {
float lookup = (*memoize_sum_of_influences_p)[n0];
LOG_OUT << indent << " sum_of_influences(" << n0 << ") memoized: " << lookup << endl;
++n_memoized;
return lookup;
}
++n_inferences;
// Now compute the log odds likelihood thing for each of
// the neighbors we're given
set<vertex_index_t> n1_neighbors;
for ( typename set<vertex_index_t>::iterator n1i = neighbors.begin(); n1i != neighbors.end(); ++n1i ) {
vertex_index_t n1 = *n1i;
float n1_sum_log_odds;
if (memoize_sum_of_influences_p && memoize_sum_of_influences_p->count(n1) > 0) {
float lookup = (*memoize_sum_of_influences_p)[n1];
LOG_OUT << indent << " sum_of_influences(" << n1 << ") memoized: " << lookup << endl;
n1_sum_log_odds = lookup;
++n_memoized;
} else {
LOG_OUT << indent << " sum_of_influences(" << n1 << ") not memoized" << endl;
// Construct vector of that person's neighbors
// (those that are in the set of neighbors we're given)
n1_neighbors.clear();
construct_neighbors_neighbors( n1, neighbors, n, n1_neighbors, state, indent + " " );
// Get the sum_of_influences log likelihood for
// neighbor's neighbors, recursively.
n1_sum_log_odds = sum_of_influences(n1_neighbors, n1, n, params, state, indent + " ");
LOG_OUT << indent << " sum of log_odds: " << n1_sum_log_odds << "\n";
}
// given the neighbor's influences and their actual
// action, there are cases giving us this neighbor's
// contribution to the log odds.
float log_alpha_n1;
int action = (state[n1].adopted ? 1 : -1);
if (n1_sum_log_odds * action > rho) {
// if the influence is enough to override their signal, we don't
// know their signal because they were part of a cascade
log_alpha_n1 = 0;
} else if (n1_sum_log_odds * action == rho) {
// if the influence is ±rho and they agreed with it, they might have
// flipped a coin
log_alpha_n1 = action * sigma;
} else {
// otherwise the influence is too weak and we're seeing their signal.
// this includes the "paradoxical" case.
log_alpha_n1 = action * rho;
}
LOG_OUT << indent << " log alpha (" << n1 << "): " << log_alpha_n1 << "\n";
// We simply add that to the total log odds.
total_log_odds += log_alpha_n1;
}
if (memoize_sum_of_influences_p) {
(*memoize_sum_of_influences_p)[n0] = total_log_odds;
}
return total_log_odds;
}
virtual void figure_out_update(vertex_index_t i, bool signal,
network_t &n, params_t ¶ms, state_container_t &state) {
// reconstruct everyone's decisions and try to infer their signals
LOG_OUT << "Update site " << i << " (signal " << signal << "):\n";
// get everyone in the neighborhood, from first to play, to last
typename graph_traits<network_t>::adjacency_iterator ai,aend;
set<vertex_index_t> neighbors;
unsigned n_decided = 0, n_adopted = 0;
for (tie(ai,aend) = adjacent_vertices(i, n); ai != aend; ++ai) {
vertex_index_t j = *ai;
if (state[j].decided) {
++n_decided;
if (state[j].adopted) {
++n_adopted;
}
neighbors.insert(j);
}
}
unsigned n_up = 0, n_down = 0;
//sort( neighbors.begin(), neighbors.end(), compare_times(state) );
if ( memoize_sum_of_influences_p == NULL ) {
static string igt = "";
if (igt == "") {
igt = params.initial_graph_type();
}
if (igt == "COMPLETE") {
memoize_sum_of_influences_p = new map<vertex_index_t,float>;
}
}
// what are all the neighbors' signals worth to me?
float total_log_alphas = sum_of_influences(neighbors, i, n, params, state, "");
// given the total influence and the signal, decide what to do
float rho_i = (signal ? rho : -rho);
LOG_OUT << " rho_i = " << rho_i << "\n";
LOG_OUT << " sum of log odds = " << (total_log_alphas + rho_i) << ": ";
if (total_log_alphas + rho_i > 0) {
state[i].adopted = true;
LOG_OUT << 1;
if (total_log_alphas > rho) {
state[i].cascaded = true;
LOG_OUT << " (cascade)";
}
} else if (total_log_alphas + rho_i < 0) {
state[i].adopted = false;
LOG_OUT << -1;
if (total_log_alphas < -rho) {
state[i].cascaded = true;
LOG_OUT << " (cascade)";
}
} else {
state[i].adopted = bernoulli_distribution<>(0.5)(this->rng);
LOG_OUT << "coin flip: " << (state[i].adopted ? 1 : -1);
state[i].flipped = true;
}
LOG_OUT << "\n";
state[i].neighbors_adopted = n_adopted;
state[i].neighbors_decided = n_decided;
}
};
// same_neighborhood_log_odds_update_rule is an approximation to the above
// bikh_log_odds rule, in which a player interprets a neighbor's action as
// if the neighbor had access to all the player's neighbors, not just the ones
// the neighbor is connected to. This should bring the combinatorics under
// control. We think it's a conservative approximation, that's likely to make
// the model population less powerful, not more, because it makes these players
// less accurate.
template<typename network_t, typename params_t, typename rng_t>
class same_neighborhood_log_odds_update_rule :
public bikh_log_odds_update_rule<network_t,params_t,rng_t> {
public:
typedef typename
bikh_on_network_update_rule<network_t,params_t,rng_t>::vertex_index_t
vertex_index_t;
typedef typename
bikh_on_network_update_rule<network_t,params_t,rng_t>::state_container_t
state_container_t;
typedef typename
bikh_on_network_update_rule<network_t,params_t,rng_t>::compare_times
compare_times;
same_neighborhood_log_odds_update_rule(double p, rng_t &__rng) :
bikh_log_odds_update_rule<network_t,params_t,rng_t>(p, __rng) {}
// unlike the standard construct_neighbors_neighbors, which constructs the
// intersection of neighborhood(n1) and neighborhood(n2), here we just say
// n2's neighborhood is everyone in neighborhood(n1) who played before n2 did.
// We also use memoize to let n1 reuse the inferences that n2 generates, which
// allows us to save a whole lot of time.
virtual void construct_neighbors_neighbors( vertex_index_t n1,
set<vertex_index_t> &all_neighbors,
network_t &n,
set<vertex_index_t> &n1_neighbors,
state_container_t &state,
string indent) {
LOG_OUT << indent << " construct neighbors of " << n1 << ':';
for ( typename set<vertex_index_t>::iterator n2i = all_neighbors.begin();
n2i != all_neighbors.end(); ++n2i ) {
vertex_index_t n2 = *n2i;
if (state[n2].decided &&
state[n2].time_of_decision < state[n1].time_of_decision) {
n1_neighbors.insert(n2);
LOG_OUT << ' ' << n2;
} else {
LOG_OUT << " (" << n2 << ')';
}
}
LOG_OUT << endl;
}
using bikh_log_odds_update_rule<network_t,params_t,rng_t>::memoize_sum_of_influences_p;
virtual void figure_out_update(vertex_index_t i, bool signal,
network_t &n, params_t ¶ms, state_container_t &state) {
LOG_OUT << "figure_out_update(" << i << ")" << endl;
if ( memoize_sum_of_influences_p == NULL ) {
memoize_sum_of_influences_p = new map<vertex_index_t,float>;
}
memoize_sum_of_influences_p->clear();
bikh_log_odds_update_rule<network_t,params_t,rng_t>::figure_out_update(
i, signal, n, params, state);
}
};
// counting_closure_log_odds_update_rule is another approximation to the
// full bikh_log_odds, in which we do the full neighborhood-intersection
// inference up to n levels of recursion, and on the nth recursion we suppose
// that that person actually used the counting rule instead of recursing
// any farther.
template<typename network_t, typename params_t, typename rng_t>
class counting_closure_log_odds_update_rule :
public bikh_log_odds_update_rule<network_t,params_t,rng_t> {
public:
unsigned int close_level, level;
typedef typename
bikh_on_network_update_rule<network_t,params_t,rng_t>::state_container_t
state_container_t;
typedef typename
bikh_on_network_update_rule<network_t,params_t,rng_t>::vertex_index_t
vertex_index_t;
counting_closure_log_odds_update_rule(double p, rng_t &__rng) :
bikh_log_odds_update_rule<network_t,params_t,rng_t>(p, __rng),
close_level(-1), level(0) {}
using bikh_log_odds_update_rule<network_t,params_t,rng_t>::rho;
virtual float sum_of_influences(set<vertex_index_t>&neighbors,
vertex_index_t n0,
network_t &n, params_t ¶ms,
state_container_t &state, string indent = "") {
if ( close_level == (unsigned int)-1 ) {
close_level = params.inference_closure_level();
}
if ( level < close_level ) {
//LOG_OUT << indent << " " << level << " < " << close_level << endl;
++level;
float soi = bikh_log_odds_update_rule<network_t,params_t,rng_t>::
sum_of_influences( neighbors, n0, n, params, state, indent );
--level;
return soi;
}
// count the neighbors
typename set<vertex_index_t>::iterator ji;
unsigned n_decided = 0, n_adopted = 0;
for (ji = neighbors.begin(); ji != neighbors.end(); ++ji) {
vertex_index_t j = *ji;
if (state[j].decided) {
++n_decided;
if (state[j].adopted) {
++n_adopted;
}
}
}
int n_up = n_adopted, n_down = n_decided - n_adopted;
LOG_OUT << indent << "closure: " << n_up << " up, "
<< n_down << " down: " << (n_up - n_down) * rho << endl;
// convert to the log-odds that the outer sum_of_influences
// wants: (adoptions - rejections) times rho.
return (n_up - n_down) * rho;
}
};
template<typename network_t, typename params_t>
class network_dynamics {
public:
network_dynamics(network_t &n0, params_t &p0) {}
void step(void) {}
};
template<typename network_t, typename params_t,
typename update_rule_t, typename rng_t>
class update_everyone_once_dynamics :
public network_dynamics<network_t,params_t> {
public:
typedef typename update_rule_t::vertex_index_t vertex_index_t;
typedef typename update_rule_t::state_container_t state_container_t;
state_container_t _state;
network_t &n;
params_t ¶ms;
double _t;
deque<vertex_index_t> yet_to_update, already_updated;
update_rule_t updater;
update_everyone_once_dynamics(network_t &_n, params_t &_params, rng_t &rng_initializer) :
n(_n), params(_params), _state(num_vertices(_n)),
updater(_params.p(),rng_initializer), _t(0),
network_dynamics<network_t,params_t>(_n,_params) {
typename graph_traits<network_t>::vertex_iterator si,send;
tie(si,send) = vertices(n);
copy(si, send, inserter(yet_to_update, yet_to_update.begin()));
random_shuffle(yet_to_update.begin(), yet_to_update.end());
}
double t() { return _t; }
state_container_t &state() { return _state; }
void step() {
if (int(_t) % 100 == 0) {
cout << _t << "\n";
}
vertex_index_t i = yet_to_update.front();
yet_to_update.pop_front();
already_updated.push_back(i);
updater.update(i, _t, n, params, _state);
_t += 1;
}
};
template<typename network_t, typename state_t>
class color_cascade_state : public color_vertices<network_t> {
public:
typedef typename color_vertices<network_t>::key_type key_type;
typedef typename color_vertices<network_t>::value_type value_type;
using color_vertices<network_t>::n;
state_t &state;
color_cascade_state(network_t&_n, state_t&_s) :
color_vertices<network_t>(_n), state(_s) {}
value_type operator[](const key_type &e) const {
return (*this)(e,n);
}
value_type operator()(const key_type &e, const network_t&c) const {
if (!state[e].decided) {
return "white";
} else if (!state[e].adopted && !state[e].cascaded) {
return "red";
} else if (!state[e].adopted && state[e].cascaded) {
return "pink";
} else if (state[e].adopted && !state[e].cascaded) {
return "blue";
} else if (state[e].adopted && state[e].cascaded) {
return "lightblue";
}
}
};
template<typename network_t, typename state_t>
color_cascade_state<network_t, state_t>
make_color_cascade_state(network_t&n, state_t &s) {
return color_cascade_state<network_t,state_t>(n,s);
}
| true |
c5b15e51ac30cf27fb55c5dd6725cbac141f08dd | C++ | danillshir/7.1 | /5/5.cpp | UTF-8 | 1,107 | 3.1875 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
setlocale(0, "");
int array[10][10], a, b;
cout << "Введите количество строк: " << endl;
cin >> a;
cout << "Введите количество столбцов: " << endl;
cin >> b;
cout << "Введите элементы массива: " << endl;
for (int i = 0; i < a; i++)
for (int j = 0; j < b; j++)
{
cin >> array[i][j];
}
cout << "Матрица:\n";
for (int i = 0; i < a; i++)
{
for (int j = 0; j < b; j++)
cout << array[i][j] << "\t";
cout << endl;
}
cout << "Подсчет количества нечетных элементов\n";
int h = 0;
int sum = 0;
for (int i = 0; i < a; i++)
{
for (int j = 0; j < b; j++)
if (array[i][j] % 2 == 1)
{
h++;
sum += array[i][j];
}
}
cout << "Нечетных элементов = " << h << "\n" << "Их сумма = " << sum << "\n";
system("pause");
} | true |
ab9c9bc7ed5e74218beefc0465baaf3275f3159b | C++ | mmorri22/cse20312 | /Lecture02/char4.cpp | UTF-8 | 1,069 | 3.78125 | 4 | [] | no_license | /**********************************************
* File: char4.cpp
* Author: Matthew Morrison
* Email: matt.morrison@nd.edu
*
* This is a basic program to show students how to
* allocate a char pointer and memory, sets all the characters
* to Hello, World, and then prints their addresses and values
*
* Lecture 02 - Slide 37
**********************************************/
#include <iostream>
#include <cstdlib>
int main(void){
long unsigned int numCharacters = 13;
char* hello = (char *)malloc( numCharacters * sizeof(char) );
char* reference = hello;
*(hello + 0) = 'H';
*(hello + 1) = 'e';
*(hello + 2) = 'l';
*(hello + 3) = 'l';
*(hello + 4) = 'o';
*(hello + 5) = ',';
*(hello + 6) = ' ';
*(hello + 7) = 'W';
*(hello + 8) = 'o';
*(hello + 9) = 'r';
*(hello + 10) = 'l';
*(hello + 11) = 'd';
*(hello + 12) = '\n';
for(long unsigned int iter = 0; iter < numCharacters; iter++){
std::cout << (void *)reference << " " << *(reference) << std::endl;
reference = reference + 1;
}
free( hello );
return 0;
}
| true |
bdd2a821c608adddc917994f60c98eefb6d26674 | C++ | mwerezak/MTE380 | /oliphaunt/action.cpp | UTF-8 | 478 | 2.59375 | 3 | [] | no_license | #include "action.h"
void Action::start(ActionArgs *args) {
if(proc_status != STOPPED) return;
proc_status = RUNNING;
setup(args);
}
void Action::stop() {
if(proc_status != RUNNING) return;
cleanup();
proc_status = STOPPED;
}
void Action::suspend() {
if(proc_status != RUNNING) return;
proc_status = SUSPENDED;
}
void Action::restart() {
if(proc_status != SUSPENDED) return;
proc_status = RUNNING;
} | true |
3e1be75de6dfcc9da12acbf650267594b6dee04c | C++ | omerkatz1999/CS2B | /Assignment3_CS2b/Assignment3_CS2b/main.cpp | UTF-8 | 5,993 | 3.4375 | 3 | [] | no_license | //
// main.cpp
// Assignment3_CS2b
//
// Created by Omer Katz on 4/20/18.
// Copyright © 2018 Omer Katz. All rights reserved.
//
#include <iostream>
#include <string>
#include <iostream>
#include <sstream>
#include <cctype>
#include <cstdlib>
#include<iomanip>
using namespace std;
class Automaton
{
private:
static const int RULES_SIZE = 8;
static const int MAX_NUM = 255;
bool rule[RULES_SIZE];
string thisGen;
string extremeBit; // bit, "*" or " ", implied everywhere "outside"
int displayWidth; // an odd number so it can be perfectly centered
public:
static const int MAX_DISPLAY_WIDTH = 121;
static const int ruleSizeBits = 8;
Automaton(int rule);
string toStringCurrentGen();
bool setRule(int newRule); // change rule set
int convertBase(int newRule);
void resetFirstGen();
bool setDisplayWidth(int width);
void propagateNewGeneration();
};
Automaton::Automaton(int rule)
{
thisGen = "*";
extremeBit = " ";
if(!setRule(rule))
{
setRule(0);
}
else
{
setRule(rule);
}
}
bool Automaton::setRule(int newRule)
{
if( newRule < 0 || newRule > MAX_NUM)
{
return false;
}
// take binary and the converts to spring
int binary = convertBase(newRule);
ostringstream newString;
newString << binary;
string s = newString.str();
// adds zeros in front of the binary in to make it the size of 8
string placeHolder ="";
for( int i = 0; i< ruleSizeBits - s.length(); i++)
{
placeHolder += "0";
}
s = placeHolder + s;
// creates the array and places 0s and 1s according to rule (string)
bool rule [8];
for( int i = 0; i < ruleSizeBits; i++)
{
rule [i] = false;
}
for( int i = 1; i < s.length()+1; i++)
{
if (s.at(i-1) == '0')
{
rule [s.length()-i] = false;
}
else rule [s.length()-i] = true;
}
for(int i = 0; i < ruleSizeBits; i++)
{
this-> rule[i] = rule[i];
}
return true;
}
void Automaton::resetFirstGen()
{
extremeBit = " ";
thisGen = "*";
}
int Automaton::convertBase(int newRule)
{
if(newRule == 0)
{
return 0;
}
else
{
return (newRule % 2 + 10*convertBase(newRule/2));
}
}
bool Automaton::setDisplayWidth( int width )
{
if( width <= MAX_DISPLAY_WIDTH && width > 0
&& width % 2 == 1)
{
displayWidth = width;
return true;
}
return false;
}
string Automaton::toStringCurrentGen()
{
if( thisGen.length() < displayWidth)
{
double difference = displayWidth - thisGen.length();
int extremeBitPerSide = difference/2;
string filler = extremeBit;
for( int i = 1; i < extremeBitPerSide; i++)
{
filler += extremeBit;
}
string returnString = filler + thisGen + filler;
return returnString;
}
else if (thisGen.length() > displayWidth)
{
double difference = thisGen.length() - displayWidth;
int reduce = difference/2;
string returnString;
returnString = thisGen.substr(reduce, displayWidth);
return returnString;
}
else return thisGen;
}
void Automaton::propagateNewGeneration()
{
thisGen = extremeBit + extremeBit +thisGen + extremeBit + extremeBit;
int sizeSubstring = 3;
double amountOfSubstrings = thisGen.length() - 2;
string newString = "";
for( int i = 0; i < amountOfSubstrings; i++)
{
string sub = thisGen.substr(i,sizeSubstring);
if(sub == " ")
{
if(rule[0] == 1)
{
newString += "*";
}
else newString += " ";
}
else if(sub == " *")
{
if(rule[1])
{
newString += "*";
}
else newString += " ";
}
else if(sub ==" * ")
{
if(rule[2] == 1)
{
newString += "*";
}
else newString += " ";
}
else if(sub ==" **")
{
if(rule[3] == 1)
{
newString += "*";
}
else newString += " ";
}
else if(sub == "* ")
{
if(rule[4] == 1)
{
newString += "*";
}
else newString += " ";
}
else if(sub == "* *")
{
if(rule[5] == 1)
{
newString += "*";
}
else newString += " ";
}
else if(sub == "** ")
{
if(rule[6] == 1)
{
newString += "*";
}
else newString += " ";
}
else
{
if(rule[7] == 1)
{
newString += "*";
}
else newString += " ";
}
}
thisGen = newString;
if(extremeBit == " ")
{
if(rule[0])
{
extremeBit = "*";
}
else extremeBit = " ";
}
else
{
if(rule[7])
{
extremeBit = "*";
}
else extremeBit = " ";
}
return;
}
int main()
{
int rule;
for ( int i = 0 ; i < 4; i++){
cout << "Enter Rule (0 - 255): ";
cin >> rule;
Automaton aut(rule);
aut.setDisplayWidth(79);
cout << "start" << endl;
for( int i = 0; i < 99; i++)
{
cout<< aut.toStringCurrentGen() << endl;
aut.propagateNewGeneration();
}
cout << "end" << endl << endl;
}
}
//78 and 45 are cool
| true |
04ce5363d5bdcbafd476f5ee144757e85693bf4b | C++ | Weirb/scientific-computing | /project1/src/testing.h | UTF-8 | 14,135 | 3.140625 | 3 | [] | no_license | #ifndef TESTING_H
#define TESTING_H
#include <iostream>
#include <fstream>
#include "mvector.h"
#include "mmatrix.h"
#include "mbandedmatrix.h"
#include "functions.h"
#include "timing.h"
#include <vector>
#include <string>
const string DATAPATH = "/data";
// Task 3.2.1.3
void test_vector_overloads(){
/*
Test the addition and subtraction of MVectors.
*/
MVector v(3, 0.);
v(0) = 0.1;
v(1) = 4.8;
v(2) = 3.7;
MVector w(3);
w(0) = 3.1;
w(1) = 8.5;
w(2) = 3.6;
MVector x(3);
x(0) = 5.8;
x(1) = 7.4;
x(2) = 12.4;
MVector u = 4.7*v + 1.3*w - 6.7*x;
double tol = 1e-5;
bool u1 = u(1) - 4.7 * 0.1 + 1.3 * 3.1 - 6.7 * 5.8 < tol;
bool u2 = u(2) - 4.7 * 4.8 + 1.3 * 8.5 - 6.7 * 7.4 < tol;
bool u3 = u(3) - 4.7 * 3.7 + 1.3 * 3.6 - 6.7 * 12.4 < tol;
if (!(u1 && u2 && u3)){
cout << "Error in addition and subtraction of vectors.\n"
<< "Implementation is incorrect.\n";
}
}
// Task 3.2.2.4
void test_norms_dotproduct(){
/*
Test the norms and dot product of MVectors
*/
MVector u(3);
u(0) = 1.5;
u(1) = 1.3;
u(2) = 2.8;
MVector v(3);
v(0) = 6.5;
v(1) = 2.7;
v(2) = 2.9;
MVector w(3);
w(0) = 0.1;
w(1) = -7.2;
w(2) = 3.4;
// Answers correct to 6sf
double tol = 1e-5;
// Test u
cout << "Test of L2Norm(u): ";
if (u.L2Norm() - 3.4322 < tol)
cout << "correct";
else
cout << "incorrect";
cout << endl;
// Test v
cout << "Test of L2Norm(v): ";
if (v.L2Norm() - 7.61249 < tol)
cout << "correct";
else
cout << "incorrect";
cout << endl;
// Test w
cout << "Test of L2Norm(w): ";
if (w.L2Norm() - 7.96304 < tol)
cout << "correct";
else
cout << "incorrect";
cout << endl;
// Test value of alpha
cout << "Test dot product: ";
double alpha = dot(u, u) / dot(v, w);
if (alpha - (-1.31915) < tol)
cout << "correct";
else
cout << "incorrect";
cout << endl;
}
// Task 3.2.3.3
void test_matrix_vector_product() {
/* MATLAB test code
m = 4; n = 3;
A = zeros(m, n);
x = [0.5, 1.6, 3.2]';
for i = 1:m
for j = 1:n
A(i,j) = 3*(i-1) + (j-1);
end
end
A*x
*/
int m = 4, n = 3;
MMatrix A(m, n);
for (int i = 0; i < m; ++i){
for (int j = 0; j < n; ++j){
A(i, j) = 3 * i + j;
}
}
MVector x(3);
x(0) = 0.5;
x(1) = 1.6;
x(2) = 3.2;
MVector b = A*x;
}
// Task 3.2.4.5
void test_cg_algorithm(){
int n = 25;
MMatrix A = laplacian_1d(n);
MVector b = create_vector1(n);
MVector x0(n, 0.);
double tol = 1e-6;
VectorSolution sol = cg(A, b, x0, 1000, tol);
if (sol.iteration_count == 12){
cout << "Conjugate gradient took 12 iterations to converge.\n"
<< "Algorithm converged in expected manner.\n";
} else {
cout << "Conjugate gradient algorithm did "
"not take 12 iterations to converge.\n";
}
}
// Task 3.2.4.6
void create_cg_plot_laplacian_1d(){
// CG variables
MMatrix A;
MVector b, x0;
double tol = 1e-6;
VectorSolution sol;
// Output files
ofstream f("task3.2.4.6.dat");
if (!f.is_open()){
cerr << "Unable to open \"task3.2.4.6.dat\" for writing.\n"
<< "Exiting...\n";
exit(-1);
}
// Size of problems to solve
vector<int> ns = {10, 25, 100};
for (size_t k = 0; k < ns.size(); ++k){
int n = ns[k];
A = laplacian_1d(n);
b = create_vector1(n);
x0 = MVector(n, 0.);
// Compute solution
sol = cg(A, b, x0, 1000, tol);
// Output problem size, pad fields
f << n << "\t0\t0" << endl;
for (int i = 0; i < n; ++ i){
// Output format: tab separated values
// i;
// (i+1)/(n+1);
// x_i;
f << i << "\t"
<< (i + 1) / double(n + 1) << "\t"
<< sol.solution(i) << endl;
}
}
f.close();
}
// Task 3.2.4.7
void create_cg_table_laplacian_1d(){
// CG variables
MMatrix A;
MVector b, x0;
double tol = 1e-6;
VectorSolution sol;
double start = 0., end = 0.;
// Output files
ofstream f("task3.2.4.7.dat");
if (!f.is_open()){
cerr << "Unable to open \"task3.2.4.7.dat\" for writing.\n"
<< "Exiting...\n";
exit(-1);
}
for (int k = 0; k < 40; ++k){
int n = 5 * (k+1);
A = laplacian_1d(n);
b = create_vector1(n);
x0 = MVector(n, 0.);
// Compute solution
start = Timer();
sol = cg(A, b, x0, 1000, tol);
end = Timer();
// Output format: tab separated values
// n;
// iterations to converge;
// time to converge;
f << n << "\t"
<< sol.iteration_count << "\t"
<< (end-start) << endl;
}
f.close();
}
// Task 3.2.4.8, part 1
void create_cg_plot_matrix2(){
/*
Solve the previous problems, but with the matrix specified in the function
create_matrix2();
*/
// CG variables
double tol = 1e-3;
int max_iterations = 10000;
VectorSolution sol;
// Output files
ofstream f("task3.2.4.8-1.dat");
if (!f.is_open()){
cerr << "Unable to open \"task3.2.4.8-1.dat\" for writing.\n"
<< "Exiting...\n";
exit(-1);
}
// Size of problems to solve
vector<int> ns = {10, 25, 100};
vector<double> ms = {10., 5., 1., 0.1};
for (size_t n_count = 0; n_count < ns.size(); ++n_count){
int n = ns[n_count];
for (size_t m_count = 0; m_count < ms.size(); ++m_count){
double m = ms[m_count];
MMatrix A = create_matrix2(n, m);
MVector b = create_vector2(n);
MVector x0(n, 0.);
// Compute solution
sol = cg(A, b, x0, max_iterations, tol);
f << n << "\t" << m << "\t0" << endl;
for (int i = 0; i < n; ++ i){
// Output format: tab separated values
// i;
// (i+1)/(n+1);
// x_i;
f << i << "\t"
<< (i + 1) / double(n + 1) << "\t"
<< sol.solution(i) << endl;
}
}
}
f.close();
}
// Task 3.2.4.8, part 2
void create_cg_table_matrix2(){
/*
Create the table of values for timing and convergence of the matrix specified in
create_matrix2()
*/
// CG variables
MMatrix A;
MVector b, x0;
double tol = 1e-3;
int max_iterations = 10000;
VectorSolution sol;
double start = 0., end = 0.;
// Output files
ofstream f("task3.2.4.8-2.dat");
if (!f.is_open()){
cerr << "Unable to open \"task3.2.4.8-2.dat\" for writing.\n"
<< "Exiting...\n";
exit(-1);
}
// vector<int> ns = {10, 25, 50, 75, 100};
vector<double> ms = {10., 5., 1., 0.1};
for (size_t m_count = 0; m_count < ms.size(); ++m_count){
for (int k = 0; k < 20; ++k){
int n = 5 * (k + 1);
double m = ms[m_count];
A = create_matrix2(n, m);
b = create_vector2(n);
x0 = MVector(n, 0.);
// Compute solution
start = Timer();
sol = cg(A, b, x0, max_iterations, tol);
end = Timer();
// Output format: tab separated values
// n;
// m;
// iterations to converge;
// time to converge;
f << n << "\t" << m << "\t"
<< sol.iteration_count << "\t"
<< (end-start) << endl;
}
}
f.close();
}
// Task 3.2.5.1
void test_mbandedmatrix_impl(){
int n = 5, l = 1, r = 1;
MBandedMatrix A(n, n, l, r, 0.);
A(0, 0) = 1;
A(1, 1) = 2;
A(2, 2) = 3;
A(3, 3) = 4;
A(4, 4) = 5;
A(5, 5) = 6;
A(2, 3) = -9;
cout << A << endl;
}
// Task 3.2.5.4
void test_mbandedmatrix_cg_impl(){
// Define variables for banded and standard matrix
int n = 25;
MMatrix A1 = laplacian_1d(n);
MBandedMatrix A2 = laplacian_1d_banded(n);
MVector b = create_vector1(n);
MVector x0(n, 0.);
double tol = 1e-6;
// Compute solutions for each matrix
VectorSolution sol_matr = cg(A1, b, x0, 1000, tol);
VectorSolution sol_band = cg(A2, b, x0, 1000, tol);
// Compute the residuals for each matrix
MVector r1 = b - A1 * sol_matr.solution;
MVector r2 = b - A2 * sol_band.solution;
double rdiff = (r1 - r2).L2Norm();
if (rdiff < tol){
cout << "MBandedMatrix solution for CG algorithm agrees with MMatrix solution." << endl;
} else {
cout << "MBandedMatrix solution for CG algorithm does not agree with MMatrix solution." << endl;
}
cout << "Norm of difference of residuals: " << rdiff << endl;
}
// Task 3.2.5.6
void create_table_laplacian_1d_banded(){
// CG variables
MBandedMatrix A;
MVector b, x0;
double tol = 1e-6;
VectorSolution sol;
double start, end;
// Output files
ofstream f("task3.2.5.6.dat");
if (!f.is_open()){
cerr << "Unable to open \"task3.2.5.6.dat\" for writing.\n"
<< "Exiting...\n";
exit(-1);
}
// We get memory issues when n > 100
for (int k = 0; k < 40; ++k){
int n = 5 * (k+1);
A = laplacian_1d_banded(n);
b = create_vector1(n);
x0 = MVector(n, 0.);
// Compute solution
start = Timer();
sol = cg(A, b, x0, 1000, tol);
end = Timer();
// Output format: tab separated values
// n;
// iterations to converge;
// time to converge;
f << n << "\t"
<< sol.iteration_count << "\t"
<< (end-start) << endl;
}
f.close();
}
// Comparison_tabulated
void create_timings_laplace_operator_1d(){
// Find execution times for computing the solution using the CG algorithm
// for MMatrix and MBandedMatrix
// Output file
ofstream f("1d_timings.dat");
if (!f.is_open()){
cerr << "Unable to open \"1d_timings.dat\" for writing.\n"
<< "Exiting...\n";
exit(-1);
}
// Variables for computing cg
MMatrix A1;
MBandedMatrix A2;
MVector b, x0;
int maxiter = 1000;
double tol = 1e-6;
// Timing variables
double start1 = 0, end1 = 0;
double start2 = 0, end2 = 0;
for (int k = 0; k < 20; ++k ){
int n = 5 + 50* k;
A1 = laplacian_1d(n);
A2 = laplacian_1d_banded(n);
b = create_vector1(n);
x0 = MVector(n, 0.);
// Time CG using MMatrix
start1 = Timer();
VectorSolution sol1 = cg(A1, b, x0, maxiter, tol);
end1 = Timer();
// Time CG using MBandedMatrix
start2 = Timer();
VectorSolution sol2 = cg(A2, b, x0, maxiter, tol);
end2 = Timer();
// Output format: tab separated values
// size of matrix;
// time to execute cg for MMatrix;
// iterations to converge for MMatrix;
// time to execute cg for MBandedMatrix;
// iterations to converge for MBandedMatrix;
f << n << "\t" << (end1 - start1) << "\t"
<< sol1.iteration_count << "\t"
<< (end2 - start2) << "\t"
<< sol2.iteration_count << endl;
}
f.close();
}
// Task 3.3.4
void create_timings_laplace_operator_2d(){
// Find execution times for computing the solution using the CG algorithm
// for MMatrix and MBandedMatrix
// Output file
ofstream f("task3.3.4.dat");
if (!f.is_open()){
cerr << "Unable to open \"task3.3.4.dat\" for writing.\n"
<< "Exiting...\n";
exit(-1);
}
// Variables for computing cg
MMatrix A1;
MBandedMatrix A2;
MVector b, x0;
int maxiter = 1000;
double tol = 1e-6;
// Timing variables
double start1 = 0, end1 = 0;
double start2 = 0, end2 = 0;
for (int k = 0; k < 20; ++k ){
int n = 5 * (k+1);
A1 = laplacian_2d(n);
A2 = laplacian_2d_banded(n);
b = create_vector1(n * n);
x0 = MVector(n * n, 0.);
// Time CG using MMatrix
start1 = Timer();
VectorSolution sol1 = cg(A1, b, x0, maxiter, tol);
end1 = Timer();
// Time CG using MBandedMatrix
start2 = Timer();
VectorSolution sol2 = cg(A2, b, x0, maxiter, tol);
end2 = Timer();
// Output format: tab separated values
// size of matrix;
// time to execute cg for MMatrix;
// iterations to converge for MMatrix;
// time to execute cg for MBandedMatrix;
// iterations to converge for MBandedMatrix;
f << n*n << "\t" << (end1 - start1) << "\t"
<< sol1.iteration_count << "\t"
<< (end2 - start2) << "\t"
<< sol2.iteration_count << endl;
}
f.close();
}
// Task 3.3.5
void create_plot_data_laplace_operator_2d(){
// Generate a plot of the solution to the 2d laplace equation whose right
// hand side is the vector whose elements are 1/(n+1)^2
// Output file
ofstream f("task3.3.5.dat");
if (!f.is_open()){
cerr << "Unable to open \"task3.3.5.dat\" for writing.\n"
<< "Exiting...\n";
exit(-1);
}
// Variables for computing cg
int n = 25;
MBandedMatrix A = laplacian_2d_banded(n);
MVector b = create_vector1(n * n);
MVector x0(n * n, 0.);
int maxiter = 1000;
double tol = 1e-6;
VectorSolution sol = cg(A, b, x0, maxiter, tol);
// We want n values (k*n..k*n-1) for k=0..n-1 on each row.
// Don't include the final tab character at the end of each line.
for (int i = 0; i < n; ++i){
for (int j = 0; j < n - 1; ++j){
f << sol.solution(i * n + j) << "\t";
}
f << sol.solution(i * n + n - 1) << endl;
}
f.close();
}
#endif | true |
46136f5fe6ffd422accf8a0669c7df604080c2b6 | C++ | dxiong2000/USACO-Gold | /StarLeague USACO Gold/Searching 1/bds/bds.cpp | UTF-8 | 1,027 | 3.265625 | 3 | [] | no_license | // bds.cpp
#include <iostream>
#include <cmath>
using namespace std;
int n, finalsum, arr[100], arr2[100];
bool mark[100];
int factorial(int a) {
if (a == 0) {
return 1;
}
return a*factorial(a - 1);
}
int comb(int a, int b) { //aCb
return (factorial(a)) / (factorial(b)*factorial(a - b));
}
int solve() { //uses binomial expansion/pascals triangle to get final sum
int sum =0;
for (int i = 0; i < n; i++) { // n iterations for n variables
sum += arr[i] * comb(n - 1, i);
}
return sum;
}
void perms(int k) { // gets all permutations
if (k == n + 1) { // compare sum from solve() to final sum
if (solve() == finalsum) {
for (int i = 0; i < n; i++) {
if (i == n - 1) {
cout << arr2[i] << endl;
}
else {
cout << arr2[i] << " ";
}
}
exit(0);
}
return;
}
for (int i = 0; i < n; i++) {
if (!mark[i]) {
arr[i] = k;
arr2[i] = k;
mark[i] = true;
perms(k + 1);
mark[i] = false;
}
}
}
int main()
{
cin >> n >> finalsum;
perms(1);
return 0;
} | true |
d03416ed22382f0c4ae4b6b2d52744818a515b3d | C++ | SaberDa/LeetCode | /C++/3-longestSubstringWithoutRepeatingCharacters.cpp | UTF-8 | 720 | 3.046875 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <unordered_map>
#include <algorithm>
using namespace std;
int main() {
string s;
s = "abcabcbb";
if (s.empty()) {
return 0;
}
int maxLength = 0;
int start = 0;
unordered_map<char, int> substr;
for (int end = 0; end < s.size(); end++) {
char cur = s.at(end);
substr[cur]++;
while (substr[cur] != 1) {
char left = s.at(start);
substr[left]--;
if (substr[left] == 0) {
substr.erase(left);
}
start++;
}
maxLength = max(maxLength, end - start + 1);
}
cout << maxLength << endl;
return maxLength;
} | true |
ec5823ed0dddc5719bd095b0dc7a6f9958a14cce | C++ | sarath1502/Programming_for_Engineers | /HW2/HW2_U107184/root_finding.cpp | UTF-8 | 837 | 2.75 | 3 | [] | no_license | #include<iostream>
#include<cmath>
int main()
{
int length, n;
double f, f_prime, i_root, f_root, thold_input, thold_calc;
std::cin >> length;
for (int i = 0; i < length; i++)
{
std::cin >> i_root >> n >> thold_input;
thold_calc = std::numeric_limits<double>::max();
std::cout << "Case " << i << ":\n";
int j;
for (j = 0; j < n && thold_calc > thold_input; j++)
{
f = std::pow(i_root, 5) + 6 * std::pow(i_root, 4) + 3 * std::pow(i_root, 3) - i_root - 50;
f_prime = 5 * std::pow(i_root, 4) + 24 * std::pow(i_root, 3) + 9 * std::pow(i_root, 2) - 1;
f_root = i_root - (f / f_prime);
thold_calc = abs((f_root - i_root) / f_root);
i_root = f_root;
}
std::cout << "root at x = " << f_root << " with error " << thold_calc << " after " << j << " iterations\n";
}
return 0;
}
| true |
fd5f2caacdbbde2708549cf31d70aad2db75c363 | C++ | jaidurn/Design-Tests-take-2 | /Design Tests/UIDeckGrid.h | UTF-8 | 801 | 2.5625 | 3 | [] | no_license | #pragma once
#include "UIMenu.h"
#include "Deck.h"
class InputMessage;
class UIDeckGrid : public UIMenu
{
public:
UIDeckGrid(Vector2D position,
int width,
int height,
string texturePath,
int cardPerRow,
int rowCount,
Deck *deck);
virtual ~UIDeckGrid();
virtual void setWidth(int width);
virtual void setHeight(int height);
virtual void setActive(bool active);
virtual void setVisible(bool visible);
virtual void update(float delta);
virtual void processMessage(IMessage *message);
virtual void addItem(int itemID, UIComponent *item);
private:
int m_cardsPerRow;
int m_rowCount;
int m_rowOffset;
int m_currentCard;
void processInput(InputMessage *input);
void decreaseCurrent(int amount);
void increaseCurrent(int amount);
void adjustCards();
Deck *m_deck;
};
| true |
5e53018c643abe1b667bfcfeb4134c69f2099e46 | C++ | nnovoice/acmuva | /solutions/acm/AndysFirstDictionary10815/AndysFirstDictionary10815.cpp | UTF-8 | 2,017 | 3.265625 | 3 | [] | no_license | #include <iostream>
#include <set>
#include <string.h>
const int MAXCHARS = 1025;
using namespace std;
int main()
{
//int num = 0; /// LEARNING: this was not required
set<string> words;
set<string>::iterator iter;
set<string>::iterator iterEnd;
set<string> newWords;
set<string>::iterator newIter;
set<string>::iterator newIterEnd;
string input;
char c = ' ';
char charArr[MAXCHARS] = {' '};
int charIndex = 0;
while (cin >> input) {
//cout << input << endl;
words.insert(input);
}
iterEnd = words.end();
for (iter = words.begin(); iter != iterEnd; ++iter) {
//cout << (*iter) << endl;
memset (charArr, '\0', sizeof(char) * MAXCHARS);
int len = strlen((*iter).c_str());
charIndex = -1;
for (int i = 0; i < len; ++i) {
c = (*iter)[i];
if (c >= 'A' && c <= 'Z') {
//cout << 'a' + (c - 'A');
charArr[++charIndex] = 'a' + (c - 'A');
//cout << "@" << charArr[charIndex] << "@";
}
else if (c >= 'a' && c <= 'z') {
//cout << c;
charArr[++charIndex] = c;
}
else { /// LEARNING: a word is a set of consecutive alphabets. If we get anything else, the word ends
if (charIndex != -1)
newWords.insert(charArr);
charIndex = -1;
memset (charArr, '\0', sizeof(char) * MAXCHARS);
}
//cout << (*iter)[i];
}
if (charIndex != -1) /// LEARNING: if we get a set of chars which are non-alphabets, don't add without this check
newWords.insert(charArr);
//cout << endl;
}
newIterEnd = newWords.end();
for (newIter = newWords.begin(); newIter != newIterEnd; ++newIter) {
// if (num > 0) cout << endl; /// LEARNING: this was not required
// else ++num;
cout << (*newIter) << endl;
}
return 0;
}
| true |
1aeb9f2db9426c1ef3ddb474ea001cb6fa7c315c | C++ | arijit91/sorting-networks | /inversion.cpp | UTF-8 | 1,177 | 3.0625 | 3 | [] | no_license | #include<iostream>
#include<vector>
#include<cstdio>
using namespace std;
vector<int> a;
long long ret;
void merge(int lb , int mid , int ub)
{
int add = 0;
int lp = lb;
int rp = mid + 1;
vector<int> temp;
while( add <= ub - lb + 1 )
{
if( lp > mid )
temp.push_back( a[rp++] );
else if( rp > ub )
{
temp.push_back( a[lp++] );
ret += ub - mid ;
}
else if( a[lp] < a[rp] )
{
temp.push_back( a[lp++] );
ret += rp - mid - 1;
}
else
temp.push_back( a[rp++] );
add++;
}
for(int i = lb ; i <= ub ; i++)
a[i] = temp[i-lb];
}
void merge_sort( int lb , int ub )
{
if( lb >= ub )
return ;
int mid = (lb + ub)/2;
merge_sort(lb , mid);
merge_sort(mid+1,ub);
merge( lb , mid , ub );
}
long long inversions()
{
ret = 0;
merge_sort( 0 , a.size() - 1 );
return ret;
}
int main()
{
int n;
scanf("%d", &n);
a.clear();
a.resize(n);
for(int i = 0 ; i < n ; i++)
scanf("%d", &a[i]);
cout<<inversions()<<endl;
return 0;
}
| true |
80433a973b5d5a1d090f6674081cb6bd8a1646b4 | C++ | Globidev/graph | /app/srcs/osm/loader.cpp | UTF-8 | 3,013 | 2.625 | 3 | [] | no_license | #include "loader.hpp"
#include "constants.hpp"
namespace osm {
struct Visitor: public osmium::handler::Handler {
Visitor(ParsedData & data):
data_ { data }
{ }
~Visitor() {
uint count = 0;
std::unordered_map<NodeId, uint> node_id_map;
// Mapping node ids to a sequence
for (const auto & edge: raw_edges) {
if (!node_id_map.count(edge.first))
node_id_map.emplace(edge.first, count++);
if (!node_id_map.count(edge.second))
node_id_map.emplace(edge.second, count++);
}
// Building the edge vector
for (const auto & edge: raw_edges)
data_.edges.emplace_back(
node_id_map[edge.first],
node_id_map[edge.second]
);
// // Building the node vector
data_.nodes.resize(count);
for (const auto & pair: node_id_map)
data_.nodes[pair.second] = nodes_by_id[pair.first];
}
void node(osmium::Node & node) {
nodes_by_id.emplace(
std::piecewise_construct,
std::forward_as_tuple(node.id()),
std::forward_as_tuple(
node.location().lon(),
node.location().lat()
)
);
}
void way(osmium::Way & way) {
auto & tags = way.tags();
auto road_type = tags["highway"];
if (!road_type || !ROAD_FILTERS.count(road_type))
return ;
auto & nodes = way.nodes();
std::transform(
std::next(nodes.begin()),
nodes.end(),
nodes.begin(),
std::back_inserter(raw_edges),
[](auto & n2, auto & n1) {
return std::make_pair(n1.ref(), n2.ref());
}
);
auto one_way = tags["oneway"];
if(!one_way || strcmp(one_way, "yes") != 0) {
std::transform(
std::next(nodes.begin()),
nodes.end(),
nodes.begin(),
std::back_inserter(raw_edges),
[](auto & n2, auto & n1) {
return std::make_pair(n2.ref(), n1.ref());
}
);
}
}
private:
using NodesById = std::unordered_map<NodeId, spatial::Coordinates>;
std::vector<std::pair<NodeId, NodeId>> raw_edges;
NodesById nodes_by_id;
ParsedData & data_;
};
ParsedData load_protobuf(const std::string & file_name) {
ParsedData data;
osmium::io::File ifs { file_name };
osmium::io::Reader reader { ifs };
{
Visitor v { data };
osmium::apply(reader, v);
}
reader.close();
return data;
}
}
| true |
6abde5d475577b45a51fea81655780f22dd9802c | C++ | Guardian820/Teal | /include/util/util.inl | UTF-8 | 519 | 2.578125 | 3 | [
"MIT"
] | permissive | // Copyright (C) 2019 Samy Bensaid
// This file is part of the Teal project.
// For conditions of distribution and use, see copyright notice in LICENSE
#include <type_traits>
template<class T, class ReturnType = T>
ReturnType distance(const T& x, const T& y)
{
static_assert(std::is_arithmetic<ReturnType>::value, "Return type is not arithmetic");
return x > y ? x - y : y - x;
}
bool isLineEven(unsigned y)
{
TealAssert(y <= (Def::ArrayMapY + 1u), "Invalid y !");
return y % 2 == 0;
}
| true |
d847e13d707ef77a95e09615856bee180a547e83 | C++ | qanyue/code | /backup/AcmSkillTest.cpp | UTF-8 | 977 | 3.484375 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <utility>
#include <cmath>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
//交换a,b 不用第三个变量
int a{10}, b{20};
a ^= b, b ^= a, a ^= b;
cout << a << " " << b << endl;
// swap函数使用(包含在<utility>中
swap(a, b);
cout << a << " " << b << endl;
// 不用%确定奇偶
int z{};
cin >> z;
if(z & 1)
{
cout << " I'm single\n";
}else{
cout << "I'm double\n";
}
//找最高位数
cout << "输入整数来(最高位数): ";
int N{};
cin >> N;
double k = log10(N);
k -= floor(k);
int x = pow(10,k);
cout << x << endl;
//确定是不是2的幂
int m;
cout << "输入数字确定位数 : ";
cin >> m;
if(x && (!(x&(x-1))))
{
cout << "yes\n" ;
}
else
{
cout << " no";
}
return 0;
}
| true |
30bca8dbe8b8f850fc27234fd1d5b2a9e9e7c863 | C++ | onurguner/HackerRank | /cpp/Insertion Sort - Part 1.cpp | UTF-8 | 1,184 | 2.703125 | 3 | [] | no_license | #include <map>
#include <set>
#include <list>
#include <cmath>
#include <ctime>
#include <deque>
#include <queue>
#include <stack>
#include <bitset>
#include <cstdio>
#include <vector>
#include <cstdlib>
#include <numeric>
#include <sstream>
#include <iostream>
#include <algorithm>
using namespace std;
void printArray(vector <int> ar) {
for (int j = 0; j<ar.size(); j++) {
cout << ar[j] << " ";
}
cout << "\n";
}
void insertionSort(vector <int> ar) {
int iSize = ar.size();
int iEnd = ar[iSize-1];
for (int i = iSize-2; i>=0; i--) {
if (iEnd < ar[i]) {
ar[i+1] = ar[i];
printArray(ar);
if (i == 0) {
ar[i] = iEnd;
printArray(ar);
}
}
else {
ar[i+1] = iEnd;
printArray(ar);
break;
}
}
}
int main(void) {
vector <int> _ar;
int _ar_size;
cin >> _ar_size;
for(int _ar_i=0; _ar_i<_ar_size; _ar_i++) {
int _ar_tmp;
cin >> _ar_tmp;
_ar.push_back(_ar_tmp);
}
insertionSort(_ar);
return 0;
} | true |
49d19a911d3236ba58ac1a73e7489f16a7fb84a0 | C++ | IngoChou/Inline-Engine | /Engine/GameLogic/ContiguousVector.hpp | UTF-8 | 2,266 | 3.25 | 3 | [] | no_license | #pragma once
#include <vector>
#include <algorithm>
namespace inl::game {
template <class T, class Alloc = std::allocator<T>>
class ContiguousVector : private std::vector<T, Alloc> {
using VectorT = std::vector<T, Alloc>;
public:
using VectorT::allocator_type;
using VectorT::const_iterator;
using VectorT::const_pointer;
using VectorT::const_reference;
using VectorT::const_reverse_iterator;
using VectorT::iterator;
using VectorT::pointer;
using VectorT::reference;
using VectorT::reverse_iterator;
using VectorT::value_type;
using VectorT::size_type;
using VectorT::VectorT;
using VectorT::operator=;
using VectorT::assign;
using VectorT::get_allocator;
using VectorT::at;
using VectorT::operator[];
using VectorT::data;
using VectorT::front;
using VectorT::back;
using VectorT::begin;
using VectorT::cbegin;
using VectorT::cend;
using VectorT::crbegin;
using VectorT::crend;
using VectorT::end;
using VectorT::rbegin;
using VectorT::rend;
using VectorT::resize;
using VectorT::capacity;
using VectorT::empty;
using VectorT::max_size;
using VectorT::reserve;
using VectorT::shrink_to_fit;
using VectorT::size;
using VectorT::clear;
using VectorT::emplace_back;
using VectorT::push_back;
void erase(const_iterator it);
void erase(const_iterator first, const_iterator last);
void swap_elements(const_iterator elem1, const_iterator elem2);
};
template <class T, class Alloc>
void ContiguousVector<T, Alloc>::erase(const_iterator it) {
iterator last = --end(); // Container must not be empty to remove from it.
const_cast<T&>(*it) = std::move(*last);
VectorT::pop_back();
}
template <class T, class Alloc>
void ContiguousVector<T, Alloc>::erase(const_iterator first, const_iterator last) {
size_type count = last - first;
const_iterator endIt = cend();
const_iterator firstToMove = endIt - count;
firstToMove = std::max(last, firstToMove);
for (; firstToMove != endIt; ++firstToMove, ++first) {
const_cast<T&>(*first) = std::move(const_cast<T&>(*last));
}
resize(size() - count);
}
template <class T, class Alloc>
void ContiguousVector<T, Alloc>::swap_elements(const_iterator elem1, const_iterator elem2) {
std::swap(const_cast<T&>(*elem1), const_cast<T&>(*elem2));
}
} // namespace inl::game | true |
fe6926bfa0b8d2b46fd8e5b258dd5ad2e21e4576 | C++ | AmonJG/AdventOfCode2020 | /AdventOfCode2020/AdventOfCodeDay1.cpp | UTF-8 | 1,032 | 3.125 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include "AdventOfCodeDays.h"
AdventOfCodeTask1Day1::AdventOfCodeTask1Day1()
{
int inputEntry;
std::vector<int> inputList;
auto inputStream = GetInput("Day1.txt");
while (inputStream >> inputEntry)
{
inputList.push_back(inputEntry);
for (size_t i = 1; i < inputList.size(); i++)
{
if (inputList[inputList.size() - 1] + inputList[i - 1] == 2020)
{
std::cout << inputList[inputList.size() - 1] * inputList[i - 1];
return;
}
}
}
}
AdventOfCodeTask2Day1::AdventOfCodeTask2Day1()
{
int inputEntry;
std::vector<int> inputList;
auto inputStream = GetInput("Day1.txt");
while (inputStream >> inputEntry)
{
inputList.push_back(inputEntry);
for (size_t i = 1; i < inputList.size(); i++)
{
for (size_t x = 2; x < inputList.size(); x++)
{
if (inputList[inputList.size() - 1] + inputList[i - 1] + inputList[x - 2] == 2020)
{
std::cout << inputList[inputList.size() - 1] * inputList[i - 1] * inputList[x - 2];
return;
}
}
}
}
}
| true |
85d67c3b9f1e39fedb1576fd986b08c3e07fa321 | C++ | vector-of-bool/leaf | /test/handle_basic_test.cpp | UTF-8 | 3,275 | 2.625 | 3 | [
"BSL-1.0"
] | permissive | // Copyright (c) 2018-2019 Emil Dotchevski and Reverge Studios, Inc.
// 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)
#include <boost/leaf/config.hpp>
#ifndef LEAF_NO_EXCEPTIONS
# include <boost/leaf/handle_exception.hpp>
#endif
#include <boost/leaf/handle_error.hpp>
#include <boost/leaf/result.hpp>
#include "lightweight_test.hpp"
namespace leaf = boost::leaf;
enum class error_code
{
error1=1,
error2,
error3
};
namespace boost { namespace leaf {
template <> struct is_e_type<error_code>: public std::true_type { };
} }
leaf::result<int> compute_answer( int what_to_do ) noexcept
{
switch( what_to_do )
{
case 0:
return 42;
case 1:
return leaf::new_error(error_code::error1);
case 2:
return leaf::new_error(error_code::error2);
default:
assert(what_to_do==3);
return leaf::new_error(error_code::error3);
}
}
leaf::result<int> handle_some_errors( int what_to_do )
{
return leaf::try_handle_some(
[=]
{
return compute_answer(what_to_do);
},
[]( leaf::match<error_code,error_code::error1> )
{
return -42;
} );
}
leaf::result<float> handle_some_errors_float( int what_to_do )
{
return leaf::try_handle_some(
[=]() -> leaf::result<float>
{
return compute_answer(what_to_do);
},
[]( leaf::match<error_code,error_code::error2> )
{
return -42.0f;
} );
}
leaf::result<void> handle_some_errors_void( int what_to_do )
{
return leaf::try_handle_some(
[=]() -> leaf::result<void>
{
LEAF_AUTO(answer, compute_answer(what_to_do));
(void) answer;
return { };
},
[]( leaf::match<error_code,error_code::error3> )
{
} );
}
int main()
{
BOOST_TEST_EQ(handle_some_errors(0).value(), 42);
BOOST_TEST_EQ(handle_some_errors(1).value(), -42);
{
int r = leaf::try_handle_all(
[]() -> leaf::result<int>
{
LEAF_AUTO(answer,handle_some_errors(3));
(void) answer;
return 0;
},
[]( leaf::match<error_code,error_code::error3> )
{
return 1;
},
[]
{
return 2;
} );
BOOST_TEST_EQ(r, 1);
}
///////////////////////////
BOOST_TEST_EQ(handle_some_errors_float(0).value(), 42.0f);
BOOST_TEST_EQ(handle_some_errors_float(2).value(), -42.0f);
{
int r = leaf::try_handle_all(
[]() -> leaf::result<int>
{
LEAF_AUTO(answer,handle_some_errors_float(1));
(void) answer;
return 0;
},
[]( leaf::match<error_code,error_code::error1> )
{
return 1;
},
[]
{
return 2;
} );
BOOST_TEST_EQ(r, 1);
}
///////////////////////////
BOOST_TEST(handle_some_errors_void(0));
BOOST_TEST(handle_some_errors_void(3));
{
int r = leaf::try_handle_all(
[]() -> leaf::result<int>
{
LEAF_CHECK(handle_some_errors_void(2));
return 0;
},
[]( leaf::match<error_code,error_code::error2> )
{
return 1;
},
[]
{
return 2;
} );
BOOST_TEST_EQ(r, 1);
}
///////////////////////////
#ifndef LEAF_NO_EXCEPTIONS
{
int r = leaf::try_handle_all(
[]() -> leaf::result<int>
{
LEAF_CHECK(handle_some_errors_void(2));
return 0;
},
[]( leaf::catch_<std::exception> )
{
return 1;
},
[]
{
return 2;
} );
BOOST_TEST_EQ(r, 2);
}
#endif
return boost::report_errors();
}
| true |
73f070486c0edebd276340b294bd4f05fdfc2727 | C++ | mynick777/msdk | /msdk/mscom/managedb/managedb/connpool.h | GB18030 | 4,272 | 2.609375 | 3 | [] | no_license |
#pragma once
#include <vector>
#include <deque>
#include <database/genericdb.h>
#include <boost/thread.hpp>
#include <boost/thread/condition.hpp>
#include <assert.h>
class CONN_IMPL;
#define ASSERT assert
class CMyEvent
{
public:
CMyEvent()
{
m_hEvent = CreateEvent(
0,
TRUE,
FALSE,
NULL
);
ASSERT(m_hEvent);
};
~CMyEvent()
{
ASSERT(m_hEvent);
BOOL bRet = CloseHandle(m_hEvent);
};
public:
BOOL SetEvent()
{
ASSERT(m_hEvent);
return ::SetEvent(m_hEvent);
};
BOOL ResetEvent()
{
ASSERT(m_hEvent);
return ::ResetEvent(m_hEvent);
};
BOOL Wait(DWORD dwTimeOutInterval)
{
DWORD dwRet = ::WaitForSingleObject(
m_hEvent
,dwTimeOutInterval
);
if(WAIT_TIMEOUT == dwRet)
return FALSE;
return TRUE;
};
private:
HANDLE m_hEvent;
};
//ź.
class CMySemaphore
{
public:
CMySemaphore()
{
//const INT MAX_SEM_COUNT = 500;
//m_hSemaphore = CreateSemaphore(
// NULL, // default security attributes
// MAX_SEM_COUNT, // initial count
// MAX_SEM_COUNT, // maximum count
// NULL); // unnamed semaphore
//if(NULL == m_hSemaphore)
// return;
//m_lMaxCount = MAX_SEM_COUNT;
};
CMySemaphore(INT nSemaCount)
{
m_hSemaphore = CreateSemaphore(
NULL, // default security attributes
nSemaCount, // initial count
nSemaCount, // maximum count
NULL); // unnamed semaphore
if(NULL == m_hSemaphore)
return;
m_lMaxCount = nSemaCount;
};
~CMySemaphore()
{
if(m_hSemaphore)
CloseHandle(m_hSemaphore);
};
VOID init(INT nSemaCount)
{
m_hSemaphore = CreateSemaphore(
NULL, // default security attributes
nSemaCount, // initial count
nSemaCount, // maximum count
NULL); // unnamed semaphore
if(NULL == m_hSemaphore)
return;
m_lMaxCount = nSemaCount;
}
BOOL WaitSem(INT iTimeOutInterval)
{
DWORD dwWaitResult = WaitForSingleObject(m_hSemaphore,iTimeOutInterval);
if(WAIT_TIMEOUT == dwWaitResult)
return FALSE;
return TRUE;
}
BOOL ReleaseSem(LONG* pCount = NULL)
{
BOOL bRet = ReleaseSemaphore(m_hSemaphore,1,pCount);
return bRet;
}
//ȴ10ms * iTimeOutInterval
BOOL WaitAllCountFree(UINT uTimeOutInterval)
{
DWORD dwWaitTimeOut = 0;
while(TRUE)
{
BOOL bRet = WaitSem(10);
if(FALSE == bRet)
{//ʱ
continue;
}
LONG lCount = 0;
bRet = ReleaseSem(&lCount);
if(m_lMaxCount - 1 ==lCount)
return TRUE;
//ѭȴ.
Sleep(10);
if(++dwWaitTimeOut >= uTimeOutInterval)
return TRUE;
}
return FALSE;
}
private:
LONG m_lMaxCount;
HANDLE m_hSemaphore;
};
class CGetSem
{
public:
CGetSem(CMySemaphore* pSem)
{
if(NULL == pSem)
return ;
m_pSem = pSem;
BOOL bRet = m_pSem->WaitSem(-1);
};
~CGetSem()
{
if(NULL == m_pSem)
return ;
BOOL bRet = m_pSem->ReleaseSem();
};
private:
CMySemaphore* m_pSem;
};
class CConnPool
{
public:
CConnPool();
HRESULT Init(IUnknown* pRot, DWORD dwMin, DWORD dwMax, MsDBType dbType, LPCTSTR szConn ,LPCTSTR szDefaultDB);
VOID Uninit( VOID );
CONN_IMPL* GetConn();
VOID FreeConn( CONN_IMPL* pConn );
VOID GetDbgInfo( IMsBuffer* pBuffer );
STDMETHOD(ClosePoolConn)(VOID);
private:
HRESULT GetRealConn( CONN_IMPL** ppConn );
//++++++++++++++++++++
/*VOID ConnVecLock() {m_mutexReal.lock();}
VOID ConnVecUnLock() {m_mutexReal.unlock();}
VOID FreeListLock() {m_mutex.lock();}
VOID FreeListUnLock() {m_mutex.unlock();}*/
//+++++++++++++++++++++
HRESULT ResetService();
BOOL IsNeedReset();
BOOL SetNeedReset(BOOL bVal);
private:
typedef std::vector<CONN_IMPL*> Conn_Vec;
typedef std::deque<CONN_IMPL*> Free_List; // ӵ
Conn_Vec m_Conns;
boost::mutex m_mutexReal;
Free_List m_freeList; // ж
boost::mutex m_mutex;
boost::condition m_condition;
MsDBType m_dbType;
tstring m_strConn;
tstring m_defaultDB;
DWORD m_dwMin; // С
DWORD m_dwMax; // С
DWORD volatile m_dwCurrent; // ǰ
CMySemaphore m_Semaphone;
CMyEvent m_Event;
//boost::mutex m_MutexConn;
boost::mutex m_theLockReset;
BOOL m_bIsNeedReset;
DWORD m_dwResetCounter;
UTIL::com_ptr<IMscomRunningObjectTable> m_pRot;
}; | true |
3db456e4f2344f32f3d8295a02a8bf104fec65e0 | C++ | GPDP2/vba-next | /src/sound_gb_apu.inl | UTF-8 | 13,461 | 2.703125 | 3 | [] | no_license | /*============================================================
GB APU
============================================================ */
/* 0: Square 1, 1: Square 2, 2: Wave, 3: Noise */
#define OSC_COUNT 4
/* Resets hardware to initial power on state BEFORE boot ROM runs. Mode selects*/
/* sound hardware. Additional AGB wave features are enabled separately.*/
#define MODE_AGB 2
#define START_ADDR 0xFF10
#define END_ADDR 0xFF3F
/* Reads and writes must be within the START_ADDR to END_ADDR range, inclusive.*/
/* Addresses outside this range are not mapped to the sound hardware.*/
#define REGISTER_COUNT 48
#define REGS_SIZE 64
/* Clock rate that sound hardware runs at.
* formula: 4194304 * 4
* */
#define CLOCK_RATE 16777216
struct gb_apu_t
{
bool reduce_clicks_;
uint8_t regs[REGS_SIZE]; // last values written to registers
int32_t last_time; // time sound emulator has been run to
int32_t frame_time; // time of next frame sequencer action
int32_t frame_period; // clocks between each frame sequencer step
int32_t frame_phase; // phase of next frame sequencer step
double volume_;
Gb_Osc* oscs [OSC_COUNT];
Gb_Sweep_Square square1;
Gb_Square square2;
Gb_Wave wave;
Gb_Noise noise;
Blip_Synth good_synth;
Blip_Synth med_synth;
} gb_apu;
// Format of save state. Should be stable across versions of the library,
// with earlier versions properly opening later save states. Includes some
// room for expansion so the state size shouldn't increase.
struct gb_apu_state_t
{
// Values stored as plain int so your code can read/write them easily.
// Structure can NOT be written to disk, since format is not portable.
typedef int val_t;
enum { format0 = 0x50414247 };
val_t format; // format of all following data
val_t version; // later versions just add fields to end
unsigned char regs [0x40];
val_t frame_time;
val_t frame_phase;
val_t sweep_freq;
val_t sweep_delay;
val_t sweep_enabled;
val_t sweep_neg;
val_t noise_divider;
val_t wave_buf;
val_t delay [4];
val_t length_ctr [4];
val_t phase [4];
val_t enabled [4];
val_t env_delay [3];
val_t env_volume [3];
val_t env_enabled [3];
val_t unused [13]; // for future expansion
};
#define VOL_REG 0xFF24
#define STEREO_REG 0xFF25
#define STATUS_REG 0xFF26
#define WAVE_RAM 0xFF30
#define POWER_MASK 0x80
#define OSC_COUNT 4
static void gb_apu_reduce_clicks( bool reduce )
{
gb_apu.reduce_clicks_ = reduce;
/* Click reduction makes DAC off generate same output as volume 0*/
int dac_off_amp = 0;
gb_apu.oscs[0]->dac_off_amp = dac_off_amp;
gb_apu.oscs[1]->dac_off_amp = dac_off_amp;
gb_apu.oscs[2]->dac_off_amp = dac_off_amp;
gb_apu.oscs[3]->dac_off_amp = dac_off_amp;
/* AGB always eliminates clicks on wave channel using same method*/
gb_apu.wave.dac_off_amp = -DAC_BIAS;
}
static void gb_apu_synth_volume( int iv )
{
double v = gb_apu.volume_ * 0.60 / OSC_COUNT / 15 /*steps*/ / 8 /*master vol range*/ * iv;
gb_apu.good_synth.volume( v );
gb_apu.med_synth .volume( v );
}
static void gb_apu_apply_volume (void)
{
int data, left, right, vol_tmp;
data = gb_apu.regs [VOL_REG - START_ADDR];
left = data >> 4 & 7;
right = data & 7;
vol_tmp = left < right ? right : left;
gb_apu_synth_volume( vol_tmp + 1 );
}
static void gb_apu_silence_osc( Gb_Osc& o )
{
int delta = -o.last_amp;
if (delta)
{
o.last_amp = 0;
if (o.output)
gb_apu.med_synth.offset( gb_apu.last_time, delta, o.output );
}
}
static void gb_apu_run_until_( int32_t end_time )
{
int32_t time;
do
{
/* run oscillators*/
time = end_time;
if ( time > gb_apu.frame_time )
time = gb_apu.frame_time;
gb_apu.square1.run( gb_apu.last_time, time );
gb_apu.square2.run( gb_apu.last_time, time );
gb_apu.wave .run( gb_apu.last_time, time );
gb_apu.noise .run( gb_apu.last_time, time );
gb_apu.last_time = time;
if ( time == end_time )
break;
/* run frame sequencer*/
gb_apu.frame_time += gb_apu.frame_period * CLK_MUL;
switch ( gb_apu.frame_phase++ )
{
case 2:
case 6:
/* 128 Hz*/
gb_apu.square1.clock_sweep();
case 0:
case 4:
/* 256 Hz*/
gb_apu.square1.clock_length();
gb_apu.square2.clock_length();
gb_apu.wave .clock_length();
gb_apu.noise .clock_length();
break;
case 7:
/* 64 Hz*/
gb_apu.frame_phase = 0;
gb_apu.square1.clock_envelope();
gb_apu.square2.clock_envelope();
gb_apu.noise .clock_envelope();
}
}while(1);
}
INLINE void Gb_Sweep_Square::write_register( int frame_phase, int reg, int old_data, int data )
{
if ( reg == 0 && sweep_enabled && sweep_neg && !(data & 0x08) )
enabled = false; // sweep negate disabled after used
if ( Gb_Square::write_register( frame_phase, reg, old_data, data ) )
{
sweep_freq = GB_OSC_FREQUENCY();
sweep_neg = false;
reload_sweep_timer();
sweep_enabled = (regs [0] & (PERIOD_MASK | SHIFT_MASK)) != 0;
if ( regs [0] & SHIFT_MASK )
calc_sweep( false );
}
}
INLINE void Gb_Wave::write_register( int frame_phase, int reg, int old_data, int data )
{
switch (reg)
{
case 0:
if (!GB_WAVE_DAC_ENABLED())
enabled = false;
break;
case 1:
length_ctr = 256 - data;
break;
case 4:
bool was_enabled = enabled;
if (write_trig( frame_phase, 256, old_data))
{
if ( !GB_WAVE_DAC_ENABLED() )
enabled = false;
phase = 0;
delay = period() + CLK_MUL_MUL_6;
}
}
}
INLINE void Gb_Noise::write_register( int frame_phase, int reg, int old_data, int data )
{
if ( Gb_Env::write_register( frame_phase, reg, old_data, data ) )
{
phase = 0x7FFF;
delay += CLK_MUL_MUL_8;
}
}
static void gb_apu_write_osc( int index, int reg, int old_data, int data )
{
reg -= index * 5;
switch ( index )
{
case 0:
gb_apu.square1.write_register( gb_apu.frame_phase, reg, old_data, data );
break;
case 1:
gb_apu.square2.write_register( gb_apu.frame_phase, reg, old_data, data );
break;
case 2:
gb_apu.wave.write_register( gb_apu.frame_phase, reg, old_data, data );
break;
case 3:
gb_apu.noise.write_register( gb_apu.frame_phase, reg, old_data, data );
break;
}
}
static INLINE int gb_apu_calc_output( int osc )
{
int bits = gb_apu.regs [STEREO_REG - START_ADDR] >> osc;
return (bits >> 3 & 2) | (bits & 1);
}
static void gb_apu_write_register( int32_t time, unsigned addr, int data )
{
int reg = addr - START_ADDR;
if ((unsigned) reg >= REGISTER_COUNT)
return;
if ( addr < STATUS_REG && !(gb_apu.regs [STATUS_REG - START_ADDR] & POWER_MASK) )
return; /* Power is off*/
if ( time > gb_apu.last_time )
gb_apu_run_until_( time );
if ( addr >= WAVE_RAM )
gb_apu.wave.write( addr, data );
else
{
int old_data = gb_apu.regs [reg];
gb_apu.regs [reg] = data;
if ( addr < VOL_REG )
gb_apu_write_osc( reg / 5, reg, old_data, data ); /* Oscillator*/
else if ( addr == VOL_REG && data != old_data )
{
/* Master volume*/
for ( int i = OSC_COUNT; --i >= 0; )
gb_apu_silence_osc( *gb_apu.oscs [i] );
gb_apu_apply_volume();
}
else if ( addr == STEREO_REG )
{
/* Stereo panning*/
for ( int i = OSC_COUNT; --i >= 0; )
{
Gb_Osc& o = *gb_apu.oscs [i];
Blip_Buffer* out = o.outputs [gb_apu_calc_output( i )];
if ( o.output != out )
{
gb_apu_silence_osc( o );
o.output = out;
}
} }
else if ( addr == STATUS_REG && (data ^ old_data) & POWER_MASK )
{
/* Power control*/
gb_apu.frame_phase = 0;
for ( int i = OSC_COUNT; --i >= 0; )
gb_apu_silence_osc( *gb_apu.oscs [i] );
for ( int i = 0; i < 32; i++ )
gb_apu.regs [i] = 0;
gb_apu.square1.reset();
gb_apu.square2.reset();
gb_apu.wave .reset();
gb_apu.noise .reset();
gb_apu_apply_volume();
gb_apu.square1.length_ctr = 64;
gb_apu.square2.length_ctr = 64;
gb_apu.wave .length_ctr = 256;
gb_apu.noise .length_ctr = 64;
gb_apu.regs [STATUS_REG - START_ADDR] = data;
}
}
}
static void gb_apu_reset( uint32_t mode, bool agb_wave )
{
/* Hardware mode*/
mode = MODE_AGB; /* using AGB wave features implies AGB hardware*/
gb_apu.wave.agb_mask = 0xFF;
gb_apu.oscs [0]->mode = mode;
gb_apu.oscs [1]->mode = mode;
gb_apu.oscs [2]->mode = mode;
gb_apu.oscs [3]->mode = mode;
gb_apu_reduce_clicks( gb_apu.reduce_clicks_ );
/* Reset state*/
gb_apu.frame_time = 0;
gb_apu.last_time = 0;
gb_apu.frame_phase = 0;
for ( int i = 0; i < 32; i++ )
gb_apu.regs [i] = 0;
gb_apu.square1.reset();
gb_apu.square2.reset();
gb_apu.wave .reset();
gb_apu.noise .reset();
gb_apu_apply_volume();
gb_apu.square1.length_ctr = 64;
gb_apu.square2.length_ctr = 64;
gb_apu.wave .length_ctr = 256;
gb_apu.noise .length_ctr = 64;
/* Load initial wave RAM*/
static unsigned char const initial_wave [2] [16] = {
{0x84,0x40,0x43,0xAA,0x2D,0x78,0x92,0x3C,0x60,0x59,0x59,0xB0,0x34,0xB8,0x2E,0xDA},
{0x00,0xFF,0x00,0xFF,0x00,0xFF,0x00,0xFF,0x00,0xFF,0x00,0xFF,0x00,0xFF,0x00,0xFF},
};
for ( int b = 2; --b >= 0; )
{
/* Init both banks (does nothing if not in AGB mode)*/
gb_apu_write_register( 0, 0xFF1A, b * 0x40 );
for ( unsigned i = 0; i < sizeof initial_wave [0]; i++ )
gb_apu_write_register( 0, i + WAVE_RAM, initial_wave [1] [i] );
}
}
static void gb_apu_new(void)
{
int i;
gb_apu.wave.wave_ram = &gb_apu.regs [WAVE_RAM - START_ADDR];
gb_apu.oscs [0] = &gb_apu.square1;
gb_apu.oscs [1] = &gb_apu.square2;
gb_apu.oscs [2] = &gb_apu.wave;
gb_apu.oscs [3] = &gb_apu.noise;
for ( i = OSC_COUNT; --i >= 0; )
{
Gb_Osc& o = *gb_apu.oscs [i];
o.regs = &gb_apu.regs [i * 5];
o.output = 0;
o.outputs [0] = 0;
o.outputs [1] = 0;
o.outputs [2] = 0;
o.outputs [3] = 0;
o.good_synth = &gb_apu.good_synth;
o.med_synth = &gb_apu.med_synth;
}
gb_apu.reduce_clicks_ = false;
gb_apu.frame_period = 4194304 / 512; /* 512 Hz*/
gb_apu.volume_ = 1.0;
gb_apu_reset(MODE_AGB, false);
}
static void gb_apu_set_output( Blip_Buffer* center, Blip_Buffer* left,
Blip_Buffer* right, int osc )
{
int i = osc;
do
{
Gb_Osc& o = *gb_apu.oscs [i];
o.outputs [1] = right;
o.outputs [2] = left;
o.outputs [3] = center;
o.output = o.outputs [gb_apu_calc_output( i )];
++i;
}while (i < osc);
}
static void gb_apu_volume( double v )
{
if (gb_apu.volume_ != v)
{
gb_apu.volume_ = v;
gb_apu_apply_volume();
}
}
static void gb_apu_apply_stereo (void)
{
int i;
for (i = OSC_COUNT; --i >= 0;)
{
Gb_Osc& o = *gb_apu.oscs [i];
Blip_Buffer* out = o.outputs [gb_apu_calc_output( i )];
if (o.output != out)
{
gb_apu_silence_osc( o );
o.output = out;
}
}
}
#define REFLECT( x, y ) (save ? (io->y) = (x) : (x) = (io->y) )
static INLINE const char* gb_apu_save_load( gb_apu_state_t* io, bool save )
{
int format, version;
format = io->format0;
REFLECT( format, format );
if ( format != io->format0 )
return "Unsupported sound save state format";
version = 0;
REFLECT( version, version );
/* Registers and wave RAM*/
if (save)
memcpy( io->regs, gb_apu.regs, sizeof io->regs );
else
memcpy( gb_apu.regs, io->regs, sizeof(gb_apu.regs) );
/* Frame sequencer*/
REFLECT( gb_apu.frame_time, frame_time );
REFLECT( gb_apu.frame_phase, frame_phase );
REFLECT( gb_apu.square1.sweep_freq, sweep_freq );
REFLECT( gb_apu.square1.sweep_delay, sweep_delay );
REFLECT( gb_apu.square1.sweep_enabled, sweep_enabled );
REFLECT( gb_apu.square1.sweep_neg, sweep_neg );
REFLECT( gb_apu.noise.divider, noise_divider );
REFLECT( gb_apu.wave.sample_buf, wave_buf );
return 0;
}
/* second function to avoid inline limits of some compilers*/
static INLINE void gb_apu_save_load2( gb_apu_state_t* io, bool save )
{
int i;
for (i = OSC_COUNT; --i >= 0;)
{
Gb_Osc& osc = *gb_apu.oscs [i];
REFLECT( osc.delay, delay [i] );
REFLECT( osc.length_ctr, length_ctr [i] );
REFLECT( osc.phase, phase [i] );
REFLECT( osc.enabled, enabled [i] );
if (i != 2)
{
int j = 2 < i ? 2 : i;
Gb_Env& env = STATIC_CAST(Gb_Env&,osc);
REFLECT( env.env_delay, env_delay [j] );
REFLECT( env.volume, env_volume [j] );
REFLECT( env.env_enabled, env_enabled [j] );
}
}
}
static void gb_apu_save_state( gb_apu_state_t* out )
{
(void) gb_apu_save_load( out, true );
gb_apu_save_load2( out, true );
}
static const char * gb_apu_load_state( gb_apu_state_t const& in )
{
RETURN_ERR( gb_apu_save_load( CONST_CAST(gb_apu_state_t*,&in), false));
gb_apu_save_load2( CONST_CAST(gb_apu_state_t*,&in), false );
gb_apu_apply_stereo();
gb_apu_synth_volume( 0 ); /* suppress output for the moment*/
gb_apu_run_until_( gb_apu.last_time ); /* get last_amp updated*/
gb_apu_apply_volume(); /* now use correct volume*/
return 0;
}
| true |
c03fb0e99fba3c5b9f0a310871a79cb0c5c74d31 | C++ | Kale-Grabovski/cpp-patterns | /Command/Broker.cpp | UTF-8 | 353 | 2.71875 | 3 | [] | no_license | #include <memory>
#include <algorithm>
#include "Order.h"
#include "Broker.h"
void Broker::takeOrder(const std::shared_ptr<Order> order) {
orderList.push_back(order);
}
void Broker::placeOrders() {
std::for_each(orderList.begin(), orderList.end(), [](std::shared_ptr<Order> order) {
order->execute();
});
orderList.clear();
}
| true |
ef2c741e47c51f283a5c15f5f2da993736d223a1 | C++ | LauraDiosan-CS/lab8-11-polimorfism-GRazvan12 | /IEntity.cpp | UTF-8 | 2,565 | 3.6875 | 4 | [] | no_license | #include "IEntity.h"
//Desc: creates a new object of type IEntity
//In: -
//Out: a new object of type IEntity with implicit values
IEntity::IEntity() {
this->id = 0;
this->name = "";
}
//Desc: creates a new object of type IEntity
//In: id, string - the id to be given to the new object
// name, string - the name to be given to the new object
//Out: a new object of type IEntity with values given by this parameters
IEntity::IEntity(int id, string name) {
this->id = id;
this->name = name;
}
//Desc: creates a new object of type Employee
//In: e, const IEntity& - an object of type IEntity
//Out: a new object of type IEntity with values given by the object in parameters
IEntity::IEntity(const IEntity& e) {
this->id = e.id;
this->name = e.name;
}
//Desc: sets a new id to the current object
//In: id, string - the new id
//Out: -
void IEntity::setID(int id) {
this->id = id;
}
//Desc: sets a new name to the current object
//In: name, string - the new name
//Out: -
void IEntity::setName(string name) {
this->name = name;
}
//Desc: access the id of the current object
//In: -
//Out: the object's id
int IEntity::getID() const {
return this->id;
}
//Desc: access the name of the current object
//In: -
//Out: the object's name
string IEntity::getName() const {
return this->name;
}
//Desc: checks if the objects are equal
//In: e, const IEntity& - an object of type IEntity
//Out: true/false
bool IEntity::operator==(const IEntity& e) {
return (this->id == e.id && this->name == e.name);
}
//Desc: checks if the objects are equal
//In: e, const IEntity& - an object of type IEntity
//Out: true/false
bool IEntity::operator!=(const IEntity& e) {
return (this->id != e.id || this->name != e.name);
}
//Desc: turns current object into a string with values separated by a delimiter
//In: del, string - the delimiter
//Out: string with current object's values separated by del
string IEntity::toString(string del) {
string obj = "";
obj = obj + to_string(this->id) + del + this->name;
return obj;
}
//Desc: creates a clone of the current object
//In: -
//Out: e, IEntity* - the clone of the current object
IEntity* IEntity::clone() {
IEntity* e = new IEntity(this->id, this->name);
return e;
}
//Desc: check if current object has the same values with another object
//In: ent, IEntity* - the object to check the equality with
//Out: true/false
bool IEntity::equals(IEntity* ent) {
return (this->id == ent->id && this->name == ent->name);
} | true |
d251470b4533c2b83cdb3bd3f7180ad6f762fe45 | C++ | marcinkociolek/CarrotMarker | /carrotdefect.h | UTF-8 | 1,267 | 2.625 | 3 | [] | no_license | #ifndef CARROTDEFECT_H
#define CARROTDEFECT_H
#include <string>
const int defectCount = 15;
const std::string DefectNames[defectCount] = {
"LargeBlackPatches - ",
"SmallBlackPatches - ",
"BlackEnd - ",
"RotEnd - ",
"RotOutEnd - ",
"WhiteFungus - ",
"GreenHead - ",
"CrackTravsverse - ",
"CrackLongitudial - ",
"Curvature - ",
"Split - ",
"OtherShapeDeformation - ",
"BiteInsect - ",
"BiteAnimal - ",
"Soilure - "
};
const std::string DefectNamesShort[defectCount] = {
"LargeBlackPatches",
"SmallBlackPatches",
"BlackEnd",
"RotEnd",
"RotOutEnd",
"WhiteFungus",
"GreenHead",
"CrackTravsverse",
"CrackLongitudial",
"Curvature",
"Split",
"OtherShapeDeformation",
"BiteInsect",
"BiteAnimal",
"Soilure"
};
class CarrotDefect
{
public:
bool defect[defectCount];
CarrotDefect();
bool GetDefect(int defectNr);
void SetDefect(int defectNr);
void Init();
void Load(std::string FileName);
void Save(std::string FileName);
};
#endif // CARROTDEFECT_H
| true |
6361206945bce1229790ba707f570e08a52d45d0 | C++ | cornell-brg/xloops-bmarks | /stdx/stdx-MiscUtils.inl | UTF-8 | 1,739 | 2.78125 | 3 | [] | no_license | //========================================================================
// stdx-MiscUtils.inl
//========================================================================
// We make the bit fields inline because often the msb and lsb are
// compile time constants so it is very likely that the compiler can
// optimize much of this away.
#include "stdx-Exception.h"
namespace stdx {
//----------------------------------------------------------------------
// nl
//----------------------------------------------------------------------
template <typename Ch, typename Tr>
std::basic_ostream<Ch,Tr>& nl( std::basic_ostream<Ch,Tr>& os )
{
return os.put(os.widen('\n'));
}
//----------------------------------------------------------------------
// verify_bit_field
//----------------------------------------------------------------------
inline void verify_bit_field( int msb, int lsb )
{
STDX_ASSERT( (msb < 32) && (msb >= 0) );
STDX_ASSERT( (lsb < 32) && (lsb >= 0) );
STDX_ASSERT( msb >= lsb );
}
//----------------------------------------------------------------------
// extract_bit_field_fast
//----------------------------------------------------------------------
inline uint32_t extract_bit_field_fast( uint32_t bits,
int msb, int lsb )
{
return (bits & ~(~1u << msb)) >> lsb;
}
//----------------------------------------------------------------------
// extract_bit_field
//----------------------------------------------------------------------
inline uint32_t extract_bit_field( uint32_t bits, int msb, int lsb )
{
verify_bit_field( msb, lsb );
return extract_bit_field_fast( bits, msb, lsb );
}
}
| true |
4f6d325b22d047cad613c303bb629137f6a9c154 | C++ | nicepepper/oop | /lab3/Car/Car/car.h | UTF-8 | 574 | 3.109375 | 3 | [] | no_license | #pragma once
#include <string>
class Car
{
public:
Car();
bool TurnOnEngine();
bool TurnOffEngine();
bool SetGear(int gear);
bool SetSpeed(int speed);
int GetGear() const;
int GetSpeed() const;
bool DoesEngineTurnedOn() const;
std::string GetMoveState() const;
private:
enum Move
{
STOP,
BACKWARD,
FORWARD
};
bool SetGearIfParamsValid(int minSpeed, int maxSpeed, int gear, Move currentMove);
bool UpdateSpeedAndCarMoveIfSpeedInRange(int minSpeed, int maxSpeed, int speed, Move move);
bool m_engineTurnedOn;
int m_speed;
int m_gear;
Move m_move;
};
| true |
7bd0c20ee2dca00ed3de3859787f99f1fec9e79d | C++ | VidushiGupta80/leetcode | /solutions/validate-stack-sequences.cpp | UTF-8 | 497 | 3.453125 | 3 | [] | no_license | //Validate Stack Sequences -> 08/22/2020 11:59
class Solution {
public:
bool validateStackSequences(vector<int>& pushed, vector<int>& popped) {
stack<int> stk;
int popp = 0;
for(int pushh = 0; pushh < pushed.size(); pushh++)
{
stk.push(pushed[pushh]);
while(!stk.empty() && stk.top() == popped[popp])
{
stk.pop();
popp++;
}
}
return popp == popped.size();
}
};
| true |
7d3c279441c49383e088a9a584160f91a1ec4d79 | C++ | coolsuperman/Practice-Cpp | /P-YinZiGeShu/main.cc | UTF-8 | 677 | 2.984375 | 3 | [] | no_license | // write your code here cpp
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
void DigitNum(vector<int>& back,int& num){
for(int i= 2;i*i<=num;i++){
if(num%i==0){
back.push_back(i);
num/=i;
DigitNum(back,num);
break;
}
}
return;
}
int main(){
int num;
while(cin>>num){
vector<int> all;
DigitNum(all,num);
if(num!=1)
all.push_back(num);
sort(all.begin(),all.end());
int count=0;
for(size_t i = 0;i<all.size();++i){
if(i==0)
count++;
else{
if(all[i-1]!=all[i])
count++;
}
}
cout<<count<<endl;
}
return 0;
}
}
}
}
}
}
}
}
| true |
c9fab6e4b742b78004c4df84b6a949c5f2509065 | C++ | jeniffer9/ETHZ-AlgoLab-2020 | /9. BGL Advanced Flows/1. Real Estate Market.cpp | UTF-8 | 2,575 | 2.65625 | 3 | [] | no_license | #include <iostream>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/push_relabel_max_flow.hpp>
#include <boost/graph/successive_shortest_path_nonnegative_weights.hpp>
#include <boost/graph/find_flow_cost.hpp>
typedef boost::adjacency_list_traits<boost::vecS, boost::vecS, boost::directedS> traits;
typedef boost::adjacency_list<boost::vecS, boost::vecS, boost::directedS, boost::no_property,
boost::property<boost::edge_capacity_t, long,
boost::property<boost::edge_residual_capacity_t, long,
boost::property<boost::edge_reverse_t, traits::edge_descriptor,
boost::property <boost::edge_weight_t, long>>>>> graph;
typedef boost::graph_traits<graph>::vertex_descriptor vertex_desc;
typedef boost::graph_traits<graph>::edge_descriptor edge_desc;
class edge_adder {
graph &G;
public:
explicit edge_adder(graph &G) : G(G) {}
void add_edge(int from, int to, long capacity, long cost) {
auto c_map = boost::get(boost::edge_capacity, G);
auto r_map = boost::get(boost::edge_reverse, G);
auto w_map = boost::get(boost::edge_weight, G); // new!
const edge_desc e = boost::add_edge(from, to, G).first;
const edge_desc rev_e = boost::add_edge(to, from, G).first;
c_map[e] = capacity;
c_map[rev_e] = 0; // reverse edge has no capacity!
r_map[e] = rev_e;
r_map[rev_e] = e;
w_map[e] = cost; // new assign cost
w_map[rev_e] = -cost; // new negative cost
}
};
void testcase() {
int N, M, S; std::cin >> N >> M >> S;
graph G(N+M+S);
edge_adder adder(G);
const vertex_desc v_source = boost::add_vertex(G);
const vertex_desc v_sink = boost::add_vertex(G);
const int si = N+M;
for (int i = 0; i < S; ++i) {
int l; std::cin >> l;
adder.add_edge(si + i, v_sink, l, 0); // capacity of l, no cost
}
const int mi = N;
for (int i = 0; i < M; ++i) {
int s; std::cin >> s;
adder.add_edge(mi+i, si+s-1, 1, 0); // no cost
}
for (int i = 0; i < N; ++i) {
adder.add_edge(v_source, i, 1, 0); // every buyer buys at most one piece, no cost
for (int j = 0; j < M; ++j) {
int b; std::cin >> b;
adder.add_edge(i, mi+j, 1, 100-b); // reverse cost to calculate minimum
}
}
int flow = boost::push_relabel_max_flow(G, v_source, v_sink);
boost::successive_shortest_path_nonnegative_weights(G, v_source, v_sink);
int cost = boost::find_flow_cost(G);
std::cout << flow << ' ' << flow*100 - cost << '\n';
}
int main() {
std::ios_base::sync_with_stdio(false);
int T; std::cin >> T;
while (T--) testcase();
} | true |
968eeecfc0a3748ef69b9d41d97f6ada1ec61dfe | C++ | ZealousCynic/CppFilestreamV2 | /FilestreamV2/Filestream.h | UTF-8 | 1,365 | 2.828125 | 3 | [] | no_license | #pragma once
#include <fstream>
#include <string>
#include <vector>
#include "rapidxml/rapidxml.hpp"
#include "rapidxml/rapidxml_print.hpp"
class Filestream
{
public:
Filestream();
~Filestream();
//FILE ACCESS
void Filepick(std::string input);
void OpenFile();
void Read();
//XML FUNCTIONALITY
void ChangeCurrentNode(std::string* input);
void AddNode(std::string name);
void AddNode(std::string name, std::string value);
void AddAttribute(std::string* name);
void AddAttribute(std::string* name, std::string* value);
void ModifyAttribute(std::string* name, std::string* value);
void RemoveAttribute(std::string* name);
void RemoveNode();
//PRINT FUNCTIONS
void PrintSiblings();
void PrintChildren();
void PrintFamily();
void PrintParent();
void PrintXMLNodes(rapidxml::xml_node<>* toPrint);
//CurrentNode is the basis for ALL navigation performed by this application. If it isn't set, navigation breaks.
rapidxml::xml_node<>* currentNode;
private:
//Filestream for accessing file.
std::fstream fs;
//Vector to store the chars read from file - vector is array<char> of varying size.
std::vector<char> buffer;
//Object to store the XML Document-Object-Model.
rapidxml::xml_document<> doc;
//File to open as string.
std::string file;
//FUNCTIONS
rapidxml::xml_node<>* SearchNode(std::string* toSearch);
void Save();
};
| true |
8a81169043615c72d3414132393ab9ed3e996e78 | C++ | mmorshed99/dynamic_programming | /word_break.cpp | UTF-8 | 956 | 3.375 | 3 | [] | no_license | /*Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words.
#
#For example, given
#
#s = "myinterviewtrainer",
#dict = ["trainer", "my", "interview"].
#Return 1 ( corresponding to true ) because "myinterviewtrainer" can be segmented as "my interview trainer".
#
#Return 0 / 1 ( 0 for false, 1 for true ) for this problem
*/
bool find (string A, vector<string>B){
for(int i = 0;i<B.size();i++){
if(A== B[i]){
return 1;
}
}
return 0;
}
int Solution::wordBreak(string A, vector<string> &B) {
int n = A.size();
vector<int>final(n+1,0);
final[n] = 1;
for(int i = n-1; i>=0; i--){
for(int j = i; j<n;j++){
string sub = A.substr(i,j-i+1);
if(find(sub,B) == 1 && final[j+1] == 1){
final[i] = 1;
break;
}
}
}
return final[0];
}
| true |
7de7a233512a9a604375d61005bdf46ac405760e | C++ | gnafit/gna | /core/parameters/changeable.hh | UTF-8 | 8,358 | 2.703125 | 3 | [
"MIT"
] | permissive | #pragma once
#include <typeinfo>
#include <functional>
#include <deque>
#include <initializer_list>
#include <set>
#include <cstring>
#include <string>
#include "arrayview.hh"
class changeable;
struct references {
using Container = std::vector<changeable>;
bool has(changeable obj) const;
size_t index(changeable obj) const;
void add(changeable obj);
void replace(changeable o, changeable n);
void remove(changeable obj);
size_t size() { return objs.size(); }
Container::iterator begin() { return objs.begin(); }
Container::iterator end() { return objs.end(); }
Container objs;
};
enum class TaintStatus {
Normal = 0, ///<
Frozen, ///<
FrozenTainted, ///<
PassThrough ///<
};
struct inconstant_header {
inconstant_header(const char* aname="", const char* alabel="", bool autoname=false, size_t size=1u) : name(aname), label(alabel), size(size) {
static size_t ih_counter=0;
autoname = autoname || !name.size();
if(autoname){
name=name+"_"+std::to_string(ih_counter);
++ih_counter;
}
}
virtual ~inconstant_header()=default;
std::string name = "";
std::string label = "";
references observers;
references emitters;
bool tainted = true;
TaintStatus status=TaintStatus::Normal;
std::function<void()> on_taint;
const std::type_info *type = nullptr;
size_t size=1u;
};
template <typename ValueType>
struct inconstant_data: public inconstant_header {
inconstant_data(size_t size=1u, const char* name="", const char* label="", bool autoname=false) : inconstant_header(name, label, autoname, size), value(size) {
//printf("make %s of size %zu\n", this->name.c_str(), size);
type = &typeid(ValueType);
}
arrayview<ValueType> value;
std::function<ValueType()> func{nullptr};
std::function<void(arrayview<ValueType>&)> vfunc{nullptr};
};
#include "parameters_debug.hh"
class changeable {
public:
void subscribe(changeable d) {
if (m_hdr->observers.has(d)) {
DPRINTF("%p/%s is already observer", static_cast<void*>(d.m_hdr), d.name());
return;
}
DPRINTF("%p/%s becomes observer", static_cast<void*>(d.m_hdr), d.name());
m_hdr->observers.add(d);
d.m_hdr->emitters.add(*this);
if(m_hdr->tainted){
DPRINTF("taint %p/%s", static_cast<void*>(d.m_hdr), d.name());
d.taint();
}
}
void subscirbeto(changeable d){
d.subscribe(*this);
}
void unsubscribe(changeable d) {
m_hdr->observers.remove(d);
d.m_hdr->emitters.remove(*this);
}
void unsubscribefrom(changeable d) {
d.unsubscribe(*this);
}
void *rawdata() const {
return static_cast<void*>(m_hdr.get());
}
size_t hash() const {
return reinterpret_cast<size_t>(rawdata());
}
const char *name() const {
return m_hdr->name.c_str();
}
const char *label() const {
return m_hdr->label.c_str();
}
bool operator==(changeable const &other) const {
return m_hdr == other.m_hdr;
}
bool is(changeable const &other) {
return *this == other;
}
bool isnull() const {
return !m_hdr;
}
bool tainted() const {
return m_hdr->tainted;
}
bool frozen() const {
return m_hdr->status==TaintStatus::Frozen || m_hdr->status==TaintStatus::FrozenTainted;
}
bool passthrough() const {
return m_hdr->status==TaintStatus::PassThrough;
}
TaintStatus taintstatus() const {
return m_hdr->status;
}
void taint() const {
if(frozen()){
m_hdr->status=TaintStatus::FrozenTainted;
return;
}
else{
if(m_hdr->tainted && m_hdr->status!=TaintStatus::PassThrough){
DPRINTF("already tainted (do not propagate)");
return;
}
}
DPRINTF("got tainted");
notify();
m_hdr->tainted = true;
if (m_hdr->on_taint) {
DPRINTF("calling on_taint callback");
m_hdr->on_taint();
}
}
void freeze(){
switch(m_hdr->status){
case TaintStatus::Normal:
if(!m_hdr->tainted){
m_hdr->status=TaintStatus::Frozen;
}else{
throw std::runtime_error("can not freeze tainted changeable");
}
break;
case TaintStatus::PassThrough:
throw std::runtime_error("can not freeze PassThrough changeable");
break;
default:
break;
}
}
void unfreeze(){
if(!frozen()) return;
auto wastainted = m_hdr->status==TaintStatus::FrozenTainted;
m_hdr->status=TaintStatus::Normal;
if(wastainted){
taint();
}
}
bool depends(changeable other) const {
if(frozen()){
return false;
}
if(*this==other){
return true;
}
std::deque<changeable> queue;
std::set<const void*> visited;
queue.push_back(*this);
while (!queue.empty()) {
changeable current = queue.front();
queue.pop_front();
if(current.frozen()){
continue;
}
references &emitters = current.m_hdr->emitters;
if (emitters.has(other)) {
return true;
}
if (visited.insert(current.rawdata()).second) {
queue.insert(queue.end(), emitters.begin(), emitters.end());
}
}
return false;
}
size_t distance(changeable other, bool skip_passthrough=false, size_t max_depth=-1lu) const {
if(*this==other){
return 0u;
}
if(!max_depth){
return -1lu;
}
std::deque<std::pair<changeable*,size_t>> queue;
std::set<const void*> visited;
queue.push_back({const_cast<changeable*>(this), 1lu});
changeable* current;
size_t depth;
while (!queue.empty()) {
std::tie(current, depth) = queue.front();
queue.pop_front();
references &emitters = current->m_hdr->emitters;
if (emitters.has(other)) {
return depth;
}
if (visited.insert(current->rawdata()).second) {
for(auto& emitter: emitters){
size_t newdepth = skip_passthrough ? depth+static_cast<size_t>(!emitter.passthrough()) : depth+1;
if(newdepth>max_depth){
continue;
}
queue.push_back({&emitter, newdepth});
}
}
}
return -1lu;
}
void replace(changeable other) {
if (this->is(other)) {
return;
}
references &obs = m_hdr->observers;
for (auto& obj: obs) {
if (!obj.isnull()) {
other.m_hdr->observers.add(obj);
obj.m_hdr->emitters.replace(*this, other);
}
}
references &ems = m_hdr->emitters;
for (auto& obj: ems) {
if (!obj.isnull()) {
other.m_hdr->emitters.add(obj);
obj.m_hdr->observers.replace(*this, other);
}
}
assign(other);
if(m_hdr->tainted){
notify();
}
}
void assign(changeable other) {
m_hdr = other.m_hdr;
}
void notify() const {
for (auto& observer: m_hdr->observers) {
if (observer.isnull()) {
continue;
}
observer.taint();
}
}
protected:
changeable() = default;
template <typename T>
void initdeps(T deps) {
DPRINTF("subscribing to %i deps", int(deps.size()));
for (auto dep: deps) {
dep.subscribe(*this);
}
}
void alloc(inconstant_header* hdr){
if(m_hdr){
throw std::runtime_error("double initialization of changeable");
}
m_hdr.reset(hdr);
}
void init(const char* name="", bool autoname=false, size_t size=0u) {
alloc(new inconstant_header(name, "", autoname, size));
DPRINTF("constructed header");
}
template <typename T>
void init(T deps, const char* name="") {
init(name);
for (auto dep: deps) {
dep.subscribe(*this);
}
}
std::shared_ptr<inconstant_header> m_hdr;
};
inline bool references::has(changeable obj) const {
for (auto& o: objs) {
if (o == obj) {
return true;
}
}
return false;
}
inline size_t references::index(changeable obj) const {
for (size_t i(0); i<objs.size(); ++i) {
if (objs[i] == obj) {
return i;
}
}
return -1u;
}
inline void references::add(changeable obj) {
if(has(obj)){
return;
}
objs.push_back(obj);
}
inline void references::replace(changeable old, changeable newobj) {
for (size_t i = 0; i < objs.size(); ++i) {
if (objs[i] == old) {
objs[i] = newobj;
}
}
}
inline void references::remove(changeable d) {
for (size_t i = 0; i < objs.size(); ++i) {
if (objs[i] == d) {
objs.erase(objs.begin()+i);
break;
}
}
}
| true |
475dd8d34629ef196cbe80664d93865d512e1d27 | C++ | idovelemon/simplepathtracer | /spt/spt/spt/sptcamera.h | UTF-8 | 1,175 | 2.5625 | 3 | [] | no_license | //----------------------------------------------------------
// Declaration: Copyright (c), by i_dovelemon, 2017. All right reserved.
// Author: i_dovelemon[1322600812@qq.com]
// Date: 2017 / 05 / 04
// Brief: Use this camera to view the world
//----------------------------------------------------------
#ifndef _SPT_SPTCAMERA_H_
#define _SPT_SPTCAMERA_H_
#include <stdint.h>
#include "sptshape.h"
#include "sptvector.h"
namespace spt {
class Camera {
public:
Camera(Vector3 pos, Vector3 target, float aspect, float fov,
float dist, int32_t screen_width, int32_t screen_height);
virtual ~Camera();
public:
Vector3 GetPos();
Vector3 GetTarget();
float GetAspect();
float GetFOV();
float GetViewDist();
Ray GenRay(int32_t x, int32_t y, Vector2 sampler);
private:
Vector3 m_Pos;
Vector3 m_Target;
float m_Aspect;
float m_FOV;
float m_Dist;
int32_t m_ScreenWidth;
int32_t m_ScreenHeight;
float m_ViewWidth;
float m_ViewHeight;
Vector3 m_ViewCenter;
Vector3 m_Right;
Vector3 m_Up;
};
}; // namespace spt
#endif // _SPT_SPTCAMERA_H_ | true |
154d1c5a3f3f69ddb1d1581e93d4681b324ff065 | C++ | edubeckha/Compiladores | /TrabalhoI/st.h | UTF-8 | 2,357 | 3.1875 | 3 | [] | no_license | /*Ja previamente definido por Laércio Lima Pilla e ampliado para aceitar funcoes e outros tipos de estruturas*/
#pragma once
#include <map>
#include "ast.h"
extern void yyerror(const char* s, ...);
namespace AST {class Node;}
namespace ST {
class Symbol;
enum Kind { variable, arranjo, function };
typedef std::map<std::string,Symbol> SymbolList; //Set of Symbols
class Symbol {
public:
Tipos::Tipo type = Tipos::indefinido; /*[Return] type of Symbol: integer, double.*/
Kind kind; /*Kind of symbol: variable, function, etc.*/
int64_t value; /*Space to store a value while we are doing interpretation.*/
bool initialized; /*Defines if symbol has been initialized or not.*/
std::vector<ST::Symbol*> parametros; /*Stores the parameters of function*/
/*Construtor de simbolos para variaveis*/
Symbol(Tipos::Tipo type, Kind kind, int64_t value, bool initialized) :
type(type), kind(kind), value(value), initialized(initialized) { }
Symbol() {type = Tipos::indefinido; kind = variable; value = 0; initialized = false;}
/*Construtor de simbolos para funcoes*/
Symbol(Tipos::Tipo type, Kind kind, std::vector<ST::Symbol*> parametros, bool initialized) :
type(type), kind(kind), parametros(parametros), initialized(initialized) { }
};
class SymbolTable {
public:
SymbolList entryList;
SymbolTable() {}
bool checkId(std::string id) {return entryList.find(id) != entryList.end();}
void addSymbol(std::string id, Symbol newsymbol) {entryList[id] = newsymbol;}
AST::Node* newVariable(std::string id, Tipos::Tipo tipo, AST::Node* next);
AST::Node* assignVariable(std::string id);
AST::Node* useVariable(std::string id);
Tipos::Tipo returnType(std::string id);
void realizaCoercao(std::string id);
void defineTabelaOrigem(ST::SymbolTable* to) {tabelaOrigem = to;};
ST::SymbolTable* tabelaOrigem = NULL;
ST::Symbol getFunction(std::string id){return entryList[id];};
AST::Node* newFunction(std::string id, Tipos::Tipo tipoVariavel, std::vector<ST::Symbol*> parametros);
AST::Node* assignFunction(std::string id, Tipos::Tipo tipoVariavel, std::vector<ST::Symbol*> next, AST::Node* body);
};
}
| true |
4217d0c1fb98434307d754995f9eabd12caba76e | C++ | YoddleK/teme | /T_3dec2013_5.cpp | UTF-8 | 759 | 2.953125 | 3 | [
"Artistic-2.0"
] | permissive | #include <iostream>
#include <math.h>
using namespace std;
//5. Se citesc numere atata timp cat sunt mai mari decat 100.
//Numarati cate dintre valorile citite sunt numere prime.
int main (int argc, char* argv[])
{
const int N = 5;
int a[N] = {131, 111, 171, 200, 101};
int count = 0, n;
for(n = 0; n < N; n++) {
cout << "a[" << n << "]="; cin >> a[n];
if(a[n] < 100)
break;
}
for(int i=0; i < n; i++) {
if(a[i] % 2 == 0) {
continue;
}
for(int div = 3; div < sqrt(a[i]); div += 2) {
if(a[i] % div == 0) {
goto flag;
}
}
count ++;
flag: continue;
}
cout << ">> count = " << count << endl;
}
| true |
76aea38d1c305738b85f356b7e4c8041d818490a | C++ | hoou/mitmProject | /src/Group.cpp | UTF-8 | 299 | 3.078125 | 3 | [] | no_license | #include "Group.h"
Group::Group(const string &name, const vector<Host> &hosts) : name(name), hosts(hosts) {}
void Group::addHost(Host host) {
hosts.push_back(host);
}
const string &Group::getName() const {
return name;
}
const vector<Host> &Group::getHosts() const {
return hosts;
}
| true |
3d1b259f302b851e1da866a89767a3f067266e71 | C++ | jclundy/MTE_380_Code | /spool_control/spool.h | UTF-8 | 548 | 2.796875 | 3 | [] | no_license | #ifndef SPOOL_H
#define SPOOL_H
#include <Servo.h>
#include <Arduino.h>
// spool servo values
#define RESTING_uS 1525
#define UNWIND_uS 1510
#define TAKE_IN_FAST_uS 1600
#define TAKE_IN_SLOW_uS 1560
class spool {
public:
spool(Servo* servo);
~spool();
// sends signal to servo to stop rotation
void stopRotating();
// unspools at moderate speed
void unspool();
// reverses with enough torque to hold itself from falling
void takeInFast();
// reverses at slow speed for loading the rope
void takeInSlow();
private:
Servo* motor;
} | true |
6c3699fbfdaf25dc276e3e0bdd00565592d9d7b5 | C++ | yzcmf/oicode | /codeforces/555B.cpp | UTF-8 | 1,382 | 3.09375 | 3 | [] | no_license | /* Codeforces 555B. Case of Fugitive
* Sortings */
#include <cstdio>
#include <iostream>
#include <set>
#include <algorithm>
const int MaxN = 200010;
int n, m;
long long L[MaxN], R[MaxN];
struct range_t
{
int id;
long long l, r;
bool operator < (const range_t& z) const
{
if(l <= z.l && z.r <= r)
return false;
else if(z.l <= l && r <= z.r)
return true;
return l < z.l;
}
} range[MaxN];
struct bridge_t
{
int id;
long long len;
bool operator < (const bridge_t& r) const
{
return len < r.len;
}
};
std::multiset<bridge_t> s;
int ans[MaxN];
int main()
{
std::ios::sync_with_stdio(false);
std::cin >> n >> m;
if(n - 1 > m)
{
std::cout << "No\n";
return 0;
}
for(int i = 0; i != n; ++i)
std::cin >> L[i] >> R[i];
for(int i = 0; i + 1 < n; ++i)
{
range[i].id = i;
range[i].l = L[i + 1] - R[i];
range[i].r = R[i + 1] - L[i];
}
std::sort(range, range + n - 1);
for(int i = 0; i != m; ++i)
{
bridge_t A;
A.id = i + 1;
std::cin >> A.len;
s.insert(A);
}
for(int i = 0; i + 1 < n; ++i)
{
bridge_t r;
r.len = range[i].l;
auto pos = s.lower_bound(r);
if(pos == s.end() || range[i].r < pos->len)
{
std::cout << "No\n";
return 0;
}
ans[range[i].id] = pos->id;
s.erase(pos);
}
std::cout << "Yes\n";
for(int i = 0; i + 1 < n; ++i)
std::cout << ans[i] << " ";
std::cout << std::endl;
return 0;
}
| true |
c9647c6ee500a8609c8bf8d51c0da3666368e3a8 | C++ | Beldex-Coin/beldex-core-custom | /external/loki-mq/tests/common.h | UTF-8 | 2,261 | 2.5625 | 3 | [
"BSD-3-Clause"
] | permissive | #pragma once
#include "oxenmq/oxenmq.h"
#include <catch2/catch.hpp>
#include <chrono>
using namespace oxenmq;
static auto startup = std::chrono::steady_clock::now();
/// Returns a localhost connection string to listen on. It can be considered random, though in
/// practice in the current implementation is sequential starting at 4500.
inline std::string random_localhost() {
static uint16_t last = 4499;
last++;
assert(last); // We should never call this enough to overflow
return "tcp://127.0.0.1:" + std::to_string(last);
}
// Catch2 macros aren't thread safe, so guard with a mutex
inline std::unique_lock<std::mutex> catch_lock() {
static std::mutex mutex;
return std::unique_lock<std::mutex>{mutex};
}
/// Waits up to 200ms for something to happen.
template <typename Func>
inline void wait_for(Func f) {
auto start = std::chrono::steady_clock::now();
for (int i = 0; i < 20; i++) {
if (f())
break;
std::this_thread::sleep_for(10ms);
}
auto lock = catch_lock();
UNSCOPED_INFO("done waiting after " << (std::chrono::steady_clock::now() - start).count() << "ns");
}
/// Waits on an atomic bool for up to 100ms for an initial connection, which is more than enough
/// time for an initial connection + request.
inline void wait_for_conn(std::atomic<bool> &c) {
wait_for([&c] { return c.load(); });
}
/// Waits enough time for us to receive a reply from a localhost remote.
inline void reply_sleep() { std::this_thread::sleep_for(10ms); }
inline OxenMQ::Logger get_logger(std::string prefix = "") {
std::string me = "tests/common.h";
std::string strip = __FILE__;
if (strip.substr(strip.size() - me.size()) == me)
strip.resize(strip.size() - me.size());
else
strip.clear();
return [prefix,strip](LogLevel lvl, std::string file, int line, std::string msg) {
if (!strip.empty() && file.substr(0, strip.size()) == strip)
file = file.substr(strip.size());
auto lock = catch_lock();
UNSCOPED_INFO(prefix << "[" << file << ":" << line << "/"
"+" << std::chrono::duration<double>(std::chrono::steady_clock::now() - startup).count() << "s]: "
<< lvl << ": " << msg);
};
}
| true |
fdeba2e8981ac1da1160fd37822d3e5ea70140e4 | C++ | mchchiang/phase_field_model | /c/benjamin_model/analysis/src/pair_corr.cpp | UTF-8 | 4,056 | 2.796875 | 3 | [] | no_license | // pair_corr.cpp
// A program to compute the pair correlation function
#include <iostream>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <string>
#include <vector>
#include <cmath>
#include <random>
#include <omp.h>
#include "position.hpp"
using std::cout;
using std::endl;
using std::ifstream;
using std::ofstream;
using std::istringstream;
using std::string;
using std::vector;
double diff(double lx, double x1, double x2);
double dist(double x, double y);
double dot(double x1, double y1, double x2, double y2);
double gauss(double sigma, double x, double y);
template <typename T> int sgn(T val);
int main(int argc, char* argv[]) {
if (argc != 9) {
cout << "usage: structure npoints lx ly startTime endTime timeInc "
<< "posFile outFile" << endl;
return 1;
}
int argi {};
int npoints {stoi(string(argv[++argi]), nullptr, 10)};
int lx {stoi(string(argv[++argi]), nullptr, 10)};
int ly {stoi(string(argv[++argi]), nullptr, 10)};
long startTime {stoi(string(argv[++argi]), nullptr, 10)};
long endTime {stoi(string(argv[++argi]), nullptr, 10)};
long timeInc {stoi(string(argv[++argi]), nullptr, 10)};
string posFile {argv[++argi]};
string outFile {argv[++argi]};
PositionReader posReader;
posReader.open(posFile, npoints, lx, ly, timeInc);
if (!posReader.isOpen()) {
cout << "Problem with opening position file!" << endl;
return 1;
}
// Read the position data
int nbins {static_cast<int>((endTime-startTime)/timeInc)+1};
vector<double> vec (2, 0.0);
vector<vector<double> > vec2 (npoints, vec);
vector<vector<vector<double> > >* pos
{new vector<vector<vector<double > > >(nbins, vec2)};
long time;
int ibin;
while (posReader.nextFrame()) {
time = posReader.getTime();
if (time < startTime) {
continue;
} else if (time >= startTime && time <= endTime) {
ibin = static_cast<int>((time-startTime)/timeInc);
for (int i {}; i < npoints; i++) {
// Use wrapped position here as we only care about relative distances
// and orientations
(*pos)[ibin][i][0] = posReader.getPosition(i, 0);
(*pos)[ibin][i][1] = posReader.getPosition(i, 1);
}
} else {
break;
}
}
posReader.close();
ofstream writer;
writer.open(outFile);
if (!writer) {
cout << "Problem with opening average output file!" << endl;
return 1;
}
ibin = 0;
double x, y;
vector<vector<vector<double> > >* diffMat
{new vector<vector<vector<double> > >(npoints, vec2)};
// Compute relative position matrix
for (int i {}; i < npoints; i++) {
x = (*pos)[ibin][i][0];
y = (*pos)[ibin][i][1];
for (int j {}; j < i; j++) {
(*diffMat)[i][j][0] = diff(lx, x, (*pos)[ibin][j][0]);
(*diffMat)[i][j][1] = diff(ly, y, (*pos)[ibin][j][1]);
(*diffMat)[j][i][0] = -(*diffMat)[i][j][0];
(*diffMat)[j][i][1] = -(*diffMat)[i][j][1];
}
}
const double sigma {0.01};
const double d {0.1};
const int nx {static_cast<int>(ceil(lx/d))};
const int ny {static_cast<int>(ceil(ly/d))};
double dx, dy, dx0, dy0, sum;
for (int i {}; i < nx; i++) {
dx = i*d-lx/2.0;
for (int j {}; j < ny; j++) {
dy = j*d-ly/2.0;
sum = 0.0;
cout << i << " " << j << endl;
for (int k {}; k < npoints; k++) {
for (int l {}; l < k; l++) {
dx0 = (*diffMat)[k][l][0];
dy0 = (*diffMat)[k][l][1];
sum += gauss(sigma, (dx-dx0), (dy-dy0));
}
}
writer << dx << " " << dy << " " << sum << endl;
}
}
// Clean up resources
delete pos;
delete diffMat;
}
double diff(double lx, double x1, double x2) {
double dx1 {x1-x2};
double dx1mag {fabs(dx1)};
double dx2mag {lx-dx1mag};
return dx2mag > dx1mag ? dx1 : -dx2mag*sgn(dx1);
}
double dist(double x, double y) {
return sqrt(x*x+y*y);
}
double dot(double x1, double y1, double x2, double y2) {
return x1*x2+y1*y2;
}
double gauss(double sigma, double x, double y) {
return exp(-(x*x+y*y)/(sigma*sigma));
}
template <typename T> int sgn(T val) {
return (T(0) < val) - (val < T(0));
}
| true |
ede4a05166180202489e87dbc934bf1cb4c077bc | C++ | elshift/ezcompile | /src/minics/cs_state.h | UTF-8 | 3,141 | 2.9375 | 3 | [] | no_license | #pragma once
#include "cs_object.h"
#include "cs_string.h"
#include "cs_bool.h"
#include "cs_int.h"
#include <vector>
#include <stack>
#include <assert.h>
class CS_Object;
#ifdef _DEBUG
#define CS_DBG_STATE(state, newHandleName) size_t newHandleName = state.Size()
#define CS_DBG_STATE_END(state, handleName) \
assert(state.Size() == handleName && "Uh oh! Looks like your stack... is out of wack!");
#else
#define CS_DBG_STATE(state, newHandleName)
#define CS_DBG_STATE_END(state, newHandleName)
#endif
class CS_State
{
public:
bool GetArg(size_t Pos, CS_Ref<CS_Object>* out_Obj);
bool GetArg(size_t Pos, bool* out_Num) { return GetArg_Num<CS_Bool>(Pos, out_Num); }
bool GetArg(size_t Pos, int* out_Num) { return GetArg_Num<CS_Int32>(Pos, out_Num); }
bool GetArg(size_t Pos, double* out_Num) { return GetArg_Num<CS_Double>(Pos, out_Num); }
bool GetArg(size_t Pos, std::string* out_Str);
bool GetArgs() { return true; }
template <class T, class ...TArgs>
bool GetArgs(T First, TArgs ...Moar)
{
size_t n = _GetArgs(First, Moar...);
if (n == (size_t)-1)
return false;
Pop(n);
return true;
}
template <class T, class ...TArgs>
bool GetArgs_Strict(T First, TArgs ...Moar)
{
size_t n = _GetArgs(First, Moar...);
if (n == (size_t)-1)
{
CS_MISMATCH();
return false;
}
Pop(n);
return true;
}
template <class ...TMany>
void Push(bool Bool, const TMany& ...Many) { Push_Prim<CS_Bool>(Bool, Many...); }
template <class ...TMany>
void Push(int32_t Int32, const TMany& ...Many) { Push_Prim<CS_Int32>(Int32, Many...); }
template <class ...TMany>
void Push(const std::string& Str, const TMany& ...Many) { Push_Prim<CS_String>(Str, Many...); }
template <class ...TMany>
void Push(const CS_Ref<CS_Object>& o, const TMany& ...Many)
{
m_stack.push_back(o);
Push(Many...);
}
CS_Ref<CS_Object> Top() { return m_stack.back(); }
void Pop(size_t N = 1)
{
assert(N <= m_stack.size() && "Tried to pop more items than exists on stack");
m_stack.resize(m_stack.size() - N);
}
size_t Size() const { return m_stack.size(); }
private:
void Push() { }
template <class TCSPrim, class TPrim, class ...TMany>
void Push_Prim(const TPrim& prim, const TMany& ...Many)
{
m_stack.emplace_back(CS_MakeObj<TCSPrim>(prim));
Push(Many...);
}
template <class TClass, class TVal>
bool GetArg_Num(size_t Pos, TVal out_Val)
{
CS_Ref<CS_Object> obj;
GetArg(Pos, &obj);
if (!TClass::_GetType()->Equals(obj))
return false;
*out_Val = ((TClass*)obj.get())->_Value();
return true;
}
size_t _GetArgs() { return 0; }
template <class ...TArgs>
size_t _GetArgs(std::string* Next, TArgs ...Args)
{
CS_Ref<CS_Object> o;
size_t pos = _GetArgs(Args...);
if (pos == (size_t)-1)
return (size_t)-1;
if (!GetArg(pos, Next))
{
if (!GetArg(pos, &o))
return (size_t)-1;
*Next = o->ToString();
}
return pos + 1;
}
template <class T, class ...TArgs>
size_t _GetArgs(T Next, TArgs ...Args)
{
size_t pos = _GetArgs(Args...);
if (pos == (size_t)-1 || !GetArg(pos, Next))
return (size_t)-1;
return pos + 1;
}
std::vector<CS_Ref<CS_Object>> m_stack;
}; | true |
84c18319a3ce391d1219bd64a6f8e725998f43eb | C++ | Robert170/Prograc-on_II_2019B_Roberto_Ramirez_Ontiveros | /Parcial_2/Practicas/Proyecto_Segundo_Parcial/Node.cpp | ISO-8859-10 | 2,954 | 3.578125 | 4 | [] | no_license | #include "Node.h"
const std::string Node::getName()
{
return name;
}
void Node::setName(std::string Nom)
{
name = Nom;
}
const std::string Node::getLastName()
{
return lastName;
}
void Node::setLastName(std::string Last)
{
lastName = Last;
}
const std::string Node::getEmail()
{
return email;
}
void Node::setEmail(std::string Email)
{
email = Email;
}
void Node::setBirthDate(unsigned char D, unsigned char M, unsigned char Y)
{
birthDay = (unsigned char)D;
birthMonth = (unsigned char)M;
birthYear = (unsigned char)Y;
}
const std::string Node::getFullName()
{
return lastName + " " + name;
}
const unsigned int Node::getAge()
{
unsigned int age = 19;
if (birthYear <= age)
{
age = age - int((unsigned char)birthYear);
return age;
}
else
{
age = 0;
return age;
}
}
bool SingleNode::operator>(SingleNode & N)
{
return this->getAge() > N.getAge();
}
bool SingleNode::operator<(SingleNode & N )
{
return this->getAge() < N.getAge();
}
SingleNode::~SingleNode()
{
if (next!=nullptr)
{
delete next;
}
}
//Funcion para imprimir los nodos
std::ostream & operator<<(std::ostream &out, SingleNode & N)
{
out << "The name is:" << N.getFullName() << "\nThe age is: " << N.getAge() << "\nThe email is: " << N.getEmail() << std::endl;
if (N.next == nullptr)
{
return out;
}
else
{
return out << N.next;
}
return out;
}
//Funcion para llenar los nodos
std::istream & operator>>(std::istream & inp, SingleNode & N)
{
std::cout << "Ingrese su nombre: "; inp >> N.name;
std::cout << "Ingrese su apellido: "; inp >> N.lastName;
std::cout << "Ingrese su email: "; inp >> N.email;
std::cout << "Ingrese el dia que naciste: "; inp >> N.birthDay;
std::cout << "Ingrese el mes que naciste: "; inp >> N.birthMonth;
std::cout << "Ingrese el ao en que naciste: "; inp >> N.birthYear;
return inp;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
std::ostream & operator<<(std::ostream & out, DoubleNode & N)
{
out << "The name is:" << N.getFullName() << "\nThe age is: " << N.getAge() << "\nThe email is: " << N.getEmail() << std::endl;
if (N.next == nullptr)
{
return out;
}
else
{
return out << N.next;
}
return out;
}
std::istream & operator>>(std::istream & inp, DoubleNode & N)
{
std::cout << "Ingrese su nombre: "; inp >> N.name;
std::cout << "Ingrese su apellido: "; inp >> N.lastName;
std::cout << "Ingrese su email: "; inp >> N.email;
std::cout << "Ingrese el dia que naciste: "; inp >> N.birthDay;
std::cout << "Ingrese el mes que naciste: "; inp >> N.birthMonth;
std::cout << "Ingrese el ao en que naciste: "; inp >> N.birthYear;
return inp;
}
bool DoubleNode::operator>(DoubleNode & N)
{
return this->getAge() > N.getAge();
}
bool DoubleNode::operator<(DoubleNode & N)
{
return this->getAge() < N.getAge();
}
DoubleNode::~DoubleNode()
{
if (next != nullptr)
{
delete next;
}
}
| true |
27b489f43d35abb7461ba7e9e8d524c6b8d6a061 | C++ | woniuge/basicCode_C-Cpp | /贪吃蛇网络版/Client/SocketClient.cpp | UTF-8 | 1,647 | 3.078125 | 3 | [] | no_license | /*程序名:SocketClient.cpp
*功能:完成客户端Socket的类实现
*作者:袁海峰
*日期:2017年11月11日
*/
#include "SocketClient.h"
#include <cstdio>
#include <sys/socket.h>
#include <cstring>
#include <arpa/inet.h>
#include <cstdlib>
#include <unistd.h>
#define LENGTH_OF_LISTEN_QUEUE 20
int SocketClient::clientGetConnection(const char * serverIP, int portNumber) { //创建socket fd给用户, 好像一个文件指针似的可以直接使用
//创建用于TCP协议的client_socket
client_socket = socket(AF_INET, SOCK_STREAM, 0); //创建socket
if (client_socket < 0) {
printf("Create Socket Failed!\n");
exit(1);
}
/*server_addr*/
//设置一个socket地址结构server_addr,代表服务器的internet地址,端口
struct sockaddr_in server_addr; // 要连接的服务器的地址
bzero(&server_addr, sizeof(server_addr));
server_addr.sin_family = AF_INET;
if (inet_aton(serverIP, &server_addr.sin_addr) == 0) { //inet_aton: 把arg1转化为二进制, 然后交付给arg2, 返回值为
printf("Server IP Address Error!\n");
exit(1);
}
server_addr.sin_port = htons(portNumber);
socklen_t server_addr_length = sizeof(server_addr);
//向服务器发起连接
if (connect(client_socket, (struct sockaddr *) &server_addr, server_addr_length) < 0) { //使得刚创立好的fd成为客户端与服务器交流的接口
printf("Can Not Connect To %s!\n", serverIP);
exit(1);
}
return 0;
}
void SocketClient::clientCloseConnection() {
close(client_socket);
printf("client_socket closed.\n");
}
| true |
8164f2c0eb42b3225e8b9953aa5aa952108e5c48 | C++ | ponxosio/protocolGraph | /protocolGraph/operations/cpuoperation.h | UTF-8 | 403 | 2.71875 | 3 | [] | no_license | #ifndef CPUOPERATION_H
#define CPUOPERATION_H
#include <graph/Node.h>
class CPUOperation : public Node {
public:
CPUOperation() :
Node()
{
}
CPUOperation(const CPUOperation & obj) :
Node(obj)
{
}
CPUOperation(int idContainer) :
Node(idContainer)
{
}
virtual ~CPUOperation(){}
virtual void execute() = 0;
};
#endif // CPUOPERATION_H
| true |
43466b4a04e5f03140a7482617c5899c829c6676 | C++ | JosephPai/LeetCode | /646. Maximum Length of Pair Chain.cpp | WINDOWS-1252 | 856 | 2.6875 | 3 | [] | no_license | #include <fstream>
#include <iostream>
#include <string>
#include <cstdlib>
#include <vector>
#include<algorithm>
// Solution: https://leetcode.com/problems/maximum-length-of-pair-chain/discuss/105602
// ̬滮
using namespace std;
class Solution {
public:
int findLongestChain(vector< vector<int> > & pairs) {
if (pairs.size()==0) return 0;
int n = pairs.size(), i, j;
int dp[n],p[n][2];
for(i=0; i<n; i++) dp[i]=1;
for(i=0;i<n;i++)
for(j=0;j<2;j++)
p[i][j]=pairs[i][j];
sort(p,key=index_0);
for(i=0; i<n; i++)
for(j=0; j<i; j++)
dp[i] = max(dp[i], p[i][0]>p[j][1]? dp[j]+1: dp[j]);
return dp[n];
}
};
int main() {
// freopen("input.txt","r",stdin);
// freopen("output.txt","w",stdout);
Solution s;;
int p[3][2];
return 0;
}
| true |
221bb2d525270811f63c36557fe5282992c50a23 | C++ | ProjectAsura/rt_study | /RealisticRayTracing/Chapter6/uv_sphere.h | UTF-8 | 459 | 2.625 | 3 | [
"MIT"
] | permissive | // UVSphere.h
#pragma once
#include "shape.h"
#include "ray.h"
#include "texture.h"
class UVSphere : public Shape
{
public:
UVSphere(const Vector3& c, float r, Texture* tex);
bool hit(const Ray& ray, float tmin, float tmax, float time, HitRecord& record) const override;
bool shadowHit(const Ray& ray, float tmin, float tmax, float time) const override;
Vector3 center;
float radius;
Texture* texture;
};
| true |
d9a68052da8f0b0c4a25b3cd6e524f9cc5eff2fc | C++ | xdfc1745/GWNU-Junior | /Algorithm/qsort/test.cpp | UTF-8 | 621 | 3.5625 | 4 | [] | no_license | #include <iostream>
#include <cstdlib>
using namespace std;
int compare(const void* a, const void* b)
{
const int* x = (int*)a;
const int* y = (int*)b;
if (*x > *y)
return 1;
else if (*x < *y)
return -1;
return 0;
}
int main()
{
const int num = 10;
int arr[num] = { 9,0,19,-1,7,9,5,15,23,3 };
cout << "Before sorting" << endl;
for (int i = 0; i < num; i++)
cout << arr[i] << " ";
qsort(arr, num, sizeof(int), compare);
cout << endl << endl;
cout << "After sorting" << endl;
for (int i = 0; i < num; i++)
cout << arr[i] << " ";
system("pause");
return 0;
} | true |
2d8c549e6bb0db7ee146c5c71c3f974f317eecca | C++ | mohammadbutt/42_cpp_piscine | /rush00/ft_retro/finished_part/Bullet.cpp | UTF-8 | 2,194 | 3 | 3 | [] | no_license | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* Bullet.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mbutt <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/01/19 19:51:20 by mbutt #+# #+# */
/* Updated: 2020/01/19 20:25:25 by mbutt ### ########.fr */
/* */
/* ************************************************************************** */
#include "Bullet.hpp"
Bullet::Bullet(void)
{
std::cout << "Default constructor - Bullet class" << std::endl;
}
Bullet::Bullet(const Bullet &srcCopy)
{
std::cout << "Copy constructor - Bullet class" << std::endl;
*this = srcCopy;
}
Bullet &Bullet::operator = (const Bullet &rhs)
{
std::cout << "Equal operator to set values - Bullet class" << std::endl;
if(this != &rhs)
{
_x = rhs._x;
_y = rhs._y;
_symbol = rhs._symbol;
_isActive = rhs._isActive;
}
return(*this);
}
Bullet::~Bullet(void)
{
std::cout << "Calling destructor" << std::endl;
}
// Above are the canonical formatted class members
//
Bullet::Bullet(int x, int y, char character) : _x(x), _y(y), _symbol(character)
{
std::cout << "Calling Bullet constructor with x, y, and character";
std::cout << std::endl;
}
int Bullet::getX(void)
{
return(_x);
}
int Bullet::getY(void)
{
return(_y);
}
void Bullet::setX(int x)
{
_x = x;
}
void Bullet::setY(int y)
{
_y = y;
}
bool Bullet::getActive(void)
{
return(_isActive);
}
void Bullet::setActive(bool active)
{
_isActive = active;
}
void Bullet::draw(void)
{
move(_y, _x);
addch(_symbol);
}
void Bullet::travel(int screenWidth)
{
if(_isActive)
{
_x++;
draw();
if((_x + 2) >= screenWidth)
_isActive = false;
}
}
/*
int main(void)
{
Bullet bullet;
}
*/
| true |
a145eb095a0615e7522eadc00b944612faf36def | C++ | iot-linti/doa-sketchs | /archivos_emilio/BlinkESP/BlinkESP.ino | UTF-8 | 511 | 3.171875 | 3 | [] | no_license | #define LED_BUILTIN 2
void setup() {
pinMode(LED_BUILTIN, OUTPUT);
Serial.begin(115200);
Serial.println();
Serial.println("Bienvenido al Blinky!!!");
}
void loop() {
Serial.print("HIGH,");
digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level)
delay(500); // wait for a second
Serial.println(" LOW.");
digitalWrite(LED_BUILTIN, LOW); // turn the LED off by making the voltage LOW
delay(1000); // wait for a second
}
| true |
f77c5fb3df308d8b6ea3a0a794d2cc9cd23e6d26 | C++ | abdelhakeem/8puzzle | /src/Solver.cpp | UTF-8 | 1,755 | 2.734375 | 3 | [] | no_license | #include <unordered_set>
#include "Solver.h"
Result Solver::solve(const Board& board, FringePolicy::sptr policy,
size_t maxNodes, size_t maxDepth) {
Result res = {
.solved = false,
.initialBoard = board,
.path = std::vector<Direction>(),
.nodesExpanded = 0,
.searchDepth = 0,
.nsRunningTime = std::chrono::nanoseconds(0)
};
Fringe::sptr fringe = policy->makeFringe();
std::unordered_set<size_t> expanded;
SearchNode::sptr node;
fringe->insert(std::make_shared<SearchNode>(board));
auto t1 = std::chrono::steady_clock::now();
while ((node = fringe->extract())) {
if (!expanded.contains(node->getBoard().hash())) {
size_t depth = node->getPath().size();
res.searchDepth = std::max(res.searchDepth, depth);
res.nodesExpanded++;
if (node->getBoard().solved()) {
auto t2 = std::chrono::steady_clock::now();
res.solved = true;
res.nsRunningTime = t2 - t1;
res.path = node->getPath();
return res;
}
bool tooDeep = maxDepth && res.searchDepth > maxDepth;
bool tooManyNodes = maxNodes && res.nodesExpanded >= maxNodes;
if (tooDeep || tooManyNodes) {
auto t2 = std::chrono::steady_clock::now();
res.nsRunningTime = t2 - t1;
return res;
}
fringe->insertAll(node->expand());
expanded.insert(node->getBoard().hash());
}
}
// Exhausted search space and found no solution
auto t2 = std::chrono::steady_clock::now();
res.nsRunningTime = t2 - t1;
return res;
}
| true |
0a068bd4dd1949c485dc3d518532d2c643234b3c | C++ | ExternalRepositories/tm | /src/tm_print/int_backend_crt.cpp | UTF-8 | 1,643 | 2.765625 | 3 | [
"LicenseRef-scancode-public-domain"
] | permissive | static PrintFormattedResult tmp_print_value(char* dest, tm_size_t maxlen, uint32_t value, const PrintFormat& format) {
TM_ASSERT(!dest || maxlen > 0);
TM_ASSERT_VALID_SIZE(maxlen);
PrintFormattedResult result = {maxlen, TM_EOVERFLOW};
const char* format_string = "%" PRIu32;
if (format.base == 16) {
format_string = (format.flags & PrintFlags::Lowercase) ? "%" PRIx32 : "%" PRIX32;
} else if (format.base == 8) {
format_string = "%" PRIo32;
}
int size = TMP_SNPRINTF(dest, (size_t)maxlen, format_string, value);
if (size < 0) {
result.ec = TM_EINVAL;
} else if ((tm_size_t)size >= maxlen) {
result.size = (tm_size_t)size;
result.ec = TM_ERANGE;
} else {
result.size = (tm_size_t)size;
result.ec = TM_OK;
}
return result;
}
static PrintFormattedResult tmp_print_value(char* dest, tm_size_t maxlen, uint64_t value, const PrintFormat& format) {
TM_ASSERT(!dest || maxlen > 0);
TM_ASSERT_VALID_SIZE(maxlen);
PrintFormattedResult result = {};
const char* format_string = "%" PRIu64;
if (format.base == 16) {
format_string = (format.flags & PrintFlags::Lowercase) ? "%" PRIx64 : "%" PRIX64;
} else if (format.base == 8) {
format_string = "%" PRIo64;
}
int size = TMP_SNPRINTF(dest, (size_t)maxlen, format_string, value);
if (size < 0) {
result.ec = TM_EINVAL;
} else if ((tm_size_t)size >= maxlen) {
result.size = (tm_size_t)size;
result.ec = TM_ERANGE;
} else {
result.size = (tm_size_t)size;
result.ec = TM_OK;
}
return result;
} | true |
5494047c20225d75d448014b3ea268e76b3c55cc | C++ | axeng/ml-lib | /tests/unit_tests/data_structure/matrix/matrix_print.cc | UTF-8 | 2,578 | 3.1875 | 3 | [] | no_license | /**
** @file tests/unit_tests/data_structure/matrix/matrix_print.cc
** @brief Tests for Print functions of ml::data_structure::matrix::Matrix
*/
#include "data_structure/matrix/matrix.hh"
#include "gtest/gtest.h"
namespace tests::unit_tests
{
TEST(DataStructureMatrix, Print)
{
ml::data_structure::matrix::Matrix<float, 3, 2> matrix({1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f});
std::stringstream string_stream;
ml::data_structure::matrix::print(matrix, string_stream);
string_stream << 1;
EXPECT_EQ("| 1.0000 2.0000 |\n| 3.0000 4.0000 |\n| 5.0000 6.0000 |\n1", string_stream.str());
}
TEST(DataStructureMatrix, PrintShortcut)
{
ml::data_structure::matrix::Matrix<float, 3, 2> matrix({1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f});
std::stringstream string_stream;
string_stream << matrix << 1;
EXPECT_EQ("| 1.0000 2.0000 |\n| 3.0000 4.0000 |\n| 5.0000 6.0000 |\n1", string_stream.str());
}
TEST(DataStructureMatrix, PrintWithNegative)
{
ml::data_structure::matrix::Matrix<float, 3, 2> matrix({1.0f, 2.0f, -3.0f, 4.0f, 5.0f, -6.0f});
std::stringstream string_stream;
ml::data_structure::matrix::print(matrix, string_stream);
string_stream << 1;
EXPECT_EQ("| 1.0000 2.0000 |\n| -3.0000 4.0000 |\n| 5.0000 -6.0000 |\n1", string_stream.str());
}
TEST(DataStructureMatrix, PrintWithNegativeShortcut)
{
ml::data_structure::matrix::Matrix<float, 3, 2> matrix({1.0f, 2.0f, -3.0f, 4.0f, 5.0f, -6.0f});
std::stringstream string_stream;
string_stream << matrix << 1;
EXPECT_EQ("| 1.0000 2.0000 |\n| -3.0000 4.0000 |\n| 5.0000 -6.0000 |\n1", string_stream.str());
}
TEST(DataStructureMatrix, PrintWithFloat)
{
ml::data_structure::matrix::Matrix<float, 3, 2> matrix({4.0f / 3.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f});
std::stringstream string_stream;
ml::data_structure::matrix::print(matrix, string_stream);
string_stream << 1;
EXPECT_EQ("| 1.3333 2.0000 |\n| 3.0000 4.0000 |\n| 5.0000 6.0000 |\n1", string_stream.str());
}
TEST(DataStructureMatrix, PrintWithFloatShortcut)
{
ml::data_structure::matrix::Matrix<float, 3, 2> matrix({4.0f / 3.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f});
std::stringstream string_stream;
string_stream << matrix << 1;
EXPECT_EQ("| 1.3333 2.0000 |\n| 3.0000 4.0000 |\n| 5.0000 6.0000 |\n1", string_stream.str());
}
} // namespace tests::unit_tests
| true |
544bebe26194aab38b644d1194aca9afbef5dc72 | C++ | Nelson-Chacon/cpp | /Ejercicios/Ejercicio29-funciones-INT/Funcion-int.cpp | UTF-8 | 461 | 3.359375 | 3 | [
"MIT"
] | permissive | #include<iostream>
using namespace std;
int suma(int a,int b){// a representa el 5 y b representa el 7 que se colocaron en la funcion main
return a + b;//realiza la operacion
}
int main(int argc, char const *argv[])
{
system("cls");
cout<<"Los resultados de la suma son: "<<endl;
cout<<suma(5,7);
cout<<endl;
cout<<suma(15,7);
cout<<endl;
cout<<suma(5,71);
cout<<endl;
cout<<suma(9,8);
cout<<endl;
return 0;
}
| true |
d75f9a55e07560d6676c2248707e46001fd7fff0 | C++ | ajsewell/Final-Project | /PredatorPrey.h | UTF-8 | 1,333 | 2.65625 | 3 | [] | no_license | // Project Name: Final Project
// Name: Allysa Sewell
// Date: 6/8/18
// Class: CS 172
#ifndef PREDATORPREY_H_
#define PREDATORPREY_H_
#include "Species.h"
class PredatorPrey: public Species
{
public:
PredatorPrey();
PredatorPrey(string name, double size, double time, double growthRate,
double pAlleleFrequency);
PredatorPrey(string name, string Predatorname, double size, double
predatorSize, double time, double growthRate, double deathRate, double
alpha, double gamma);
PredatorPrey(const PredatorPrey&);
string getPredatorName() const;
void setPredatorName(string predatorName);
double getPredatorSize() const;
void setPredatorSize(double predatorSize);
double getPredatorDeathRate() const;
void setPredatorDeathRate(double deathRate);
double getTime() const;
void setTime(double time);
double getPreyGrowthRate() const;
double getAlpha() const;
void setAlpha(double alpha);
double getGamma() const;
void setGamma(double gamma);
double calculatePreyPopulation();
double calculatePredatorPopulation();
private:
string predatorName;
double predatorSize;
double preyGrowthRate;
double predatorDeathRate;
double time;
double alpha;
double gamma;
double findPhi() const;
double findK() const;
bool isValid() const;
};
#endif | true |
c67988caefd8ed15b5133224453bb2327d8eeadd | C++ | alexZalachenko/Roland | /Roland/ShadersManager.cpp | UTF-8 | 3,130 | 3.265625 | 3 | [] | no_license | #include "ShadersManager.h"
#include <fstream>
#include <iostream>
#include <string>
ShadersManager::ShadersManager()
{
}
ShadersManager::~ShadersManager()
{
//std::map<std::string, GLuint>::iterator t_iterator;
for (auto t_iterator = c_programs.begin(); t_iterator != c_programs.end(); ++t_iterator)
glDeleteProgram(t_iterator->second);
}
GLuint ShadersManager::CreateProgram(std::string p_vertexShaderFile, std::string p_fragmentShaderFile, std::string p_programName)
{
//compile both shaders
GLuint t_compiledVertexShader = CompileShader(p_vertexShaderFile, GL_VERTEX_SHADER);
GLuint t_compiledFragmentShader = CompileShader(p_fragmentShaderFile, GL_FRAGMENT_SHADER);
if (t_compiledFragmentShader == 0 || t_compiledVertexShader == 0)
return 0;
//create a program
GLuint t_shaderProgram = glCreateProgram();
//link the compiled shaders to a program
glAttachShader(t_shaderProgram, t_compiledVertexShader);
glAttachShader(t_shaderProgram, t_compiledFragmentShader);
LinkProgram(&t_shaderProgram, t_compiledVertexShader, t_compiledFragmentShader);
//store the program
c_programs[p_programName] = t_shaderProgram;
return t_shaderProgram;
}
GLuint ShadersManager::GetProgram(std::string p_shaderName)
{
return c_programs[p_shaderName];
}
GLuint ShadersManager::CompileShader(std::string p_shaderFile, unsigned short p_shaderType)
{
//read the shader from the specified file
std::string t_shaderCode;
std::ifstream t_shaderStream(p_shaderFile, std::ios::in);
if (t_shaderStream.is_open()) {
std::string Line = "";
while (getline(t_shaderStream, Line))
t_shaderCode += "\n" + Line;
t_shaderStream.close();
}
else
{
std::cout << "Impossible to open " << p_shaderFile << std::endl;
return 0;
}
char const * t_shaderCodeConverted = t_shaderCode.c_str();
GLuint r_shaderID = glCreateShader(p_shaderType);//create a empty shader of the passed type
glShaderSource(r_shaderID, 1, &t_shaderCodeConverted, NULL);//set the source code to the created shader
glCompileShader(r_shaderID);
// Check for compile time errors
GLint t_success;
GLchar t_infoLog[512];
glGetShaderiv(r_shaderID, GL_COMPILE_STATUS, &t_success);//set the shader to be queried and what to query about. Store the result code
if (!t_success)
{
glGetShaderInfoLog(r_shaderID, 512, NULL, t_infoLog);//store the query info in t_infoLog
std::cout << "ERROR COMPILING SHADER " << p_shaderFile << " COMPILATION_FAILED. INFO LOG: " << t_infoLog << std::endl;
std::cin.get();
return 0;
}
return r_shaderID;
}
void ShadersManager::LinkProgram(GLuint* p_program, GLuint p_vertexShader, GLuint p_fragmentShader)
{
glLinkProgram(*p_program);
// Print linking errors if any
GLint t_success;
GLchar t_infoLog[512];
glGetProgramiv(*p_program, GL_LINK_STATUS, &t_success);
if (!t_success)
{
glGetProgramInfoLog(*p_program, 512, NULL, t_infoLog);
std::cout << "ERROR::SHADER::PROGRAM::LINKING_FAILED\n" << t_infoLog << std::endl;
std::cin.get();
}
// Delete the shaders as they're linked into our program now and no longer necessery
glDeleteShader(p_vertexShader);
glDeleteShader(p_fragmentShader);
} | true |
e833919b2fc96db16b685d74242fecd3e72cb8d0 | C++ | dungkaito/TTUD2020 | /0/11.cpp | UTF-8 | 588 | 2.75 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
void rec(string s, int k, string &maxx) {
if (k==0) return;
for (int i=0; i<s.size(); i++) {
for (int j=i+1; j<s.size(); j++) {
if (s[i]<s[j]){
swap(s[i],s[j]);
if (s.compare(maxx)>0) maxx=s;
rec(s, k-1, maxx);
swap(s[i],s[j]);
}
}
}
}
int main() {
int t; cin >> t;
while (t--) {
int k;
string s; cin >> k >> s;
string maxx = s;
rec(s, k, maxx);
cout << maxx << endl;
}
} | true |
77fff992d364f8ba2bccc70caa6b919edd819091 | C++ | AnnaEnakieva/zadachi | /26.12.18/7.cpp | UTF-8 | 648 | 3.359375 | 3 | [] | no_license | /*Напишите программу переводящую число в систему счисления с основанием k, где k не превышает 30.*/
#include <iostream>
using namespace std;
int main() {
int n,k;
cin >> n >> k;
int amount = 0; //количество цифр в записи данной системы счисления
for (int i = k; i < n; i*=k)
{
amount ++;
}
amount ++;
int*arr = new int [amount];
for (int i = 0; i < amount; i++)
{
*(arr + i) = n%k;
n /= k;
}
for (int i = amount - 1; i >=0; i--)
cout « *(arr + i);
return 0;
}
| true |
565a74fd068ce6750fc784e030034ee18eaf3cbd | C++ | subnr01/subs-practice | /leet_code/arrays/2Darray/maximal/maximal_square.cpp | UTF-8 | 4,571 | 3.734375 | 4 | [] | no_license | /*
Given a 2D binary matrix filled with 0's and 1's, find the largest square containing all 1's and return its area.
For example, given the following matrix:
1101
1101
1111
Return 4.
*/
//Brute force
class Solution {
public:
int maximalSquare(vector<vector<char>>& matrix) {
/*
if (matrix.size() == 0) {
return 0;
}*/
int rows = matrix.size();
//int cols = matrix[0].size();
int cols = rows;
int sqlen = 0;
int maxlen = 0;
bool flag = false;
for( int i = 0; i < rows; ++i)
{
for (int j = 0; j < cols; ++j) {
if(matrix[i][j] == '1') {
sqlen = 1;
flag = true;
while(i + sqlen < rows && j + sqlen < cols && flag) {
for(int k = j; k <= j + sqlen; k++) {
if(matrix[i+sqlen][k] == '0') {
flag = false;
break;
}
}
for(int k = i; k <= i + sqlen; k++) {
if(matrix[k][j+sqlen] == '0') {
flag = false;
break;
}
}
if (flag) {
sqlen++;
}
}
}
maxlen = max(maxlen, sqlen);
}
}
return maxlen * maxlen;
}
};
//For explanation read https://leetcode.com/problems/maximal-square/discuss/61803
/*
First, it is obvious that for the topmost row (i = 0) and the leftmost column (j = 0),
P[i][j] = matrix[i][j]. This is easily understood. Let’s suppose that the topmost row of
matrix is like [1, 0, 0, 1]. Then we can immediately know that the first and last point can be a
square of size 1 while the two middle points cannot make any square, giving a size of 0.
Thus, P = [1, 0, 0, 1], which is the same as matrix. The case is similar for the leftmost column.
Till now, the boundary conditions of this DP problem are solved.
Let’s move to the more general case for P[i][j] in which i > 0 and j > 0. First of all,
let’s see another simple case in which matrix[i][j] = 0. It is obvious that P[i][j] = 0 too.
Why? Well, since matrix[i][j] = 0, no square will contain matrix[i][j]. According to our
definition of P[i][j], P[i][j] is also 0.
Now we are almost done. The only unsolved case is matrix[i][j] = 1. Let’s see an example.
Suppose matrix = [[0, 1], [1, 1]], it is obvious that P[0][0] = 0, P[0][1] = P[1][0] = 1, what
about P[1][1]? Well, to give a square of size larger than 1 in P[1][1], all of its
three neighbors (left, up, left-up) should be non-zero, right? In this case, the
left-up neighbor P[0][0] = 0, so P[1][1] can only be 1, which means that it contains the square of itself.
*/
//Dynamic programming using a 2D array
int maximalSquare(vector<vector<char>>& matrix) {
int m = matrix.size();
if (!m) return 0;
int n = matrix[0].size();
vector<vector<int> > size(m, vector<int>(n, 0));
int maxsize = 0;
for (int j = 0; j < n; j++) {
size[0][j] = matrix[0][j] - '0';
maxsize = max(maxsize, size[0][j]);
}
for (int i = 1; i < m; i++) {
size[i][0] = matrix[i][0] - '0';
maxsize = max(maxsize, size[i][0]);
}
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
if (matrix[i][j] == '1') {
size[i][j] = min(size[i - 1][j - 1], min(size[i - 1][j], size[i][j - 1])) + 1;
maxsize = max(maxsize, size[i][j]);
}
}
}
return maxsize * maxsize;
}
//Dynamic programming using a 1D array
class Solution {
public:
int maximalSquare(vector<vector<char>>& matrix) {
int nr = matrix.size(); if (nr == 0) return 0;
int nc = matrix[0].size(); if (nc == 0) return 0;
vector<int> dp(nc+1, 0);
int maxsize = 0;
int last_topleft = 0; // This is 'pre[i-1]' for the current element
for (int ir = 1; ir <= nr; ++ir) {
for (int ic = 1; ic <= nc; ++ic) {
int temp = dp[ic]; // This is 'pre[i-1]' for the next element
if (matrix[ir-1][ic-1] == '0') dp[ic] = 0;
else {
dp[ic] = min(min(dp[ic], dp[ic-1]), last_topleft) + 1;
maxsize = max(maxsize, dp[ic]);
}
last_topleft = temp; // update 'pre[i-1]'
}
}
return maxsize * maxsize;
}
};
| true |
10c49e8ec5e5bdda4ae6ed3b822d098b984ef0c7 | C++ | MaxCarlson/Containers | /Containers/UnorderedSet.h | UTF-8 | 1,090 | 2.859375 | 3 | [] | no_license | #pragma once
#include <utility>
#include "RobinHood.h"
template<class Key,
class Hash,
class KeyEqual,
class Allocator>
struct USetTraits
{
using key_type = Key;
using value_type = Key;
using hasher = Hash;
using key_equal = KeyEqual;
using allocator_type = Allocator;
using node_type = key_type;
struct node_equal
{
bool operator()(const node_type& left, const node_type& right) const
{
return comp(left, right);
}
key_equal comp;
};
struct get_key
{
const key_type& operator()(const node_type& n) const
{
return n;
}
};
};
// UnorderedSet is just a wrapper for differerent unordered class templates
// Default is the Open Address Robinhood hash table at the moment.
//
// TODO: Write copy and move constructors that are compatible
// between base template classes
template<class Key,
template<class, bool> class MyBase = RobinhoodHash,
class Hash = std::hash<Key>,
class KeyEqual = std::equal_to<Key>,
class Allocator = std::allocator<Key>>
class UnorderedSet : public MyBase<USetTraits<Key, Hash, KeyEqual, Allocator>, false>
{
}; | true |
6b52731905cb523c0529c442eb62f85ab4b5c1d7 | C++ | mlekon/Qboy | /Z80.cpp | UTF-8 | 5,049 | 2.59375 | 3 | [] | no_license | #include "Z80.h"
#include "allegro.h"
#include <fstream>
Z80::Z80()
{
reset();
}
Z80::~Z80()
{
#ifdef DEBUG
logger.close();
#endif
}
/////////////////////////////////
//reset all registers and control variables
//so that it behaves as if the system experienced a hard reset
void Z80::reset()
{
instructionsExecuted = 0;
cpuClocks = 0;
clockCounter = 0;
current_op = 0;
p1 = p2 = 0;
delayedInterrupt = false;
lastOpClocks = 0;
reg[A] = 0x11;
reg[F] = 0xb0;
reg[B] = 0;
reg[C] = 0x13;
reg[D] = 0;
reg[E] = 0xd8;
reg[H] = 1;
reg[L] = 0x4d;
movReg16(SP, 0xfffe);
programCounter = 0x0100;
ZF = NF = HF = CF = RESET;
interruptMasterEnable = true;
cpuActive = true;
#ifdef DEBUG
memset(opFreq, 0, sizeof(opFreq));
logger.open("opcode_log.txt");
oplog_next = 0;
#endif
}
/////////////////////////////////
//sets the necessary links to the components
//the CPU needs to communicate with
void Z80::setComponents(MemoryManager* m, Cartridge* c, LCD* l, Gameboy* gb)
{
this->gb = gb;
lcd = l;
mem = m;
cart = c;
}
/////////////////////////////////
//gets the value of the specified register
word Z80::readReg(Register r)
{
switch(r)
{
case AF:
case BC:
case DE:
case HL:
case SP:
return getReg16(r);
case PC:
return programCounter;
default:
return reg[r];
}
}
/////////////////////////////////
//begin executing an interrupt handler
//after pushing the PC onto the stack
void Z80::interrupt(InterruptHandler i)
{
mem->pushStack16(programCounter);
programCounter = i;
}
/////////////////////////////////
//returns the value of a 16 bit register
word Z80::getReg16(Register r)
{
return *((word*)®[r]);
}
/////////////////////////////////
//changes the values of a 16 bit register
//relative to the 'v' parameter
void Z80::modReg16(Register r, int v)
{
*((word*)®[r]) += v;
}
/////////////////////////////////
//write a value to a 16-bit register
void Z80::movReg16(Register r, byte l, byte h)
{
*((word*)®[r]) = ((word)h << 8) + l;
}
/////////////////////////////////
//copies the 16-bit immediate value
//to a 16-bit register
void Z80::movReg16(Register r, word s)
{
*((word*)®[r]) = s;
}
/////////////////////////////////
//swaps the upper and lower 4 bits of
//the given 8 bit register
void Z80::swap8(Register r)
{
reg[r] = ((reg[r] & 0xf) << 4) + (reg[r] >> 4);
}
/////////////////////////////////
//swaps the upper and lower 4 bits of
//the given 16 bit register
void Z80::swap16(Register r)
{
byte temp = reg[r];
reg[r] = reg[r+1];
reg[r+1] = temp;
}
/////////////////////////////////
//saves values of the CPU into the given state
//such that the state of the CPU can be recreated
void Z80::constructState(State* s)
{
reg[F] = CF + HF + ZF + NF;
memcpy(s->registers, this->reg, sizeof(reg));
s->programCounter = programCounter;
s->CF = CF; s->ZF = ZF; s->HF = HF; s->NF = NF;
s->interruptMasterEnable = interruptMasterEnable;
s->cpuHalted = this->cpuActive;
s->clocks = this->cpuClocks;
}
/////////////////////////////////
//recreate the CPU state given by the state parameter
void Z80::restoreState(State* s)
{
memcpy(this->reg, s->registers, sizeof(reg));
programCounter = s->programCounter;
CF = s->CF; HF = s->HF; ZF = s->ZF; NF = s->NF;
reg[F] = CF + HF + ZF + NF;
interruptMasterEnable = s->interruptMasterEnable;
this->cpuActive = true;
this->cpuClocks = s->clocks;
}
void Z80::printDebugInfo()
{
//GBOPCODE i = opcodes[p1];
//printf("Op: 0x%x\tp1 %x, p2 %x\n", current_op, p1, p2);
//std::cout << "Registers: \n";
//for(int i = 0; i < REG_MAX; i++)
//{
// printf("%x\t", reg[i]);
//}
//std::cout << "\n";
}
/////////////////////////////////
//test for interrupt requests and calls the appropriate
//interrupt handler routine
void Z80::interrupts()
{
//interrupt may only occur if the master enable switch is on
//if 0xff0f is 0, then no interrupts have been requested
//if 0xffff is 0, then no interrupts have been enabled
if(interruptMasterEnable && mem->readRam(0xff0f) > 0 && mem->readRam(0xffff) > 0)
{
//loop through the 5 interrupts in decending priority
for(int i = 0; i < 5; i++)
{
if(mem->readRam(0xffff) & (1 << i) && mem->readRam(0xff0f) & (1 << i))
{
//interrupt is enabled and requested. call the handler
interrupt((InterruptHandler)(0x40 + (8 * i)));
mem->write(0xff0f, mem->readRam(0xff0f) ^ (1 << i)); //reset interrupt flag bit
cpuActive = true;
interruptMasterEnable = false;
//only the highest priority interrupt can execute
break;
}
}
}
}
/////////////////////////////////
//sets the audio counter to 0
void Z80::resetClockCounter()
{
clockCounter = 0;
}
/////////////////////////////////
//returns the audio counter
int Z80::getClockCounter()
{
return clockCounter;
}
/////////////////////////////////
//gets a dump of the current cpu registers
RegisterInfo Z80::getRegisterInfo()
{
RegisterInfo ri;
memcpy(ri.reg, reg, REG_MAX);
ri.PC = programCounter;
ri.CF = CF != 0;
ri.HF = HF != 0;
ri.NF = NF != 0;
ri.ZF = ZF != 0;
return ri;
} | true |
95d9436dbdae8a8da9e15423cbacbb371429a4de | C++ | aa10402tw/interview_prepare | /Coding(c++)/4_STL/stack-queue/152. Maximum Product Subarray.cpp | UTF-8 | 1,207 | 3.609375 | 4 | [] | no_license | /* [Question Description]
Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product.
# Example 1
Input: [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.
# Example 2
Input: [-2,0,-1]
Output: 0
Explanation: The result cannot be 2, because [-2,-1] is not a subarray.
*/
#include <iostream>
#include <vector>
#include <queue>
int maxProduct(std::vector<int>& nums) {
int N = nums.size();
std::vector<int> maxs(N, 0); // maxs[i] store the largest product which last number is nums[i] (i.e., maxs[i] = max (N_j * N_j-1 * ... N_i) for all j <= i)
std::vector<int> mins(N, 0); // mins[i] store the smallest product which last number is nums[i]
for (int i = 0; i < nums.size(); i++) {
if (i == 0) {
maxs[i] = nums[i];
mins[i] = nums[i];
}
else {
int maxProd = std::max(maxs[i - 1] * nums[i], mins[i - 1] * nums[i]);
int minProd = std::min(maxs[i - 1] * nums[i], mins[i - 1] * nums[i]);
maxs[i] = std::max(nums[i], maxProd);
mins[i] = std::min(nums[i], minProd);
}
}
int ans = nums[0];
for (int i = 1; i < N; i++) {
ans = std::max(ans, maxs[i]);
}
return ans;
}
int main() {
}
| true |
bc6064c6a37183ede4ef2abe5d74b24b429e1871 | C++ | louiswins/sendit | /client/recv_buf.h | UTF-8 | 745 | 2.9375 | 3 | [
"MIT"
] | permissive | #ifndef RECV_BUF_H
#define RECV_BUF_H
#include <streambuf>
#include <vector>
#include <cstdlib> /* std::size_t */
#include <sys/socket.h>
/**
* Usage:
* recv_buf buf(socket);
* istream is(&buf);
* (Now you can use is as any other istream, e.g. is >> variable, is.get(), &c.
*/
class recv_buf : public std::streambuf {
public:
explicit recv_buf(int sockfd, std::size_t buff_sz = 1024, std::size_t put_back = 8);
private:
// overrides base class underflow()
int_type underflow();
// copy ctor and assignment are not implemented;
// copying not allowed
recv_buf(const recv_buf &);
recv_buf &operator=(const recv_buf &);
private:
int sockfd_;
const std::size_t put_back_;
std::vector<char> buffer_;
};
#endif /* RECV_BUF_H */
| true |
f43042995eefdb38fb1eaaa29b1f1f09cafab3e4 | C++ | aka0909/Data-Structures-and-Algorithms | /DATA STRUCTURES/MATRIX/Transpose_Efficient.cpp | UTF-8 | 549 | 3.15625 | 3 | [] | no_license | #include <iostream>
#include <cmath>
#include <bits/stdc++.h>
#include <climits>
#include <deque>
using namespace std;
const int R=4,C=4;
void Transpose(int arr[R][C])
{
for(int i=0;i<R;i++)
{
for(int j=i+1;j<C;j++)
swap(arr[i][j],arr[j][i]);
}
}
int main()
{
int arr[R][C] = {{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15, 16}};
Transpose(arr);
for(int i = 0; i < C; i++)
{
for(int j = 0; j < R; j++)
{
cout << arr[i][j] << " ";
}
cout << endl;
}
return 0;
}
| true |
1cfbf1614f2b563a532f97746a1cb0c426d0d101 | C++ | sw15-algorithm-study/algorithm_study | /영재/8주차/8_3_1932.cpp | UTF-8 | 1,054 | 3.28125 | 3 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
int main()
{
int n;
cin >> n;
// 0번째는 사용하지 않고 1 ~ n 번째 인덱스만 사용
int** dp = new int*[n+1]();
vector<vector<int> > triangle;
for(int i = 0; i <= n; i++)
{
dp[i] = new int[n+1];
vector<int> tmpVector;
triangle.push_back(tmpVector);
}
for(int i = 1; i <= n; i++)
{
for(int j = 0; j < i; j++)
{
int tmpNum;
cin >> tmpNum;
triangle[i].push_back(tmpNum);
}
}
dp[1][1] = triangle[1].front();
for(int i = 2; i <= n; i++)
{
dp[1][i] = dp[1][i-1] + triangle[i].front();
}
for(int x = 2; x <= n; x++)
{
for(int y = 2; y <= x; y++)
{
dp[y][x] = max(dp[y][x-1], dp[y-1][x-1]) + triangle[x][y-1];
}
}
int answer = 0;
for(int i = 1; i <= n; i++)
{
if(dp[i][n] > answer)
{
answer = dp[i][n];
}
}
cout << answer;
} | true |
239f288f9f0909c45f7067dab943fe28f4401e3b | C++ | GlassyYang/leetcode-cplusplus | /Solution97.cpp | UTF-8 | 858 | 3.171875 | 3 | [] | no_license | //
// Created by zhang on 2021/5/10.
//
// 五分钟解决
#include <string>
#include <iostream>
#include <cstring>
using namespace std;
class Solution {
public:
bool isInterleave(string s1, string s2, string s3) {
const int s1Length = s1.length(), s2Length = s2.length();
bool dp[s2.length() + 1];
memset(dp, true, sizeof(dp));
dp[0] = true;
for(auto i = 0; i < s1Length; i++) {
for(auto j = 1; j <= s2Length; j++) {
char c1 = s1[i], c2 = s2[j - 1], c3 = s3[i + j - 1];
dp[j] = (c3 == c1 && dp[j]) || (c3 == c2 && dp[j - 1]);
}
}
return dp[s2Length];
}
};
int main(int argc, char **argv) {
string s1 = "aabcc", s2 = "dbbca", s3 = "aadbbbaccc";
Solution solution;
cout << solution.isInterleave(s1, s2, s3);
return 0;
}
| true |
a38fd2ee023e2bdfd2fa15c50c1801687d1200d9 | C++ | Vaishu2001/Guess-the-number-c- | /guess.cpp | UTF-8 | 489 | 3.421875 | 3 | [] | no_license | //Guessing a number
#include<iostream>
using namespace std;
int main()
{
int snum=30,num,x=0,chance=5;
while(x!=5)
{
cout<<"Guess a number out of "<<chance <<" chances"<<endl;
cout<<"Enter a number in the range of 1 to 100 :"<<endl;
cin>>num;
if(num==snum)
{
cout<<"Right answer!!!You nailed it!!!";
break;
}
else if(num>30)
{
cout<<"lesser\n";
}
else
{
cout<<"greater\n";
}
x++;
chance--;
}
if(x==5)
{
cout<<"You lost!!!Try again...";
}
return 0;
}
| true |
aa160e191e1db9990c4cf91c632287131463b594 | C++ | YangRT/About_C- | /八皇后问题.cpp | UTF-8 | 520 | 2.640625 | 3 | [] | no_license | #include<iostream>
using namespace std;
int ans[20],b[20],c[2][28];
int n,sum=0;
void search(int i){
if(i>n){
sum++;
if(sum>3){
return;
}else{
for(int j=1;j<=n;j++){
cout<<ans[j]<<" ";
}
cout<<endl;
return;
}
}
for(int k=1;k<=n;k++){
if((!b[k])&&(!c[0][i+k])&&(!c[1][i-k+n])){
ans[i] = k;
b[k] = 1;
c[0][i+k] = 1;
c[1][i-k+n] = 1;
search(i+1);
b[k] = 0;
c[0][i+k] = 0;
c[1][i-k+n] = 0;
}
}
}
int main(){
cin>>n;
search(1);
cout<<sum<<endl;
return 0;
}
| true |
e5c560030160769c07a0b3e03f649c2782eb0a0a | C++ | hjchai/ECS60 | /p5/TripsRunner.cpp | UTF-8 | 4,079 | 2.796875 | 3 | [] | no_license | // Author: Sean Davis
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include "TripsRunner.h"
#include "router.h"
#include "CPUTimer.h"
typedef struct
{
int originIndex;
int destinationIndex;
} CityIndices;
using namespace std;
void readFile(Flight **flights2, Trip **trips2, int *numTrips, int *numFlights,
int *numCities, const char *filename, Flight **flights3)
{
ifstream inf(filename);
inf >> *numCities >> *numFlights >> *numTrips;
Flight *flights = new Flight[*numFlights];
Flight *flights1 = new Flight[*numFlights];
Trip *trips = new Trip[*numTrips];
inf.ignore(1000, '\n');
for(int i = 0; i < *numFlights; i++)
{
flights[i].flightNum = i;
inf >> flights[i].departureTime >> flights[i].duration
>> flights[i].originIndex >> flights[i].destinationIndex;
flights1[i] = flights[i];
} // for each flight
for(int i = 0; i < *numTrips; i++)
inf >> trips[i].departureTime >> trips[i].originIndex
>> trips[i].destinationIndex;
*flights2 = flights;
*flights3 = flights1;
*trips2 = trips;
} // readFile())
int checkRoutes(Flight *flights, Trip *trips, int numTrips, int numFlights,
Itinerary *itineraries, int argc, char **argv)
{
unsigned currentCityIndex, flightNum, currentCityTime, tripTime, totalTime = 0,
dayCount;
ofstream outf;
if(argc > 2)
outf.open(argv[2]);
for(int i = 0; i < numTrips; i++)
{
if(argc > 2)
outf << i << ": (" << trips[i].departureTime << ") ";
currentCityIndex = trips[i].originIndex;
currentCityTime = trips[i].departureTime;
tripTime = 0;
dayCount = 0;
for(int j = 0; j < itineraries[i].numFlights; j++)
{
flightNum = itineraries[i].flightNums[j];
if(argc > 2)
outf << flightNum << '(' << flights[flightNum].departureTime << ","
<< (flights[flightNum].duration + flights[flightNum].departureTime) % 1440
<< ") ";
if(flights[flightNum].originIndex != currentCityIndex)
cout << "\nTrip #" << i << " connection #" << j << " starts at "
<< flights[flightNum].originIndex << " instead of "
<< currentCityIndex << endl;
if(flights[flightNum].departureTime < currentCityTime) // next day
dayCount++;
currentCityIndex = flights[flightNum].destinationIndex;
currentCityTime = flights[flightNum].departureTime
+ flights[flightNum].duration;
if(currentCityTime > 1440)
{
currentCityTime %= 1440;
dayCount++;
}
if(j + 1 < itineraries[i].numFlights) // not last flight so add necessary wait
currentCityTime += 30;
} // for each connection
if(flights[flightNum].destinationIndex != trips[i].destinationIndex)
cout << "\nTrip #" << i << " ends at " << flights[flightNum].destinationIndex
<< " instead of " << trips[i].destinationIndex << endl;
tripTime = ((flights[flightNum].departureTime + flights[flightNum].duration) % 1440)
- trips[i].departureTime + dayCount * 1440;
totalTime += tripTime;
if(argc > 2)
outf << "= " << tripTime << endl;
} // for each trip
if(argc > 2)
{
outf << "Total time: " << totalTime << endl;
outf.close();
} // if printing solution
cout << " Total time: " << totalTime << endl;
return totalTime;
} // checkRoutes()
int main(int argc, char** argv)
{
int numTrips, numFlights, numCities;
Flight *flights, *flights2;
Trip *trips;
readFile(&flights, &trips, &numTrips, &numFlights, &numCities, argv[1],
&flights2);
Itinerary *itineraries = new Itinerary[numTrips];
CPUTimer ct;
Router *router = new Router(numCities, numFlights, flights2);
delete [] flights2;
for(int i = 0 ; i < numTrips; i++)
router->findRoute((const Trip*) &trips[i], &itineraries[i]);
cout << "CPU Time: " << ct.cur_CPUTime();
checkRoutes(flights, trips, numTrips, numFlights, itineraries, argc, argv);
return 0;
} // main()
| true |
414d73533dfef43ae4d9de01c954f1c0b938afbf | C++ | whhpc19891120/algorithm | /LetCode26.cpp | UTF-8 | 643 | 3.046875 | 3 | [] | no_license | #include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
auto itpos = unique(nums.begin(), nums.end());
nums.erase(itpos, nums.end());
return itpos - nums.begin();
}
int removeDuplicates2(vector<int>& nums) {
if (nums.size() == 0) return 0;
int i = 0;
for (int j = 1; j < nums.size(); j++)
{
if (nums[j] != nums[i])
{
i++;
nums[i] = nums[j];
}
}
return i + 1;
}
};
#if defined(__LETCODE26__)
void main()
{
Solution solution;
vector<int> vect = { 1,1,2,2,2,3,3 };
int count = solution.removeDuplicates2(vect);
return;
}
#endif | true |
0254f8727037418fbbdb5ebb29afaf96594507aa | C++ | YanzeChu/MyDataStructureAndAlgorithm | /图/vector_search_binary_a.h | GB18030 | 336 | 3.21875 | 3 | [] | no_license | #pragma once
#include "vector.h"
/*
ֲңǰźvector
*/
template<typename T>
static Rank Bin_Search(T* A, T const& e, Rank lo, Rank hi)
{
while (lo < hi)
{
Rank mi = (lo + hi) >> 1;
if (e < A[mi]) //[lo,mi)
hi = mi;
else if (e > A[mi]) //(mi,hi)
lo = mi + 1;
else
return mi;
}
}
| true |
1f2cc5cc3a49367489d97e5a878ffd713868009e | C++ | liaorongfan/GoDataStructure | /dataStructure/16.AVL_tree.cpp | UTF-8 | 2,298 | 3.09375 | 3 | [] | no_license | /*************************************************************************
> File Name: 16.AVL_tree.cpp
> Author:
> Mail:
> Created Time: Sat 17 Apr 2021 07:47:55 PM CST
************************************************************************/
#include<stdio.h>
#include<time.h>
#include<stdlib.h>
#define max(a,b) ((a) > (b) ?(a) :(b))
typedef struct Node {
int key, h;
struct Node *lchild, *rchild;
} Node;
Node __NIL;
#define NIL (&__NIL)
__attribute__((constructor))
void init_NIL() {
NIL->key = -1;
NIL->lchild = NIL.rchild = NIL;
NIL->h = 0;
return ;
}
void update_height(Node *root) {
root->h = max(root->lchild->h, root->rchild->h) + 1;
return ;
}
Node *getNewNode(int key) {
Node *p = (Node *)malloc(sizeof(Node));
p->key = key;
p->lchilde = p->rchild = NIL;
p->h = 1;
return p;
}
Node *inser(Node *root, int key) {
if (root == NIL) return getNewNode(key);
if (root->key == key) return root;
if (key < root->key) {
root->lchild = insert(root->lchild, key);
} else {
root->rchild = insert(root->rchild, key);
}
update_height(root);
return root;
}
Node *predecessor(Node *root) {
Node *temp = root->lchild;
while (tem->rchild != NIL) temp = temp->rchild;
return temp;
}
Node *erase(Node *root, int key) {
if (root == NIL) return root;
if (key < root->key) {
root->lchild = erase(root->lchild, key);
} else if (key > root->key) {
root->rchild = erase(root->rchild, key);
} else {
if (root->lchild == NIL || root->rchild == NIL) {
Node *temp = (root->lchild == NIL ? root->rchild : root->lchild);
free(root);
return temp;
} else {
Node *temp = predecessor(root);
root->key = temp->key;
root->lchild = erase(root->lchild, temp->key);
}
}
update_height(root);
return root;
}
void clear(Node *root) {
if (root == NIL) return ;
clear(root->lchild);
clear(root->rchild);
free(root)
return ;
}
void output(Node *root) {
if (root == NIL) retun ;
printf("(%d(%d) | %d, %d)\n", root-key, root->h, root->lchild->key, root->rchild->key);
output(root->lchild);
output(root->rchild);
return ;
}
| true |
f878463531dd1c6a368f5e0518f2efe409be2fd7 | C++ | fionser/YELL | /include/yell/utils/math.hpp | UTF-8 | 965 | 2.859375 | 3 | [] | no_license | #pragma once
#include "yell/ops.hpp"
#include <cmath>
namespace yell {
namespace math {
// compute a^{-1} mod prime
// i.e., a^{prime - 2}
template <typename T>
T inv_mod_prime(T a, size_t cm)
{
yell::ops::mulmod mulmod;
T ret{1};
T y = yell::params::P[cm] - 2;
while (y > 0) {
if (y & 1)
ret = mulmod(ret, a, cm);
y >>= 1u;
a = mulmod(a, a, cm);
}
return ret;
}
template <typename T, typename F>
inline T round(F a)
{
return a >= 0 ? (T)(a + 0.5f) : (T) (a - 0.5f);
}
template <typename T>
void revbin_permute(T *array, int length) {
if (!array || length <= 2) return;
for (int i = 1, j = 0; i < length; ++i) {
int bit = length >> 1;
for (; j >= bit; bit >>= 1) {
j -= bit;
}
j += bit;
if (i < j) {
std::swap(array[i], array[j]);
}
}
}
/* Reverse 32-bit */
uint32_t reverse_bits(uint32_t operand);
uint32_t reverse_bits(uint32_t operand, int32_t bit_count);
}} // namespace yell::math
| true |
b5f21d9142d32d11e4e6e3e95494fd1060239a86 | C++ | malysz/Algorithms-and-Data-Structures | /DataStructures/hashTable.cpp | UTF-8 | 1,302 | 3.84375 | 4 | [] | no_license | #include <iostream>
using namespace std;
class hashTable{
private:
int size;
int *key = new int[size];
int *state = new int[size];
//0-empty, 1-occupied, -1-deleted
public:
hashTable(int s);
void insert(int k);
bool search(int k);
void remove(int k);
};
int h(int key, int size){ return key%size; }
int h(int key, int size, int i){ return (h(key, size)+i)%size; }
hashTable::hashTable(int s){
size = s;
for(int i=0; i<s; i++){
key[i]=NULL;
state[i]=0;
}
}
void hashTable::insert(int k){
int idx;
for(int i=0; i<size; i++){
idx = h(k, size, i);
if(state[idx] != 1) break;
}
key[idx] = k;
state[idx] = 1;
}
bool hashTable::search(int k){
int idx;
for(int i=0; i<size; i++){
idx = h(k, size, i);
if(state[idx]==0 || key[idx]==k) break;
}
return key[idx] == k;
}
void hashTable::remove(int k){
int idx;
for(int i=0; i<size; i++){
idx = h(k, size, i);
if(state==0 || key[idx]==k) break;
}
if(key[idx]==k){
key[idx]=NULL;
state[idx]=-1;
}
}
int main(){
hashTable ht=hashTable(1000);
ht.insert(500);
if(ht.search(500)) cout << "znaleziono\n";
}
| true |
270142db9b842fa4c9d5f29d7bd6647cbbf19b20 | C++ | duchevich/c-plus-plus-VS2017-course | /Проект1/Проект1/Source.cpp | UTF-8 | 2,554 | 3.40625 | 3 | [] | no_license | /*
10. Написати програму, яка шукає індекси всіх сідлових точок матриці.
Сідлова точка – елемент матриці, який є найбільшим у рядку і одночасно
найменший в стовпці, або навпаки.
*/
#include <iostream>
using namespace std;
#define N 100
#define M 100
void dots(int arr[N][M]);
void matr(int arr[N][M]);
int main()
{
setlocale(0, "");
/*int m[N][N] = {
{ 2, 3, 5 },
{ 2, 4, 6 },
{ -2, 7, 2 }
};*/
int m[N][M];
int a = 0;
int b = 0;
matr(m,a,b);
dots(m,a,b);
system("pause");
return 0;
}
void matr(int arr[N][M], int &a, int &b)
{
cout << "Введiть розмірність квадратної матриці";
cin >> a;
cin >> b;
cout << "Введiть значення 1 квадратної матриці";
for (int i = 0; i < a; i++) {
for (int j = 0; j < b; j++) {
cout << "[" << i + 1 << "]" << "[" << j + 1 << "]" << ": ";
cin >> arr[i][j];
}
}
}
void dots(int arr[N][M])
{
int max, min;
int jmin;
for (int i = 0; i < N; i++) {
min = arr[i][0];
jmin = 0;
for (int j = 0; j < M; j++) {
if (arr[i][j] < min) {
min = arr[i][j];
jmin = j;
}
}
for (int k = 0; k < N; k++) {
max = arr[0][jmin];
if (arr[k][jmin] > max) {
max = arr[k][jmin];
}
}
if (min == max)
{
cout << "Сідлова точка " << min << endl;
}
}
}
/*#include <conio.h>
#include <iostream>
#define n 5
using namespace std;
void Vvid(int *x)
{
for (int i = 0; i < n; i++)
cin >> x[i];
}
int main()
{
int a[n];
Vvid(a);
for (int i = 0; i < n; i++)
cout << a[i] << " ";
cout << endl;
system("pause");
}*/
/*#include <iostream>
#define n 5
using namespace std;
float dil(int, int);
int main()
{
setlocale(0, "");
int x = 0;
int y = 0;
cout << "Введите данные: " << endl;
cin >> x >> y;
float p = dil(x, y);
cout << p << endl;
system("pause");
return 0;
}
float dil(int a, int b)
{
float d = (float)a / b;
if (b == 0) {
cout << "Делить на ноль нельзя" << endl;
return -1;
}
return d;
}*/
/*#include <iostream>
#define n 5
using namespace std;
int perimetr(int, int, int);
int main()
{
setlocale(0, "");
int x = 0;
int y = 0;
int z = 0;
cout << "Введите данные: " << endl;
cin >> x >> y >> z;
int p = perimetr(x, y, z);
cout << p << endl;
system("pause");
return 0;
}
int perimetr(int a, int b, int c)
{
int p = a + b + c;
return p;
}*/
| true |
6e66a7a4c6a67039ddbab1f1c244c7b1db02ea76 | C++ | alaneos777/club | /spoj/PROBLEM4.cpp | UTF-8 | 737 | 2.796875 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
vector<int> primos;
vector<bool> es_primo;
void criba(int n){
es_primo.resize(n + 1, true);
es_primo[0] = es_primo[1] = false;
for(int i = 4; i <= n; i += 2){
es_primo[i] = false;
}
primos.push_back(2);
int limit = sqrt(n);
for(int i = 3; i <= n; i += 2){
if(es_primo[i]){
primos.push_back(i);
if(i <= limit){
for(int j = i * i; j <= n; j += 2 * i){
es_primo[j] = false;
}
}
}
}
}
int main(){
ios_base::sync_with_stdio(0);
criba(10000);
int t, n;
cin >> t;
for(int i = 1; i <= t; i++){
cin >> n;
cout << i << ":";
if(!es_primo[n]){
cout << "NOTPRIME\n";
}else if(n == 3){
cout << "2\n";
}else{
cout << "1\n";
}
}
return 0;
} | true |
10a71e4d9de1d8b2c8e59a9b212e1320601212e0 | C++ | mdclyburn/rfm69hcw | /src/metrics.h | UTF-8 | 910 | 2.75 | 3 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | /** @file
*
* Reading statistics
*/
#ifndef RFM69_METRICS_H
#define RFM69_METRICS_H
#include "core.h"
#include "registers.h"
namespace mardev::rfm69
{
/** Returns the RSSI value.
*
* \returns RSSI value.
*/
inline int16_t rssi()
{
return - read(registers::RSSIValue) / 2;
}
/** Return the reading of the CMOS temperature sensor.
*
* Returns the temperature value read by the CMOS temperature sensor.
* The temperature cannot be read while the receiver block is in use or while the radio is in sleep mode.
* If this function is called while in either of the aforementioned modes, a 0 will be returned.
* This function requires RFM_FEATURE_TEMPERATURE.
*
* \param offset adjustment value to add to the returned value
*
* \returns Temperature value.
*/
uint8_t temperature(const int8_t offset = 0);
}
#endif
| true |
7d28378beffb926f85660680fbf8d969c3851251 | C++ | fish-ball/acm.zju.edu.cn | /24XX/zoj.2420.src.1.cpp | UTF-8 | 1,089 | 3.15625 | 3 | [] | no_license | #include <cstdio>
const int dayInYear[] = { 365, 366 };
const int dayInMonth[2][13] = {
{ 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },
{ 0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 } };
inline bool isLeap( int year ) {
return year % 400 == 0 ||
year % 4 == 0 &&
year % 100;
}
const char* WD[] = { "Saturday",
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday" };
int main() {
int days;
while( scanf( "%d", &days ) && days != -1 ) {
int year = 2000;
int month = 1;
int weekDay = days % 7;
days += 1;
while( days > dayInYear[ isLeap( year ) ] ) {
days -= dayInYear[ isLeap( year++ ) ];
}
const int* MD = dayInMonth[ isLeap( year ) ];
while( days > MD[month] ) {
days -= MD[month];
month++;
}
printf( "%d-%02d-%02d %s\n",
year, month, days, WD[weekDay] );
}
}
| true |