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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
a6d73493511a8ce0c2aedae1a7e8760623015881 | C++ | Josedm92/UD3 | /menu_calculadora.cpp | UTF-8 | 2,641 | 4.34375 | 4 | [] | no_license | //Programa que pide al usuario dos números y hace los cálculos básicos usando funciones.
#include <iostream> //Incluimos librería iostream que permite la entrada por teclado y la salida por pantalla.
using namespace std; //Sentencia obligatoria.
//Creación de las funciones.
double suma(double numero1, double numero2){
return numero1+numero2;
}
double resta(double numero1, double numero2){
return numero1-numero2;
}
double multiplicacion(double numero1, double numero2){
return numero1*numero2;
}
double division(double numero1, double numero2){
return numero1/numero2;
}
//Inicio del programa.
int main () {
//Declaración e inicialización de variables.
double numero1=0.0, numero2=0.0, resultado=0.0;
char opcion;
//Pedimos dos números por pantalla.
cout << "Introduce el primer número: ";
cin >> numero1;
cout << "Introduce el segundo número: ";
cin >> numero2;
//Pedimos al usuario que escoja una operación para realizar con dichos números (suma, resta, multiplicación o división).
cout << "\nEscoja una opción: " << endl;
cout << "\t(s) Sumar los números: " << endl;
cout << "\t(r) Restar los números: " << endl;
cout << "\t(m) Multiplicar los números: " << endl;
cout << "\t(d) Dividir los números: " << endl;
cin >> opcion;
//Comprobamos el dato introducido.
switch (opcion) {
case 's':
case 'S': //Si introduce s o S se hace la suma de los números y se saca el resultado por pantalla.
resultado=suma(numero1,numero2);
cout << "\nLa suma de " << numero1 << " y " << numero2 << " da como resultado: " << resultado << endl;
break;
case 'r':
case 'R': //Si introduce r o R se hace la resta de los números y se saca el resultado por pantalla.
resultado=resta(numero1,numero2);
cout << "\nLa resta de " << numero1 << " y " << numero2 << " da como resultado: " << resultado << endl;
break;
case 'm':
case 'M': //Si introduce m o M se hace la multiplicación de los números y se saca el resultado por pantalla.
resultado=multiplicacion(numero1,numero2);
cout << "\nLa multiplicación de " << numero1 << " y " << numero2 << " da como resultado: " << resultado << endl;
break;
case 'd':
case 'D': //Si introduce d o D se hace la división de los números y se saca el resultado por pantalla.
resultado=division(numero1,numero2);
cout << "\nLa división de " << numero1 << " y " << numero2 << " da como resultado: " << resultado << endl;
break;
default: //En caso de que no introduzca ninguna de las opciones anteriores, se finaliza el programa con un mensaje de error.
cout << "\nOpción incorrecta." << endl;
}
} | true |
9390ca7984cac811db53abe8b12ea31cad6aaa57 | C++ | btcup/sb-admin | /exams/2558/02204111/1/midterm/2_2_714_5420502844.cpp | UTF-8 | 687 | 2.8125 | 3 | [
"MIT"
] | permissive | #include<iostream>
using namespace std;
int main (){
float A,B,C,F,G,c,N;
int x=55,y=80,z=90,m=17,n=32,o=50;
cout<<"wellcome to The fantastic Tilles !!"<<endl;
cout<<"Please enter room size in meter (H x W x D) :";
cin>>A>>B>>C;
cout<<"Please select floor tile...(A/B/C) :";
cin>>F;
cout<<"Please select wall tile...(A/B/C) :";
cin>>G;
cout<<"--------------------------------"<<endl;
cout<<"number of floor tile :";
cin>>N;
cout<<"---> Price = "<<(N*x);
cout<<"number of floor tile :";
cin>>N;
cout<<"---> Price = "<<(N*b);
cout<<"number of wall tile :"<<b<<endl;
system("pause");
return 0;
}
| true |
3797372c3b365afa5290fb2585d555eac03dffcf | C++ | dskut/junk | /map-alloc/test.cpp | UTF-8 | 5,645 | 3.203125 | 3 | [] | no_license |
#include <map>
#include <vector>
#include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>
#include <sys/time.h>
#include <climits>
#include <boost/pool/pool_alloc.hpp>
using namespace std;
class Timer {
private:
timespec start_;
public:
Timer()
{
reset();
}
void reset() {
clock_gettime(CLOCK_REALTIME, &start_);
}
unsigned long getMilliseconds() const {
timespec end;
clock_gettime(CLOCK_REALTIME, &end);
time_t secs = end.tv_sec - start_.tv_sec;
long nanosecs = end.tv_nsec - start_.tv_nsec;
return secs*1000 + nanosecs/1000000;
}
};
const int MaxInt = 100;
const size_t MaxStringLen = 100;
int randomInt(int max) {
return (double)rand()/RAND_MAX * (max+1);
}
string randomString() {
size_t size = randomInt(MaxStringLen);
string res(size, '\0');
for (size_t i = 0; i < size; ++i) {
res[i] = randomInt(255);
}
return res;
}
template <typename T>
class MyAlloc {
public:
char* pool_;
size_t next_;
typedef T value_type;
typedef T* pointer;
typedef const T* const_pointer;
typedef T& reference;
typedef const T& const_reference;
typedef size_t size_type;
typedef ptrdiff_t difference_type;
template <typename U>
struct rebind {
typedef MyAlloc<U> other;
};
MyAlloc(char* pool) throw()
: pool_(pool)
, next_(0)
{
//cout << "ctor" << endl;
}
MyAlloc(const MyAlloc& other) throw()
: pool_(other.pool_)
, next_(other.next_)
{
//cout << "copy ctor" << endl;
}
template <typename U>
MyAlloc(const MyAlloc<U>& other) throw()
: pool_(other.pool_)
, next_(other.next_)
{
//cout << "template ctor" << endl;
}
~MyAlloc() throw() {
//cout << "detor" << endl;
}
pointer address(reference x) const {
//cout << "address" << endl;
return &x;
}
const_pointer address(const_reference x) const {
//cout << "address const" << endl;
return &x;
}
pointer allocate(size_type n, allocator<void>::const_pointer hint = 0) {
//cout << "allocating" << endl;
pointer res = (pointer)(&pool_[next_]);
next_ += sizeof(T);
return res;
}
void deallocate(pointer p, size_type n) {
//cout << "deallocate" << endl;
(void)p;
(void)n;
}
size_type max_size() const throw() {
//cout << "max_size" << endl;
//return PoolSize;
return INT_MAX;
}
void construct(pointer p, const value_type& val) {
//cout << "construct" << endl;
new(p) T(val);
}
void destroy(pointer p) {
//cout << "destroy" << endl;
p->~T();
}
};
ostream& operator<<(ostream& o, const pair<string, int>& p) {
o << p.first << "," << p.second;
return o;
}
template <typename Dict>
void testInsert(Dict& dict, const vector<string>& strings, const vector<int>& nums, const string& prefix) {
Timer timer;
for (size_t i = 0; i < nums.size(); ++i) {
dict.insert(make_pair(strings[i], nums[i]));
}
cout << prefix << " insert " << timer.getMilliseconds() << "ms" << endl;
}
template <typename Dict>
void testRead(Dict& dict, const vector<string>& strings, const string& prefix) {
Timer timer;
for (size_t i = 0; i < strings.size(); ++i) {
(void)dict.find(strings[i]);
}
cout << prefix << " read " << timer.getMilliseconds() << "ms" << endl;
}
template <typename Dict>
void testDelete(Dict& dict, const string& prefix) {
Timer timer;
for (typename Dict::iterator iter = dict.begin(); iter != dict.end();) {
dict.erase(iter++);
}
cout << prefix << " delete " << timer.getMilliseconds() << "ms" << endl;
}
void runDefault(const vector<string>& strings, const vector<int>& nums) {
typedef map<string, int> Dict;
Dict dict;
string prefix = "default";
testInsert(dict, strings, nums, prefix);
testRead(dict, strings, prefix);
testDelete(dict, prefix);
}
void runCustom(const vector<string>& strings, const vector<int>& nums) {
size_t poolSize = 512*1024*1024;
char* pool = new char[sizeof(int)*poolSize];
MyAlloc<pair<string, int> > myAlloc(pool);
typedef map<string, int, less<string>, MyAlloc<pair<string, int> > > MyDict;
MyDict dict(less<string>(), myAlloc);
string prefix = "custom";
testInsert(dict, strings, nums, prefix);
testRead(dict, strings, prefix);
testDelete(dict, prefix);
delete[] pool;
}
void runBoost(const vector<string>& strings, const vector<int>& nums) {
typedef map<string, int, less<string>, boost::fast_pool_allocator<pair<string, int> > > BoostDict;
BoostDict dict;
string prefix = "boost";
testInsert(dict, strings, nums, prefix);
testRead(dict, strings, prefix);
testDelete(dict, prefix);
}
int main(int argc, char** argv) {
if (argc < 3) {
cout << "usage: " << argv[0] << " <d,c,b> <count>" << endl;
return 1;
}
srand(time(NULL));
int insertCount = atoi(argv[2]);
vector<string> strings(insertCount);
vector<int> nums(insertCount);
for (size_t i = 0; i < insertCount; ++i) {
strings[i] = randomString();
nums[i] = randomInt(MaxInt);
}
char c = argv[1][0];
if (c == 'c') {
runCustom(strings, nums);
} else if (c == 'd') {
runDefault(strings, nums);
} else if (c == 'b') {
runBoost(strings, nums);
} else {
cerr << "unknown choice" << endl;
}
return 0;
}
| true |
4cf7f64611324677b3025c7cd2d3048a674b0060 | C++ | villadox/PrimeWorldEditor | /src/Editor/Widgets/WTextureGLWidget.cpp | UTF-8 | 4,469 | 2.515625 | 3 | [
"MIT"
] | permissive | #include "WTextureGLWidget.h"
#include <Common/Math/CTransform4f.h>
#include <Core/GameProject/CResourceStore.h>
#include <Core/Render/CDrawUtil.h>
#include <Core/Render/CGraphics.h>
#include <iostream>
#include <iomanip>
WTextureGLWidget::WTextureGLWidget(QWidget *pParent, CTexture *pTex)
: QOpenGLWidget(pParent)
{
SetTexture(pTex);
mInitialized = false;
}
WTextureGLWidget::~WTextureGLWidget()
{
if (mInitialized) CGraphics::ReleaseContext(mContextID);
}
void WTextureGLWidget::initializeGL()
{
CGraphics::Initialize();
glEnable(GL_BLEND);
mContextID = CGraphics::GetContextIndex();
mInitialized = true;
}
void WTextureGLWidget::paintGL()
{
CGraphics::SetActiveContext(mContextID);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glClearColor(1.f, 0.f, 0.f, 0.f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glDisable(GL_DEPTH_TEST);
// Set matrices to identity
CGraphics::sMVPBlock.ModelMatrix = CMatrix4f::skIdentity;
CGraphics::sMVPBlock.ViewMatrix = CMatrix4f::skIdentity;
CGraphics::sMVPBlock.ProjectionMatrix = CMatrix4f::skIdentity;
CGraphics::UpdateMVPBlock();
// Draw checkerboard background
CDrawUtil::UseTextureShader();
glDepthMask(GL_FALSE);
CDrawUtil::LoadCheckerboardTexture(0);
CDrawUtil::DrawSquare(&mCheckerCoords[0].X);
// Make it darker
CDrawUtil::UseColorShader(CColor::Integral(0.0f, 0.0f, 0.0f, 0.5f));
glDepthMask(GL_FALSE);
CDrawUtil::DrawSquare();
// Leave it at just the checkerboard if there's no texture
if (!mpTexture) return;
// Draw texture
CDrawUtil::UseTextureShader();
mpTexture->Bind(0);
CGraphics::sMVPBlock.ModelMatrix = mTexTransform;
CGraphics::UpdateMVPBlock();
CDrawUtil::DrawSquare();
glEnable(GL_DEPTH_TEST);
}
void WTextureGLWidget::resizeGL(int Width, int Height)
{
mAspectRatio = (float) Width / (float) Height;
glViewport(0, 0, Width, Height);
CalcTexTransform();
CalcCheckerCoords();
update();
}
void WTextureGLWidget::SetTexture(CTexture *pTex)
{
mpTexture = pTex;
if (pTex) mTexAspectRatio = (float) pTex->Width() / (float) pTex->Height();
else mTexAspectRatio = 0.f;
CalcTexTransform();
CalcCheckerCoords();
update();
}
void WTextureGLWidget::CalcTexTransform()
{
// This is a simple scale based on the dimensions of the viewport, in order to
// avoid stretching the texture if it doesn't match the viewport aspect ratio.
mTexTransform = CTransform4f::skIdentity;
float Diff = mTexAspectRatio / mAspectRatio;
if (mAspectRatio >= mTexAspectRatio)
mTexTransform.Scale(Diff, 1.f, 1.f);
else
mTexTransform.Scale(1.f, 1.f / Diff, 1.f);
}
void WTextureGLWidget::CalcCheckerCoords()
{
// The translation vector is set up so the checkerboard stays centered on the screen
// rather than expanding from the bottom-left corner. This makes it look more natural.
CVector2f Trans;
float InvAspect = (mAspectRatio == 0.f) ? 0.f : 1.f / mAspectRatio;
float InvTexAspect = (mTexAspectRatio == 0.f) ? 0.f : 1.f / mTexAspectRatio;
float XBase, YBase, XScale, YScale;
// Horizontal texture
if ((mpTexture != nullptr) && (mpTexture->Width() > mpTexture->Height()))
{
XBase = 1.f;
YBase = InvTexAspect;
XScale = InvTexAspect;
YScale = 1.f;
}
// Vertical texture
else
{
XBase = mTexAspectRatio;
YBase = 1.f;
XScale = 1.f;
YScale = mTexAspectRatio;
}
// Space on left/right
if (mAspectRatio > mTexAspectRatio)
{
Trans = CVector2f(mAspectRatio / 2.f, 0.5f) * -XScale;
mCheckerCoords[0] = CVector2f(0.f, YBase);
mCheckerCoords[1] = CVector2f(mAspectRatio * XScale, YBase);
mCheckerCoords[2] = CVector2f(mAspectRatio * XScale, 0.f);
mCheckerCoords[3] = CVector2f(0.f, 0.f);
}
// Space on top/bottom
else
{
Trans = CVector2f(0.5f, InvAspect / 2.f) * -YScale;
mCheckerCoords[0] = CVector2f(0.f, InvAspect * YScale);
mCheckerCoords[1] = CVector2f(XBase, InvAspect * YScale);
mCheckerCoords[2] = CVector2f(XBase, 0.f);
mCheckerCoords[3] = CVector2f(0.f, 0.f);
}
// Finally, apply translation/scale
for (uint32 iCoord = 0; iCoord < 4; iCoord++)
{
mCheckerCoords[iCoord] += Trans;
mCheckerCoords[iCoord] *= 10.f;
}
}
| true |
0ad2a5e82db6136ea3b26b3ed34e8d0639fa8d09 | C++ | ojy0216/BOJ | /2156.cpp | UTF-8 | 688 | 2.6875 | 3 | [] | no_license | #include <cstdio>
#include <algorithm>
using namespace std;
#define MAX 10000
int wine[MAX + 1] = {0, };
int dp[MAX + 1] = {0, };
void f(int n){
int x = dp[n - 2] + wine[n];
int y = dp[n - 3] + wine[n - 1] + wine[n];
int z = dp[n - 1];
dp[n] = max(x, max(y, z));
}
int main(){
int n;
scanf("%d", &n);
for(int i = 0; i < n; i++)
scanf("%d", &wine[i + 1]);
if(n >= 1)
dp[1] = wine[1];
if(n >= 2)
dp[2] = wine[1] + wine[2];
if(n >= 3)
dp[3] = max(wine[1] + wine[2], max(wine[1] + wine[3], wine[2] + wine[3]));
if(n >= 4){
for(int i = 4; i <= n; i++)
f(i);
}
printf("%d", dp[n]);
} | true |
e62c0a2108ddb8f8486b70d673bf6c79c203b109 | C++ | ammarhusain/lost-robot | /particle_filter/src/MapData.h | UTF-8 | 2,441 | 2.96875 | 3 | [] | no_license | /** ----------------------------------------------------------------------
* Copyright 2014 < Ammar Husain (Carnegie Mellon University) >
*
* @file MapData.h
* @author Ammar Husain <ahusain@nrec.ri.cmu.edu>
* @date Tue Nov 11 15:39:00 2014
*
* @brief Declarations for MapData
* This class handles all manipulations and checks required by ParticleFilter
* on a map
---------------------------------------------------------------------- */
#include <opencv2/opencv.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <cstdio>
#include <iostream>
#include <cmath>
class MapData{
public:
/// ------------------------------------------------------- ///
/// Member Functions
/// constructor: no args
MapData();
/// constructor
MapData(char* mapName);
/// initializes the object with map specified
void initialize(char* mapName);
/// returns width in centimeters
int getMapWidth_cm();
/// return height in centimeters
int getMapHeight_cm();
/// checks if the cell is free to place robot
bool checkMap(double x, double y);
/// initialize a new image for visualization
void initImg();
/// draws particle to image
void addPoint(double x, double y);
/// casts a ray in space to compute expected range to hit
int rayCast(double lx,double ly,double ltheta);
/// turns the write flag on and sets the directory to write to
void setWrite(std::string output);
/// visualize map with particles to screen
void showMap();
private:
/// initializes a template image colored according to P(occupied)
int initThreshMap();
/// read the map and load into memory: provided by CMU 16-831 course staff
int popMap(char *mapName);
/// save the current visual map to disk
void saveMap();
/// ------------------------------------------------------- ///
/// Memeber Variables
/// map containing probability of free space at each grid
cv::Mat m_prob;
/// image to store initial colored prob threshold
cv::Mat m_threshMap;
/// image of map with particles floating inside
cv::Mat m_img;
/// resolution of the map
int m_resolution;
double m_offset_x;
double m_offset_y;
int m_size_x;
int m_size_y;
int m_min_x;
int m_max_x;
int m_min_y;
int m_max_y;
bool writeFlag;
std::string writeDirectory;
/// ------------------------------------------------------- ///
};
| true |
13e02a821147536a278535aecb5c3292d388f942 | C++ | senior-sigan/omsu_cpp_course | /code/_sem_2/fantasy_asm/mem.h | UTF-8 | 776 | 2.84375 | 3 | [
"MIT"
] | permissive | #pragma once
#include <map>
#include <stack>
#include <vector>
#include "ops.h"
#include "reg.h"
// НЕ редактируйте этот файл.
namespace fasm {
class Memory {
std::map<Register, int> registers{{r0, 0}, {r1, 0}, {r2, 0}, {line, 0}, {cmp, 0}};
std::vector<IOperation*> instructions{};
std::stack<int> stack{};
public:
IOperation* GetCurrentOp()
const; // helper function to get current operation based on the value in `line` register
int GetOpsCount() const; // helper function to get count of all instructions
void PushOp(IOperation* op);
// To work with registers
int GetReg(Register reg) const;
void SetReg(Register reg, int value);
// To work with stack
void Push(int value);
int Pop();
};
} // namespace fasm
| true |
b8f2ad5ae5520ac7f5b338532b2c40f50a777563 | C++ | cafel176/cafelRenderer | /cafelRenderer/includes/cafel/basic/matrix.hpp | UTF-8 | 4,804 | 2.90625 | 3 | [] | no_license | #pragma once
#if !defined(_CAFEL_MATRIX_HPP_)
#define _CAFEL_MATRIX_HPP_
#include <cafel/basic/vector.hpp>
#define _USE_MATH_DEFINES
#include <math.h>
#include <string>
#include <memory>
CAFEL_NAMESPACE_BEGIN
template<typename T, int row, int col>
class Matrix : public Basic
{
public:
Matrix(T t)
{
data = std::shared_ptr<T*[row]>(new T*[row]);
for (int i = 0; i < row; i++)
{
data[i] = new T[col];
for (int j = 0; j < col; j++)
data[i][j] = t;
}
}
Matrix()
{
data = std::shared_ptr<T*[row]>(new T*[row]);
for (int i = 0; i < row; i++)
{
data[i] = new T[col];
for (int j = 0; j < col; j++)
if(i==j)
data[i][j] = 1;
else
data[i][j] = 0;
}
}
Matrix(const Matrix& other) :data(other.data){}
Matrix& operator=(const Matrix& other)
{
data = other.data;
return *this;
}
Vector<T,row> operator*(const Vector<T, col> &v) const
{
Vector<T, col> re;
for (int i = 0; i < row; i++)
for (int j = 0; j < col; j++)
re[i] += data[i][j] * v[j];
return re;
}
template<int col2>
Matrix<T,row,col2> operator*(const Matrix<T,col, col2> &m2) const
{
Matrix<T, row, col2> Result(0);
for (int i = 0; i < row; i++)
for (int j = 0; j < col2; j++)
for (int k = 0; k < col; k++)
Result[i][j] += data[i][k] * m2[k][j];
return Result;
}
T*& operator[](int i)
{
if (i >= 0 && i < row)
return data[i];
else
return data[0];
}
T* operator[](int i) const
{
if (i >= 0 && i < row)
return data[i];
else
return nullptr;
}
operator std::string() const
{
std::string str = "(";
for (int i = 0; i < row; i++)
{
if (i > 0)
str += ",";
str += std::to_string(i) + ":(";
for (int j = 0; j < col; j++)
{
if (j > 0)
str += ",";
str += data[i][j];
}
str += ")";
}
str += ")";
return str;
}
Matrix<T,4,4> static lookAt(const Vector<T,3>& eye, const Vector<T, 3>& center, const Vector<T, 3>& up)
{
Vector<T, 3> f(center - eye);
f.norm();
Vector<T, 3> s(f % up);
s.norm();
Vector<T, 3> u(s % f);
Matrix<T, 4, 4> Result;
Result[0][0] = s.x;
Result[1][0] = s.y;
Result[2][0] = s.z;
Result[0][1] = u.x;
Result[1][1] = u.y;
Result[2][1] = u.z;
Result[0][2] = -f.x;
Result[1][2] = -f.y;
Result[2][2] = -f.z;
Result[3][0] = s.dot(eye)*-1;
Result[3][1] = u.dot(eye)*-1;
Result[3][2] = f.dot(eye);
return Result;
}
Matrix<T, 4, 4> static perspective(T fovy, T aspect, T zNear, T zFar)
{
const T tanHalfFovy = tan(fovy / 2.0);
Matrix<T, 4, 4> Result(0);
Result[0][0] = 1.0 / (aspect * tanHalfFovy);
Result[1][1] = 1.0 / (tanHalfFovy);
Result[2][2] = -(zFar + zNear) / (zFar - zNear);
Result[2][3] = -1.0;
Result[3][2] = -(2.0 * zFar * zNear) / (zFar - zNear);
return Result;
}
Matrix<T, 4, 4> static translate(const Matrix<T, 4, 4>& m, const Vector<T, 3>& v)
{
Matrix<T, 4, 4> Result(m);
Vector<T, 3> dv0(m[0]);
Vector<T, 3> dv1(m[1]);
Vector<T, 3> dv2(m[2]);
Vector<T, 3> dv3(m[3]);
Vector<T, 3> re = dv0 * v[0] + dv1 * v[1] + dv2 * v[2] + dv3;
for(int i=0;i<4;i++)
Result[3][i] = re[i];
return Result;
}
Matrix<T, 4, 4> static scale(const Matrix<T, 4, 4>& m, const Vector<T, 3>& v)
{
Matrix<T, 4, 4> Result(m);
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
Result[i][j] *= v[j];
return Result;
}
Matrix<T, 4, 4> static rotate(const Matrix<T, 4, 4>& m,T angel, const Vector<T, 3>& v)
{
T const a = angle;
T const c = cos(a);
T const s = sin(a);
Vector<T, 3> qw = v;
qw.norm();
Vector<T, 3> axis(qw);
Vector<T, 3> temp(axis * (T(1) - c));
Matrix<T, 4, 4> Rotate(0);
Rotate[0][0] = c + temp[0] * axis[0];
Rotate[0][1] = 0 + temp[0] * axis[1] + s * axis[2];
Rotate[0][2] = 0 + temp[0] * axis[2] - s * axis[1];
Rotate[1][0] = 0 + temp[1] * axis[0] - s * axis[2];
Rotate[1][1] = c + temp[1] * axis[1];
Rotate[1][2] = 0 + temp[1] * axis[2] + s * axis[0];
Rotate[2][0] = 0 + temp[2] * axis[0] + s * axis[1];
Rotate[2][1] = 0 + temp[2] * axis[1] - s * axis[0];
Rotate[2][2] = c + temp[2] * axis[2];
Matrix<T, 4, 4> Result(0);
Result[0] = m[0] * Rotate[0][0] + m[1] * Rotate[0][1] + m[2] * Rotate[0][2];
Result[1] = m[0] * Rotate[1][0] + m[1] * Rotate[1][1] + m[2] * Rotate[1][2];
Result[2] = m[0] * Rotate[2][0] + m[1] * Rotate[2][1] + m[2] * Rotate[2][2];
Result[3] = m[3];
return Result;
}
private:
std::shared_ptr<T*[row]> data;
};
typedef Matrix<double, 2, 2> dMatrix2;
typedef Matrix<float, 2, 2> fMatrix2;
typedef Matrix<int, 2, 2> iMatrix2;
typedef Matrix<double,3,3> dMatrix;
typedef Matrix<float, 3, 3> fMatrix;
typedef Matrix<int,3,3> iMatrix;
typedef Matrix<double, 4, 4> dMatrix4;
typedef Matrix<float, 4, 4> fMatrix4;
typedef Matrix<int, 4, 4> iMatrix4;
CAFEL_NAMESPACE_END
#endif | true |
c047320c2be18119600dac2d3a33694666d7790a | C++ | BDavidd/CppTraining | /CppPrimer/Chapter_3/3.1/3.1/2.41/1.23.cpp | UTF-8 | 1,117 | 3.421875 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <map>
using std::cout;
using std::cin;
using std::endl;
using std::string;
using std::map;
struct SalesData
{
string bookNo;
unsigned int unitsSold = 0;
double revenue = 0.0;
};
int main()
{
SalesData sale;
double price = 0.0;
map<string, int> isbnMap;
cout << "Enter a transaction: " << endl;
cin >> sale.bookNo >> sale.unitsSold >> price;
sale.revenue = sale.unitsSold * price;
isbnMap[sale.bookNo] = 1;
cout << "Enter the next transaction: " << endl;
while (cin >> sale.bookNo >> sale.unitsSold >> price)
{
if (isbnMap.find(sale.bookNo) != isbnMap.end())
{
++isbnMap[sale.bookNo];
}
else
{
isbnMap[sale.bookNo] = 1;
}
cout << "Enter the next transaction: " << endl;
}
cout << "The number of transactions for each ISBN: " << endl;
for (const auto& isbn : isbnMap)
{
cout << isbn.first << " : " << isbn.second << endl;
}
return 0;
}
| true |
c287d73c209c5995dd1d4e9f311549dcde85107b | C++ | georgerapeanu/c-sources | /apropiate1/main.cpp | UTF-8 | 865 | 2.546875 | 3 | [] | no_license | #include <fstream>
using namespace std;
ifstream f("apropiate1.in");
ofstream g("apropiate1.out");
long long x,y,a,i,j,n,distx,disty;
short c;
int ifprim(long long nr)
{
long long l;
for(l=2;l<=nr/2;l++)
if(nr%l==0)
return 0;
return 1;
}
int main()
{
f>>n>>c;
for(i=1;i<=n;i++)
{
f>>a;
if(ifprim(a)==1)
g<<a<<" ";
else
{
x=y=a;
while(ifprim(x)==0)
x--;
while(ifprim(y)==0)
y++;
distx=a-x;
disty=y-a;
if(distx>disty)
g<<y<<" ";
else if(distx<disty)
g<<x<<" ";
else
{
if(c==1)
g<<x<<" ";
else
g<<y<<" ";
}
}
}
f.close();g.close();
return 0;
}
| true |
a3d9d08d06b582ee803d933417b1e51a224cf971 | C++ | tbgeorge/putty_engine | /Renderer/TextRenderer.cpp | UTF-8 | 1,237 | 2.5625 | 3 | [] | no_license | //=================================================================================
// TextRenderer.cpp
// Author: Tyler George
// Date : June 10, 2015
//=================================================================================
#include <fstream>
#include <iostream>
#include "Engine/Renderer/TextRenderer.hpp"
///---------------------------------------------------------------------------------
///
///---------------------------------------------------------------------------------
TextRenderer::TextRenderer( const std::string& fontInfoFilePath, const std::string& fontFile, OpenGLRenderer* renderer )
: m_renderer( renderer )
, m_font( NULL )
{
if (!m_font)
m_font = Texture::CreateOrGetTexture( fontFile );
LoadFontInfo( fontInfoFilePath );
}
///---------------------------------------------------------------------------------
///
///---------------------------------------------------------------------------------
void TextRenderer::LoadFontInfo( const std::string& fontInfoFilePath )
{
std::ifstream fontInfoFile( fontInfoFilePath );
std::string line = "";
while (fontInfoFile.good())
{
getline( fontInfoFile, line );
ConsolePrintf( "%s", line.c_str() );
}
} | true |
f621645189fb635240b00040cbe307dcef53e2a1 | C++ | torehc/ProjectEuler | /274.cc | UTF-8 | 903 | 2.953125 | 3 | [] | no_license | #include <iostream>
#include <map>
#include <stdio.h>
#define SIEVE_RANGE (10000000)
#define PRIME_COUNT (664579)
bool sieve_visited[SIEVE_RANGE] = {};
std::map<int, int> aux_map;
void InitAuxMap()
{
aux_map[1] = 9;
aux_map[3] = 3;
aux_map[7] = 7;
aux_map[9] = 1;
}
long long GetDivisibilityMultiplier(long long p)
{
if ((p % 2 == 0) || (p % 5 == 0))
{
return 0LL;
}
return (p * aux_map[p % 10] + 1) / 10;
}
void Solve()
{
long long sum = 0;
for (long long i = 2; i < SIEVE_RANGE; i++)
{
if (!sieve_visited[i])
{
sum += GetDivisibilityMultiplier(i);
for (long long j = i + i; j < SIEVE_RANGE; j += i)
{
sieve_visited[j] = true;
}
}
}
std::cout << sum << std::endl;
}
int main(int argc, char* argv[])
{
InitAuxMap();
Solve();
return 0;
}
| true |
5062f0dd4c10e9cf842133417862e0e84b3f8428 | C++ | 7182514362/leetcode | /026-050/048_旋转图像_M/main.cpp | UTF-8 | 1,278 | 3.546875 | 4 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
void rotate(vector<vector<int>> &matrix) {
int size = matrix.size();
if (size <= 1) {
return;
}
int n = (size + 1) / 2;
for (int i = 0; i < n; ++i) {
for (int j = i; j < size - i - 1; ++j) {
int t = matrix[i][j];
matrix[i][j] = matrix[size - j - 1][i];
matrix[size - j - 1][i] = matrix[size - i - 1][size - j - 1];
matrix[size - i - 1][size - j - 1] = matrix[j][size - i - 1];
matrix[j][size - i - 1] = t;
}
}
}
};
void printMatrix(vector<vector<int>> &mtx) {
cout << "[" << endl;
for (auto &&i : mtx) {
for (auto &&j : i) {
if (j >= 0)
cout << " " << j;
else
cout << " " << j;
}
cout << endl;
}
cout << "]" << endl;
}
int main() {
vector<vector<int>> matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
vector<vector<int>> matrix2 = {
{5, 1, 9, 11}, {2, 4, 8, 10}, {13, 3, 6, 7}, {15, 14, 12, 16}};
printMatrix(matrix2);
Solution sol;
sol.rotate(matrix2);
printMatrix(matrix2);
return 0;
} | true |
ed4d993a3c2961b197864fe7d7727d819d1fbe01 | C++ | the-gooniest/lateral-controller | /src/CarConstants.cpp | UTF-8 | 1,472 | 2.921875 | 3 | [] | no_license | #include <CarConstants.h>
// Total mass of the the 2017 Chevy Bolt in kg.
// TODO: change mass with added weight from sensors, people, etc
const float CarConstants::mass = 1605.0f;
// Yaw inertia of the 2017 Chevy Bolt in kg*m^2.
// This value is not used for now.
const float CarConstants::yaw_inertia = 2045.0f;
// Length from CG (Center of Gravity) to the front wheels of the 2017 Chevy Bolt in m.
// TODO: check if this is correct.
const float CarConstants::front_length = 1.135f;
// Length from CG to the rear wheels of the 2017 Chevy Bolt in m.
// TODO: check if this is correct.
const float CarConstants::rear_length = 1.465f;
// Cornering stiffness of the front wheels of a 1949 Buick in N/rad.
// TODO: Testing is required to find actual value
const float CarConstants::front_stiffness = 77850.0f;
// Cornering stiffness of the rear wheels of a 1949 Buick in N/rad.
// TODO: Testing is required to find actual value
const float CarConstants::rear_stiffness = 76510.0f;
// Gravity in m/s
const float CarConstants::gravity = 9.81f;
// Front weight of the vehicle in N.
const float CarConstants::front_weight = (mass*rear_length*gravity)/(front_length+rear_length);
// Rear weight of the vehicle in N.
const float CarConstants::rear_weight = (mass*front_length*gravity)/(front_length+rear_length);
// Steering Gradient of the vehicle in radians.
const float CarConstants::steering_gradient = (front_weight/front_stiffness) - (rear_weight/rear_stiffness);
| true |
eb64d5444136e0f35e2d6c18643d69404e200e7a | C++ | jessicahe21/Software | /src/thunderbots/software/ai/hl/stp/evaluation/robot.cpp | UTF-8 | 1,404 | 2.78125 | 3 | [
"MIT"
] | permissive | #include "ai/hl/stp/evaluation/robot.h"
#include <shared/constants.h>
bool Evaluation::robotOrientationWithinAngleThresholdOfTarget(const Point position,
const Angle orientation,
const Point target,
Angle threshold)
{
// Calculate the target orientation, then calculate the difference between facing
// orientation and target orientation. The difference in angle will be in the range of
// [0, pi]. Return true if the difference is smaller than threshold, false otherwise
Angle target_orientation = (target - position).orientation();
Angle diff_orientation = orientation.minDiff(target_orientation);
return diff_orientation < threshold;
}
bool Evaluation::robotHasPossession(const Ball ball, const Robot robot)
{
// The actual vector to the ball from the center of the robot
Vector robot_center_to_ball = ball.position() - robot.position();
// Calculate the ideal vector from the robot to the ball for the robot to have
// possession.
Angle orientation = robot.orientation();
Vector expected_point =
Point::createFromAngle(orientation).norm(DIST_TO_FRONT_OF_ROBOT_METERS);
return robot_center_to_ball.isClose(expected_point, DRIBBLER_WIDTH / 2);
};
| true |
fd79d486a928814136074f4cf2055b072dbfd6c1 | C++ | awtrix/AWTRIX2.0-Controller | /lib/LDR/LightDependentResistor.cpp | UTF-8 | 2,412 | 2.578125 | 3 | [
"LicenseRef-scancode-proprietary-license",
"CC-BY-NC-SA-4.0",
"LicenseRef-scancode-other-copyleft"
] | permissive | /*
* \brief et light intensity from Light dependent Resistor (implementation)
*
* \author Quentin Comte-Gaz <quentin@comte-gaz.com>
* \date 4 July 2016
* \license MIT License (contact me if too restrictive)
* \copyright Copyright (c) 2016 Quentin Comte-Gaz
* \version 1.0
*/
#include "LightDependentResistor.h"
LightDependentResistor::LightDependentResistor(int pin, unsigned long other_resistor, ePhotoCellKind kind) :
_photocell_on_ground (true),
_pin (pin),
_other_resistor (other_resistor)
{
switch (kind) {
case GL5516:
_mult_value = 29634400;
_pow_value = 1.6689;
break;
case GL5537_1:
_mult_value = 32435800;
_pow_value = 1.4899;
break;
case GL5537_2:
_mult_value = 2801820;
_pow_value = 1.1772;
break;
case GL5539:
_mult_value = 208510000;
_pow_value = 1.4850;
break;
case GL5549:
_mult_value = 44682100;
_pow_value = 1.2750;
break;
case GL5528:
default:
_mult_value = 32017200;
_pow_value = 1.5832;
}
}
LightDependentResistor::LightDependentResistor(int pin, unsigned long other_resistor, float mult_value, float pow_value) :
_photocell_on_ground (true),
_pin (pin),
_other_resistor (other_resistor),
_mult_value (mult_value),
_pow_value (pow_value)
{
}
void LightDependentResistor::updatePhotocellParameters(float mult_value, float pow_value)
{
_mult_value = mult_value;
_pow_value = pow_value;
}
void LightDependentResistor::updateResistor(unsigned long other_resistor)
{
_other_resistor = other_resistor;
}
float LightDependentResistor::luxToFootCandles(float intensity_in_lux)
{
return 10.764*intensity_in_lux;
}
float LightDependentResistor::footCandlesToLux(float intensity_in_footcandles)
{
return intensity_in_footcandles/10.764;
}
void LightDependentResistor::setPhotocellPositionOnGround(bool on_ground)
{
_photocell_on_ground = on_ground;
}
float LightDependentResistor::getCurrentLux() const
{
int photocell_value = analogRead(_pin);
unsigned long photocell_resistor;
float ratio = ((float)1024/(float)photocell_value) - 1;
if (_photocell_on_ground) {
photocell_resistor = _other_resistor / ratio;
} else {
photocell_resistor = _other_resistor * ratio;
}
return _mult_value / (float)pow(photocell_resistor, _pow_value);
}
float LightDependentResistor::getCurrentFootCandles() const
{
return luxToFootCandles(getCurrentLux());
}
| true |
7b1e0cbb2274e92ba22627a90154ca1fe2a45378 | C++ | chronos38/exa | /exa/source/buffered_stream.cpp | UTF-8 | 6,794 | 2.96875 | 3 | [
"MIT"
] | permissive | #include <exa/buffered_stream.hpp>
#include <algorithm>
namespace exa
{
buffered_stream::buffered_stream(const std::shared_ptr<stream>& s, std::streamsize buffer_size)
: stream_(s), buffer_size_(buffer_size)
{
if (s == nullptr)
{
throw std::invalid_argument("Given stream for buffered stream is nullptr.");
}
if (buffer_size <= 0)
{
throw std::out_of_range("Buffer size for buffered stream needs to greater than 0.");
}
if (!s->can_read() && !s->can_write())
{
throw std::invalid_argument("Stream needs to be both read and writable.");
}
buffer_.resize(static_cast<size_t>(buffer_size_));
}
bool buffered_stream::can_read() const
{
return stream_->can_read();
}
bool buffered_stream::can_seek() const
{
return stream_->can_seek();
}
bool buffered_stream::can_write() const
{
return stream_->can_write();
}
std::streamoff buffered_stream::size() const
{
return stream_->size();
}
void buffered_stream::size(std::streamsize value)
{
if (value < 0)
{
throw std::out_of_range("Length of buffered stream can't be negative.");
}
flush();
stream_->size(value);
}
std::streamoff buffered_stream::position() const
{
return stream_->position() + (read_pos_ - read_size_ + write_pos_);
}
void buffered_stream::position(std::streamoff value)
{
if (value < 0)
{
throw std::out_of_range("Can't set a negative stream position.");
}
if (write_pos_ > 0)
{
flush_write();
}
read_pos_ = 0;
read_size_ = 0;
stream_->seek(value, seek_origin::begin);
}
void buffered_stream::flush()
{
if (write_pos_ > 0)
{
flush_write();
}
else if (read_pos_ < read_size_)
{
if (stream_->can_seek())
{
flush_read();
}
if (stream_->can_write())
{
stream_->flush();
}
}
else
{
if (stream_->can_write())
{
stream_->flush();
}
write_pos_ = 0;
read_pos_ = 0;
}
}
std::streamsize buffered_stream::read(gsl::span<uint8_t> b)
{
if (b.data() == nullptr)
{
throw std::invalid_argument("Read buffer is a nullptr.");
}
auto n = read_buffered(b);
if (n == static_cast<std::streamsize>(b.size()))
{
return n;
}
auto already_read = n;
if (n > 0)
{
b = gsl::span<uint8_t>(b.data() + n, b.size() - static_cast<ptrdiff_t>(n));
}
read_pos_ = 0;
read_size_ = 0;
if (write_pos_ > 0)
{
flush_write();
}
if (b.size() >= buffer_size_)
{
return stream_->read(b) + already_read;
}
read_size_ = stream_->read(buffer_);
n = read_buffered(b);
return already_read + n;
}
std::streamoff buffered_stream::seek(std::streamoff offset, seek_origin origin)
{
if (write_pos_ > 0)
{
flush_write();
return stream_->seek(offset, origin);
}
if (read_size_ - read_pos_ > 0 && origin == seek_origin::current)
{
offset -= (read_size_ - read_pos_);
}
auto old_pos = position();
auto new_pos = stream_->seek(offset, origin);
read_pos_ = new_pos - (old_pos - read_pos_);
if (read_pos_ >= 0 && read_pos_ < read_size_)
{
stream_->seek(read_size_ - read_pos_, seek_origin::current);
}
else
{
read_pos_ = 0;
read_size_ = 0;
}
return new_pos;
}
void buffered_stream::write(gsl::span<const uint8_t> b)
{
if (b.data() == nullptr)
{
throw std::invalid_argument("Read buffer is a nullptr.");
}
if (write_pos_ == 0)
{
clear_read_buffer();
}
auto total_bytes = write_pos_ + b.size();
if (total_bytes < buffer_size_)
{
write_buffered(b);
if (write_pos_ >= buffer_size_)
{
stream_->write(buffer_);
write_pos_ = 0;
write_buffered(b);
}
}
else
{
if (write_pos_ > 0 && write_pos_ < buffer_size_)
{
stream_->write(gsl::span<uint8_t>(buffer_.data(), static_cast<ptrdiff_t>(write_pos_)));
write_pos_ = 0;
}
stream_->write(b);
}
}
std::shared_ptr<stream> buffered_stream::underlying_stream() const
{
return stream_;
}
std::streamsize buffered_stream::buffer_size() const
{
return buffer_size_;
}
void buffered_stream::flush_write()
{
stream_->write(gsl::span<uint8_t>(buffer_.data(), static_cast<ptrdiff_t>(write_pos_)));
stream_->flush();
write_pos_ = 0;
}
void buffered_stream::flush_read()
{
if (read_pos_ - read_size_ != 0)
{
stream_->seek(read_pos_ - read_size_, seek_origin::current);
}
read_size_ = 0;
read_pos_ = 0;
}
std::streamsize buffered_stream::read_buffered(gsl::span<uint8_t> b)
{
auto n = read_size_ - read_pos_;
if (n <= 0)
{
return 0;
}
if (n > b.size())
{
n = b.size();
}
std::copy(std::next(std::begin(buffer_), static_cast<ptrdiff_t>(read_pos_)),
std::next(std::begin(buffer_), static_cast<ptrdiff_t>(read_pos_ + n)), std::begin(b));
read_pos_ += n;
return n;
}
void buffered_stream::write_buffered(gsl::span<const uint8_t>& b)
{
auto n = std::min<std::streamsize>(buffer_size_ - write_pos_, b.size());
if (n > 0)
{
std::copy(std::begin(b), std::next(std::begin(b), static_cast<ptrdiff_t>(n)),
std::next(std::begin(buffer_), static_cast<ptrdiff_t>(write_pos_)));
write_pos_ += n;
b = gsl::span<const uint8_t>(b.data() + n, b.size() - static_cast<ptrdiff_t>(n));
}
}
void buffered_stream::clear_read_buffer()
{
if (read_pos_ == read_size_)
{
read_pos_ = 0;
read_size_ = 0;
}
else
{
flush_read();
}
}
}
| true |
4477bc916ce9b354638838d2410d96a2468da1a9 | C++ | rpuntaie/c-examples | /cpp/memory_destroy_at.cpp | UTF-8 | 662 | 3.40625 | 3 | [
"MIT"
] | permissive | /*
g++ --std=c++20 -pthread -o ../_build/cpp/memory_destroy_at.exe ./cpp/memory_destroy_at.cpp && (cd ../_build/cpp/;./memory_destroy_at.exe)
https://en.cppreference.com/w/cpp/memory/destroy_at
*/
#include <memory>
#include <new>
#include <iostream>
struct Tracer {
int value;
~Tracer() { std::cout << value << " destructed\n"; }
};
int main()
{
alignas(Tracer) unsigned char buffer[sizeof(Tracer) * 8];
for (int i = 0; i < 8; ++i)
new(buffer + sizeof(Tracer) * i) Tracer{i}; //manually construct objects
auto ptr = std::launder(reinterpret_cast<Tracer*>(buffer));
for (int i = 0; i < 8; ++i)
std::destroy_at(ptr + i);
}
| true |
f2a62179ea650b8f10a1fea9dd9d2e0e5679010b | C++ | Bambia/Algorithm | /2.Algorithm_study/2019.08.05/11965_Bessie_s_Dream.cpp | UTF-8 | 3,127 | 3.328125 | 3 | [] | no_license | #include <iostream>
#include <queue>
using namespace std;
struct POS{
int x,y;
int pDir;
int count,smell; // smell -> 1 orange, 0 no smell
};
const int MX = 1001;
int N,M,ans;
int dx[4] = {0,1,0,-1};
int dy[4] = {1,0,-1,0};
int map[MX][MX],visited[MX][MX];
// statement
/*
0 can't go through
1 go to any direction
2 go to any direction and get orange smell
3 if you have orange small, go through
4 slide to that direction until land on another tile. number 4 tiles will remove any smell.
*/
int passProcessing(POS pos){
queue <POS> q;
q.push(pos);
//visited[pos.y][pos.x] =1;
//0 exception precess
// 1 find next dircetion
//2 change smell to orenge and find
//3 check smell and decide whather should go or not.
//4 The most difficult one ...3 memorize before dirction and color
while(!q.empty()){
POS cur = q.front();
q.pop();
if(cur.y== (M-1) && cur.x == (N-1)) {
ans = cur.count;
//cout <<"find ans \n";
queue<POS> temp;
q.swap(temp);
break;
}
if(map[cur.y][cur.x] == 4){
//cout <<"find purple tile "<<cur.y<<' '<<cur.x<<' '<<"dir: "<<cur.pDir<<'\n';
POS next;
next.x = cur.x + dx[cur.pDir];
next.y = cur.y + dy[cur.pDir];
next.pDir = cur.pDir;
next.count = cur.count +1;
next.smell = 0;
if(next.x < 0 || next.y < 0 || next.x >= N || next.y >= M ) continue; // out of map
q.push(next);
}
else if(map[cur.y][cur.x] == 0) continue;
else {
for(int i =0; i<4; i++){
POS next;
next.x = cur.x + dx[i];
next.y = cur.y + dy[i];
next.pDir = i;
next.count = cur.count +1;
next.smell = cur.smell;
//cout <<"finding...."<<next.y<<' '<<next.x<<'\n';
if(next.x < 0 || next.y < 0 || next.x >= N || next.y >= M ) continue; // out of map
if(map[next.y][next.x] == 0) continue;
else if(map[next.y][next.x] == 2) next.smell = 1;
else if(map[next.y][next.x] == 3){
if(cur.smell != 1) {
//cout << "smell is not orange \n";
continue;
}
}
if(!visited[next.y][next.x]) {
//cout << "put other land to queue "<<next.y<<' '<<next.x<<'\n';
if(map[next.y][next.x]!= 4) visited[next.y][next.x] = 1;
q.push(next);
}
}
}
}
}
int main(){
POS start;
cin >> N >> M;
for(int i =0; i<M; i++){
for(int j=0; j<N; j++){
cin >> map[i][j];
}
}
start.x = 0; start.y = 0;
start.pDir = 0;
start.smell = 0; start.count = 0;
passProcessing(start);
if(ans == 0) ans = -1;
cout << ans <<'\n';
return 0;
}
4 4
1 0 1 4 1
1 1 4 1 1
0 0 0 | true |
00a0f662e12295795d20043aa3bc00713a5befa5 | C++ | knightzf/review | /leetcode/3sum/learnedsolution.cpp | UTF-8 | 1,407 | 3.453125 | 3 | [] | no_license | #include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
class Solution
{
public:
vector<vector<int>> threeSum(vector<int>& nums)
{
std::vector<std::vector<int>> resultVec;
if(nums.empty())
{
return resultVec;
}
std::sort(nums.begin(), nums.end());
for(size_t i = 0; i < nums.size() - 2 && nums[i] <= 0; ++i)
{
if(i == 0 || (nums[i] != nums[i-1]))
{
int first = nums[i];
size_t begin = i + 1;
size_t end = nums.size() - 1;
int lastSecond = 0;
bool findMatch = false;
while(begin < end)
{
int sum = first + nums[begin] + nums[end];
if(sum < 0)
{
++begin;
}
else if(sum > 0)
{
--end;
}
else
{
if(!findMatch || nums[begin] != lastSecond)
{
resultVec.push_back(std::vector<int>{first, nums[begin], nums[end]});
lastSecond = nums[begin];
findMatch = true;
}
++begin;
--end;
}
}
}
}
return resultVec;
}
};
int main()
{
Solution sol;
std::vector<int> data{-2, 0, 0, 2, 2};
sol.threeSum(data);
return 0;
} | true |
9f74db35cf767734852e33650635882145dd7827 | C++ | lacretelle/42_cursus | /CPP/cpp_pool/day04/ex00/Victim.hpp | UTF-8 | 458 | 3.015625 | 3 | [] | no_license | #ifndef VICTIM_HPP
# define VICTIM_HPP
# include <string>
# include <iostream>
class Victim
{
public:
Victim(std::string name);
Victim(Victim const &);
Victim & operator=(Victim const &);
~Victim();
std::string getName() const;
void virtual getPolymorphed() const;
protected:
std::string _name;
Victim();
};
std::ostream & operator<<(std::ostream & o, Victim const &);
#endif | true |
744a13a5d998f3012caeaedb1b9612f30ebf4e67 | C++ | vasharm2/Homework | /PS2/zchen142/problem2.cpp | UTF-8 | 305 | 2.953125 | 3 | [] | no_license |
Created by Daniel Chen on 9/22/15.
Copyright (c) 2015 Daniel. All rights reserved.
#include <iostream>
#include <cmath>
using namespace std;
int main() {
for (int i = 0; i < 3; i++) {
for (int j = 3; j > 0; j--) {
cout << pow(i, j) << endl;
}
}
return 0;
} | true |
12e298e9921c782caddbe49af9f94a1b68cf2d58 | C++ | jun094/Study-cpp | /Week3_Day2/Week2__/ex05_class2_sansungja2.cpp | UHC | 1,498 | 3.921875 | 4 | [] | no_license | //#include<iostream>
//#include<cstdio>
//
//using namespace std;
//
//// class ߰ϱ_
//// class ߰ϱ_ public ۿ
//
//int g_numStudent = 14000000; //
//
//class Student
//{
//
// int num; // public ۿ -> й ߺx, ȭx̴.
//
//public:
// char name[10];
// float grade;
//
// Student()
// {
// //ڴ
// // 1.ݵ ҷ
// // 2. ͺ ռ
// // 3. ѹ ҷ !
//
// //num = 1400000; // ߺ x , ȭ x
// num = g_numStudent++; // й = ο
//
// strcpy(name,""); // ߺo , ȭ x
// grade = 0.0f; //ߺ o, ȭ o
// }
//
// void print()
// {
// cout<<"̸:"<<name<<endl;
// cout<<"й:"<<num<<endl;
// cout<<""<<grade<<endl;
// }
//};
//
//int main()
//{
// Student a;
//
// // aл
// //a.num = 14011208;
// // й public ۿ ڵ ǵ.
// strcpy(a.name,"ö"); // strcpy(ڿ, "")
// a.grade = 3.5;
//
// // bл x
// Student b; // bл ƹ͵ Է x̹Ƿ ̴.
//
//
// a.print(); // print(a) ƴϴ
// b.print(); // print(b) ƴϴ
//
// Student c[10]; // Ŭ 迭 , ̷ Ǹ л ڵ +10ȴ.
//
// cout<<"л:"<<g_numStudent<<endl;
//
//
// return 0;
//} | true |
49a2c13080888e3938e04582947d470074e428ad | C++ | rayray2002/cpl | /preview/function_preview/p44.cpp | UTF-8 | 338 | 3.1875 | 3 | [] | no_license | #include <iostream>
using namespace std;
void commute_time (double, double=20, int=8);
int main( )
{
commute_time(40);
commute_time(30, 20);
commute_time(35, 30, 8);
}
void commute_time(double velocity, double distance, int num_lights)
{
cout<<"The commute time is " <<(distance/velocity + num_lights*0.01)
<<" hours."<<endl;
} | true |
964d9a334146b037fd5cdee4dd140e8196242d91 | C++ | Leslie-Zhou/Group_Project_Mirrored | /Semester 1/Code/vectorClass.cpp | UTF-8 | 10,987 | 4.03125 | 4 | [] | no_license | #include <iostream>
#include "vectorClass.h"
#include <math.h>
vectorClass::vectorClass(){
}
vectorClass::~vectorClass(){
}
vectorClass::vectorClass(int id, float x, float y, float z) // Constructor
{
// Store values in respective indexes
this->x = x;
this->y = y;
this->z = z;
this->id = id;
}
void vectorClass::setVector(int id, float x, float y, float z)
{
this->x = x;
this->y = y;
this->z = z;
this->id = id;
}
void vectorClass::getVector(int id, float *x, float *y, float *z) // Function to get values of a vector
{
*x = this->x; // Assign stored values of vector to variables
*y = this->y;
*z = this->z;
cout << "v " << id << " "<< *x << ". " << *y << ". " << *z << "."<< endl; // Output vector in required format
}
float vectorClass::getID()
{
id = this->id;
return id;
}
float vectorClass::getX() // Function to get x value of vector
{
x = this->x;
return x;
}
float vectorClass::getY() // Function to get y value of vector
{
y = this->y;
return y;
}
float vectorClass::getZ() // Function to get z value of vector
{
z = this->z;
return z;
}
void vectorClass::setX(float x) // Function to set x value of vector
{
this->x = x;
}
void vectorClass::setY(float y) // Function to set y value of vector
{
this->y = y;
}
void vectorClass::setZ(float z) // Function to set z value of vector
{
this->z = z;
}
vectorClass::vectorClass(vectorClass &v1) // Copy constructor
{
this->x = v1.getX(); //Must copy each coordinate from v1
this->y = v1.getY();
this->z = v1.getZ();
}
vectorClass operator +(vectorClass &v1, vectorClass &v2) // '+' operator overload
{
vectorClass result; // Create vector to store result
result.setX(v1.getX() + v2.getX()); // Set x value of result to total of x values
result.setY(v1.getY() + v2.getY()); // Set y value of result to total of y values
result.setZ(v1.getZ() + v2.getZ()); // Set z value of result to total of z values
return result; // Return result vector
}
vectorClass operator -(vectorClass &v1, vectorClass &v2) // '-' operator overload
{
vectorClass result; // Create vector to store result
result.setX(v1.getX() - v2.getX()); // Set x value of result to total of x values
result.setY(v1.getY() - v2.getY()); // Set y value of result to total of y values
result.setZ(v1.getZ() - v2.getZ()); // Set z value of result to total of z values
return result; // Return result vector
}
vectorClass operator *(vectorClass& v1, float val) // '*' operator overload
{
vectorClass result; // Create vector to store result
result.setX(v1.getX()*val); // Set x value of result to total of x values
result.setY(v1.getY()*val); // Set y value of result to total of y values
result.setZ(v1.getZ()*val); // Set z value of result to total of z values
return result; // Return result vector
}
vectorClass operator /(vectorClass& v1, float val) // '/' operator overload
{
vectorClass result; // Create vector to store result
result.setX(v1.getX()/val); // Set x value of result to x value divided by 'val'
result.setY(v1.getY()/val); // Set y value of result to y value divided by 'val'
result.setZ(v1.getZ()/val); // Set z value of result to z value divided by 'val'
return result; // Return result vector
}
vectorClass vectorClass::scalarProduct(vectorClass v1, vectorClass v2) // Function to perform scalar product calculation
{
vectorClass result; // Create vector to store result
result.setX(v1.getX()*v2.getX()); // Set x value of result to product of x values
result.setY(v1.getY()*v2.getY()); // Set y value of result to product of y values
result.setZ(v1.getZ()*v2.getZ()); // Set z value of result to product of z values
return result; // Return result vector
}
float vectorClass::getScalarProduct() // Function to return scalar product total
{
float result; // Create variable to store result
result = this->x + this->y + this->z; // Calculate total of all coordinates
return result; // Return calculated value
}
vectorClass vectorClass::vectorProduct(vectorClass v1, vectorClass v2) // Function to perform vector product calculation
{
vectorClass result; // Create vector to store result
// Calculate result coordinates using vector product formula
result.setX( (v1.getY()*v2.getZ()) - (v1.getZ()*v2.getY()) );
result.setY( (v1.getZ()*v2.getX()) - (v1.getX()*v2.getZ()) );
result.setZ( (v1.getX()*v2.getY()) - (v1.getY()*v2.getX()) );
return result; // Return result vector
}
// Functions to rotate vectors
vectorClass vectorClass::rotateX(vectorClass v1, double angle)
{
vectorClass result;
matrixClass rX;
rX.xRotationMatrix(angle);
result = rX*v1;
return result;
}
vectorClass vectorClass::rotateY(vectorClass v1, double angle)
{
vectorClass result;
matrixClass rY;
rY.yRotationMatrix(angle);
result = rY*v1;
return result;
}
vectorClass vectorClass::rotateZ(vectorClass v1, double angle)
{
vectorClass result;
matrixClass rZ;
rZ.zRotationMatrix(angle);
result = rZ*v1;
return result;
}
// Operator overload for multiplying matrix by vector
vectorClass operator *(matrixClass& m1, vectorClass& v1)
{
vectorClass result;
result.setX((m1.getM11()*v1.getX())+(m1.getM12()*v1.getY())+(m1.getM13()*v1.getZ()));
result.setY((m1.getM21()*v1.getX())+(m1.getM22()*v1.getY())+(m1.getM23()*v1.getZ()));
result.setZ((m1.getM31()*v1.getX())+(m1.getM32()*v1.getY())+(m1.getM33()*v1.getZ()));
return result;
}
//----Matrix functions-----------------------------------------------------------
// Constructor
matrixClass::matrixClass(){
}
matrixClass::matrixClass(float m11, float m12, float m13, float m21, float m22, float m23, float m31, float m32, float m33)
{
this->m11 = m11;
this->m12 = m12;
this->m13 = m13;
this->m21 = m21;
this->m22 = m22;
this->m23 = m23;
this->m31 = m31;
this->m32 = m32;
this->m33 = m33;
}
// Destructor
matrixClass::~matrixClass(){
}
// Function to output matrix
void matrixClass::getMatrix()
{
cout << m11 << " " << m12 << " " << m13 << endl;
cout << m21 << " " << m22 << " " << m23 << endl;
cout << m31 << " " << m32 << " " << m33 << endl;
}
// Get individual matrix values
float matrixClass::getM11()
{
m11 = this->m11;
return m11;
}
float matrixClass::getM12()
{
m12 = this->m12;
return m12;
}
float matrixClass::getM13()
{
m13 = this->m13;
return m13;
}
float matrixClass::getM21()
{
m21 = this->m21;
return m21;
}
float matrixClass::getM22()
{
m22 = this->m22;
return m22;
}
float matrixClass::getM23()
{
m23 = this->m23;
return m23;
}
float matrixClass::getM31()
{
m31 = this->m31;
return m31;
}
float matrixClass::getM32()
{
m32 = this->m32;
return m32;
}
float matrixClass::getM33()
{
m33 = this->m33;
return m33;
}
// Function to create an identity matrix
void matrixClass::identityMatrix()
{
this->m11 = 1;
this->m12 = 0;
this->m13 = 0;
this->m21 = 0;
this->m22 = 1;
this->m23 = 0;
this->m31 = 0;
this->m32 = 0;
this->m33 = 1;
}
// Function to create rotation matrix with angle given
void matrixClass::xRotationMatrix(double angle)
{
this->m11 = 1;
this->m12 = 0;
this->m13 = 0;
this->m21 = 0;
this->m22 = float(cos((angle*M_PI)/180));
this->m23 = float(-sin((angle*M_PI)/180));
this->m31 = 0;
this->m32 = float(sin((angle*M_PI)/180));
this->m33 = float(cos((angle*M_PI)/180));
}
// Function to create rotation matrix with angle given
void matrixClass::yRotationMatrix(double angle)
{
this->m11 = float(cos((angle*M_PI)/180));
this->m12 = 0;
this->m13 = float(sin((angle*M_PI)/180));
this->m21 = 0;
this->m22 = 1;
this->m23 = 0;
this->m31 = float(-sin((angle*M_PI)/180));
this->m32 = 0;
this->m33 = float(cos((angle*M_PI)/180));
}
// Function to create rotation matrix with angle given
void matrixClass::zRotationMatrix(double angle)
{
this->m11 = float(cos((angle*M_PI)/180));
this->m12 = float(-sin((angle*M_PI)/180));
this->m13 = 0;
this->m21 = float(sin((angle*M_PI)/180));
this->m22 = float(cos((angle*M_PI)/180));
this->m23 = 0;
this->m31 = 0;
this->m32 = 0;
this->m33 = 1;
}
// Function to calculate determinant of 3x3 matrix
float matrixClass::calcDeterminant(matrixClass m1)
{
float a11 = m1.m11*((m1.m22 * m1.m33) - (m1.m32 * m1.m23));
float a12 = -m1.m12*((m1.m22 * m1.m33) - (m1.m31 * m1.m23));
float a13 = m1.m13*((m1.m21 * m1.m32) - (m1.m31 * m1.m22));
float result = a11 + a12 + a13;
return result;
}
// Function to transpose 3x3 matrix
matrixClass matrixClass::transpose(matrixClass m1)
{
matrixClass mT;
mT.m11 = m1.m11;
mT.m12 = m1.m21;
mT.m13 = m1.m31;
mT.m21 = m1.m12;
mT.m22 = m1.m22;
mT.m23 = m1.m32;
mT.m31 = m1.m13;
mT.m32 = m1.m23;
mT.m33 = m1.m33;
return mT;
}
// Function to create adjugate matrix
matrixClass matrixClass::adjugate(matrixClass m1)
{
matrixClass adjM;
adjM.m11 = ((m1.m22*m1.m33) - (m1.m32*m1.m23));
adjM.m12 = -1*((m1.m21*m1.m33) - (m1.m31*m1.m23));
adjM.m13 = ((m1.m21*m1.m32) - (m1.m31*m1.m22));
adjM.m21 = -1*((m1.m12*m1.m33) - (m1.m32*m1.m13));
adjM.m22 = ((m1.m11*m1.m33) - (m1.m31*m1.m13));
adjM.m23 = -1*((m1.m11*m1.m32) - (m1.m31*m1.m12));
adjM.m31 = ((m1.m12*m1.m23) - (m1.m22*m1.m13));
adjM.m32 = -1*((m1.m11*m1.m23) - (m1.m21*m1.m13));
adjM.m33 = ((m1.m11*m1.m22) - (m1.m21*m1.m12));
return adjM;
}
// Function to invert 3x3 matrix
matrixClass matrixClass::invert(matrixClass m1)
{
matrixClass m, mT, adjM, inverseM;
float determinant = calcDeterminant(m1);
cout << "Determinant: " << determinant << endl;
if (determinant == 0) {
cout << "Matrix has no inverse" << endl;
}
else {
mT = m.transpose(m1);
adjM = m.adjugate(mT);
inverseM = adjM / determinant;
return inverseM;
}
}
// Copy constructor
matrixClass::matrixClass(matrixClass &m1)
{
this->m11 = m1.m11;
this->m12 = m1.m12;
this->m13 = m1.m13;
this->m21 = m1.m21;
this->m22 = m1.m22;
this->m23 = m1.m23;
this->m31 = m1.m31;
this->m32 = m1.m32;
this->m33 = m1.m33;
}
// Function to divide a matrix by a value
matrixClass operator /(matrixClass& m1, float val )
{
matrixClass result;
result.m11 = m1.m11/val;
result.m12 = m1.m12/val;
result.m13 = m1.m13/val;
result.m21 = m1.m21/val;
result.m22 = m1.m22/val;
result.m23 = m1.m23/val;
result.m31 = m1.m31/val;
result.m32 = m1.m32/val;
result.m33 = m1.m33/val;
return result;
}
| true |
aae7476cbf0f3b8c5757dac4ee7bc2c7e8d41b26 | C++ | mart123p/INF1995 | /projet/lib/uart.h | UTF-8 | 3,962 | 3.0625 | 3 | [] | no_license | #ifndef UART_H
#define UART_H
/**
* Envoyer et recevoir diverses messages avec l'interface de communication UART.
* Ces messages peuvent être reçus à l'aide du programme sérieViaUSB. Certaines
* méthodes ont été conçues pour être utilisé avec les logiciels de diagnostique
* maison dont il est question dans readme.md
*/
#include <avr/io.h>
#include "sensors.h"
namespace uart {
/**
* Configuration des registres nécessaire pour la communication UART
* @return void
*/
void init();
/**
* Afficher en UART un tableau de caractères ou une chaîne de caractères
* @param c Chaîne de caractères
* @param size Taille de la chaîne de caractère
* @return void
*/
void print(const char *c, const uint8_t size);
/**
* Afficher en UART un tableau de caractères ou une chaîne de caractères. La
* taille n'est pas nécessaire, car le code regarde pour le caractère nul.
* @param c Chaîne de caractères
* @return void
*/
void print(const char *c);
/**
* Afficher un entier en ascii sur UART
* @param n L'entier à afficher
* @return void
*/
void print(const int n);
/**
* Afficher un gros entier en ascii sur UART
* @param n Le long à afficher
* @return void
*/
void print(const long n);
/**
* Afficher un uint8_t en ascii sur UART
* @param n L'octet à afficher
* @return void
*/
void print(const uint8_t n);
/**
* Afficher un uint16_t en ascii sur UART
* @param n Le mot à afficher
* @return void
*/
void print(const uint16_t n);
/**
* Afficher un uint32_t en ascii sur UART
* @param n Le uint32_t à afficher
* @return void
*/
void print(const uint32_t n);
/**
* Afficher un caractère sur UART
* @param c Le caractère à afficher
* @return void
*/
void print(const char c);
/**
* Afficher un retour à la ligne sur UART
* @return void
*/
void println();
/**
* Lire les données en entrée sur UART
* @return uint8_t L'octet
*/
uint8_t readData();
/**
* Envoyer des données en UART
* @param data L'octet à envoyer
* @return void
*/
void sendData(uint8_t data);
/**
* Nettoyage de la console
* @return void
*/
void clear();
/**
* Tester toutes les méthodes UART
* @return void
*/
void test();
// Débogage maison
/**
* Rafraîchir le logiciel de débogage avec de nouvelles données, afficher en
* même temps une chaîne de caractère sur le moniteur série.
* @param Sensor* sensor La classe Sensor pour obtenir les valeurs des capteurs
* actuellement
* @param uint8_t state État de la machine a état
* @param const char *c Chaîne de caractère à afficher sur le moniteur série
*/
void parcoursDebug(Sensor &sensor, uint8_t state, const char *c);
/**
* Rafraîchir le logiciel de débogage avec de nouvelles données, afficher en
* même temps une chaîne de caractère sur le moniteur série.
* @param Sensor &sensor La classe Sensor pour obtenir les valeurs des capteurs
* actuellement
* @param uint8_t state État de la machine a état
* @param const char *c Chaîne de caractère à afficher sur le moniteur série
*/
void parcoursDebug(Sensor *sensor, uint8_t state, const char *c);
/**
* Rafraîchir le logiciel de débogage avec de nouvelles données, afficher en
* même temps une valeur sur le moniteur série.
* @param Sensor &sensor La classe Sensor pour obtenir les valeurs des capteurs
* actuellement
* @param uint8_t state État de la machine a état
* @param uint8_t num Valeur à afficher sur le moniteur série.
*/
void parcoursDebug(Sensor &sensor, uint8_t state, uint8_t num);
/**
* Rafraîchir le logiciel de débogage avec de nouvelles données, afficher en
* même temps une valeur sur le moniteur série.
* @param Sensor* sensor La classe Sensor pour obtenir les valeurs des capteurs
* actuellement
* @param uint8_t state État de la machine a état
* @param uint8_t num Valeur à afficher sur le moniteur série.
*/
void parcoursDebug(Sensor *sensor, uint8_t state, uint8_t num);
} // namespace uart
#endif
| true |
49fd1d306afef43d5aa47ee379b215d96e8bae3b | C++ | GabeOchieng/ggnn.tensorflow | /program_data/PKU_raw/102/1218.c | UTF-8 | 892 | 3.046875 | 3 | [] | no_license |
int main()
{
int n;
double x;
double a[40];
double b[40];
int counta = 0;
int countb = 0;
cin >> n;
for(int i = 0; i < n; i ++)
{
char ch[10];
cin >> ch >> x;
if(ch[0] == 'm')
{
a[counta] = x;
counta ++;
}
else
{
b[countb] = x;
countb ++;
}
}
for(int i = 0; i < counta - 1; i ++)
for(int j = 0; j < counta - 1 - i; j ++)
{
if(a[j] > a[j + 1])
{
x = a[j];
a[j] = a[j + 1];
a[j + 1] = x;
}
}
for(int i = 0; i < countb - 1; i ++)
for(int j = 0; j < countb - 1 - i; j ++)
{
if(b[j] < b[j + 1])
{
x = b[j];
b[j] = b[j + 1];
b[j + 1] = x;
}
}
cout << fixed << setprecision(2);
cout << a[0];
for(int i = 1; i < counta ; i ++)
cout << " " << a[i];
for(int i = 0; i < countb ; i ++)
cout << " " << b[i];
return 0;
} | true |
a5dbd966e38feb8b6f03f1c0159d69d3fd0d62a8 | C++ | kaityo256/mdacp | /mdrect.cc | UTF-8 | 1,609 | 2.703125 | 3 | [
"BSD-3-Clause",
"MIT"
] | permissive | #include <iostream>
#include "mdrect.h"
//----------------------------------------------------------------------
bool
MDRect::IsOverBoundary(int dir, double q[D]) {
switch (dir) {
case D_LEFT:
return (q[X] < s[X]);
case D_RIGHT:
return (q[X] >= e[X]);
case D_BACK:
return (q[Y] < s[Y]);
case D_FORWARD:
return (q[Y] >= e[Y]);
case D_DOWN:
return (q[Z] < s[Z]);
case D_UP:
return (q[Z] >= e[Z]);
}
return false;
}
//---------------------------------------------------------------------
bool
MDRect::IsInsideEdge(int dir, double q[D], SimulationInfo *sinfo) {
const double SL = sinfo->SearchLength;
switch (dir) {
case D_LEFT:
return (q[X] < s[X] + SL && q[X] > s[X]);
case D_RIGHT:
return (q[X] > e[X] - SL && q[X] < e[X]);
case D_BACK:
return (q[Y] < s[Y] + SL && q[Y] > s[Y]);
case D_FORWARD:
return (q[Y] > e[Y] - SL && q[Y] < e[Y]);
case D_DOWN:
return (q[Z] < s[Z] + SL && q[Z] > s[Z]);
case D_UP:
return (q[Z] > e[Z] - SL && q[Z] < e[Z]);
}
return false;
}
//---------------------------------------------------------------------
std::ostream& operator<<(std::ostream& os, const MDRect& rect) {
return (os << "(" << rect.s[X] << "," << rect.s[Y] << "," << rect.s[Z] << ")-("
<< rect.e[X] << "," << rect.e[Y] << "," << rect.e[Z] << ")");
}
//---------------------------------------------------------------------
void
MDRect::ChangeScale(double alpha) {
for (int i = 0; i < D; i++) {
s[i] *= alpha;
e[i] *= alpha;
}
}
//---------------------------------------------------------------------
| true |
77dc5dd3a434ec2cd2047867fc343f34c3cf197e | C++ | yashAgarwal41/Awesome-Projects-Collection | /Unique C++ Projects/Bookshop management system using file handling.cpp | UTF-8 | 8,174 | 3.40625 | 3 | [] | no_license | // C++ program to illustrate bookshop
// management system using File Handling
#include <fstream>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
// Bookshop Class
class bookshope {
public:
void control_panel();
void add_book();
void show_book();
void check_book();
void update_book();
void del_book();
};
// Function to display the menus
void bookshope::control_panel()
{
system("cls");
cout << "\n\n\t\t\t\tCONTROL PANEL";
cout << "\n\n1. ADD BOOK";
cout << "\n2. DISPLAY BOOKS";
cout << "\n3. CHECK PARTICULAR BOOK";
cout << "\n4. UPDATE BOOK";
cout << "\n5. DELETE BOOK";
cout << "\n6. EXIT";
}
// Function to add book
void bookshope::add_book()
{
system("cls");
fstream file;
int no_copy;
string b_name, a_name, b_id;
cout << "\n\n\t\t\t\tADD BOOKS";
cout << "\n\nBook ID : ";
cin >> b_id;
cout << "\nBook Name : ";
cin >> b_name;
cout << "\nAuthor Name : ";
cin >> a_name;
cout << "\nNo. of Books : ";
cin >> no_copy;
// Open file in append or
// output mode
file.open("D:// book.txt",
ios::out | ios::app);
file << " " << b_id << " "
<< b_name << " " << a_name
<< " " << no_copy << "\n";
file.close();
}
// Function to display book
void bookshope::show_book()
{
system("cls");
fstream file;
int no_copy;
string b_name, b_id, a_name;
cout << "\n\n\t\t\t\t\tAll BOOKS";
// Open the file in input mode
file.open("D:// book.txt", ios::in);
if (!file)
cout << "\n\nFile Opening Error!";
else {
cout << "\n\n\nBook ID\t\tBook"
<< "\t\tAuthor\t\tNo. of "
"Books\n\n";
file >> b_id >> b_name;
file >> a_name >> no_copy;
// Till end of file is reached
while (!file.eof()) {
cout << " " << b_id
<< "\t\t" << b_name
<< "\t\t" << a_name
<< "\t\t" << no_copy
<< "\n\n";
file >> b_id >> b_name;
file >> a_name >> no_copy;
}
system("pause");
// Close the file
file.close();
}
}
// Function to check the book
void bookshope::check_book()
{
system("cls");
fstream file;
int no_copy, count = 0;
string b_id, b_name, a_name, b_idd;
cout << "\n\n\t\t\t\tCheck "
<< "Particular Book";
// Open the file in input mode
file.open("D:// book.txt", ios::in);
if (!file)
cout << "\n\nFile Opening Error!";
else {
cout << "\n\nBook ID : ";
cin >> b_idd;
file >> b_id >> b_name;
file >> a_name >> no_copy;
while (!file.eof()) {
if (b_idd == b_id) {
system("cls");
cout << "\n\n\t\t\t\t"
<< "Check Particular Book";
cout << "\n\nBook ID : "
<< b_id;
cout << "\nName : "
<< b_name;
cout << "\nAuthor : "
<< a_name;
cout << "\nNo. of Books : "
<< no_copy;
cout << endl
<< endl;
count++;
break;
}
file >> b_id >> b_name;
file >> a_name >> no_copy;
}
system("pause");
file.close();
if (count == 0)
cout << "\n\nBook ID Not"
<< " Found...";
}
}
// Function to update the book
void bookshope::update_book()
{
system("cls");
fstream file, file1;
int no_copy, no_co, count = 0;
string b_name, b_na, a_name;
string a_na, b_idd, b_id;
cout << "\n\n\t\t\t\tUpdate Book Record";
file1.open("D:// book1.txt",
ios::app | ios::out);
file.open("D:// book.txt", ios::in);
if (!file)
cout << "\n\nFile Opening Error!";
else {
cout << "\n\nBook ID : ";
cin >> b_id;
file >> b_idd >> b_name;
file >> a_name >> no_copy;
// Till end of file is reached
while (!file.eof()) {
if (b_id == b_idd) {
system("cls");
cout << "\t\t\t\t"
<< "Update Book Record";
cout << "\n\nNew Book Name : ";
cin >> b_na;
cout << "\nAuthor Name : ";
cin >> a_na;
cout << "\nNo. of Books : ";
cin >> no_co;
file1 << " " << b_id << " "
<< b_na << " "
<< a_na << " " << no_co
<< "\n\n";
count++;
}
else
file1 << " " << b_idd
<< " " << b_name
<< " " << a_name
<< " " << no_copy
<< "\n\n";
file >> b_idd >> b_name;
file >> a_name >> no_copy;
}
if (count == 0)
cout << "\n\nBook ID"
<< " Not Found...";
}
cout << endl;
system("pause");
// Close the files
file.close();
file1.close();
remove("D:// book.txt");
rename("D:// book1.txt",
"D:// book.txt");
}
// Function to delete book
void bookshope::del_book()
{
system("cls");
fstream file, file1;
int no_copy, count = 0;
string b_id, b_idd, b_name, a_name;
cout << "\n\n\t\t\t\tDelete a Book";
// Append file in output mode
file1.open("D:// book1.txt",
ios::app | ios::out);
file.open("D:// book.txt",
ios::in);
if (!file)
cout << "\n\nFile Opening Error...";
else {
cout << "\n\nBook ID : ";
cin >> b_id;
file >> b_idd >> b_name;
file >> a_name >> no_copy;
while (!file.eof()) {
if (b_id == b_idd) {
system("cls");
cout << "\n\n\t\t\t\t"
<< "Delete a Book";
cout << "\n\nBook is Deleted "
"Successfully...\n\n";
count++;
}
else
file1 << " " << b_idd
<< " " << b_name
<< " " << a_name
<< " " << no_copy
<< "\n\n";
file >> b_idd >> b_name;
file >> a_name >> no_copy;
}
if (count == 0)
cout << "\n\nBook ID "
<< "Not Found...";
}
system("pause");
// Close the file
file.close();
file1.close();
remove("D:// book.txt");
rename("D:// book1.txt",
"D:// book.txt");
}
// Function for book shop record
void bookShopRecord()
{
int choice;
char x;
bookshope b;
while (1) {
b.control_panel();
cout << "\n\nEnter your choice : ";
cin >> choice;
switch (choice) {
case 1:
do {
b.add_book();
cout << "\n\nWant to add"
<< " another book? "
"(y/n) : ";
cin >> x;
} while (x == 'y');
break;
case 2:
b.show_book();
break;
case 3:
b.check_book();
break;
case 4:
b.update_book();
break;
case 5:
b.del_book();
break;
case 6:
exit(0);
break;
default:
cout << "\n\nINVALID CHOICE\n";
}
}
}
// Driver Code
int main()
{
// Function Call
bookShopRecord();
return 0;
}
| true |
10f4277600d972639db084443272d5473966f46b | C++ | Hekiat/Jikan | /src/ApplicationData.cpp | UTF-8 | 5,471 | 2.578125 | 3 | [
"Unlicense"
] | permissive | #include "ApplicationData.h"
#include <iostream>
#include <QJsonObject>
#include <QJsonDocument>
#include <QJsonArray>
ApplicationData::ApplicationData(int argc, char** argv, QObject* parent) : QObject(parent)
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
m_app = new QGuiApplication(argc, argv);
m_engine = new QQmlApplicationEngine();
m_engine->rootContext()->setContextProperty("_applicationData", this);
}
ApplicationData::~ApplicationData()
{
}
void ApplicationData::updatePopupBackground() {
foreach(QObject* obj, m_engine->rootObjects())
{
QQuickWindow* window = qobject_cast<QQuickWindow*>(obj);
if(window)
{
QImage image = window->grabWindow();
image.save("popupBackground.png");
}
}
}
void ApplicationData::createTag(const QString& tagName, const QColor& tagColor)
{
auto* const tag = new Tag();
tag->setName(tagName);
tag->setColor(tagColor);
connect(tag, &Tag::removed, this, &ApplicationData::removeTag);
m_tags.push_back(tag);
m_qtags.append(tag);
QQmlContext* ctxt = m_engine->rootContext();
ctxt->setContextProperty("tagModel", QVariant::fromValue(m_qtags));
std::cout << "Create Tag name " << tagName.toStdString() << std::endl;
}
QQmlApplicationEngine* ApplicationData::engine()
{
return m_engine;
}
int ApplicationData::exec()
{
return m_app->exec();
}
void ApplicationData::loadTags()
{
auto* const tagA = new Tag();
auto* const tagB = new Tag();
tagA->setName(QString("TAG A"));
tagB->setName(QString("TAG B"));
tagA->setColor(Qt::red);
tagB->setColor(Qt::green);
m_tags.push_back(tagA);
m_tags.push_back(tagB);
connect(tagA, &Tag::removed, this, &ApplicationData::removeTag);
connect(tagB, &Tag::removed, this, &ApplicationData::removeTag);
// Data Filtering
for(auto* tag : m_tags)
{
m_qtags.append(tag);
}
QQmlContext* ctxt = m_engine->rootContext();
ctxt->setContextProperty("tagModel", QVariant::fromValue(m_qtags));
}
void ApplicationData::removeTag()
{
auto* removedTag = sender();
//ctxt->setContextProperty("tagModel", QVariant::fromValue(nullptr));
m_tags.erase(
std::remove_if(m_tags.begin(), m_tags.end(),
[removedTag](auto* tag)
{
if(tag == removedTag)
{
tag->deleteLater();
return true;
}
return false;
}),
m_tags.end());
m_qtags.clear();
for(auto* tag : m_tags)
{
m_qtags.append(tag);
}
QQmlContext* ctxt = m_engine->rootContext();
ctxt->setContextProperty("tagModel", QVariant::fromValue(m_qtags));
}
void ApplicationData::removeNote()
{
auto* removedNote = sender();
m_notes.erase(
std::remove_if(m_notes.begin(), m_notes.end(),
[removedNote](auto* note)
{
if(note == removedNote)
{
note->deleteLater();
return true;
}
return false;
}),
m_notes.end());
m_qnotes.clear();
for(auto* note : m_notes)
{
m_qnotes.append(note);
}
QQmlContext* ctxt = m_engine->rootContext();
ctxt->setContextProperty("noteModel", QVariant::fromValue(m_qnotes));
}
void ApplicationData::loadNotes()
{
auto* const noteA = new Note();
auto* const noteB = new Note();
noteA->setContent(QString("Note A\n ligne 2\n \t ligne 3"));
noteB->setContent(QString("Note B"));
noteA->setDate(QDate(1989, 9, 16));
noteB->setDate(QDate(1989, 9, 17));
noteA->setDuration(0.5f);
noteB->setDuration(2.0f);
noteA->addTag(m_tags[0]);
connect(noteA, &Note::removed, this, &ApplicationData::removeNote);
connect(noteB, &Note::removed, this, &ApplicationData::removeNote);
// if append after setContextProperty have to set the list again
m_notes.push_back(noteA);
m_notes.push_back(noteB);
m_notes.push_back(noteA);
m_notes.push_back(noteB);
// Data Filtering
for(auto* note : m_notes)
{
m_qnotes.append(note);
}
QQmlContext* ctxt = m_engine->rootContext();
ctxt->setContextProperty("noteModel", QVariant::fromValue(m_qnotes));
}
void ApplicationData::save() const
{
//QFile saveFile(saveFormat == Json ? QStringLiteral("test_save.json") : QStringLiteral("test_save.dat"));
QFile saveFile(QStringLiteral("test_save.json"));
if (!saveFile.open(QIODevice::WriteOnly)) {
qWarning("Couldn't open save file.");
return;
}
QJsonObject gameObject;
write(gameObject);
QJsonDocument saveDoc(gameObject);
//saveFile.write(saveFormat == Json ? saveDoc.toJson() : saveDoc.toBinaryData());
saveFile.write(saveDoc.toJson());
}
void ApplicationData::write(QJsonObject& json) const
{
/*
QJsonObject playerObject;
mPlayer.write(playerObject);
json["player"] = playerObject;
QJsonArray levelArray;
foreach (const Level level, mLevels) {
QJsonObject levelObject;
level.write(levelObject);
levelArray.append(levelObject);
}*/
QJsonArray tagArray;
for(const auto* tag : m_tags)
{
QJsonObject tagObject;
tag->write(tagObject);
tagArray.append(tagObject);
}
json["tags"] = tagArray;
json["notes"] = "NOTES";
}
| true |
79eae6e4993e29df96f61393dc6a9783dd5e89a4 | C++ | cwielgosz/CFDgrid | /CFD2dGrid.cc | UTF-8 | 3,210 | 3.140625 | 3 | [] | no_license | #include <iostream>
#include <iomanip>
using namespace std;
class Grid2d{
private:
const static int SIZE = 10;
double* g;
double* gf;
uint32_t rows;
uint32_t cols;
public:
Grid2d(uint32_t rows, uint32_t cols, double val = 0) : rows(rows), cols(cols){ //CONSTRUCTOR
g = new double[rows * cols];
gf = new double[rows * cols];
for(int p = 0; p < rows * cols; p++)
g[p] = val;
}
~Grid2d(){ //DESTRUCTOR
delete []g;
}
Grid2d(const Grid2d& orig){ //COPY CONSTRUCTOR
g = new double[orig.rows * orig.cols];
rows = orig.rows;
cols = orig.cols;
for(int p = 0; p < rows * cols; p++)
g[p] = orig.g[p];
}
Grid2d& operator =(const Grid2d& orig){ //OPERATOR =
Grid2d copy(orig);
swap(copy.g,g);
swap(copy.rows,rows);
swap(copy.cols,cols);
}
void startPoint(uint32_t r, uint32_t c, double conc){
g[r*cols + c] = conc;
}
/* void specPoint(uint32_t r, uint32_t c) const { instead overload ()
cout << g[r*cols + c] << '\n';
}*/
double operator ()(uint32_t r, uint32_t c) const{
return g [r*cols + c];
}
/*
const int N = -cols; outside method!!! YOU DON'T WANT TO INITIALIZE IT EVERY TIME
const int S = cols;
const int E = 1;
const int W = -1;
void diffuse(double c1, double c2){ PROBLEM WITH BOUNDARIES
for(int i = 0; i < rows * cols; i++){
gf[i] = c1*g[i];
if( i+N >= 0 && i+N < rows*cols )
gf[i] += c2*g[i+N];
if( i+S >= 0 && i+S < rows*cols )
gf[i] += c2*g[i+S];
if( i+E >= 0 && i+E < rows*cols )
gf[i] += c2*g[i+E];
if( i+W >= 0 && i+W < rows*cols )
gf[i] += c2*g[i+W];
}
double* temp = g;
g = gf;
gf = g;
}
*/
const int dirs[4][2] = {{-1,0},{0, -1}, {1, 0}, {0, 1}};
void diffuse(double c1, double c2){
for(int i = 0; i < rows; i++){
for(int j = 0; j < cols; j++){
double cur = c1 * g[ i * cols + j];
for(auto dir : dirs){
int x = i + dir[0];
int y = j + dir[1];
if( x >= 0 && x < rows && y >= 0 && y < cols)
cur += c2 * g[ x * cols + y];
}
gf [ i * cols + j] = cur;
}
}
double* temp = g;
g = gf;
gf = temp;
}
bool checkDisp(){
for(int i = 0; i < rows*cols; i++){
if(g[i] == 0)
return true;}
return false;
}
friend ostream& operator << (ostream& s, const Grid2d& grid);
};
ostream& operator << (ostream& s, const Grid2d& grid){
for(int p = 0; p < grid.rows * grid.cols; p++){
if( p != 0 && p % grid.cols == 0)
s << '\n';
s << grid.g[p] << '\t';
}
return s << '\n';
}
int main() {
Grid2d grid(10, 10);
// cout << grid;
grid.startPoint(0,0,5);
grid.startPoint(9,9,2.5);
cout << grid << endl;
for(int i = 0; i < 5; i++) {
grid.diffuse(0.8, 0.2);
}
cout << grid << endl;
//grid.specPoint(0,0);
/*
while(grid.checkDisp()){
grid.diffuse(0.4, 0.2);
cout << grid;}
/*
g.printInitGrid();
g.printGrid();
g.printFinalGrid();*/
}
| true |
8b3aa3a67ad5c747466f94d87c2857690bf3cbb1 | C++ | wittekin/Ising2_Eclipse | /main.cpp | UTF-8 | 825 | 2.75 | 3 | [] | no_license | /*
* File: main.cpp
* Author: Mark Wittekind
*
* Created on March 5, 2015, 6:03 PM
*/
#include <cstdlib>
#include "CLattice.h"
#include <fstream>
#include <streambuf>
#include <iostream>
#include <vector>
#include "CObject.h"
using namespace std;
/*
*
*/
int main(int argc, char** argv) {
//CONSTANTS
const unsigned short WIDTH = 50;
const unsigned short HEIGHT = 70;
//output stream for debugging
streambuf * buf;
buf = cout.rdbuf();
ostream debug_stream(buf);
//constants that will be command line params
short MAXTIMESTEPS = 100;
float TIMESTEP = 1;
float kB = 1;
float T = 1;
//"calculated" constants
vector<CObject> objects;
CLattice lattice(WIDTH,HEIGHT);
objects.push_back(lattice);
for(int t = 0; t<MAXTIMESTEPS; t+=TIMESTEP)
lattice.print_all(debug_stream);
return 0;
}
| true |
4bd1c6b57fe75027de857a29588ff1fa1f367b2d | C++ | goku1997/GenesisBlockZero | /ochotest.cc | UTF-8 | 766 | 2.515625 | 3 | [] | no_license | #include <stdio.h>
#include "sha256.h"
unsigned char *SHA256(const unsigned char *d, size_t n,unsigned char *md) {
CSHA256 bob;
bob.Write(d,n);
bob.Finalize(md);
return md;
}
//msg: 00CDF9B24885C203B8F2C7939DABE2D5F6668C0C9C
//hsh: 0B49BA51CE57043361EB1DC5D7779DADE79D23C61F679A90EBABE48B39CFFBCC
//msg: 0B49BA51CE57043361EB1DC5D7779DADE79D23C61F679A90EBABE48B39CFFBCC
//hsh: 6A57B86D3FB0203A6111CFD765410CABFB506C2788BF1D9888AD321AE2023262
//5184BCF58C538C38B26535897BB35EA2D22CA8BF81FC5F3C0254677049A7B2B4
int main() {
int i;
uint8_t out[0x20];
SHA256((const unsigned char *)"\x00\xCD\xF9\xB2\x48\x85\xC2\x03\xB8\xF2\xC7\x93\x9D\xAB\xE2\xD5\xF6\x66\x8C\x0C\x9C", 20, out);
for (i=0;i<0x20;i++) { printf("%02X", out[i]); } printf("\n");
return 0;
} | true |
bd3f74eb00b44beda7eef287684e741f7cb05465 | C++ | zu8/COVID_contacts | /infected.h | WINDOWS-1251 | 2,246 | 2.796875 | 3 | [] | no_license | #ifndef INFECTEDH
#define INFECTEDH
#include<fstream>
#include<iostream>
#include<string>
#include<list>
#include<vector>
#include<regex>
#include<algorithm>
#include<iterator>
#include<iomanip>
using namespace std;
struct Tdate {
int day;
int month;
int year;
int daysFromPivot; // 01.01.2000
// =================================
Tdate(int d=1, int m=1, int y=2000);
bool operator ==(const Tdate&) const;
bool operator <(const Tdate&) const;
bool operator >(const Tdate&) const;
};
struct Tgroup {
int id; //
Tdate date; //
list <int> persons; //
list<int> thanksTo; // ,
// ===================================
Tgroup(const string,const string);
bool operator ==(const Tgroup&) const;
bool operator <(const Tgroup&) const;
bool operator >(const Tgroup&) const;
};
list<Tgroup> createGroups(const char* filename); //
Tdate getStructTdate(string a); //
void expandGroups(list<Tgroup>& somelist,unsigned int Range); // ( , )
void AddToList(list<int> &patient, const list<int> donor); //
vector<Tgroup*> findMax(list<Tgroup> &somelist); // /
void writeMaxGroup(list<Tgroup> somelist, const char* filename); // /
#endif
| true |
42ab3e4dcb5ebb6ecb6ea6171fd7820d03e31861 | C++ | afawa/OI-problem | /codeforces/Hungarian.cc | UTF-8 | 717 | 2.71875 | 3 | [] | no_license | #include <cstdio>
#include <cstring>
using namespace std;
int n;
int map[205][205];
int p[205];
int vis[205];
bool match(int i){
for(int j=0;j<n;++j){
if(map[i][j] && !vis[j]){
vis[j]=1;
if(p[j] == -1 || match(p[j])){
p[j] = i;
return true;
}
}
}
return false;
}
int Hungarian(){
int cnt=0;
for(int i=0;i<n;++i){
memset(vis,0,sizeof(vis));
if(match(i)){
++cnt;
}
}
return cnt;
}
int main(){
int t;
scanf("%d",&t);
while(t--){
scanf("%d",&n);
memset(p,-1,sizeof(p));
for(int i=0;i<n;++i){
for(int j=0;j<n;++j){
scanf("%d",&map[i][j]);
}
}
puts(Hungarian() == n ? "Yes" : "No");
}
return 0;
} | true |
ee27a97469ccfb07a0cfd39e119e82a24d187723 | C++ | losuffi/core | /test/test_container_slist.cpp | UTF-8 | 4,072 | 2.84375 | 3 | [] | no_license |
#include<ccdk/container/slist.h>
#include<stdio.h>
#include<string>
using namespace ccdk;
using namespace ccdk::mpl;
using namespace ccdk::ct;
void debug_slist()
{
DebugNewTitle("ctor");
{
DebugSubTitle("default");
{
slist<int> s1{};
slist<int> s2{ nullptr };
}
DebugSubTitle("fill ctor");
{
slist<int> s1{ 5, 1 };
slist<std::string> s2{ 5, "hello" };
s1.debug_value();
s2.debug_value();
}
DebugSubTitle("range/range-n/array ctor");
{
slist<int> s1{ 5, 1 };
slist<int> s2{ s1.begin(), s1.end() };
slist<int> s3{ s1.cbegin(), s1.size() };
s2.debug_value();
s3.debug_value();
slist<std::string> s4{ {"hello", "world", "c++"} };
slist<std::string> s5{ s4.begin(), s4.end() };
slist<std::string> s6{ s4.cbegin(), s4.cend() };
s5.debug_value();
s6.debug_value();
}
DebugSubTitle("copy/move ctor");
{
slist<int> s1{ 5, 2 };
slist<int> s2{ s1 };
slist<int> s3{ util::move(s1) };
s1.debug_value();
s2.debug_value();
s3.debug_value();
slist<std::string> s4{ { "hello", "world", "c++" } };
slist<std::string> s5{ s4 };
slist<std::string> s6{ util::move(s5) };
s4.debug_value();
s5.debug_value();
s6.debug_value();
}
DebugSubTitle("swap");
{
slist<int> s1{ 5, 2 };
slist<int> s2{ 5,1 };
s1.debug_value();
s2.debug_value();
s1.swap(s2);
s1.debug_value();
s2.debug_value();
}
}
DebugNewTitle("assign");
{
DebugSubTitle("copy/move assign");
{
slist<int> s1{ 5, 1 };
slist<int> s2{ 3, 2 };
slist<int> s3{ 6, 3 };
slist<int> s4{ 10, 4 };
s1.debug_value();
s1 = s2;
s1.debug_value();
s1 = s3;
s1.debug_value();
s1 = util::move(s4);
s4.debug_value();
s1.debug_value();
slist<std::string> s5{ 5, "hello" };
slist<std::string> s6{ 3, "world" };
slist<std::string> s7{ 6, "c++" };
slist<std::string> s8{ 10, "java" };
s5.debug_value();
s5 = s6;
s5.debug_value();
s5 = s7;
s5.debug_value();
s5 = util::move(s8);
s8.debug_value();
s5.debug_value();
}
DebugSubTitle("assign fill");
{
slist<int> s1{ 5, 1 };
s1.debug_value();
s1.assign(3, 2);
s1.debug_value();
s1.assign(6, 3);
s1.debug_value();
slist<std::string> s2{ 5, "c++" };
s2.debug_value();
s2.assign(3, "java");
s2.debug_value();
s2.assign(6, "scala");
s2.debug_value();
}
DebugSubTitle("assign array");
{
slist<int> s1{ 5, 1 };
s1 = { 1,2,3,4,5 };
s1.debug_value();
slist<std::string> s2{ 5, "c++" };
s2 = { "c++", "java", "scala", "python" };
s2.debug_value();
}
}
DebugNewTitle("it");
{
slist<int> s1{ { 1,2,3,4,5,4,3,2 } };
ccdk_assert(s1.size() == 8);
ccdk_assert(s1.begin() == s1.cbegin());
slist<int>::const_iterator bg = s1.begin();
for (auto &it : s1) {
DebugValueIt(it);
}
}
DebugNewTitle("pop/push");
{
slist<int> s1{ { 1,2,3,4,5,4,3,2 } };
s1.pop_front();
s1.debug_value();
s1.push_front(3);
s1.debug_value();
s1.push_back(10);
s1.debug_value();
ccdk_assert(s1.back() == 10);
ccdk_assert(s1.front() == 3);
}
DebugNewTitle("empty op");
{
{
slist<int> s{};
s.push_back(1);
}
{
slist<int> s{};
s.push_front(1);
}
{
slist<int> s{};
s = { 1,2,3,4 };
}
{
slist<int> s{};
s.pop_front();
}
{
slist<int> s{ {1,2,3,4,5} };
s.foreach([](int v) {
DebugValueIt(v);
});
DebugValueItEnd();
}
{
slist<int> s{ { 1,2,3,4,5 } };
auto news = s.map([](int v) { return v + 3; });
news.debug_value();
}
}
DebugNewTitle("test que");
{
int i = 0;
slist<int> que;
que.push_back(1);
while (!que.empty() && i<5) {
int top = que.front();
que.pop_front();
DebugValueIt(top);
que.push_back(top * 2);
que.push_back(top * 2 + 1);
++i;
}
}
}
void debug_cached_slist()
{
cached_slist<int> lst{ {1,2,3,4,5,6} };
lst.pop_front();
lst.pop_front();
lst.push_front(2);
lst.push_front(1);
DebugValue("before destruct");
}
int main()
{
debug_slist();
debug_cached_slist();
getchar();
ccdk_open_leak_check();
return 0;
} | true |
c1a1c3a3bb5a802baef0fa20dfade2c5d543106e | C++ | Tass0sm/DataStructures | /Polynomial/polynomialMain.cpp | UTF-8 | 3,029 | 3.75 | 4 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
struct node {
int cData = 0;
int eData = 0;
node *next = NULL;
};
class LinkedList {
private:
int length = 0;
int item;
node *head, *previous, *current;
public:
void renew() {
length = 0;
head = NULL;
previous = NULL;
current = NULL;
}
int getLength() {
return length;
}
bool empty() {
return length == 0;
}
bool atEnd() {
return current == NULL;
}
void next() {
if (current != NULL) {
node *temp = current;
current = current->next;
previous = temp;
}
}
void first() {
if (head != NULL) {
current = head;
previous = NULL;
}
}
int retrieve() {
if (current != NULL) {
return current->cData;
}
return 0;
}
void insert(int coeffData, int expData) {
node *newNode = new node;
newNode->cData = coeffData;
newNode->eData = expData;
if (previous != NULL && current != NULL) {
previous->next = newNode;
newNode->next = current;
} else if (previous == NULL && current == NULL) {
head = newNode;
current = newNode;
} else if (previous == NULL && current != NULL) {
head = newNode;
newNode->next = current;
} else if (previous != NULL && current == NULL) {
previous->next = newNode;
current = newNode;
}
length++;
}
void remove() {
if (current != NULL) {
current = (*current).next;
(*previous).next = current;
}
length--;
}
void expSort() {
for (int i = 0; i < length; i++) {
first();
for (int k = 1; k < i; k++) {
next();
}
node* origin = current;
if (i != 0) {
next();
}
node* highest = current;
for (int j = i; j < length; j++) {
if (current) {
if (current->eData > highest->eData) {
highest = current;
}
}
next();
}
if (highest != origin) {
if (i == 0) {
head = highest;
origin->next = highest->next;
highest->next = origin;
} else {
highest->next = origin->next;
origin->next = highest;
}
}
display();
}
}
void display() {
first();
for (int i = 0; i < length; i++) {
if (current->cData > 0) {
if (current->cData > 1) {
cout << current->cData;
}
if (current->eData > 0) {
cout << "x";
}
if (current->eData > 1) {
cout << "^";
cout << current->eData;
}
if (i < length-1) {
cout << " + ";
}
}
next();
}
cout << "\n";
}
};
int main(int argc, char *argv[]) {
LinkedList test;
test.renew();
cout << "Enter integer values until done. Quit with 'n'." << endl;
int c = 0;
int e = 0;
char f = 'y';
while (f == 'y') {
cout << "Enter term coefficient." << endl;
cin >> c;
cout << "Enter term exponent." << endl;
cin >> e;
test.insert(c, e);
test.next();
cout << "\nContinue? (y/n)" << endl;
cin >> f;
}
test.expSort();
test.display();
return 0;
}
| true |
98b8d8937ff6b1f87adcf0617c7c7ae7cb60c3d0 | C++ | andreikl/gexplorer | /handlers/namespoolhandler.cpp | UTF-8 | 928 | 2.515625 | 3 | [] | no_license | #include "config.h"
#include "handlers/namespoolhandler.h"
NamesPoolHandler* NamesPoolHandler::handler = NULL;
NamesPoolHandler* NamesPoolHandler::createInstance()
{
if(!handler) {
handler = new NamesPoolHandler();
for(int i = 0; i < Config::getInstance()->getActiveDownloadCount(); i++) {
NamePoolData data;
data.name = Config::getInstance()->getApplicationName() + QString::number(i) + ".bak";
data.isBusy = false;
handler->datas.append(data);
}
}
return handler;
}
NamesPoolHandler* NamesPoolHandler::getInstance()
{
return handler;
}
NamesPoolHandler::~NamesPoolHandler()
{
handler = NULL;
}
NamesPoolHandler::NamesPoolHandler()
{
}
NamePoolData* NamesPoolHandler::GetEmptyData()
{
for(int i = 0; i < datas.length(); i++) {
if(!datas[i].isBusy) {
return &datas[i];
}
}
return NULL;
}
| true |
de29e8c37a03644535a6d24bcd41bce771ee875a | C++ | Bingyy/Algorithms | /Tutorials/CSKaoyan/test.cpp | UTF-8 | 310 | 3.296875 | 3 | [] | no_license | #include <iostream>
#include <cmath>
using namespace std;
#define INF 100000
int main()
{
double sum = 0.0;
for(int i = 1; i < INF; i++ )
{
for(int j = 1; j < INF; j++)
{
sum += pow(-1,i+j) / (i + j);
}
}
cout << "Sum is : "<< sum << endl; // 0.193153,实际趋向值是:In2 - 1/2
return 0;
} | true |
7ebc25eed8e76441cba58d4fde3f25d3bde9b987 | C++ | samanseifi/Tahoe | /toolbox/src/C1functions/CubicSplineT.cpp | UTF-8 | 9,899 | 2.671875 | 3 | [
"BSD-3-Clause"
] | permissive | /* $Id: CubicSplineT.cpp,v 1.7 2004/07/20 23:23:33 rdorgan Exp $ */
/* created: paklein (12/02/1996) */
#include "CubicSplineT.h"
#include "dArray2DT.h"
#include "dMatrixT.h"
#include "TriDiagdMatrixT.h"
#include "iArrayT.h"
using namespace Tahoe;
const int kNumSplineCoeffs = 4;
/* constructor */
CubicSplineT::CubicSplineT(void)
{
SetName("cubic_spline");
}
CubicSplineT::CubicSplineT(const dArrayT& knots, const dArray2DT& coefficients):
fXPoints(knots),
fCoefficients(coefficients)
{
SetName("cubic_spline");
/* check dimensions */
if (fCoefficients.MajorDim() != fXPoints.Length() + 1)
throw ExceptionT::kSizeMismatch;
if (fCoefficients.MinorDim() != kNumSplineCoeffs)
throw ExceptionT::kGeneralFail;
}
CubicSplineT::CubicSplineT(const dArray2DT& points, FixityT fixity):
fXPoints(0,points),
fCoefficients(fXPoints.Length() + 1, kNumSplineCoeffs)
{
SetName("cubic_spline");
/* compute spline coefficients */
SetSpline(points, fixity);
}
/* I/O */
void CubicSplineT::Print(ostream& out) const
{
int d_width = OutputWidth(out, &fXPoints[0]);
/* parameters */
out << " Knots:\n";
for (int i = 0; i < fXPoints.Length(); i++)
out << setw(kIntWidth) << i+1
<< setw(d_width) << fXPoints[i]
<< setw(d_width) << Function(fXPoints[i]) << '\n';
}
void CubicSplineT::PrintName(ostream& out) const
{
out << " Cubic spline\n";
}
/* returning values */
double CubicSplineT::Function(double x) const { return function(x); }
double CubicSplineT::DFunction(double x) const { return Dfunction(x); }
double CubicSplineT::DDFunction(double x) const { return DDfunction(x); }
double CubicSplineT::DDDFunction(double x) const { return DDDfunction(x); }
double CubicSplineT::DDDDFunction(double x) const { return DDDDfunction(x); }
/* returning values in groups - returns refence to out to allow:
*
* dArrayT& goodname = pfunc->MapFunction(in, tempspace);
*/
dArrayT& CubicSplineT::MapFunction(const dArrayT& in, dArrayT& out) const
{
/* dimension check */
if ( in.Length() != out.Length() ) throw ExceptionT::kGeneralFail;
const double *pin = in.Pointer();
double *pout = out.Pointer();
int length = in.Length();
/* fast mapping */
for (int i = 0; i < length; i++)
*pout++ = function(*pin++);
return out;
}
dArrayT& CubicSplineT::MapDFunction(const dArrayT& in, dArrayT& out) const
{
/* dimension check */
if ( in.Length() != out.Length() ) throw ExceptionT::kGeneralFail;
const double *pin = in.Pointer();
double *pout = out.Pointer();
int length = in.Length();
/* fast mapping */
for (int i = 0; i < length; i++)
*pout++ = Dfunction(*pin++);
return out;
}
dArrayT& CubicSplineT::MapDDFunction(const dArrayT& in, dArrayT& out) const
{
/* dimension check */
if ( in.Length() != out.Length() ) throw ExceptionT::kGeneralFail;
const double *pin = in.Pointer();
double *pout = out.Pointer();
int length = in.Length();
/* fast mapping */
for (int i = 0; i < length; i++)
*pout++ = DDfunction(*pin++);
return out;
}
dArrayT& CubicSplineT::MapDDDFunction(const dArrayT& in, dArrayT& out) const
{
/* dimension check */
if ( in.Length() != out.Length() ) throw ExceptionT::kGeneralFail;
const double *pin = in.Pointer();
double *pout = out.Pointer();
int length = in.Length();
/* fast mapping */
for (int i = 0; i < length; i++)
*pout++ = DDDfunction(*pin++);
return out;
}
dArrayT& CubicSplineT::MapDDDDFunction(const dArrayT& in, dArrayT& out) const
{
/* dimension check */
if ( in.Length() != out.Length() ) throw ExceptionT::kGeneralFail;
const double *pin = in.Pointer();
double *pout = out.Pointer();
int length = in.Length();
/* fast mapping */
for (int i = 0; i < length; i++)
*pout++ = DDDDfunction(*pin++);
return out;
}
/*
* Return 0th, 1st, and 2nd derivative in the respective
* fields of the dArrayT.
*/
void CubicSplineT::SetAll(double x, dArrayT& data) const
{
all_functions(x, data[0], data[1], data[2]);
}
/* accessor to the spline information */
const dArray2DT& CubicSplineT::Coefficients(void) const
{
return fCoefficients;
}
/**********************************************************************
* Protected
**********************************************************************/
/* non-virtual function calls */
double CubicSplineT::function(double x) const
{
int i = fXPoints.Range(x);
double dx = (i == 0) ? x - fXPoints[i] :
((i == fXPoints.Length()) ? x - fXPoints[i-1] :
x - fXPoints[i-1]);
const double* a = fCoefficients(i);
return a[0] + a[1]*dx + a[2]*dx*dx + a[3]*dx*dx*dx;
}
double CubicSplineT::Dfunction(double x) const
{
int i = fXPoints.Range(x);
double dx = (i == 0) ? x - fXPoints[i] :
((i == fXPoints.Length()) ? x - fXPoints[i-1] :
x - fXPoints[i-1]);
const double* a = fCoefficients(i);
return a[1] + 2.0*a[2]*dx + 3.0*a[3]*dx*dx;
}
double CubicSplineT::DDfunction(double x) const
{
int i = fXPoints.Range(x);
double dx = (i == 0) ? x - fXPoints[i] :
((i == fXPoints.Length()) ? x - fXPoints[i-1] :
x - fXPoints[i-1]);
const double* a = fCoefficients(i);
return 2.0*a[2] + 6.0*a[3]*dx;
}
double CubicSplineT::DDDfunction(double x) const
{
int i = fXPoints.Range(x);
double dx = (i == 0) ? x - fXPoints[i] :
((i == fXPoints.Length()) ? x - fXPoints[i-1] :
x - fXPoints[i-1]);
const double* a = fCoefficients(i);
return 6.0*a[3];
}
double CubicSplineT::DDDDfunction(double x) const
{
int i = fXPoints.Range(x);
double dx = (i == 0) ? x - fXPoints[i] :
((i == fXPoints.Length()) ? x - fXPoints[i-1] :
x - fXPoints[i-1]);
const double* a = fCoefficients(i);
return 0.0;
}
void CubicSplineT::all_functions(double x, double& f, double& Df, double& DDf) const
{
int i = fXPoints.Range(x);
double dx = (i == 0) ? x - fXPoints[i] :
((i == fXPoints.Length()) ? x - fXPoints[i-1] :
x - fXPoints[i-1]);
const double* a = fCoefficients(i);
f = a[0] + a[1]*dx + a[2]*dx*dx + a[3]*dx*dx*dx;
Df = a[1] + 2.0*a[2]*dx + 3.0*a[3]*dx*dx;
DDf = 2.0*a[2] + 6.0*a[3]*dx;
}
/**********************************************************************
* Private
**********************************************************************/
/* compute spline coefficients */
void CubicSplineT::SetSpline(const dArray2DT& points, FixityT fixity)
{
/* allocate work space */
dArrayT YPoints(fXPoints.Length());
dArrayT DDY(fXPoints.Length());
dArrayT dxi(fXPoints.Length() - 1);
/* copy y-values */
points.ColumnCopy(1,YPoints);
/* set delta's */
for (int ii = 1; ii < fXPoints.Length(); ii++)
dxi[ii-1] = fXPoints[ii] - fXPoints[ii-1];
/* construct solver */
int numeqs = fXPoints.Length() - 2;
TriDiagdMatrixT LHS(numeqs);
dArrayT RHS(numeqs, DDY.Pointer() + 1);
/* build equation system */
double* pdx = dxi.Pointer();
double* pY = YPoints.Pointer() + 1;
double* pRHS = RHS.Pointer();
for (int i = 0; i < numeqs; i++)
{
LHS.SetRow(i, *pdx/6.0, (*pdx + *(pdx+1))/3.0, *(pdx+1)/6.0);
*pRHS = ((*(pY+1) - *pY)/(*(pdx+1))) -
((*pY - *(pY-1))/(*pdx));
pdx++; pY++; pRHS++;
}
/* set end conditions */
if (fixity == kParabolic)
{
LHS.AddToRow(0,0.0,dxi[0]/6.0,0.0);
LHS.AddToRow(numeqs-1,0.0,dxi[numeqs-1]/6.0,0.0);
}
/* solve */
LHS.LinearSolve(RHS);
/* end conditions */
if (fixity == kFreeRun)
DDY[0] = DDY[numeqs+1] = 0.0;
else if (fixity == kParabolic)
{
DDY[0] = DDY[1];
DDY[numeqs+1] = DDY[numeqs];
}
else
throw ExceptionT::kBadInputValue;
/* store spline coefficients */
for (int j = 1; j < fXPoints.Length(); j++)
{
int i = j-1;
double* coeff = fCoefficients(j);
double dx = dxi[i];
coeff[0] = YPoints[i];
coeff[1] = -dx*(2.0*DDY[i] + DDY[i+1])/6.0 +
(YPoints[i+1] - YPoints[i])/dx;
coeff[2] = DDY[i]/2.0;
coeff[3] = (DDY[i+1] - DDY[i])/(6.0*dx);
}
/* extensions */
fCoefficients(0,0) = fCoefficients(1,0);
fCoefficients(0,1) = fCoefficients(1,1);
fCoefficients(0,2) = fCoefficients(1,2);
fCoefficients(0,3) = 0.0;
int dex = fXPoints.Length() - 1;
fCoefficients(dex+1,0) = YPoints[dex];
fCoefficients(dex+1,1) = dxi[dex-1]*(DDY[dex-1] + 2.0*DDY[dex])/6.0 +
(YPoints[dex] - YPoints[dex-1])/dxi[dex-1];
fCoefficients(dex+1,2) = DDY[dex]/2.0;
fCoefficients(dex+1,3) = 0.0;
}
/* describe the parameters needed by the interface */
void CubicSplineT::DefineParameters(ParameterListT& list) const
{
/* inherited */
C1FunctionT::DefineParameters(list);
ParameterT fixity(ParameterT::Enumeration, "fixity");
fixity.AddEnumeration("parabolic", kParabolic);
fixity.AddEnumeration("free_run", kFreeRun);
fixity.SetDefault(kParabolic);
list.AddParameter(fixity);
}
/* information about subordinate parameter lists */
void CubicSplineT::DefineSubs(SubListT& sub_list) const
{
/* inherited */
C1FunctionT::DefineSubs(sub_list);
/* spline points */
sub_list.AddSub("OrderedPair", ParameterListT::OnePlus);
}
/* accept parameter list */
void CubicSplineT::TakeParameterList(const ParameterListT& list)
{
/* inherited */
C1FunctionT::TakeParameterList(list);
/* fixity */
int i_fixity = list.GetParameter("fixity");
FixityT fixity = (i_fixity == kFreeRun) ? kFreeRun : kParabolic;
/* collect spline points */
dArray2DT knots(list.NumLists("OrderedPair"), 2);
for (int i = 0; i < knots.MajorDim(); i++)
{
const ParameterListT* knot = list.List("OrderedPair", i);
knots(i,0) = knot->GetParameter("x");
knots(i,1) = knot->GetParameter("y");
}
/* dimension internal data structures */
dArrayT x_points(knots.MajorDim());
knots.ColumnCopy(0, x_points);
fXPoints.SetValues(x_points);
fCoefficients.Dimension(fXPoints.Length() + 1, kNumSplineCoeffs);
/* compute spline coefficients */
SetSpline(knots, fixity);
}
| true |
f7c342628682a0abf704db382f3f7c3e92ed3669 | C++ | antisvin/MyPatches | /C++/DiscreteSummationOscillator.hpp | UTF-8 | 7,338 | 2.78125 | 3 | [] | no_license | #ifndef __DISCRETE_SUMMATION_OSCILLATOR_HPP__
#define __DISCRETE_SUMMATION_OSCILLATOR_HPP__
#include "ComplexOscillator.h"
enum DSFShape {
DSF1,
DSF2,
DSF3,
DSF4,
};
/**
* Quadrature oscillator based on Moorer's discrete summation formulas
*
* See The Synthesis of Complex Audio Spectra by Means of Discrete Summation Formulas - James A. Moorer.
*
* https://www.desmos.com/calculator/xhuksewprf
*
* DSF1: finite series, one-sided spectrum (-b != b)
* DSF2: infinite series, one-sided spectrum (-b != b)
* DSF3: finite series, two-sided spectrum (-b == b)
* DSF4: infinite series, two-sided spectrum (-b == b)
**/
template <DSFShape shape>
class DiscreteSummationOscillator
: public ComplexOscillatorTemplate<DiscreteSummationOscillator<shape>> {
public:
static constexpr float begin_phase = 0.f;
static constexpr float end_phase = M_PI * 2;
DiscreteSummationOscillator()
: mul(0)
, phase(0)
, modPhase(0)
, incr(0)
, last_x(0)
, last_y(0)
, ComplexOscillatorTemplate<DiscreteSummationOscillator<shape>>() {
}
DiscreteSummationOscillator(float freq, float sr)
: DiscreteSummationOscillator() {
setFrequency(freq);
setFeedback(0, 0);
}
void reset() {
phase = 0.0f;
}
void setSampleRate(float sr) {
float freq = getFrequency();
mul = 2 * M_PI / sr;
setFrequency(freq);
}
float getSampleRate() {
return (2 * M_PI) / mul;
}
void setFrequency(float freq) {
incr = freq * mul;
}
float getFrequency() {
return incr / mul;
}
void setPhase(float ph) {
phase = ph;
}
float getPhase() {
return phase;
}
void setA(float a) {
this->a = a;
}
void setB(float b) {
this->b = b;
}
void setN(float n) {
this->n = n;
}
void setFeedback(float magnitude, float phase) {
feedback.setPolar(magnitude, phase);
}
ComplexFloat getSample();
void generate(ComplexFloatArray output) override {
render<false>(output.getSize(), NULL, output.getData());
}
ComplexFloat generate() override {
ComplexFloat sample;
render<false>(1, nullptr, &sample);
return sample;
}
ComplexFloat generate(float fm) override {
ComplexFloat sample;
render<true>(1, &fm, &sample);
return sample;
}
void generate(ComplexFloatArray output, FloatArray fm) {
render<true>(output.getSize(), fm.getData(), output.getData());
}
protected:
float mul;
float incr;
float phase;
float modPhase;
float a, b, n;
ComplexFloat feedback;
float last_x, last_y;
template <bool with_fm>
void render(size_t size, float* fm, ComplexFloat* out);
};
template <>
template <bool with_fm>
void DiscreteSummationOscillator<DSF1>::render(
size_t size, float* fm, ComplexFloat* out) {
float a1 = powf(a, n + 1.f);
float a2 = n + 1.f;
float a3 = (1.f + a * a);
float a4 = 2.f * a;
float gain = (a - 1.f) / (a1 - 1.f);
float s = modPhase;
float _last_x = last_x;
float _last_y = last_y;
while (size--) {
float phase_re = phase + _last_x * feedback.re;
float phase_im = phase + _last_y * feedback.im;
if (with_fm) {
float fm_mod = M_PI * 2.f * *fm++;
phase_re += fm_mod;
phase_im += fm_mod;
}
out->re = gain *
(cos(phase_re) - a * cos(phase_re - s) -
a1 * (cos(phase_re + s * a2) - a * cos(phase_re + n * s))) /
(a3 - a4 * cos(s));
out->im = gain *
(sin(phase_im) - a * sin(phase_im - s) -
a1 * (sin(phase_im + s * a2) - a * sin(phase_im + n * s))) /
(a3 - a4 * cos(s));
out++;
phase += incr;
s += b * incr;
}
phase = fmodf(phase, M_PI * 2.f);
modPhase = fmodf(s, M_PI * 2.f);
last_x = _last_x;
last_y = _last_y;
}
template <>
template <bool with_fm>
void DiscreteSummationOscillator<DSF2>::render(
size_t size, float* fm, ComplexFloat* out) {
float a1 = (1.f + a * a);
float a2 = 2.f * a;
float gain = (1.f - a);
float s = modPhase;
float _last_x = last_x;
float _last_y = last_y;
while (size--) {
float phase_re = phase + _last_x * feedback.re;
float phase_im = phase + _last_y * feedback.im;
if (with_fm) {
float fm_mod = M_PI * 2.f * *fm++;
phase_re += fm_mod;
phase_im += fm_mod;
}
_last_x =
gain * (cos(phase_re) - a * cos(phase_re - s)) / (a1 - a2 * cos(s));
out->re = _last_x;
_last_y =
gain * (sin(phase_im) - a * sin(phase_im - s)) / (a1 - a2 * cos(s));
out->im = _last_y;
out++;
phase += incr;
s += b * incr;
}
phase = fmodf(phase, M_PI * 2.f);
modPhase = fmodf(s, M_PI * 2.f);
last_x = _last_x;
last_y = _last_y;
}
template <>
template <bool with_fm>
void DiscreteSummationOscillator<DSF3>::render(
size_t size, float* fm, ComplexFloat* out) {
float a1 = powf(a, n + 1.f);
float a2 = n + 1.f;
float a3 = 1.f + a * a;
float a4 = 2.f * a;
float gain = (a - 1.f) / (2 * a1 - a - 1.f);
float s = modPhase;
float _last_x = last_x;
float _last_y = last_y;
while (size--) {
float phase_re = phase + _last_x * feedback.re;
float phase_im = phase + _last_y * feedback.im;
if (with_fm) {
float fm_mod = M_PI * 2.f * *fm++;
phase_re += fm_mod;
phase_im += fm_mod;
}
float b1 = 1.f / (a3 - a4 * cos(s));
_last_x = gain *
(cos(phase_re) - a * cos(phase_re - s) -
a1 * (cos(phase_re + s * a2) - a * cos(phase_re + n * s))) *
b1;
out->re = _last_x;
_last_y = gain *
(sin(phase_im) - a * sin(phase_im - s) -
a1 * (sin(phase_im + s * a2) - a * sin(phase_im + n * s))) *
b1;
out->im = _last_y;
out++;
phase += incr;
s += b * incr;
}
phase = fmodf(phase, M_PI * 2.f);
modPhase = fmodf(s, M_PI * 2.f);
last_x = _last_x;
last_y = _last_y;
}
template <>
template <bool with_fm>
void DiscreteSummationOscillator<DSF4>::render(
size_t size, float* fm, ComplexFloat* out) {
float a1 = 1.f - a * a;
float a2 = 1.f + a * a;
float a3 = 2.f * a;
float gain = (1.f - a) / (1.f + a);
float s = modPhase;
float _last_x = last_x;
float _last_y = last_y;
while (size--) {
float phase_re = phase + _last_x * feedback.re;
float phase_im = phase + _last_y * feedback.im;
if (with_fm) {
float fm_mod = M_PI * 2.f * *fm++;
phase_re += fm_mod;
phase_im += fm_mod;
}
float b1 = 1.f / (a2 - a3 * cos(s));
_last_x = gain * a1 * cos(phase_re) * b1;
out->re = _last_x;
_last_y = gain * a1 * sin(phase_im) * b1;
out->im = last_y;
out++;
phase += incr;
s += b * incr;
}
phase = fmodf(phase, M_PI * 2.f);
modPhase = fmodf(s, M_PI * 2.f);
last_x = _last_x;
last_y = _last_y;
}
#endif
| true |
13b6015a79e8fd5f00f05e5f0b01e3f3c09b9435 | C++ | ctrimble98/Solitaire | /source/heuristic.cpp | UTF-8 | 7,797 | 2.890625 | 3 | [] | no_license | #include "heuristic.h"
int Heuristic::run(Klondike game, Move move) {
return fcn(game, move, score);
}
int Heuristic::getScore() {
return score;
}
Heuristic::Heuristic(HeuristicType type, int score) : score(score) {
switch (type) {
case FOUNDATION:
fcn = foundationHeur;
break;
case REVEAL_HIDDEN:
fcn = revealHiddenHeur;
break;
case PLAN_REVEAL_HIDDEN:
fcn = planRevealHiddenHeur;
break;
case EMPTY_SPACE_NO_KING:
fcn = emptyNoKingHeur;
break;
case STOCK_SAFE:
fcn = scoreSafeStockMove;
break;
case STOCK_DISTANCE:
fcn = scoreStockDistanceMove;
break;
case SMOOTH:
fcn = scoreSmoothMove;
break;
case TABLEAU:
fcn = scoreTableauMove;
break;
}
}
bool operator> (Heuristic h1, Heuristic h2) {
return h1.score > h2.score;
}
int foundationHeur(Klondike game, Move move, int score) {
if (move.getEnd()[0] == static_cast<int>(CardLocation::FOUNDATION)) {
if (getSafeFoundation(game, move)) {
return SAFE_SCORE;
}
return score;
} else {
return 0;
}
}
int revealHiddenHeur(Klondike game, Move move, int score) {
if (move.getStart()[0] == static_cast<int>(CardLocation::TABLEAU) && move.getStart()[2] > 0 && game.getTableau()[move.getStart()[1]][move.getStart()[2] - 1].isFaceDown()) {
return score + move.getStart()[2];
} else {
return 0;
}
}
int planRevealHiddenHeur(Klondike game, Move move, int score) {
if (move.getStart()[0] == static_cast<int>(CardLocation::STOCK) && move.getEnd()[0] == static_cast<int>(CardLocation::TABLEAU) && move.getEnd()[2] > 0) {
int tempScore = checkFutureStock(game, move);
if (tempScore > 0) {
return score - tempScore;
}
}
return 0;
}
int emptyNoKingHeur(Klondike game, Move move, int score) {
if (checkNothingMove(game, move)) {
return score;
} else {
return 0;
}
}
int scoreTableauMove(Klondike game, Move move, int score) {
if (move.getStart()[0] == static_cast<int>(CardLocation::TABLEAU)) {
return score;
}
return 0;
}
int scoreSafeStockMove(Klondike game, Move move, int score) {
if (move.getStart()[0] == static_cast<int>(CardLocation::STOCK) && game.getStockPointer() + 1 % game.getDeal() == 0 && move.getStart()[2] == (int)game.getStock().size() - 1) {
return score;
}
return 0;
}
int scoreStockDistanceMove(Klondike game, Move move, int score) {
if (move.getStart()[0] == static_cast<int>(CardLocation::STOCK) && game.getStockPointer() + 1 % game.getDeal() == 0 && move.getStart()[2] != (int)game.getStock().size() - 1) {
return score * move.getStart()[2]/(int)game.getStock().size();
}
return 0;
}
int scoreSmoothMove(Klondike game, Move move, int score) {
if (move.getEnd()[0] == static_cast<int>(CardLocation::TABLEAU) && move.getEnd()[2] >= 2 && game.getTableau()[move.getEnd()[1]][move.getEnd()[2] - 2].getSuit() == move.getCard().getSuit()) {
return score;
}
return 0;
}
bool getSafeFoundation(Klondike game, Move move) {
std::array<int, 2> minFoundation = getFoudationMin(game);
if (move.getEnd()[0] == static_cast<int>(CardLocation::FOUNDATION) && ((move.getCard().getColour() == Colour::RED && move.getCard().getRank() <= minFoundation[1] + 2) || (move.getCard().getColour() == Colour::BLACK && move.getCard().getRank() <= minFoundation[0] + 2))) {
return true;
}
return false;
}
int checkFutureStock(Klondike game, Move move) {
if (move.getStart()[0] == static_cast<int>(CardLocation::STOCK) && move.getEnd()[0] == static_cast<int>(CardLocation::TABLEAU)) {
int minDiff = 13;
Card destCard = game.getTableau()[move.getEnd()[1]][move.getEnd()[2] - 1];
for (int i = 0; i < STACKS; i++) {
std::vector<Card> stack = game.getTableau()[i];
if (stack.empty()) {
continue;
}
int stackSize = stack.size();
Card card = stack.back();
std::vector<Card> v;
if (stackSize >= 2 && stack[stackSize - 2].isFaceDown() && card.getRank() <= 11) {
if (destCard.getRank() >= card.getRank() + 2) {
int diff = destCard.getRank() - card.getRank();
if (diff < minDiff) {
bool evenSplit = diff% 2 == 0;
bool sameColour = card.getColour() == destCard.getColour();
if (evenSplit == sameColour) {
minDiff = diff;
}
}
}
}
}
if (minDiff < 13) {
bool foundAll = true;
int target = 2;
while (target < minDiff) {
Colour targetColour = (target % 2 == 0) == (destCard.getColour() == Colour::RED) ? Colour::RED : Colour::BLACK;
if (!findCardInStock(game, destCard.getRank() - target, targetColour)) {
foundAll = false;
break;
}
target++;
}
if (foundAll) {
return minDiff;
}
}
}
return 0;
}
bool findCardInStock(Klondike game, int rank, Colour colour) {
for (auto &card: game.getStock()) {
if (card.getRank() == rank && card.getColour() == colour) {
return true;
}
}
return false;
}
std::array<int, 2> getFoudationMin(Klondike game) {
std::array<std::stack<Card>, 4> foundation = game.getFoundation();
std::array<int, 2> min = {CARDS_PER_SUIT, CARDS_PER_SUIT};
int i = 0;
while (i < 2) {
if (foundation[i].empty()) {
min[0] = 0;
} else if (foundation[i].top().getRank() < min[0]) {
min[0] = foundation[i].top().getRank();
}
i++;
}
while (i < 4) {
if (foundation[i].empty()) {
min[1] = 0;
} else if (foundation[i].top().getRank() < min[1]) {
min[1] = foundation[i].top().getRank();
}
i++;
}
return min;
}
int checkFutureHidden(Klondike game, Move move) {
for (int i = 0; i < STACKS; i++) {
if (game.getTableau()[i].size() >= 2 && game.getTableau()[i].back().getRank() == move.getCard().getRank() - 1 && game.getTableau()[i].back().getColour() != move.getCard().getColour() && game.getTableau()[i][game.getTableau()[i].size() - 2].isFaceDown()) {
return game.getTableau()[i].size();
}
}
return 0;
}
bool checkNothingMove(Klondike game, Move move) {
if (move.getStart()[0] == static_cast<int>(CardLocation::TABLEAU) && move.getStart()[2] == 0) {
//If the move is just shifting a king then it is a nothing move
if (move.getCard().getRank() == 13) {
if (move.getEnd()[0] == static_cast<int>(CardLocation::TABLEAU) && move.getEnd()[2] == 0) {
return true;
}
return false;
}
int n = game.getStock().size();
for (int i = 0; i < n; i++) {
if (game.getStock()[i].getRank() == 13) {
return false;
}
}
for (int i = 0; i < STACKS; i++) {
int j = game.getTableau()[i].size() - 1;
while (j >= 0 && !game.getTableau()[i][j].isFaceDown()) {
j--;
}
j++;
if (j > 0 && game.getTableau()[i][j].getRank() == 13) {
return false;
}
}
return true;
}
return false;
}
| true |
90c84fc1f5f6b9b094a58cf17eb61ab5bd2d9e13 | C++ | quantumsteve/SpinWaveGenie | /libSpinWaveGenie/src/Containers/HKLDirections.cpp | UTF-8 | 724 | 2.765625 | 3 | [
"BSD-2-Clause"
] | permissive | //
// HKLDirection.cpp
// spin_wave_genie
//
// Created by Hahn, Steven E. on 5/22/14.
//
//
#include "SpinWaveGenie/Containers/HKLDirections.h"
namespace SpinWaveGenie
{
void HKLDirections::addDirection(double v0, double v1, double v2, double delta)
{
Axis direction;
direction.v0 = v0;
direction.v1 = v1;
direction.v2 = v2;
direction.delta = delta;
integrationDirections.push_back(direction);
}
void HKLDirections::addDirection(int direction, double delta)
{
double v0 = 0.0, v1 = 0.0, v2 = 0.0;
switch (direction)
{
case 0:
v0 = 1.0;
break;
case 1:
v1 = 1.0;
break;
case 2:
v2 = 1.0;
break;
}
this->addDirection(v0, v1, v2, delta);
}
} // namespace SpinWaveGenie | true |
44cc7abc2b05dc5b810916d2662777ea1bbc4a13 | C++ | makio93/atcoder | /OtherSites/LeetCode/explore/challenge/february-leetcoding-challenge-2021/week-4-february-22nd-february-28th/Day27/main.cpp | UTF-8 | 923 | 2.90625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int divide(int dividend, int divisor) {
long long dividend2 = dividend, divisor2 = divisor;
if (divisor2 < 0) {
dividend2 = -dividend2;
divisor2 = -divisor2;
}
bool neg = (dividend2 < 0LL);
if (neg) dividend2 = -dividend2;
long long res = 0LL;
for (int i=31; i>=0; --i) {
long long sub = divisor2<<i;
while (dividend2 - sub >= 0) {
dividend2 -= sub;
res += 1LL<<i;
}
}
if (neg) res = -res;
if (res<(-(1LL<<31)) || res>(1LL<<31)-1) res = (1LL<<31)-1;
return (int)(res);
}
};
int main(){
Solution cl;
int dividend, divisor;
cin >> dividend >> divisor;
cout << cl.divide(dividend, divisor) << endl;
return 0;
}
| true |
ebbc59064a07362194705f3ca3147768c7a432f8 | C++ | ImagineMiracle-wxn/Book_Management_System | /图书馆管理系统/Book.cpp | GB18030 | 5,430 | 3.21875 | 3 | [] | no_license | #include "Book.h"
Book * Library = NULL;
Book::Book(const string name, const string id, const string press, const string author, const unsigned int num)
{
next = NULL;
Name = name;
ID = id;
Press = press;
Author = author;
Nums = num;
if (Library)
{
Book * p = Get_Library_Index();
while (p->Next())
{
p = p->Next();
}
p->Set_Next(this);
}
}
Book * Book::Next()
{
return next;
}
void Book::Set_Next(Book * const p)
{
next = p;
}
string Book::Get_Book_Name(void)
{
return Name;
}
string Book::Get_Book_ID(void)
{
return ID;
}
string Book::Get_Book_Press(void)
{
return Press;
}
string Book::Get_Book_Author(void)
{
return Author;
}
unsigned int Book::Get_Book_Nums(void)
{
return Nums;
}
void Book::Set_Book_Name(const string name)
{
Name = name;
}
void Book::Set_Book_ID(const string id)
{
ID = id;
}
void Book::Set_Book_Press(const string press)
{
Press = press;
}
void Book::Set_Book_Author(const string author)
{
Author = author;
}
void Book::Set_Book_Nums(const unsigned int num)
{
Nums = num;
}
void Book::Show_Oneself_Detail(void)
{
cout << " ID : " << std::left << setw(5) << ID << " ";
cout << "Name : " << std::left << setw(15) << Name << " ";
cout << "Press : " << std::left << setw(15) << Press << " ";
cout << "Author : "<< std::left << setw(8) << Author << " ";
cout << "Nums : " << std::left << setw(5) << Nums << endl;
}
void Init_Book_List(void)
{
Library = new Book();
}
Book * Get_Library_Index(void)
{
return Library;
}
void Sort_Book_List(void)
{
for (Book * i = Get_Library_Index(); i->Next() != NULL; i = i->Next())
{
for (Book * j = i->Next(); j->Next() != NULL; j = j->Next())
{
if (i->Next()->Get_Book_ID() > j->Next()->Get_Book_ID())
{
string book_id_tmp = i->Next()->Get_Book_ID();
string book_name_tmp = i->Next()->Get_Book_Name();
string book_press_tmp = i->Next()->Get_Book_Press();
string book_author_tmp = i->Next()->Get_Book_Author();
unsigned int book_nums_tmp = i->Next()->Get_Book_Nums();
i->Next()->Set_Book_ID(j->Next()->Get_Book_ID());
i->Next()->Set_Book_Name(j->Next()->Get_Book_Name());
i->Next()->Set_Book_Press(j->Next()->Get_Book_Press());
i->Next()->Set_Book_Author(j->Next()->Get_Book_Author());
i->Next()->Set_Book_Nums(j->Next()->Get_Book_Nums());
j->Next()->Set_Book_ID(book_id_tmp);
j->Next()->Set_Book_Name(book_name_tmp);
j->Next()->Set_Book_Press(book_press_tmp);
j->Next()->Set_Book_Author(book_author_tmp);
j->Next()->Set_Book_Nums(book_nums_tmp);
}
}
}
}
int Auto_Allot_BookID(void)
{
Book * p = Get_Library_Index();
int Book_ID = 0;
Sort_Book_List();
if (Get_Library_Index()->Next())
{
while (p->Next())
{
if (p->Next()->Next())
{
if ((atoi(p->Next()->Get_Book_ID().c_str()) + 1) != atoi(p->Next()->Next()->Get_Book_ID().c_str()))
{
Book_ID = atoi(p->Next()->Get_Book_ID().c_str()) + 1;
return Book_ID;
}
}
p = p->Next();
}
istringstream iss(p->Get_Book_ID());
iss >> Book_ID;
Book_ID++;
return Book_ID;
}
else
{
Book_ID = 0;
return Book_ID;
}
}
void Add_Book_to_Library(const string name, const string press, const string author, const unsigned int num)
{
stringstream id;
id << Auto_Allot_BookID();
Book * p = new Book(name, id.str(), press, author, num);
}
void Del_Book_from_Library_By_Name(const string name)
{
Book * p = Get_Library_Index();
while (p->Next())
{
if (p->Next()->Get_Book_Name() == name)
{
Book * tmp = p->Next();
p->Set_Next(p->Next()->Next());
delete tmp;
break;
}
p = p->Next();
}
}
void Del_Book_from_Library_By_ID(const string ID)
{
Book * p = Get_Library_Index();
while (p->Next())
{
if (p->Next()->Get_Book_ID() == ID)
{
Book * tmp = p->Next();
p->Set_Next(p->Next()->Next());
delete tmp;
break;
}
p = p->Next();
}
}
Book * Seach_in_Library_By_Name(const string name)
{
Book * p = Get_Library_Index();
while (p->Next())
{
if (p->Next()->Get_Book_Name() == name)
{
return p->Next();
}
p = p->Next();
}
return NULL;
}
void Seach_in_Library_By_Name(const string name, const int n)
{
Book * p = Get_Library_Index();
int flag = 0;
string::size_type idx = string::npos;
while (p->Next())
{
idx = p->Next()->Get_Book_Name().find(name);
if (idx != string::npos)
{
flag++;
idx = string::npos;
p->Next()->Show_Oneself_Detail();
}
p = p->Next();
}
if (flag == 0)
{
cout << "δҵϢ!!!" << endl;
}
}
Book * Seach_in_Library_By_ID(const string id)
{
Book * p = Get_Library_Index();
while (p->Next())
{
if (p->Next()->Get_Book_ID() == id)
{
return p->Next();
}
p = p->Next();
}
return NULL;
}
void Show_Books_Detail_in_Library(void)
{
Book * p = Get_Library_Index();
Sort_Book_List();
bool flag = true;
while (p->Next())
{
flag = false;
cout << " ID : " << std::left << setw(5) << p->Next()->Get_Book_ID() << " ";
cout << "Name : " << std::left << setw(15) << p->Next()->Get_Book_Name() << " ";
cout << "Press : " << std::left << setw(15) << p->Next()->Get_Book_Press() << " ";
cout << "Author : "<< std::left << setw(8) << p->Next()->Get_Book_Author() << " ";
cout << "Nums : " << std::left << setw(5) << p->Next()->Get_Book_Nums() << endl;
p = p->Next();
}
if (flag)
{
cout << "----------ǰûκͼϢ!!!" << endl;
}
} | true |
f09c9042b67983d3fc26bb3eb3fb3c9d41892e3b | C++ | acrord/algorithm_study | /iter/heap.cpp | UTF-8 | 837 | 2.921875 | 3 | [] | no_license | #include <string>
#include <vector>
#include <deque>
#include <queue>
#include <iostream>
#include <sstream>
#include <iterator>
using namespace std;
vector<int> solution(vector<string> operations) {
string str = "This is a string";
istringstream buf(str);
istream_iterator<std::string> beg(buf), end;
vector<string> tokens(beg, end); // done!
vector<int> answer;
deque<string> op;
queue<int> que;
while(!op.empty()){
string operation = op.front();
op.pop_front();
switch(operation[0]){
case "I":
// cout<<<<endl;
// que.push(strtok(operation, "I "));
cout<<que.front()<<endl;
break;
case "D": break;
}
}
return answer;
} | true |
8ff191181e84d516c30b6b0940826349e28f3e4c | C++ | vikram7599/Cpp-Codes | /SumKOrderN.cpp | UTF-8 | 653 | 3.453125 | 3 | [] | no_license | #include <iostream>
#include<unordered_map>
using namespace std;
int countPairs(int *arr, int n, int k){
unordered_map<int, int> omap;
int i, twice_count =0 ;
for(i=0; i<n; i++){
omap[arr[i]]++;
}
for(i=0; i<n; i++){
twice_count += omap[k-arr[i]];
if(k-arr[i] == arr[i]){
twice_count--;
}
}
return (twice_count/2);
}
int main() {
//code
int t;
cin >> t;
while(t--){
int n, k;
cin >> n >> k;
int arr[n];
int i;
for(i=0; i<n; i++){
cin >> arr[i];
}
int ans = countPairs(arr,n, k);
cout << ans <<endl;
}
return 0;
}
| true |
49bcd960c6e6c87552ded3d3cb7d135d6e404e5d | C++ | jt2603099/ThavisayJohnny_CSC5_42480 | /Hmwk/Assignment_4/Savitch_9thEd_Ch4_PracProg_3/main.cpp | UTF-8 | 2,168 | 3.6875 | 4 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: main.cpp
* Author: jt2603099
* Find out the value of your stock
* Created on April 7, 2018, 5:46 PM
*/
#include <iostream>
#include <cstdlib>
//Function Declaration of sPrice
int sPrice(int stocks, int whole, int numer, int denom);
//Computes value of a user's stock. 1st parameter is total number of stocks.
//Whole = Whole-Dollar price of stock.
//Numer = numerator, and denom = denominator for the fraction portion.
using namespace std;
int main(int argc, char** argv) {
//Declare variables
int stock, x, y, z, stockval;//stock=total shares of stock, x=whole, y=numerator, z=denominator, stockval = stock value
char ans('y');//Set ans to y to start the loop
do {
//Start of program
//Gather inputs
cout << "Enter the total of owned shares." <<endl;
cin >> stock;
cout << "Enter the whole-dollar portion of the price." <<endl;
cin >> x;
cout << "Enter the numerator for the fraction portion of the price." <<endl;
cin >> y;
cout << "Enter the denominator for the fraction portion of the price." <<endl;
cin >> z;
//Function call of sPrice
stockval = sPrice(stock, x, y, z);
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(3);
//Display outputs from inputs
cout << "The value of your stock is " << stockval << "." <<endl;
//Output to continue loop?
cout << "Try another?: ";
cin >> ans;
} while (ans == 'y' || ans == 'Y');
//End of loop
//Function Closing Output
cout << "Goodbye." <<endl;
return 0;
}
//Function definition for sPrice
int sPrice(int stock, int whole, int numer, int denom)
{
double fraction;//fraction to compute stock
double realval;//Real value of the stock
fraction = whole + (static_cast<double>(numer)/denom);
realval = stock * fraction;
return realval;
}
| true |
155c5c403a0e0059f2c9c31c7a7a6c966626ff5c | C++ | AK2001/Video-management-application | /Management Application/main_runner.cpp | UTF-8 | 2,016 | 2.96875 | 3 | [] | no_license |
#include <cmath>
#include "videodata.h"
#include "vectordata.h"
#include "gui.h"
#include "functions.h"
int main() {
cout<<"----------------------------------------------CourseWork-----------------------------------------------\n"
<<endl;
//Note: don't force close
//The app saves in .txt when case is 0
VectorVideoData videos; //Creats an object of the VectorVideoData class. NOTE: .data is the vector
//videos is going to be used in order to save into .txt file and videos.data in memory
VideoData a("First Video","11/5/2020",42.3,700,"|","|","|");//The first 3 default videos as VideoData objects
VideoData b("Second Video","9/9/2001",11.2,1070,"|","|","|");//NOTE: <"|"> is only for decoration purposes and can be changed
VideoData c("Third Video","24/1/2019",6.5,1230,"|","|","|");
videos.data.push_back(a);//Adding the first 3 video objects to the videos vector
videos.data.push_back(b);
videos.data.push_back(c);
Gui gui;
VideoData newVideo;//Used in Case 2
int index;
while(1){
int choice=gui.menu();
switch(choice){
case 1: cout<<"You selected to search "<<endl;
videosSearcher(videos);
break;
case 2: cout<<"You selected to add a video"<<endl;
videos.data.push_back(read(newVideo));//Adds a new object to the vector videos (it saves objects in memory)
break;
case 3: cout<<"You selected to remove a video"<<endl;
index=unwantedVideoIndex(videos);
if(index>=0){
videos.data.erase(videos.data.begin()+index);
}
break;
case 4: cout<<"You selected to view the videos"<<endl;
videoListShower(videos);
break;
case 5: cout<<"You selected to view the stats"<<endl;
statsShower(videos);
break;
case 0:
default:cout<<"You selected to exit"<<endl;
videos.save("videos.txt");//Creates and writes all the video objects to a .txt file
videos.populate("videos.txt");
return 0;
}
}
}
| true |
a103da65c5e694f6d51b1f7bd9d3d97cce036d9c | C++ | blambov/RealLib | /manual/harm.cpp | UTF-8 | 1,323 | 2.984375 | 3 | [
"Apache-2.0"
] | permissive | #include <iostream>
#include <iomanip>
#include <ctime>
#include "Real.h"
using namespace RealLib;
using namespace std;
#define LENGTH 1000000
#define MACROTOSTRING2(x) # x
#define MACROTOSTRING(x) MACROTOSTRING2(x)
Real Harmonic(const long mcnt)
{
Real one(1);
Real s(0.0);
for (int i=1; i<=mcnt; ++i) {
s += one/i;
}
return s;
}
int main()
{
clock_t starttime, endtime;
cout << "Computing the sum for " MACROTOSTRING(LENGTH) " members" << endl;
starttime = clock();
InitializeRealLib();
{
Real h(Harmonic(LENGTH));
endtime = clock();
cout << "construction time: " <<
double(endtime - starttime) / CLOCKS_PER_SEC << endl;
for (int n=8; n<500; n*=7) {
starttime = clock();
cout << unitbuf << setprecision(n);
cout << n <<" digits: \t" << h << endl;
endtime = clock();
cout << setprecision(6);
cout << "prec: " << GetCurrentPrecision() << " time elapsed: " <<
double(endtime - starttime) / CLOCKS_PER_SEC << endl;
}
starttime = clock();
}
FinalizeRealLib();
endtime = clock();
cout << "destruction time: " <<
double(endtime - starttime) / CLOCKS_PER_SEC << endl;
return 0;
}
| true |
ee327ac1f1d2e85e0b103937446d715c390a2b80 | C++ | TakuyaKimura/Leetcode | /259 3Sum Smaller/259.cpp | UTF-8 | 1,093 | 3.703125 | 4 | [] | no_license | /*
Given an array of n integers nums and a target, find the number of index triplets i, j, k
with 0 <= i < j < k < n that satisfy the condition nums[i] + nums[j] + nums[k] < target.
For example, given nums = [-2, 0, 1, 3], and target = 2.
Return 2. Because there are two triplets which sums are less than 2:
[-2, 0, 1]
[-2, 0, 3]
Follow up:
Could you solve it in O(n2) runtime?
*/
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
int threeSumSmaller(vector<int>& nums, int target) {
sort(nums.begin(), nums.end());
int n = nums.size(), first, result = 0;
for (int i = 0; i < n - 2; ++i)
{
first = nums[i];
for (int j = i + 1, k = n - 1; j < k;)
{
if (first + nums[j] + nums[k] < target)
{
result += k - j; // the third number could be any of the nums[j + 1] ... nums[k]
++j;
}
else
--k;
}
}
return result;
}
}; | true |
75d84b974199c0879d589226eabe672330b2f09a | C++ | afif95/Programming_problem | /SPOJ/ETF - Euler Totient Function.cpp | UTF-8 | 511 | 2.890625 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int totient(int n)
{
int ret=n;
if(!(n%2)){
while(!(n%2))
{
n/=2;
}
ret-=ret/2;
}
for(int i=3;i*i<=n;i+=2)
{
if(!(n%i)){
while(!(n%i))
{
n/=i;
}
ret-=ret/i;
}
}
if(n>1)
{
ret-=ret/n;
}
return ret;
}
int main()
{
int n,t;
cin>>t;
while(t--)
{
cin>>n;
cout<<totient(n)<<endl;
}
return 0;
}
| true |
4d003224b8392cacd4c072fbf68697047a009acf | C++ | AngelRodriguez319/CompetitiveProgramming | /Codeforces/GeneralProblems/200B.cpp | UTF-8 | 295 | 2.625 | 3 | [] | no_license | #include <iostream>
using namespace std;
// Author: Angel Gabriel Rodriguez
// Date: March / 100 / 2021
// https://codeforces.com/problemset/problem/200/B
int main(){
int prov = 0, n, i;
float sum = 0;
cin >> n;
for(i = 0; i < n; i++){
cin >> prov;
sum += prov;
}
cout << sum/n << endl;
return 0;
} | true |
cdd765c437e626363799c283a4961c860156d46e | C++ | MrGodin67/New3d | /New3D/New3D/Player.h | UTF-8 | 1,917 | 2.515625 | 3 | [] | no_license | #pragma once
#include "Camera3D_2.h"
#include <DirectXMath.h>
struct PlayerAmmo
{
DirectX::XMVECTOR pos;
DirectX::XMVECTOR vel;
DirectX::XMVECTOR collisionPt;
DirectX::XMFLOAT3 mat_scale = {1.0f,1.0f,1.0f};
DirectX::XMMATRIX mat_rot;
float speed;
float lifeSpan = 1.0f;
float timer = 0.0f;
bool active = true;
float rotation = 0.0f;
DirectX::XMMATRIX GetMatrix();
void update(float dt, DirectX::XMFLOAT3 playerPos);
};
struct Gun
{
DirectX::XMVECTOR pos;
DirectX::XMVECTOR vel;
float speed = 10.0f;
float sideOffset;
float timer = 0.0f;
float shotDelay;
bool canShoot = true;
Gun(float side_offset)
:sideOffset(side_offset)
{}
void update(float dt,DirectX::XMMATRIX mat)
{
(timer += dt) > shotDelay ? canShoot = true : canShoot = false;
pos = XMVector3TransformCoord(DirectX::XMVectorSet(sideOffset, 0.0f, 0.15f, 1.0f), XMMatrixInverse(&DirectX::XMVectorSet(0.0f, 0.0f, 0.0f, 1.0f), mat));
}
void setTarget(DirectX::XMVECTOR targetPos)
{
vel = DirectX::XMVector3Normalize(DirectX::XMVectorSubtract(pos, targetPos));
}
bool fireShot(PlayerAmmo& ammo)
{
if (canShoot)
{
ammo.lifeSpan = 3.0f;
ammo.pos = pos;
ammo.vel = vel;
ammo.speed = speed;
ammo.active = true;
ammo.mat_scale = { 0.1f,0.1f,0.1f };
timer = 0.0f;
return true;
}
return false;
}
};
class Player
{
private:
CFirstPersonCamera& m_cam;
float m_heightOffTerrain = 0.25f;
Gun m_leftGun;
Gun m_rightGun;
int leftShots = 0;
int rightShots = 0;
float timer = 0.0f;
float gunShotInterval = 1.0f;
bool flipShot = false;
public:
Player(CFirstPersonCamera& cam)
:m_cam(cam),m_leftGun(-0.15f),m_rightGun(0.15f)
{
m_leftGun.shotDelay = m_rightGun.shotDelay = 0.75f;
}
void Update(float dt, class Terrain* terrain,bool doShot);
void SetHeight(float height);
void RenderDebugStats(class Graphics& gfx, size_t n_ammo);
PlayerAmmo FireShot(DirectX::XMVECTOR target);
}; | true |
bdd44171dc524cd00832bdd99af2b4da6043dcda | C++ | geeklhem/spopdyn | /spopdyn/libpssa/libpssa/include/sampling/SamplingModule_PSSACR.h | UTF-8 | 1,089 | 2.5625 | 3 | [] | no_license | /**
* \file SamplingModule_PSSACR.h
* \copybrief SamplingModule.h
*
* \date 22.02.2011
* \author sanyi
*/
#ifndef SAMPLINGMODULE_PSSACR_H_
#define SAMPLINGMODULE_PSSACR_H_
#include "./SamplingModule_PDM.h"
#include "./CompositionRejectionSampler.h"
namespace pssalib
{
namespace sampling
{
/**
* \class SamplingModule_PSSACR
* \brief Purpose of this class is to sample reaction index and time for the Partial Propensity Direct Method with Compositio-Rejection sampling.
*
* \copydetails SamplingModule
*/
class SamplingModule_PSSACR : public SamplingModule_PDM
{
////////////////////////////////
// Attributes
protected:
CompositionRejectionSampler crSampler;
////////////////////////////////
// Constructors
public:
// Default Constructor
SamplingModule_PSSACR();
// Destructor
virtual ~SamplingModule_PSSACR();
//////////////////////////////
// Methods
protected:
// Sample reaction index
virtual bool sample_reaction(pssalib::datamodel::SimulationInfo* ptrSimInfo);
};
}
}
#endif /* SAMPLINGMODULE_PSSACR_H_ */
| true |
d63fa3dd6aad73ccbbfdafe1200b9a7f291b0e83 | C++ | DoctorLai/ACM | /leetcode/724. Find Pivot Index/724-2.cpp | UTF-8 | 466 | 3.03125 | 3 | [] | no_license | // https://helloacm.com/how-to-find-pivot-index-of-array/
// https://leetcode.com/problems/find-pivot-index/
class Solution {
public:
int pivotIndex(vector<int>& nums) {
int sum = 0;
for (const auto &n: nums) sum += n;
int psum = 0;
for (int i = 0; i < nums.size(); ++ i) {
if (sum - psum - nums[i] == psum) {
return i;
}
psum += nums[i];
}
return -1;
}
};
| true |
901614c592878b401ef6e921b14b2dea67f7615f | C++ | warcin/PRozSzafy | /structs.h | UTF-8 | 2,441 | 3.125 | 3 | [] | no_license | #ifndef STRUCTSH
#define STRUCTSH
#include <vector>
#include "consts.h"
using namespace std;
void incLamportTime(int received); // increments / updates lamportTime to the highest (received or our local) + 1
void updateRequestTime(int time); // updates our data variable - see requestTime in Data
// communication is based around 3 integers sent in packets
typedef struct {
int lamportTime;
int resourceCount;
int resourceType;
} packet_t;
// resourceType: 0 = Elevator, 1 = Room
enum Resource {
ELEVATOR,
ROOM
};
// states that process can be in
enum State {
INIT,
SEARCHING_FOR_ROOM,
SEARCHING_FOR_ELEVATOR,
IN_ELEVATOR,
OCCUPYING,
IDLE
};
// communication uses only two types (tags) of messages
enum Message {
CHECK_STATE,
ANSWER_STATE
};
// collection of all data used by one process
class Data {
public:
State state;
int rank, size; // our rank and size of whole communication world
int lamportTime; // our current logical time
int requestTime; // our logical time of current request for resource - used for resolving who has higher priority (it's time process uses to broadcast CHECK_STATE)
int roomDemand; // how many rooms do we want for current state loop
vector<int> knownRoomOccupancies; //both Occupancies vectors hold information about global state known to us
vector<int> knownElevatorOccupancies;
vector<int> roomReservations; //both Reservations vectors hold information who should we inform that we stopped using resource we had reserved / priority to reserve - used with broadcastRelease method
vector<int> elevatorReservations;
bool occupyingRoom; // information whether process wants to get in or out of the room
void init(int rank, int size);
void resetOccupancies(); // method to clear both vectors
void broadcastCheckState(int type); // method used to broadcast our need to get type of resource - sends appropiate CHECK_STATE
void broadcastRelease(vector<int> recipents, int type); // method used to update other processes that might still want to get resource we reserved / had higher priority on - sends ANSWER_STATE with 0 as resourceCount
};
//helper method to resolve who has higher priority towards resource two processes compete to get - when the lamportTime is equal the process with lesser rank has priority
bool doWeHavePriority(int theirRank, int theirLamport, int ourLamport);
#endif | true |
39433bd8f3aff429062a9dc107ac1af3b6433e73 | C++ | itsss/SASA_ComputingBasics | /2017-1-exam(08)/E.cpp | UTF-8 | 183 | 2.75 | 3 | [] | no_license | #include <stdio.h>
int main()
{
int a;
do
{
scanf("%d", &a);
}
while(a < 1 || a >= 10);
{
for(int i = 1; i < 10; i++)
{
printf("%d * %d = %2d\n", a, i, a*i);
}
}
}
| true |
cdc48b3668594f4c91d425b1e4084806421a4563 | C++ | mohamedabdelhakem1/problem-solving---competitive-programing | /C. Two TVs/main.cpp | UTF-8 | 827 | 2.921875 | 3 | [] | no_license | #include <iostream>
#include<algorithm>
using namespace std;
int main() {
int n;
cin>>n;
pair <int,int > arr [n];
for(int i = 0 ; i < n; i++) {
cin>>arr[i].first>> arr[i].second ;
}
sort(arr,arr+n);
pair <int,int > tv1, tv2;
if(n <= 2) {
printf("YES");
} else {
tv1 = arr[0];
tv2 = arr[1];
int counter;
for(int i = 2 ; i < n ; i++) {
if(arr[i].first > tv1.second ) {
counter = i;
tv1 = arr[i];
} else if(arr[i].first > tv2.second ) {
counter = i ;
tv2 = arr[i];
} else {
printf("NO");
break;
}
}
if(counter == n-1) {
printf("YES");
}
}
return 0;
}
| true |
dbcc9588d24ee201e96c98e58b0a3c601ca667c3 | C++ | usiksan/SaliCAD | /src/windows/SdStringHistory.cpp | UTF-8 | 2,320 | 2.859375 | 3 | [] | no_license | /*
Project "Electronic schematic and pcb CAD"
Author
Sibilev Alexander S.
Web
www.saliLab.com
www.saliLab.ru
Description
Represent history of strings.
Support history limitation, recently used
*/
#include "SdStringHistory.h"
#include <QDebug>
SdStringHistory::SdStringHistory(int limit, int precision) :
mPrecision(precision),
mLimit(limit)
{
}
//Append string to history
int SdStringHistory::addString(const QString str)
{
//Test if string already present in history
int i = indexOf( str );
if( i >= 0 ) {
//String present
if( i > 0 ) {
//We need move str to first position in history
//Remove it from current position
removeAt( i );
//Insert string to first position
insert( 0, str );
}
}
else {
//Test if history is full
if( count() >= mLimit ) {
//History is full, remove last item
i = count() - 1;
removeAt( i );
}
insert( 0, str );
}
return i;
}
//Append string representation of double to history
//This function normalize string to double
//Return index which index must removed from history
int SdStringHistory::addDoubleString(const QString str)
{
QString db( str );
db.replace( QChar(','), QChar('.') );
return addDouble( db.toDouble() );
}
//Append double.
//Converted double to string representation and append as string
//Return index which index must removed from history
int SdStringHistory::addDouble(double val)
{
return addString( QString::number( val, 'f', mPrecision ) );
}
//Entered or selected new current string in combo box
//With this fucntion we reorder stringHistory itself and comboBox
void SdStringHistory::reorderComboBoxString(QComboBox *box)
{
QString str = box->currentText();
//qDebug() << "reorder" << str;
int i = addString( str );
if( i >= 0 )
box->removeItem( i );
box->insertItem( 0, str );
box->setCurrentText( str );
}
//Entered or selected new current string represented double in combo box
//With this fucntion we reorder stringHistory itself and comboBox
void SdStringHistory::reorderComboBoxDoubleString(QComboBox *box)
{
QString str = box->currentText();
int i = addDoubleString( str );
if( i >= 0 )
box->removeItem( i );
box->insertItem( 0, str );
box->setCurrentText( str );
}
| true |
10487bd8c14402e17a9805d57d48345f75deded7 | C++ | XessWaffle/radiocontroller | /Transmitter/Manager.cpp | UTF-8 | 923 | 3.03125 | 3 | [
"MIT"
] | permissive | #include "Manager.h"
Manager::Manager(char* designator, int managedPin, bool sticky){
_designator = designator;
_managedPin = managedPin;
_reversed = false;
_sticky = sticky;
_updateDelay = millis();
}
Manager::Manager(){
char buff[20];
sprintf(buff, "DEFAULT");
_designator = buff;
_managedPin = 0;
_sticky = false;
_currValue = 0;
}
int Manager::getManagedPin(){
return _managedPin;
}
void Manager::setManagedPin(int pin){
_managedPin = pin;
}
bool Manager::isSticky(){
return _sticky;
}
void Manager::setSticky(bool sticky){
_sticky = sticky;
}
bool Manager::isReversed(){
return _reversed;
}
void Manager::setReversed(bool reversed){
_reversed = reversed;
}
char* Manager::getDesignator(){
return _designator;
}
void Manager::printString(){
char buff[200];
sprintf(buff, "%s at pin %u set to %u", _designator, _managedPin, _currValue);
Serial.println(buff);
}
| true |
a94b524a8942847974fe69fecad85cbc3239bdd8 | C++ | ohz10/Dot-pp | /Dot++/tests/unit_test/Parser-ReadAttributeEqualState-UT.cpp | UTF-8 | 6,163 | 2.625 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-4-Clause",
"BSD-2-Clause"
] | permissive | #include "./platform/UnitTestSupport.hpp"
#include <Dot++/Exceptions.hpp>
#include <Dot++/NullConstructionPolicy.hpp>
#include <Dot++/lexer/TokenInfo.hpp>
#include <Dot++/parser/states/ReadAttributeEqualState.hpp>
#include <map>
#include <string>
#include <utility>
namespace {
using namespace dot_pp::lexer;
using namespace dot_pp::parser;
struct NullConstructionPolicy
{
void createGraph(const std::string&) {}
void createDigraph(const std::string&) {}
void createVertex(const std::string&) {}
void createEdge(const std::string&, const std::string&){}
void applyGraphAttribute(const std::string&, const std::string&){}
void applyVertexAttribute(const std::string&, const std::string&, const std::string&) {}
void applyEdgeAttribute(const std::string& v1, const std::string& v2, const std::string& attr, const std::string& value)
{
edgeAttributes.insert(std::make_pair(std::make_pair(std::make_pair(v1, v2), attr), value));
}
void finalize() {}
// key: ((v1, v2), attr)
std::map<std::pair<std::pair<std::string, std::string>, std::string>, std::string> edgeAttributes;
};
struct ReadAttributeEqualStateFixture
{
std::string edgeAttribute(const std::string& v1, const std::string& v2, const std::string& attribute)
{
const auto iter = constructor.edgeAttributes.find(std::make_pair(std::make_pair(v1, v2), attribute));
if(iter != constructor.edgeAttributes.end())
{
return iter->second;
}
throw std::runtime_error("Edge Attribute Key Not Found");
}
TokenStack attributes;
TokenStack stack;
NullConstructionPolicy constructor;
states::ReadAttributeEqualState<NullConstructionPolicy> state;
};
TEST_FIXTURE(ReadAttributeEqualStateFixture, verifyInstatiation)
{
}
TEST_FIXTURE(ReadAttributeEqualStateFixture, verifyTransitionsToReadLeftBracketOnString)
{
std::deque<TokenInfo> tokens;
// a -> b -> c -> d [ attribute = value ];
tokens.emplace_back(Token("a", TokenType::string), FileInfo("test.dot"));
tokens.emplace_back(Token("b", TokenType::string), FileInfo("test.dot"));
tokens.emplace_back(Token("c", TokenType::string), FileInfo("test.dot"));
tokens.emplace_back(Token("d", TokenType::string), FileInfo("test.dot"));
tokens.emplace_back(Token("attribute", TokenType::string), FileInfo("test.dot"));
tokens.emplace_back(Token("value", TokenType::string), FileInfo("test.dot"));
auto handle = tokens.cbegin();
stack.push(handle++);
stack.push(handle++);
stack.push(handle++);
stack.push(handle++);
attributes.push(handle++);
CHECK_EQUAL(1U, attributes.size());
CHECK_EQUAL(4U, stack.size());
CHECK_EQUAL(ParserState::ReadLeftBracket, state.consume(handle++, stack, attributes, constructor));
CHECK_EQUAL(0U, attributes.size());
CHECK_EQUAL(4U, stack.size());
REQUIRE CHECK_EQUAL(3U, constructor.edgeAttributes.size());
CHECK_EQUAL("value", edgeAttribute("a", "b", "attribute"));
CHECK_EQUAL("value", edgeAttribute("b", "c", "attribute"));
CHECK_EQUAL("value", edgeAttribute("c", "d", "attribute"));
}
TEST_FIXTURE(ReadAttributeEqualStateFixture, verifyTransitionsToReadLeftBracketOnStringLiteral)
{
std::deque<TokenInfo> tokens;
// a -> b -> c [ attribute = value ];
tokens.emplace_back(Token("a", TokenType::string), FileInfo("test.dot"));
tokens.emplace_back(Token("b", TokenType::string), FileInfo("test.dot"));
tokens.emplace_back(Token("c", TokenType::string), FileInfo("test.dot"));
tokens.emplace_back(Token("attribute", TokenType::string), FileInfo("test.dot"));
tokens.emplace_back(Token("value", TokenType::string_literal), FileInfo("test.dot"));
auto handle = tokens.cbegin();
stack.push(handle++);
stack.push(handle++);
stack.push(handle++);
attributes.push(handle++);
CHECK_EQUAL(1U, attributes.size());
CHECK_EQUAL(3U, stack.size());
CHECK_EQUAL(ParserState::ReadLeftBracket, state.consume(handle++, stack, attributes, constructor));
CHECK_EQUAL(0U, attributes.size());
CHECK_EQUAL(3U, stack.size());
REQUIRE CHECK_EQUAL(2U, constructor.edgeAttributes.size());
CHECK_EQUAL("value", edgeAttribute("a", "b", "attribute"));
CHECK_EQUAL("value", edgeAttribute("b", "c", "attribute"));
}
TEST_FIXTURE(ReadAttributeEqualStateFixture, verifyThrowsOnInvalidTokens)
{
std::deque<TokenInfo> tokens;
tokens.emplace_back(Token("keyword", TokenType::keyword), FileInfo("test.dot"));
tokens.emplace_back(Token("edge", TokenType::edge), FileInfo("test.dot"));
tokens.emplace_back(Token("directed_edge", TokenType::directed_edge), FileInfo("test.dot"));
tokens.emplace_back(Token("l_paren", TokenType::l_paren), FileInfo("test.dot"));
tokens.emplace_back(Token("r_paren", TokenType::r_paren), FileInfo("test.dot"));
tokens.emplace_back(Token("l_bracket", TokenType::l_bracket), FileInfo("test.dot"));
tokens.emplace_back(Token("r_bracket", TokenType::r_bracket), FileInfo("test.dot"));
tokens.emplace_back(Token(";", TokenType::end_statement), FileInfo("test.dot"));
tokens.emplace_back(Token("blah blah", TokenType::comment), FileInfo("test.dot"));
tokens.emplace_back(Token("blah \n blah", TokenType::multiline_comment), FileInfo("test.dot"));
for(auto handle = tokens.cbegin(), end = tokens.cend(); handle != end; ++handle)
{
CHECK_THROW(state.consume(handle, stack, attributes, constructor), dot_pp::SyntaxError);
}
}
}
| true |
43b5a28865681e6596e109d92ab12d4b35d9f3bc | C++ | JeckyllIsHyde/sim-methods-for-physics | /clase20171017/AutomatasContinuos.cpp | UTF-8 | 1,850 | 3.28125 | 3 | [] | no_license | #include <iostream>
#include <cmath>
using namespace std;
const int Lx=200;
const double p=0.5;
class LatticeGas {
private:
int v[2]; // V[i] con i=0, derecha y i=1 izquierda
double n[Lx][2], nnew[Lx][2]; // n[ix][i]: la probabilidad de q se encuentre una bolita en una posicion
public:
LatticeGas(void);
void inicie(double mu, double sigma);
void muestre(void);
void colisione(void);
void adveccione(void);
double GetRho(int ix) {return n[ix][0]+n[ix][1]; };
double GetSigma2(void);
};
LatticeGas::LatticeGas(void) {
v[0] = 1; v[1] = -1;
}
void LatticeGas::inicie(double mu, double sigma) {
for (int ix=0;ix<Lx;ix++)
n[ix][0] = n[ix][1] = 1.0/(2.*sigma*sqrt(2*M_PI))*exp(-0.5*pow((ix-mu)/sigma,2));
}
void LatticeGas::muestre(void) {
for (int ix=0;ix<Lx;ix++)
cout << GetRho(ix) << endl;
}
void LatticeGas::colisione(void) {
// de n a nnew
for (int ix=0;ix<Lx;ix++) {
nnew[ix][0]=p*n[ix][0]+(1-p)*n[ix][1];// dejelo quieto
nnew[ix][1]=p*n[ix][1]+(1-p)*n[ix][0];// dejelo quieto
}
}
void LatticeGas::adveccione(void) {
// de nnew a n
for (int ix=0;ix<Lx;ix++)
for (int i=0;i<2;i++)
n[(ix+v[i]+Lx)%Lx][i]=nnew[ix][i];
}
// ------ funciones globales -----
const int N=1000;
double LatticeGas::GetSigma2(void) {
double N, xprom, xsigma2;
int ix;
// calculo N
for (N=0,ix=0;ix<Lx;ix++)
N+=GetRho(ix);
int c;
for (xprom=0,ix=0;ix<N;ix++)
xprom+=ix*GetRho(ix);
xprom/=N;
for (xsigma2=0,ix=0;ix<Lx;ix++)
xsigma2+=pow(ix-xprom,2)*GetRho(ix);
xsigma2/=N;
return xsigma2;
}
int main() {
LatticeGas difusion;
int t,tmax=400;
difusion.inicie(Lx/2,Lx/12);
for (t=0;t<tmax;t++) {
cout << t << " " << difusion.GetSigma2() << endl;
difusion.colisione();
difusion.adveccione();
}
// Mostrar resultado
// difusion.muestre();
return 0;
}
| true |
65bb88157c4a780221d588389a0833e1300e482a | C++ | jahnf/dcled-hidapi | /output.h | UTF-8 | 323 | 2.875 | 3 | [
"MIT"
] | permissive | #pragma once
#include <iostream>
struct print {
template<typename T>
auto& operator<<(const T& a) const { return std::cout << a; }
~print() { std::cout << std::endl; }
};
struct error {
template<typename T>
auto& operator<<(const T& a) const { return std::cerr << a; }
~error() { std::cerr << std::endl; }
};
| true |
8d24f0bf7039fe1c6dc75c2d167f1f9c7d4f1308 | C++ | xiongqiyu/c-firstyear | /C++ 2/1.cpp | UTF-8 | 9,675 | 2.8125 | 3 | [] | no_license | #include <iostream>
#include <cstdlib>
#include <ctime>
#include <vector>
void set_random_seed();
int randn(int n);
struct mm_code_maker{
void init(int i_length, int i_num){
length = i_length;
num = i_num;
}
void generate_sequence(){
for(int i = 0; i < length; i++){
sequence.push_back(randn(num));
}
}
void give_feedback(const std::vector<int>& attempt, int& black_hits, int& white_hits){
white_hits=0;//initialize
black_hits=0;
int total=0, min=0;
for(int i=0; i<sequence.size(); i++){
if(attempt[i]==sequence[i]){
black_hits++;
}
}
for(int i=0; i<num; i++){
int n=0, m=0;
for(int j=0; j<length; j++){
if(i==sequence[j]){
n++;
}
if(i==attempt[j]){
m++;
}
}
if(n<=m){
min=n;
}
else{
min=m;
}
total = total+min;
}
white_hits=total-black_hits;
}
/*void give_feedback(const std::vector<int>& attempt, int& black_hits, int& white_hits){
black_hits=0;
white_hits=0;
std::vector<int>vt;
std::vector<int>va;
std::vector<int>va1;
for(int i=0; i<sequence.size();i++){
if(sequence[i]==attempt[i]){
black_hits++;
}
else{
vt.push_back(sequence[i]);
va1.push_back(attempt[i]);
va.push_back(attempt[i]);
}
}
int p=va.size();
for (int i=0; i<vt.size(); i++) {
for (int k=0; k<p; k++) {
if (vt[i]==va[k]){
int o=k;
va.clear();
for (int m=0; m<o; m++) {
va.push_back(va1[m]);
}
for (int m=o+1; m<va1.size(); m++) {
va.push_back(va1[m]);
}
std::cout<<std::endl;
white_hits++;
k=p;
va1.clear();
for (int t=0; t<va.size(); t++) {
va1.push_back(va[t]);
}
}
}
}
}*/
std::vector<int> sequence;
int length;
int num;
};
struct mm_solver{
void init(int i_length, int i_num){
length = i_length;
num = i_num;
}
void give_feedback1(const std::vector<int>& attempt,std::vector<int>store, int& black_hits, int& white_hits){
white_hits=0;//initialize
black_hits=0;
int total=0, min=0;
for(int i=0; i<store.size(); i++){
if(attempt[i]==store[i]){
black_hits++;
}
}
for(int i=0; i<num; i++){
int n=0, m=0;
for(int j=0; j<length; j++){
if(i==store[j]){
n++;
}
if(i==attempt[j]){
m++;
}
}
if(n<=m){
min=n;
}
else{
min=m;
}
total = total+min;
}
white_hits=total-black_hits;
}
/*void give_feedback1(const std::vector<int>& attempt, std::vector<int>store,int& black_hits, int& white_hits,int k1){
black_hits=0;
white_hits=0;
std::vector<int>vt;
std::vector<int>va;
std::vector<int>va1;
for(int i=0; i<store[i].size();i++){
if(store[k1][i]==attempt[i]){
black_hits++;
}
else{
vt.push_back(store[k1][i]);
va1.push_back(attempt[i]);
va.push_back(attempt[i]);
}
}
int p=va.size();
for (int i=0; i<vt.size(); i++) {
for (int k=0; k<p; k++) {
if (vt[i]==va[k]){
int o=k;
va.clear();
for (int m=0; m<o; m++) {
va.push_back(va1[m]);
}
for (int m=o+1; m<va1.size(); m++) {
va.push_back(va1[m]);
}
std::cout<<std::endl;
white_hits++;
k=p;
va1.clear();
for (int t=0; t<va.size(); t++) {
va1.push_back(va[t]);
}
}
}
}
}*/
void create_attempt(std::vector<int>& attempt){
bool ready = false;
while(!ready){
for(int i = 0; i < length; i++){
attempt.push_back(randn(num));
}
bool found = false;
for(int i = 0; i < not_correct.size()&& !found; i++){
if(attempt == not_correct[i]){
found = true;
}
}
if(found){
attempt.clear();
}
else{
ready = true;
}
}
}
void learn(std::vector<int>& attempt, int black_hits, int white_hits){
int b=0;
int w=0;
int n=0;
int b1=0;
int w1=0;
std::vector<int>v1;
for(int k=0;k<store.size();k++)
{
int n=0;
for(int i=0;i<length;i++)
{
if(store[k][i]==attempt[i])
{
n=n;
}
else
{
n++;
}
}
if(n==length)
{
k=store.size();
}
}
v1.push_back(n);
for(int i=0;i<store.size();i++){
give_feedback1(attempt,store[i],b,w);
if(b!=black_hits)
{
b1=b1;
}
if(w!=white_hits){
w1=w1;
}
else{
b1++;
w1++;
}
}
attempt.push_back(v1[0]);
attempt.push_back(b1);
attempt.push_back(w1);
}
void learn2(std::vector<int>& attempt, int black_hits, int white_hits){
if(black_hits != attempt.size()){
not_correct.push_back(attempt);
}
}
std::vector<std::vector<int> > not_correct;
std::vector<std::vector<int> > store;
void check(int &m ,std::vector<int>v,int i){
if((v[i]==m)&&(i<v.size())){
m=randn(length);
return check(m, v, 0);
}
if((v[i]!=m)&&(i<v.size()))
{
return check(m, v, i+1);
}
else
{
m=m;
}
}
int length;
int num;
};
int main(){
set_random_seed();
std::vector<int>b;
std::vector<int>w;
std::vector<int>v;
std::vector<int>tmp;
int length, num;
std::cout << "enter length of sequence and number of possible values:" << std::endl;
std::cin >> length >> num;
mm_solver solver;
solver.init(length, num);
mm_code_maker maker;
maker.init(length, num);
maker.generate_sequence();
int black_hits=0;
int white_hits=0;
int attempts_limit = 5000;
int attempts = 0;
std::vector<int> attempt;
while((black_hits < length) && (attempts < attempts_limit))
{
if (attempts==0)
{
attempt.push_back(0);
attempt.push_back(0);
attempt.push_back(1);
attempt.push_back(1);
}
else{
attempt.clear();
solver.create_attempt(attempt);
while (((attempt[length+1]!=length)||(attempt[length+2]!=b.size())||attempt[length+3]!=w.size())||(attempt.size()==length))//这个循环条件是应该为均不满足才能跳出循环 即 当没有找到xiang tong
{
solver.create_attempt(attempt);
for (int l=0; l<b.size(); l++)
{
solver.learn(attempt, b[l], w[l]);
}
}
for (int i=0; i<length; i++)
{
tmp.push_back(attempt[i]);
}
attempt.clear();
for (int i=0; i<length; i++)
{
attempt.push_back(tmp[i]);
}
solver.store.push_back(attempt);
maker.give_feedback(attempt, black_hits, white_hits);
solver.learn2(attempt, black_hits, white_hits);
b.push_back(black_hits);
w.push_back(white_hits);
std::cout << "attempt: " << std::endl;
for(int i = 0; i < attempt.size(); i++){
std::cout << attempt[i] << " ";
}
std::cout << std::endl;
std::cout << "black hits: " << black_hits << " " << " white hits: " << white_hits << std::endl;
attempts++;
}
}
if(black_hits == length){
std::cout << "the solver has found the sequence in " << attempts << " attempts" << std::endl;
}
else{
std::cout << "after " << attempts << " attempts still no solution" << std::endl;
}
std::cout << "the sequence generated by the code maker was:" << std::endl;
for(int i = 0; i < maker.sequence.size(); i++){
std::cout << maker.sequence[i] << " ";
}
std::cout << std::endl;
return 0;
}
void set_random_seed(){
std::srand(std::time(0));
}
int randn(int n){
return std::rand() % n;
}
| true |
1bdaefc2c03cee6e17475a131d0f28799e2ea3fb | C++ | AcumenDev/DB | /Test/DataAccess/main.cpp | UTF-8 | 912 | 2.5625 | 3 | [] | no_license | #include <iostream>
#include "DBEn/DBEntityTestDB.h"
#include <vector>
using namespace std;
int main() {
DBEntityTestDB dbEntity("../../TestDB.db","");
for(const auto& row :dbEntity.Test1.GetList() ) {
std::cout<<row.Id<<" "<<row.Name<<std::endl;
}
std::vector<Test1> vectorTest;
vectorTest.push_back(Test1 {2,"124"});
vectorTest.push_back(Test1 {3,"124"});
vectorTest.push_back(Test1 {4,"124"});
vectorTest.push_back(Test1 {5,"124"});
vectorTest.push_back(Test1 {6,"124"});
vectorTest.push_back(Test1 {7,"124"});
vectorTest.push_back(Test1 {8,"124"});
vectorTest.push_back(Test1 {9,"124"});
vectorTest.push_back(Test1 {10,"124"});
dbEntity.Test1.InsertList(vectorTest);
for(const auto& row :dbEntity.Test1.GetList(1,1) ) {
std::cout<<row.Id<<" "<<row.Name<<std::endl;
}
// cout << "Hello world!" << endl;
return 0;
}
| true |
78fc1eafa11903ff357d32a3a3c7738b790ba2c1 | C++ | LXShades/comp140-worksheetc | /Pong/Player.h | UTF-8 | 603 | 2.875 | 3 | [
"MIT"
] | permissive | #pragma once
#include "Object.h"
class Player : public Object
{
public:
void virtual init();
void virtual Move();
enum Side{Side_Undefined,Side_Left,Side_Right};
void SetSide(Side eSide);
void SetController(const class ArduinoController* controller);
inline float YToKnob(float Y) const;
inline float KnobToY(float Knob) const;
private:
Side mySide;
int speed;
const class ArduinoController* controller;
};
inline float Player::KnobToY(float Knob) const
{
return (100 + (600 - 100 - h) * Knob);
}
inline float Player::YToKnob(float Y) const
{
return (Y - 100) / (600 - 100 - h);
} | true |
9a35ce6e51848daa0b53e6a0068171ad75ef17d2 | C++ | kth4540/cpp_study | /Ch_12/12-9/12-9/12-9.cpp | UHC | 922 | 3.625 | 4 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
class Base
{
public:
int m_i = 0;
virtual void print()
{
cout << "i'm base" << endl;
}
};
class Derived : public Base
{
public:
int m_j = 1;
virtual void print() override
{
cout << "i'm derived" << endl;
}
};
void dosome(Base b)
{
b.print();
}
void dosome() {}
int main()
{
Derived d;
Base b = d; //-> m_j ߷
b.print();
dosome(b);
vector<Base*> my_vec; //-> Ϳ reference Ұ
//vector<std::reference_wrapper<Base>> my_vec;
//->reference_wrapper ϸ reference
my_vec.push_back(&b);
my_vec.push_back(&d); // -> ߷
for (auto& ele : my_vec)
ele->print();
//my_vec.push_back(b);
//my_vec.push_back(d); // -> ߷
//for (auto& ele : my_vec)
// ele.get().print();
//-> reference_wrapper get() base reference Ϲƾ
return 0;
}
| true |
0a92df566d4cdd57baf8b37d936815126c470ee7 | C++ | makodoJ/CLRS_cpp | /ch6/6.2.h | UTF-8 | 1,757 | 3.15625 | 3 | [] | no_license | //
// Created by Banana on 2020/12/3.
//
#ifndef ch6_2_h
#define ch6_2_h
#include "6.1.h"
#include "../Heap.h"
using std::swap;
namespace CLRS{
namespace CH6{
// - Time : O(lgn)
template <typename T>
void max_heapify(Heap<T>& A, int i){
int l = left(i);
int r = right(i);
int largest;
if(l <= A.heapsize - 1 && A[l] > A[i])
largest = l;
else largest = i;
if(r <= A.heapsize - 1 && A[r] > A[largest])
largest = r;
if(largest != i)
swap(A[i], A[largest]);
max_heapify(A, largest);
}
// - Time : O(lgn)
template <typename T>
void min_heapify(Heap<T>& A, int i){
int l = left(i);
int r = right(i);
int smallest;
if(l <= A.heapsize - 1 && A[l] < A[i])
smallest = l;
else smallest = i;
if(r <= A.heapsize - 1 && A[r] < A[smallest])
smallest = r;
if(smallest != i)
swap(A[i], A[smallest]);
min_heapify(A, smallest);
}
template <typename T>
void iterative_max_heapify(Heap<T>& A, int i){
while(true){
int l = left(i);
int r = right(i);
int largest;
if(l <= A.heapsize - 1 && A[l] > A[i])
largest = l;
else largest = i;
if(r <= A.heapsize - 1 && A[r] > A[largest])
largest = r;
if(largest == i)
return;
swap(A[i], A[largest]);
i = largest;
}
}
}
}
| true |
8ea912aaa0bdd8f58778b97da7582fe85b5e20ab | C++ | nihalkun/programming | /sortedIpos.cpp | UTF-8 | 545 | 2.984375 | 3 | [] | no_license | //sorted insertion position
#include<bits/stdc++.h>
using namespace std;
int search(int a[],int l,int r,int x)
{
while (l<=r)
{
int mid=l+(r-l)/2;
if(a[mid]==x)
{
return mid;
}
else if(a[mid]>x)
{
r=mid-1;
}
else
{
l=mid+1;
}
}
return l;
}
int main()
{
int n,x;
cin>>n;
cin>>x;
int a[n];
for (int i = 0; i < n; i++)
{
cin>>a[i];
}
cout<<search(a,0,n-1,x);
return 0;
} | true |
98e62773479641defe99ccfe6010c63b598af518 | C++ | Wolfasaurus1/Project8 | /Project8/Source.cpp | UTF-8 | 1,236 | 3.90625 | 4 | [] | no_license | #include <iostream>
//include c++ standard library as a prefix when necessary so that you don't have to repeat it manually and redundantly
using namespace std;
//create box class
class box
{
public:
//declare variables
int height;
int width;
int length;
//function to set the length of the box
int setLength(int &l)
{
return length = l;
}
//function to set the width of the box
int setwidth(int &w)
{
return width = w;
}
//function to set the height of the box
int setheight(int &h)
{
return height = h;
}
};
int main()
{
//initialize an isntance of the box class and enter argument within parameters, then declare a pointer
box box1;
box *ptrbox;
//set the pointer equal to the address of the instance of the class
ptrbox = &box1;
//de-reference the pointer to the box and intialize the height attribute with a value of 5
ptrbox->height = 5;
//initialize a reference and call the setWidth function inside the box class, setting necessary parameters
int b = 5;
box1.setwidth(b);
//display the value of the width of box1 using a pointer
cout << ptrbox->width << endl;
//keep the window open after the results are shown
cin.ignore(10, '\n');
cin.get();
//return value of 0
return 0;
}
| true |
c7f48fae825f49aafc12c254abb200d82c388622 | C++ | IvoTod/tetrisPi | /src/SceneManager.cpp | UTF-8 | 3,448 | 2.640625 | 3 | [] | no_license | #include <SceneManager.h>
#include <ButtonManager.h>
#include <iostream>
#include <ali_colors.h>
#include <Button.h>
#include <Tetris.h>
#include <Text.h>
#include <NamePicker.h>
#include <vector>
#include <map>
#include <fstream>
#include <algorithm>
#include <Input.h>
void scoreboardPress() {
SceneManager* sceneManager;
sceneManager = sceneManager->getInstance();
sceneManager->loadScoreboardScene();
Input* input;
input = input->getInstance();
input->newFrame();
}
void playPress() {
SceneManager* sceneManager;
sceneManager = sceneManager->getInstance();
sceneManager->loadInGameScene();
Input* input;
input = input->getInstance();
input->newFrame();
}
void backPress() {
SceneManager* sceneManager;
sceneManager = sceneManager->getInstance();
sceneManager->loadMainMenuScene();
Input* input;
input = input->getInstance();
input->newFrame();
}
SceneManager::SceneManager() {}
void SceneManager::loadMainMenuScene() {
Button* playButton = new Button(29, 40, 66, 20, "PLAY", &playPress, ALI_WHITE, ALI_BLUE);
Button* scoreboardButton = new Button(29, 70, 66, 20, "SCOREBOARD", &scoreboardPress, ALI_WHITE, ALI_BLUE);
playButton->setNextButtonUp(scoreboardButton);
playButton->setNextButtonDown(scoreboardButton);
scoreboardButton->setNextButtonUp(playButton);
scoreboardButton->setNextButtonDown(playButton);
ButtonManager* buttonManager = new ButtonManager(playButton);
currentScene = Scene();
currentScene.addGameObject(playButton);
currentScene.addGameObject(scoreboardButton);
currentScene.addGameObject(buttonManager);
setClear();
}
void SceneManager::loadInGameScene() {
currentScene = Scene();
Tetris* tetris = new Tetris();
currentScene.addGameObject(tetris);
setClear();
}
bool compareScores(const std::pair<std::string, int> &a, const std::pair<std::string, int> &b) {
return a.second > b.second;
}
void SceneManager::loadScoreboardScene() {
currentScene = Scene();
std::vector<std::pair<std::string, int> > scores;
std::ifstream iScoresFile("highscores.txt");
std::string temp;
while(iScoresFile >> temp) {
std::string name = temp.substr(0, 3);
std::string score = temp.substr(4);
scores.push_back(std::pair<std::string, int>(name, std::stoi(score)));
}
iScoresFile.close();
std::sort(scores.begin(), scores.end(), compareScores);
for(int i = 0; i < scores.size(); i++) {
std::string scoreString;
scoreString = scores[i].first + ":" + std::to_string(scores[i].second);
Text* text = new Text(20, 10+i*10, scoreString, ALI_WHITE);
currentScene.addGameObject(text);
}
Button* backButton = new Button(20, 135, 50, 20, "BACK", &backPress, ALI_WHITE, ALI_BLUE);
ButtonManager* buttonManager = new ButtonManager(backButton);
currentScene.addGameObject(backButton);
currentScene.addGameObject(buttonManager);
setClear();
}
void SceneManager::loadRecordScoreScene(int finalScore) {
currentScene = Scene();
NamePicker* np = new NamePicker(finalScore);
currentScene.addGameObject(np);
setClear();
}
void SceneManager::clearScreen(TFT_ST7735& tft) {
if(clear) {
clear = false;
tft.setBackground(TFT_BLACK);
tft.clearScreen();
}
}
void SceneManager::setClear() {
clear=true;
}
Scene& SceneManager::getCurrentScene() {
return currentScene;
}
SceneManager* SceneManager::instance;
| true |
f26cde95bd9c7e5a2f241dac321252ae3fc071b1 | C++ | Zbyl/terminal-editor | /text_ui/screen_functions.cpp | UTF-8 | 1,724 | 2.921875 | 3 | [
"CC0-1.0",
"MIT",
"BSL-1.0"
] | permissive | // Distributed under MIT License, see LICENSE file
// (c) 2018 Jakub Skowron, jskowron183@gmail.com
#include "screen_functions.h"
#include <cerrno>
#include <cstdio>
#include <system_error>
static void fputs_ex(const char* s, std::FILE* stream, const char* err_msg) {
int ret = std::fputs(s, stream); // DEC Private Mode Set (DECSET)
if (ret == EOF)
throw std::system_error(errno, std::generic_category(), err_msg);
}
namespace terminal_editor {
void cursor_goto(int x, int y) {
int ret = std::printf("\x1B[%d;%dH", y + 1, x + 1);
if (ret < 0)
throw std::system_error(errno, std::generic_category(), __func__);
}
void cursor_goto(std::ostream& os, int x, int y) {
os << "\x1B[" << (y + 1) << ";" << (x + 1) << "H";
}
FullscreenOn::FullscreenOn() {
// Turn on Alternate Screen Bufer
// DEC Private Mode Set (DECSET)
fputs_ex("\x1B[?1049h", stdout, __func__);
}
FullscreenOn::~FullscreenOn() {
try {
// Fail-safe for ANSI tty, which does not have xterm's alternate buffer.
// Move to column 1, reset parameters, clear to end of screen
fputs_ex("\x1B[G\x1B[0m\x1B[J", stdout, __func__);
// DEC Private Mode Reset (DECRST)
fputs_ex("\x1B[?1049l", stdout, __func__);
}
catch (std::exception& e) {
std::fputs(e.what(), stderr);
std::fputs("\n", stderr);
}
}
HideCursor::HideCursor() {
fputs_ex("\x1B[?25l", stdout, __func__); // Hide Cursor (DECTCEM)
}
HideCursor::~HideCursor() {
try {
fputs_ex("\x1B[?25h", stdout, __func__); // Show Cursor (DECTCEM)
}
catch (std::exception& e) {
std::fputs(e.what(), stderr);
std::fputs("\n", stderr);
}
}
} // namespace terminal_editor
| true |
2ccfd06a445edda81fbb1b090e25b9a7bd8b0e03 | C++ | aimoonchen/easyeditor | /easyeditor/source/data/common/TPNode.cpp | UTF-8 | 4,835 | 2.796875 | 3 | [
"MIT"
] | permissive | #include "TPNode.h"
#include <algorithm>
#include <stdio.h>
#include <assert.h>
namespace ee
{
TPNode::TPNode()
: m_used(false)
{
m_xmin = m_ymin = m_xmax = m_ymax = 0;
m_is_rotated = m_is_split_y = false;
m_next = m_child = m_parent = NULL;
m_remain_area = m_remain_len = m_remain_space = 0;
}
TPNode::TPNode(int width, int height)
: m_used(false)
{
m_xmin = m_ymin = 0;
m_xmax = width;
m_ymax = height;
m_is_rotated = m_is_split_y = false;
m_next = m_child = m_parent = NULL;
m_remain_area = width * height;
m_remain_len = std::max(width, height);
m_remain_space = width;
}
TPNode* TPNode::Insert(int w, int h)
{
// sm::rect r = img.getSymbol().getImage()->getRegion();
// int w = r.Width(),
// h = r.Height();
int dw = m_xmax - m_xmin,
dh = m_ymax - m_ymin;
if ((w > dw && h > dh) || (w > dh && h > dw)) {
return NULL;
}
if (!m_child)
{
if (m_used) {
return NULL;
}
if (w <= dw && h <= dh)
{
TPNode* n = Split(w, h);
if (n) {
n->m_used = true;
}
return n;
}
else if (w <= dh && h <= dw)
{
TPNode* n = Split(h, w);
if (n) {
n->m_used = true;
n->m_is_rotated = true;
}
return n;
}
else
{
return NULL;
}
}
else
{
TPNode* next = m_child;
while (next)
{
TPNode* n = NULL;
if (next->IsRoomEnough(w, h)) {
n = next->Insert(w, h);
}
if (n) {
return n;
} else {
next = next->m_next;
}
}
return NULL;
}
}
void TPNode::Clear()
{
m_used = false;
}
bool TPNode::IsRoomEnough(int w, int h) const
{
return (w <= m_remain_space || h <= m_remain_space)
&& w*h <= m_remain_area
&& w <= m_remain_len && h <= m_remain_len;
}
TPNode* TPNode::Split(int w, int h)
{
TPNode* _next = new TPNode;
TPNode* _child = new TPNode;
TPNode* _child_next = new TPNode;
assert(_child_next);
if (m_is_split_y)
{
_next->m_xmin = m_xmin;
_next->m_xmax = m_xmax;
_next->m_ymin = m_ymin+h;
_next->m_ymax = m_ymax;
m_ymax = _next->m_ymin;
_next->m_is_split_y = true;
_child->m_ymin = m_ymin;
_child->m_ymax = m_ymax;
_child->m_xmin = m_xmin;
_child->m_xmax = m_xmin+w;
_child->m_is_split_y = false;
_child_next->m_ymin = m_ymin;
_child_next->m_ymax = m_ymax;
_child_next->m_xmin = _child->m_xmax;
_child_next->m_xmax = m_xmax;
_child_next->m_is_split_y = false;
}
else
{
_next->m_ymin = m_ymin;
_next->m_ymax = m_ymax;
_next->m_xmin = m_xmin+w;
_next->m_xmax = m_xmax;
m_xmax = _next->m_xmin;
_next->m_is_split_y = false;
_child->m_xmin = m_xmin;
_child->m_xmax = m_xmax;
_child->m_ymin = m_ymin;
_child->m_ymax = m_ymin+h;
_child->m_is_split_y = true;
_child_next->m_xmin = m_xmin;
_child_next->m_xmax = m_xmax;
_child_next->m_ymin = _child->m_ymax;
_child_next->m_ymax = m_ymax;
_child_next->m_is_split_y = true;
}
m_next = _next;
_next->m_parent = m_parent;
m_child = _child;
_child->m_parent = m_parent;
_child->m_next = _child_next;
_child_next->m_parent = this;
// remain area
_next->m_remain_area = static_cast<int>(_next->GetArea());
_child_next->m_remain_area = static_cast<int>(_child_next->GetArea());
_child->m_remain_area = static_cast<int>(_child->GetArea());
m_remain_area = _child_next->m_remain_area;
// remain len
_next->m_remain_len = static_cast<int>(_next->GetMaxLength());
_child_next->m_remain_len = static_cast<int>(_child_next->GetMaxLength());
_child->m_remain_len = static_cast<int>(_child->GetMaxLength());
m_remain_len = _child_next->m_remain_len;
// remain_space
if (m_is_split_y)
{
_next->m_remain_space = _next->m_ymax - _next->m_ymin;
_child_next->m_remain_space = _child_next->m_xmax - _child_next->m_xmin;
_child->m_remain_space = _child->m_xmax - _child->m_xmin;
m_remain_space = _child_next->m_remain_space;
}
else
{
_next->m_remain_space = _next->m_xmax - _next->m_xmin;
_child_next->m_remain_space = _child_next->m_ymax - _child_next->m_ymin;
_child->m_remain_space = _child->m_ymax - _child->m_ymin;
m_remain_space = _child_next->m_remain_space;
}
UpdateRemain();
return _child;
}
float TPNode::GetMaxLength() const
{
float w = static_cast<float>(m_xmax - m_xmin),
h = static_cast<float>(m_ymax - m_ymin);
return w > h ? w : h;
}
float TPNode::GetArea() const
{
return static_cast<float>((m_xmax-m_xmin)*(m_ymax-m_ymin));
}
void TPNode::UpdateRemain()
{
TPNode* p = m_parent;
while (p)
{
p->m_remain_area = 0;
p->m_remain_len = 0;
p->m_remain_space = 0;
TPNode* c = p->m_child;
while (c)
{
if (c->m_remain_area > p->m_remain_area)
p->m_remain_area = c->m_remain_area;
if (c->m_remain_len > p->m_remain_len)
p->m_remain_len = c->m_remain_len;
if (c->m_remain_space > p->m_remain_space)
p->m_remain_space = c->m_remain_space;
c = c->m_next;
}
p = p->m_parent;
}
}
} | true |
b99744dc5edc442e4ddf2e87c247d86e5021b97e | C++ | JWaters02/Year1-CPP-Project | /Stock.cpp | UTF-8 | 1,953 | 3.3125 | 3 | [
"MIT"
] | permissive | /*
* THIS CLASS MANAGES LOGGING OF EVENTS
* */
#include "Stock.h"
//region Constructor
//endregion
//region Functions
//endregion
//region Setters
/**
* Sets all items to have random numbers of stock.
*
* @return List of items.
*/
std::vector<Item> Stock::setRandomStock() {
// Get stock of amount of items; names, costs, nums
std::vector<Item> items;
for (int item = 0; item < getItemBank().size(); item++) {
const int ITEMSPERSTOCK = rand() % 50 + 1;
std::unique_ptr<Item> newItem = std::make_unique<Item>(getItemBank()[item], getItemCostBank()[item], ITEMSPERSTOCK);
items.push_back(*newItem);
}
return items;
}
/**
* Initialises the stock with a new item.
*
* @param itemName Item name.
* @param itemCost Item cost.
* @param numItems Number of items to add.
* @return Item.
*/
Item Stock::setStock(std::string itemName, double itemCost, int numItems) {
std::unique_ptr<Item> newItem = std::make_unique<Item>(itemName, itemCost, numItems);
return *newItem;
}
//endregion
//region Getters
std::vector<std::string> Stock::getItemBank() {
return {"Apple", "Banana", "Cherry",
"Date", "Elderberry", "Fig",
"Grape", "Huckleberry", "Kiwi",
"Lemon", "Mango", "Nectarine",
"Orange", "Pear", "Quince",
"Raisin", "Satsuma", "Tomato",
"Ugli", "Victoria Plum",
"Watermelon", "Zucchini"};
}
std::vector<double> Stock::getItemCostBank() {
return {1.2, 0.8, 0.2,
0.3, 0.6, 1,
0.1, 1, 1.2,
0.5, 1.6, 1,
1, 1.1, 2,
0.1, 1, 0.7,
2, 1.5,
2.3, 5};
}
std::vector<double> Stock::getSupplierItemCostBank() {
return {1, 0.6, 0.1,
0.2, 0.4, 0.8,
0.1, 0.9, 1.1,
0.2, 1.3, 0.7,
0.5, 0.9, 1.3,
0.1, 0.5, 0.5,
1.6, 1.4,
2, 3};
}
//endregion
| true |
b8437d9b5e5c4d25c9a011932290b0bc61ce0166 | C++ | johnbower2012/devel | /old/old_bayes/prior/prior.cpp | UTF-8 | 2,460 | 2.71875 | 3 | [] | no_license | #include<iostream>
#include<iomanip>
#include<cmath>
#include<cstdlib>
#include<random>
#include<chrono>
#include<fstream>
#include<string>
#include "time.h"
#include "memory.cpp"
#include "armadillo"
std::ofstream ofile;
int main(int argc, char* argv[]){
int i, j, k,
length, input_values, samples;
unsigned seed;
double x_ini, x_fin, dx,
xi, xj, sigma;
std::string outfilename;
clock_t start, finish;
if(argc<8){
std::cout << "Improper entry. Please also enter 'length test x_ini x_fin sigma samples outfilename' on same line." << std::endl;
exit(1);
}
else{
length = atoi(argv[1]);
if(length<2){
std::cout << "Improper entry. 'Length' must be greater than 1." << std::endl;
exit(1);
}
else{
length = atoi(argv[1]);
test = atoi(argv[2]);
x_ini = atof(argv[3]);
x_fin = atof(argv[4]);
sigma = atof(argv[5]);
samples = atof(argv[6]);
outfilename = argv[7];
dx = (x_fin - x_ini)/(double) (length-1);
input_values = 1;
seed = std::chrono::system_clock::now().time_since_epoch().count();
}
}
std::default_random_engine generator(seed);
std::normal_distribution<double> dist(0,1.0);
arma::mat xvec_train_mat = arma::zeros<arma::mat>(length,input_values),
xvec_test_mat = arma::zeros<arma::mat>(length,input_values),
cov_mat = arma::zeros<arma::mat>(length,length),
L = cov_mat,
prior_func = arma::zeros<arma::mat>(length,samples),
random_sample = prior_func,
I = arma::eye<arma::mat>(length,length);
for(i=0;i<length;i++){
for(j=0;j<input_values;j++){
xvec_train_mat(i,j) = x_ini + ((double) i)*dx;
}
}
dx = (x_fin - x_ini)/(double) (test+1);
for(i=0;i<test;i++){
for(j=0;j<input_values;j++){
xvec_test_mat(i,j) = x_ini + ((double) (i+1))*dx;
}
}
//calculate covariance matrix
for(i=0;i<length;i++){
xi = xvec_mat(i,0);
for(j=0;j<length;j++){
xj = xvec_mat(j,0);
cov_mat(i,j) = exp(-(xi-xj)*(xi-xj)/(2.0*sigma*sigma));
}
}
//Cholesky Decomposition
L = arma::chol(cov_mat + I*1e-15, "lower");
//prior distribution
for(i=0;i<length;i++){
for(j=0;j<samples;j++){
random_sample(i,j) = dist(generator);
}
}
//sample prior functions
prior_func = L*random_sample;
//write to file
ofile.open(outfilename);
for(i=0;i<length;i++){
ofile << std::setw(15) << xvec_mat(i,0);
for(j=0;j<samples;j++){
ofile << std::setw(15) << prior_func(i,j);
}
ofile << std::endl;
}
ofile.close();
return 0;
}
| true |
ba8f0c7e4a3d587d8415dce6d91e398d9834f2a0 | C++ | jariasf/Online-Judges-Solutions | /UVA/Volume 114 (11400 - 11499)/11494 - Queen.cpp | UTF-8 | 541 | 3.3125 | 3 | [] | no_license | /*****************************************
***Problema: Queen
***ID: 11494
***Juez: UVA
***Tipo: Ad hoc
***Autor: Jhosimar George Arias Figueroa
******************************************/
#include <stdio.h>
int abs( int x ){
if( x < 0 ) x = -x;
return x;
}
int main(){
int x1 , y1 , x2 , y2;
while( scanf("%d %d %d %d" , &x1 , &y1 , &x2 , &y2 ) , x1|x2|y1|y2){
if( x1 == x2 && y1 == y2 ) puts("0");
else if( x1 == x2 || y1 == y2 || abs( x1 - x2 ) == abs( y1 - y2 ) )puts("1");
else puts("2");
}
return 0;
}
| true |
bb62bd0118b341ee111eeaf3d7e99e26e34fd9b7 | C++ | Mikanwolfe/SodukuChecker | /SodukuChecker/main.cpp | UTF-8 | 2,557 | 3.796875 | 4 | [] | no_license | //Sudoku Checker
#include <iostream>
using namespace std;
bool checkRow(int lBoard[9][9], int rowIndex) {
int rowArray[9] = { 0 };
int element = 0;
bool isGood = true;
for (int i = 0; i < 9; i++) {
element = lBoard[rowIndex][i];
if (element != 0) {
rowArray[element-1]++;
if (rowArray[element - 1] > 1) {
isGood = false;
cout << "Faulty row element found at: (Row,Column)" << i + 1 << ", " << rowIndex + 1 << endl;
}
}
}
return isGood;
}
bool checkColumn(int lBoard[9][9], int columnIndex) {
int columnArray[9] = { 0 };
int element = 0;
bool isGood = true;
for (int i = 0; i < 9; i++) {
element = lBoard[i][columnIndex];
if (element != 0) {
columnArray[element - 1]++;
if (columnArray[element - 1] > 1) {
isGood = false;
cout << "Faulty column element found at: (Row,Column)" << i + 1 << ", "<< columnIndex + 1 << endl;
}
}
}
return isGood;
}
bool checkSquare(int lBoard[9][9], int squareIndex) {
int squareArray[9] = { 0 };
int element = 0, xPos = 0, yPos = 0, i = 0, j = 0;
bool isGood = true;
/* Indexing:|
i = -> j = v
012
345
678
therefore for the full square:
012 | 345 | 678
*/
i = squareIndex % 3;
j = (int)(squareIndex / 3);
//cout << "ij:" << i << j << endl;
for (int k = 0; k < 9; k++) {
xPos = i * 3 + (k % 3);
yPos = j * 3 + (int)(k / 3);
//cout << "xpos:" << xPos << "ypos: " << yPos << endl;
element = lBoard[yPos][xPos];
if (element != 0) {
squareArray[element - 1]++;
if (squareArray[element - 1] > 1) {
isGood = false;
cout << "Faulty square element found at: (Row,Column)" << xPos + 1 << ", " << yPos + 1 << endl;
}
}
}
return isGood;
}
bool checkBoard(int lBoard[9][9]) {
//returns 'true' if board is good
int i = 0;
bool isGood = true;
i = 0;
while (i < 9 && isGood) {
isGood = checkRow(lBoard, i);
i++;
}
i = 0;
while (i < 9 && isGood) {
isGood = checkColumn(lBoard, i);
i++;
}
i = 0;
while (i < 9 && isGood) {
isGood = checkSquare(lBoard, i);
i++;
}
return isGood;
}
int main() {
int lBoard[9][9] = {
{ 5, 0, 0, 8, 0, 0, 7, 9, 0 },
{ 0, 0, 0, 1, 0, 0, 0, 3, 0 },
{ 0, 6, 9, 0, 0, 0, 8, 0, 0 },
{ 0, 4, 0, 6, 3, 0, 0, 0, 0 },
{ 1, 0, 2, 0, 0, 0, 3, 0, 6 },
{ 0, 0, 0, 0, 5, 1, 0, 7, 0 },
{ 0, 0, 1, 0, 0, 0, 9, 2, 0 },
{ 0, 2, 0, 0, 0, 4, 0, 0, 0 },
{ 0, 9, 6, 0, 0, 3, 0, 0, 8 }
};
if (checkBoard(lBoard)) {
cout << "The board is in a correct configuration" << endl;
}
else {
cout << "The board is in an incorrect configuration" << endl;
}
return 0;
} | true |
99af8110945635c2cbe9680cdbf10e9b8f655fbe | C++ | baslack/CS5310-a0 | /Tests/TEST_sorts.cpp | UTF-8 | 670 | 2.921875 | 3 | [] | no_license | /**
* Benjamin A. Slack
* CS5310, Summer 1 2017
* a0, Selection Sort
* 05.13.17
* benjamin.slack@wmich.edu
*/
#include <gtest/gtest.h>
#include <gmock/gmock.h>
#include "../sorts.h"
TEST(selection_sort, reverse){
vector<int> test;
for (int i = 15; i >= 0; i--){
test.push_back(i);
}
sorts::selectionSort(test);
for (int i = 0; i < 16; i++){
ASSERT_EQ(i, test[i]);
}
}
TEST(selection_sort, empty_list){
vector<int> test;
int ret_val = sorts::selectionSort(test);
ASSERT_EQ(-1, ret_val);
}
int main (int argc, char **argv){
testing::InitGoogleTest(&argc, argv);
RUN_ALL_TESTS();
exit(0);
}
| true |
856f083d7ce211551ed16c28d0a3a5d23c113915 | C++ | if1live/cocos2d-x-ani | /Classes/xml_reader.cpp | UTF-8 | 3,240 | 2.734375 | 3 | [] | no_license | // Ŭnicode please
#include "stdafx.h"
#include "xml_reader.h"
#include "xml_node.h"
#include <iostream>
#include <memory>
#include "assert_include.h"
#include <sstream>
#include <tinyxml/tinyxml.h>
using namespace std;
namespace sora {;
// tinyxml based implementation
class XmlReaderImpl {
public:
XmlReaderImpl() {}
~XmlReaderImpl() {}
bool Read(XmlNode *root, const char *content);
bool IsErrorOccur() const;
XmlReaderError *GetError();
private:
void Parse(XmlNode *self, TiXmlNode *node);
std::unique_ptr<XmlReaderError> error_;
};
bool XmlReaderImpl::IsErrorOccur() const {
return (error_.get() != NULL);
}
XmlReaderError *XmlReaderImpl::GetError() {
return error_.get();
}
bool XmlReaderImpl::Read(XmlNode *root, const char *content) {
//error초기화
error_.reset();
TiXmlDocument doc;
doc.Parse(content);
if(doc.Error()) {
//ASSERT(!"Xml Error");
//xml문법 에러로 프로그램이 그냥 죽어버리면 여러모로 골치아프다.
//그렇다고 예외를 던지면 받기가 미묘하다
//널 노드를 반환하고 이후 적절히 받은곳에서 처리하도록하자
const char *errorMsg = doc.ErrorDesc();
int row = doc.ErrorRow();
int col = doc.ErrorCol();
error_ = unique_ptr<XmlReaderError>(new XmlReaderError(errorMsg, row, col));
return false;
}
//root + construct custom xml tree
TiXmlNode *ti_root = doc.RootElement();
IUASSERT(root);
this->Parse(root, ti_root);
return true;
}
void XmlReaderImpl::Parse(XmlNode *self, TiXmlNode *node) {
if(node->Type() != TiXmlNode::TINYXML_ELEMENT) {
IUASSERT(!"Not valid recursive call");
}
//casting
TiXmlElement *elem = static_cast<TiXmlElement*>(node);
self->name = elem->Value();
//attribute
TiXmlAttribute *attr = elem->FirstAttribute();
for( ; attr != NULL ; attr = attr->Next()) {
string key(attr->Name());
string value(attr->Value());
self->SetAttribute(key, value);
}
//get child
TiXmlNode *child = elem->FirstChildElement();
for( ; child != NULL ; child = child->NextSibling()) {
if(child->Type() == TiXmlNode::TINYXML_ELEMENT) {
//일반 노드인 경우
XmlNode *child_node = new XmlNode();
Parse(child_node, child);
self->AddChild(child_node);
}
}
//content
child = elem->FirstChild();
for( ; child != NULL ; child = child->NextSibling()) {
if(child->Type() == TiXmlNode::TINYXML_TEXT) {
//text content인 경우 뺴내기
string content(child->Value());
self->content = content.c_str();
break; //text content는 1개 존재햐야한다
}
}
}
/////////////////////////////////////////////
XmlReader::XmlReader()
: impl_(new XmlReaderImpl()) {
}
XmlReader::~XmlReader() {
}
bool XmlReader::Read(XmlNode *root, const char *content) {
return impl_->Read(root, content);
}
bool XmlReader::IsErrorOccur() const {
return impl_->IsErrorOccur();
}
XmlReaderError *XmlReader::GetError() {
return impl_->GetError();
}
//////////////////////////////////////////////
std::string XmlReaderError::str() const {
ostringstream oss;
oss << "[row=" << row << "/col=" << col << "]";
oss << "Msg:" << msg;
return oss.str();
}
}
| true |
d11f30e13a34595a3692df61d7032c2f7b35183f | C++ | razmikTovmas/Graph | /include/impl/_graph_iterator.hpp | UTF-8 | 3,247 | 3.03125 | 3 | [
"MIT"
] | permissive | #pragma once
namespace impl
{
////////////////////////////////////////////////////////////////////////////////
///// graph::iterator
////////////////////////////////////////////////////////////////////////////////
graph::iterator::iterator(const graph& g, node* n, iter_type type)
: m_type(type)
, m_node(n)
, m_visited(g.size(), false)
, m_deque()
{
if (nullptr != m_node) {
m_visited[m_node->get_id()] = true;
collect_nodes();
}
}
graph::iterator& graph::iterator::operator++()
{
if (m_deque.empty()) {
m_node = nullptr;
return *this;
}
if (iter_type::BFS == m_type) {
m_node = m_deque.front();
m_deque.pop_front();
} else {
m_node = m_deque.back();
m_deque.pop_back();
}
collect_nodes();
return *this;
}
graph::iterator graph::iterator::operator++(int)
{
iterator tmp = *this;
++*this;
return tmp;
}
bool graph::iterator::operator==(const iterator& other) const
{
return (m_type == other.m_type && m_node == other.m_node);
}
bool graph::iterator::operator!=(const iterator& other) const
{
return !(other == *this);
}
graph::iterator::reference graph::iterator::operator*() const
{
return *m_node;
}
void graph::iterator::collect_nodes()
{
assert(nullptr != m_node);
//for (auto* edge : m_node->get_edges()) {
for (auto it = m_node->begin_nodes(); it != m_node->end_nodes(); ++it) {
node* to = *it;
const graph::size_type id = to->get_id();
if (!m_visited[id]) {
m_visited[id] = true;
m_deque.push_back(to);
}
}
}
////////////////////////////////////////////////////////////////////////////////
graph::const_iterator::const_iterator(const graph& g, const node* n, iter_type type)
: m_type(type)
, m_node(n)
, m_visited(g.size(), false)
, m_deque()
{
if (nullptr != m_node) {
m_visited[m_node->get_id()] = true;
collect_nodes();
}
}
graph::const_iterator& graph::const_iterator::operator++()
{
if (m_deque.empty()) {
m_node = nullptr;
return *this;
}
if (iter_type::BFS == m_type) {
m_node = m_deque.front();
m_deque.pop_front();
} else {
m_node = m_deque.back();
m_deque.pop_back();
}
collect_nodes();
return *this;
}
graph::const_iterator graph::const_iterator::operator++(int)
{
const_iterator tmp = *this;
++*this;
return tmp;
}
bool graph::const_iterator::operator==(const const_iterator& other) const
{
return (m_type == other.m_type && m_node == other.m_node);
}
bool graph::const_iterator::operator!=(const const_iterator& other) const
{
return !(other == *this);
}
graph::const_iterator::const_reference graph::const_iterator::operator*() const
{
return *m_node;
}
void graph::const_iterator::collect_nodes()
{
assert(nullptr != m_node);
//for (auto* edge : m_node->get_edges()) {
for (auto it = m_node->begin_nodes(); it != m_node->end_nodes(); ++it) {
const node* to = *it;
const graph::size_type id = to->get_id();
if (!m_visited[id]) {
m_visited[id] = true;
m_deque.push_back(to);
}
}
}
}
| true |
8a27d3f5d5f74487f734b20996ed16fff0f266e8 | C++ | BaiMoHan/AlgorithmUpCpp_ING_20200701 | /剑指Offer_II/23_EntryNodeInListLoop/code.cpp | UTF-8 | 1,197 | 3.328125 | 3 | [] | no_license | struct ListNode
{
int m_nValue;
ListNode* m_pNext;
};
ListNode* MeetingNode(ListNode* pHead)
{
if(pHead==nullptr)
return nullptr;
ListNode *pSlow=pHead->m_pNext;
if(pSlow==nullptr)
return nullptr;
ListNode *pFast=pSlow->m_pNext;
while (pFast!=nullptr&&pSlow!=nullptr)
{
if(pFast==pSlow)
return pFast;
pSlow=pSlow->m_pNext;
pFast=pFast->m_pNext;
if(pFast!=nullptr)
pFast=pFast->m_pNext;
}
return nullptr;
}
ListNode* EntryNodeOfLoop(ListNode* pHead)
{
ListNode *meetingNode=MeetingNode(pHead);
if(meetingNode==nullptr)
return nullptr;
//得到环中节点的数目
int nodeInLoop=1;
ListNode *pNode1=meetingNode;
while (pNode1->m_pNext!=meetingNode)
{
pNode1=pNode1->m_pNext;
++nodeInLoop;
}
//先移动pNode1,次数为环中节点的数目
pNode1=pHead;
for(int i=0;i<nodeInLoop;i++)
pNode1=pNode1->m_pNext;
//再移动pNode1和pNode2
ListNode *pNode2=pHead;
while (pNode1!=pNode2)
{
pNode1=pNode1->m_pNext;
pNode2=pNode2->m_pNext;
}
return pNode1;
} | true |
47fe7128cc784d71a83ef6fd730359e86d71c19e | C++ | corinrose/Intro-to-Programming-2013- | /Game of Life Folder/GameObject.h | UTF-8 | 379 | 2.71875 | 3 | [] | no_license | #ifndef GAMEOBJECT_H
#define GAMEOBJECT_H
#include <vector>
class GameObject
{
public:
GameObject(int xVal, int yVal, char dispVal);
void display(std::vector<std::vector<char> > &world);
void moveObj(int mx, int my, std::vector<std::vector<char> > &world);
protected:
int x;
int y;
char disp;
};
#endif // GAMEOBJECT_H
| true |
91ed510dc8b38d149ca3cdae187abbd1fc88d8f7 | C++ | huangshenno1/algo | /模板/Hungarian.cpp | UTF-8 | 583 | 2.875 | 3 | [
"MIT"
] | permissive | //Hungarian
#include <cstdio>
#include <cstring>
const int maxn = 505;
int un,vn;
int g[maxn][maxn];
int link[maxn];
bool vis[maxn];
bool dfs(int u)
{
for (int v = 0; v < vn; v++)
{
if (g[u][v] && !vis[v])
{
vis[v] = 1;
if (link[v]==-1 || dfs(link[v]))
{
link[v] = u;
return 1;
}
}
}
return 0;
}
int Hungarian()
{
int res = 0;
memset(link, -1, sizeof(link));
memset(vis, 0, sizeof(vis));
for (int u = 0; u < un; u++)
{
if (dfs(u))
{
res++;
memset(vis, 0, sizeof(vis));
}
}
return res;
}
| true |
f35ccfc84ecccf79d09b07fd0bf86ecce1b1615b | C++ | janek-bieser/glsl-preview | /glsl-preview-app/glview/shaderuniformlist.h | UTF-8 | 1,496 | 2.828125 | 3 | [
"MIT"
] | permissive | #ifndef SHADERUNIFORMLIST_H
#define SHADERUNIFORMLIST_H
#include <QAbstractListModel>
#include <QHash>
#include "shaderuniform.h"
/*!
* \brief Represents the list of all found uniforms. The ShaderUniformList
* can be used as ListModel inside the QML User Interface.
*/
class ShaderUniformList : public QAbstractListModel
{
Q_OBJECT
public:
enum UniformRole {
TypeRole = Qt::UserRole + 1,
NameRole
};
ShaderUniformList(QObject *parent = 0);
~ShaderUniformList();
QHash<int, QByteArray> roleNames() const override;
int rowCount(const QModelIndex &parent = QModelIndex()) const override;
QVariant data(const QModelIndex &index, int role) const override;
/*!
* \brief Adds a ShaderUniform to the list.
* \param uniform A ShaderUniform object.
*/
void add(const ShaderUniform& uniform);
/*!
* \brief Replace all uniform with a new list of uniforms..
* \param uniforms List of new uniforms.
*/
void setUniforms(const QList<ShaderUniform*>& uniforms);
/*!
* \brief Remove all unfiroms from the list.
*/
void clear();
public slots:
void add(const QVariantMap& uMap);
/*!
* \brief Gets a uniform at a specific index.
* \param idx The index
* \return A ShaderUniform object.
*/
ShaderUniform* get(int idx) const;
private:
QList<ShaderUniform*> m_uniforms;
bool contains(const ShaderUniform& su);
};
#endif // SHADERUNIFORMLIST_H
| true |
c6e9857318bbabd7ef30b72292063eb6303d5156 | C++ | FelixKimmerle/Informatik-II | /Blatt10/10_3_b.cpp | UTF-8 | 1,484 | 3.65625 | 4 | [] | no_license | #include <vector>
#include <iostream>
class tier
{
public:
tier(std::string p_art);
~tier();
virtual void hallo(std::string prefix);
private:
std::string art;
};
tier::tier(std::string p_art = "ein Tier")
{
art = p_art;
}
tier::~tier()
{
}
void tier::hallo(std::string prefix)
{
std::cout << prefix << "Ich bin " << art << std::endl;
}
class raubtier : public tier
{
public:
raubtier(std::string p_art);
~raubtier();
void friss(tier *dersnack);
virtual void hallo(std::string prefix);
private:
tier *im_bauch;
};
raubtier::raubtier(std::string p_art = "ein Tier") : tier(p_art)
{
im_bauch = nullptr;
}
raubtier::~raubtier()
{
}
void raubtier::friss(tier *dersnack)
{
im_bauch = dersnack;
}
void raubtier::hallo(std::string prefix)
{
tier::hallo(prefix);
if (im_bauch != nullptr)
{
im_bauch->hallo(prefix + " ");
}
}
class zoo
{
public:
zoo();
~zoo();
void kaufe_tier(tier *p_tier);
void alle_hallo();
private:
std::vector<tier *> tiere;
};
zoo::zoo()
{
}
zoo::~zoo()
{
}
void zoo::kaufe_tier(tier *p_tier)
{
tiere.push_back(p_tier);
}
void zoo::alle_hallo()
{
for (tier *t : tiere)
{
t->hallo("");
}
}
int main()
{
raubtier *A, *B;
A = new raubtier("der erste Fisch");
for (int i = 0; i < 5; i++)
{
B = new raubtier("der " + std::to_string(i+2) + "te Fisch");
B->friss(A);
A = B;
}
A->hallo("");
} | true |
93dbb6e4b777012ccd6f5766eccccd7c15f7f910 | C++ | liuzhenghuia/programming | /oj/leetcode/src/leetcode80.cpp | UTF-8 | 591 | 2.78125 | 3 | [] | no_license | #include <vector>
using namespace std;
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int n = nums.size();
if(n < 3) return n;
int repeatTimes = 1;
int curIndex = 0;
for(int i=1;i<n;i++){
if(nums[curIndex] == nums[i]){
if(repeatTimes < 2){
repeatTimes++;
nums[++curIndex] = nums[i];
}
}else{
nums[++curIndex] = nums[i];
repeatTimes = 1;
}
}
return curIndex+1;
}
};
| true |
dfa0691537e32e4e16639b5b41fd8f43b4a95f97 | C++ | jfwyble/udacity-linux-sys-mon | /src/format.cpp | UTF-8 | 568 | 3.375 | 3 | [
"MIT"
] | permissive | #include <string>
#include <iomanip>
#include <sstream>
#include "format.h"
using std::string;
// INPUT: Long int measuring seconds
// OUTPUT: HH:MM:SS
string Format::ElapsedTime(long seconds)
{
long hours = seconds / 3600;
// To get the minutes, get the modulus of
int minutes = (seconds % 3600) / 60;
int secs = seconds % 60;
std::stringstream s;
s << std::setfill('0') << std::setw(2) << hours << ':' << std::setfill('0') << std::setw(2) << minutes << ':' << std::setfill('0') << std::setw(2) << secs;
return s.str();
} | true |
698f252d19c32a52455bd85bb924cd307c189ff2 | C++ | wxx5433/USACO | /gift1.cpp | UTF-8 | 1,580 | 3.25 | 3 | [] | no_license | /*
ID: wxx54331
PROG: gift1
LANG: C++
*/
#include<iostream>
#include<fstream>
#include<string>
#include<vector>
using namespace std;
struct personStruct {
string name;
int initialMoney;
int finalMoney;
};
ifstream fin("gift1.in");
int getIndex(string name, vector<personStruct> person, int number);
int distribute(vector<personStruct> &person);
int main()
{
ofstream fout("gift1.out");
vector<personStruct> person;
personStruct onePerson;
string name;
int number;
fin >> number;
fin.get(); //读掉换行符
for(int i = 0; i < number; ++i)
{
getline(fin,name);
onePerson.name = name;
onePerson.initialMoney = 0;
onePerson.finalMoney = 0;
person.push_back(onePerson);
}
while(distribute(person))
;
for(int i = 0; i < number; ++i)
fout << person[i].name << " " << person[i].finalMoney - person[i].initialMoney << endl;
return 0;
}
int getIndex(string name, vector<personStruct> person)
{
for(int i = 0; i < person.size(); ++i)
if(name == person[i].name)
return i;
}
int distribute(vector<personStruct> &person)
{
string name;
int initialMoney, senderNum;
int index;
if(!getline(fin,name))
return 0;
fin >> initialMoney >> senderNum;
fin.get();
index = getIndex(name, person);
person[index].initialMoney += initialMoney;
if(senderNum == 0)
person[index].finalMoney += initialMoney;
else
person[index].finalMoney += initialMoney % senderNum;
for(int i = 0; i < senderNum; ++i)
{
getline(fin, name);
index = getIndex(name, person);
person[index].finalMoney += initialMoney / senderNum;
}
return 1;
}
| true |
7602d7214c02bcb8d80790fed2b36be80f62959b | C++ | 3IFBinomeB3121/TP_C-_Analog | /B3121/Log.h | UTF-8 | 5,190 | 2.8125 | 3 | [] | no_license | /*************************************************************************
Log - description
-------------------
début : 10/01/2018
copyright : (C) 2018 par Christophe ETIENNE & William Occelli
e-mail : christophe.etienne@insa-lyon.fr
william.occelli@insa-lyon.fr
*************************************************************************/
//---------- Interface de la classe <Log> (fichier Log.h) ----------------
#if ! defined ( Log_H )
#define Log_H
//--------------------------------------------------- Interfaces utilisées
using namespace std;
#include <iostream>
#include <string>
#include <sstream>
#include <cstring>
//------------------------------------------------------------- Constantes
//------------------------------------------------------------------ Types
//------------------------------------------------------------------------
// Rôle de la classe <Log>
// Permet de stocker toutes les informations d'une ligne de log, précedemment
// lue dans un fichier de log Apache. Les différentes informations stockées sont
// le référent, l'adresse IP, le nom d'utilisateur du visiteur, son pseudo,
// la date et l'heure (greenwich) de la requête, la méthode HTTP utilisée,
// l'url du document recherché, l'url du document consulté,
// le protocole HTTP utilisé, le status code HTTP, la quantité de données
// transférées en octet et enfin l'identification du client navigateur.
//
//------------------------------------------------------------------------
class Log
{
//----------------------------------------------------------------- PUBLIC
public:
//----------------------------------------------------- Méthodes publiques
string GetExtension();
// Mode d'emploi : Cette méthode permet de récupérer
// l'information concernant l'extension de l'url du document
// consulté.
// Retourne un string contenant l'extension de l'url du document
// consulté.
//
// Contrat :
//
string GetCible();
// Mode d'emploi : Cette méthode permet de récupérer
// l'information concernant l'url du document consulté.
// Retourne un string contenant l'url du document consulté.
//
// Contrat :
//
string GetSource();
// Mode d'emploi : Cette méthode permet de récupérer
// l'information concernant l'url du document à partir duquel on
// effectue la requête.
// Retourne un string contenant l'url du document à partir duquel
// on effectue la requête.
//
// Contrat :
//
int GetHeure();
// Mode d'emploi : Cette méthode permet de récupérer
// l'information concernant l'heure à laquelle on effectue la requête.
// Retourne un entier correspondant à l'heure où la requête est effectuée.
//
// Contrat :
//
friend ostream & operator << ( ostream & flux, const Log & unLog );
// Mode d'emploi : Surcharge de la fonction non membre operator <<
// déclarée amie de la classe Log.
// L'affichage pour un objet de la classe Log est formaté de la manière suivante:
// Affichage de tous les attributs( les différentes informations), un par ligne.
// Le premier paramètre est une référence sur un objet de type ostream.
// Le second paramètre est une référence constante sur un objet de type Log qui est
// l'objet dont on souhaite affiché les informations.
// Retourne une référence sur un objet de type ofstream qui est le flux manipulé.
//
// Contrat :
//
//------------------------------------------------- Surcharge d'opérateurs
Log & operator = ( const Log & unLog );
// Mode d'emploi : La surchage d'operator = est juste déclaré.
//
// Contrat :
//
//-------------------------------------------- Constructeurs - destructeur
Log ( const Log & unLog );
// Mode d'emploi (constructeur de copie) : Le constructeur de copie
// de Log est juste déclaré.
//
// Contrat :
//
Log (string ligneFichier = "");
// Mode d'emploi : Construit un objet de type Log qui initialise tous les
// attributs avec les informations contenues dans la ligne lue dans le fichier
// de log Apache passé en paramètre.
// Si aucun fichier n'est précisé, renvoie un message d'erreur.
// Le paramètre <ligneFichier> est une string contenant la ligne dont on souhaite
// récupérer les informations.
//
// Contrat :
//
virtual ~Log ( );
// Mode d'emploi : Le destructeur de Log est juste déclaré.
//
// Contrat :
//
//------------------------------------------------------------------ PRIVE
protected:
//----------------------------------------------------- Méthodes protégées
//----------------------------------------------------- Attributs protégés
string referent;
string adresseIP;
string nom_visiteur;
string pseudo;
string date;
int heure;
string methode;
string cible;
string protocole;
int status_code;
int nbOctet;
string source;
string id_client_navigateur;
};
//-------------------------------- Autres définitions dépendantes de <Log>
#endif // Log_H
| true |
53fa8c70942dc85b97d55e398b31c257c1dbf26f | C++ | yangzhiye/Algorithm | /北大算法课/枚举/熄灯问题.cpp | UTF-8 | 1,057 | 2.765625 | 3 | [] | no_license | #include <iostream>
using namespace std;
int puzzle[6][8],press[6][8];
bool guess(){
int c,r;
for(r = 1 ; r < 5 ; ++r)
for(c = 1 ; c < 7 ; ++c){
press[r+1][c] = (puzzle[r][c]+press[r][c]+press[r-1][c]+press[r][c-1]+press[r][c+1])%2;
}
for(c = 1 ; c < 7 ; ++c){
if((press[5][c-1]+press[5][c]+press[5][c+1]+press[4][c])%2!=puzzle[5][c])
return false;
}
return true;
}
void enumerate(){
int c;
bool success;
for(c = 1 ; c < 7 ; c++)
press[1][c] = 0;
while(guess()==false){
press[1][1]++;
c=1;
while(press[1][c]>1){
press[1][c] = 0;
c++;
press[1][c]++;
}
}
return;
}
int main(int argc, char *argv[]) {
int cases,i,r,c;
cin>>cases;
for(r = 0 ; r < 6 ; r++)
press[r][0] = press[r][7] = 0;
for(c = 1 ; r < 7 ; r++)
press[0][c] = 0;
for(i = 0 ; i < cases ; i++){
for(r = 1 ; r < 6 ;r++)
for(c = 1 ; c < 7 ; c++)
cin>>puzzle[r][c];
enumerate();
cout<<"PUZZLE #"<<i+1<<endl;
for(r = 1 ; r < 6 ; r++){
for(c = 1 ; c < 7 ; c++){
cout<<press[r][c]<<" ";
}
cout<<endl;
}
}
return 0;
} | true |
0ee8a9e9bde1793bf6f9573ab9f0493baf183a0c | C++ | zontar/ProjectEuler | /euler/task4.cpp | WINDOWS-1251 | 744 | 3.59375 | 4 | [] | no_license | #include "task.h"
const std::string taskName = "Task4";
/*
A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 * 99.
Find the largest palindrome made from the product of two 3-digit numbers.
*/
/*
100000a + 10000b + 1000c + 100c + 10b + a.
(9091*a + 910*b + 100*c)*11.
*/
int run()
{
int r = 0;
for(int a=9; a>0; --a)
{
for(int b=9; b>=0; --b)
{
for(int c=9; c>=0; --c)
{
int m = (9091*a + 910*b + 100*c);
for(int i=10; i<=90; ++i)
{
if(m%i==0)
{
if(m/i>999) break;
if(r<m) r=m;
}
}
}
}
}
std::cout << r*11;
return 0;
} | true |
ea4b828d85a867f8cb81a6068409751fbd287dfb | C++ | aartic88/msl | /tests/LinkedStack_test.cpp | UTF-8 | 979 | 2.859375 | 3 | [] | no_license | #include "LinkedStack.hpp"
#include "LinkedDeque.hpp"
#include "LinkedQueue.hpp"
#include <gtest/gtest.h>
using namespace std;
TEST(testIsLinkedList, StackTest) {
LinkedStack<int> greekGod;
greekGod.push(345);
greekGod.push(23);
greekGod.push(67);
greekGod.print();
greekGod.pop();
greekGod.print();
//greekGod.pop();
//greekGod.pop();
cout << greekGod.top();
}
TEST(testIsLinkedList, DequeTest) {
LinkedDeque<std::string> greekGod;
greekGod.insertfront("345");
greekGod.insertfront("23");
greekGod.insertfront("67");
greekGod.print();
greekGod.removefront();
greekGod.print();
greekGod.removefront();
//greekGod.removeback();
cout << greekGod.front();
}
TEST(testIsLinkedList, QueueTest) {
LinkedQueue<std::string> greekGod;
greekGod.enqueue("345");
greekGod.enqueue("23");
greekGod.enqueue("67");
greekGod.print();
greekGod.dequeue();
greekGod.print();
//greekGod.pop();
//greekGod.pop();
cout << greekGod.front();
} | true |
dbdc70e86c86cc7762628085838e712d41bf7e1a | C++ | tc-irl/GameEngine | /GameEngine/Triangle.cpp | UTF-8 | 5,752 | 3.046875 | 3 | [] | no_license | #include "Triangle.h"
Triangle::Triangle(GLuint shaderID, Particle *p1, Particle *p2, Particle *p3, int ID)
{
this->shaderID = shaderID;
this->p1 = p1;
this->p2 = p2;
this->p3 = p3;
this->ID = ID;
GenerateBuffer();
drawTriangle = true;
}
void Triangle::GenerateBuffer()
{
points.clear();
normals.push_back(p1->GetNormal());
normals.push_back(p2->GetNormal());
normals.push_back(p3->GetNormal());
points.push_back(p1->GetPos());
points.push_back(p2->GetPos());
points.push_back(p3->GetPos());
colors.push_back(glm::vec4(1.0f, 0.0f, 0.0f, 1.0f));
colors.push_back(glm::vec4(1.0f, 0.0f, 0.0f, 1.0f));
colors.push_back(glm::vec4(1.0f, 0.0f, 0.0f, 1.0f));
//Initialize VAO
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
//Calc Array Sizes
vSize = points.size() * sizeof(glm::vec3);
cSize = colors.size() * sizeof(glm::vec4);
nSize = normals.size() * sizeof(glm::vec3);
//Initialize VBO
glGenBuffers( 1, &vbo );
glBindBuffer( GL_ARRAY_BUFFER, vbo );
glBufferData( GL_ARRAY_BUFFER, vSize + cSize + nSize, NULL, GL_STATIC_DRAW);
glBufferSubData( GL_ARRAY_BUFFER, 0, vSize, (const GLvoid*)(&points[0]));
glBufferSubData( GL_ARRAY_BUFFER, vSize, cSize, (const GLvoid*)(&colors[0]));
glBufferSubData( GL_ARRAY_BUFFER, vSize + cSize, nSize, (const GLvoid*)(&normals[0]));
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(vSize));
glEnableVertexAttribArray(2);
glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(vSize + cSize));
//Unbind
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
}
void Triangle::SetColor(glm::vec3 color)
{
this->color = color;
std::vector<glm::vec4> newColor;
for(int i = 0; i < points.size(); i++)
{
newColor.push_back(glm::vec4(color,1.0f));
}
vSize = points.size() * sizeof(glm::vec3);
cSize = newColor.size() * sizeof(glm::vec4);
glBindVertexArray(vao);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferSubData( GL_ARRAY_BUFFER, vSize, cSize, (const GLvoid*)(&newColor[0]));
glBindVertexArray(0);
}
void Triangle::Draw()
{
if(drawTriangle)
{
glBindVertexArray (vao);
glDrawArrays (GL_TRIANGLES, 0, 3);
glBindVertexArray(0);
}
}
void Triangle::Update()
{
points.clear();
normals.clear();
points.push_back(p1->GetPos());
points.push_back(p2->GetPos());
points.push_back(p3->GetPos());
normals.push_back(p1->GetNormal());
normals.push_back(p2->GetNormal());
normals.push_back(p3->GetNormal());
glBindVertexArray(vao);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferSubData( GL_ARRAY_BUFFER, 0, vSize, (const GLvoid*)(&points[0]));
glBufferSubData( GL_ARRAY_BUFFER, vSize + cSize, nSize, (const GLvoid*)(&normals[0]));
glBindVertexArray(0);
}
bool Triangle::CompareParticles(Particle *p)
{
if(p == p1)
{
return true;
}
else
{
return false;
}
}
glm::vec3 Triangle::GetTriangleNormal()
{
glm::vec3 v1 = p2->GetPos() - p1->GetPos();
glm::vec3 v2 = p3->GetPos() - p1->GetPos();
return glm::cross(v1,v2);
}
bool Triangle::RayIntersectsTriangle(glm::vec3 previousPos, glm::vec3 pos)
{
glm::vec3 e1 = p2->GetPos() - p1->GetPos();
glm::vec3 e2 = p3->GetPos() - p1->GetPos();
glm::vec3 rayDir = pos - previousPos;
glm::vec3 pvec = glm::cross(rayDir,e2);
float det = glm::dot(e1, pvec);
if(det < 0.000001 && det > 0.000001)
{
return false;
}
float invDet = 1 / det;
glm::vec3 tvec = previousPos - p1->GetPos();
float u = glm::dot(tvec, pvec) * invDet;
if (u < 0 || u > 1)
return false;
// prepare to compute v
glm::vec3 qvec = glm::cross(tvec, e1);
float v = glm::dot(rayDir, qvec) * invDet;
if (v < 0 || u + v > 1)
return false;
// calculate t, ray intersects triangle
float t = glm::dot(e2, qvec) * invDet;
return true;
//float r,a,b;
//glm::vec3 u = p2->GetPos() - p1->GetPos();
//glm::vec3 v = p3->GetPos() - p1->GetPos();
//glm::vec3 normal = glm::cross(u,v);
//if(normal == glm::vec3(0))
//{
// return -1;
//}
//glm::vec3 dir = pos - previousPos;
//glm::vec3 w0 = previousPos - p1->GetPos();
//a = -glm::dot(normal,w0);
//b = glm::dot(normal, dir);
//if(fabs(b) < SMALL_NUM)
//{
// if(a == 0)
// {
// return 2;
// }
// else
// {
// return 0;
// }
//}
//r = a / b;
//if(r < 0.0)
//{
// return 0;
//}
//else if (r > 1.0)
//{
// return 0;
//}
//glm::vec3 intersectionPoint = previousPos + r * dir;
//float uu, uv, vv, wu, wv, D;
//uu = glm::dot(u, u);
//uv = glm::dot(u, v);
//vv = glm::dot(v, v);
//
//glm::vec3 w = intersectionPoint - p1->GetPreviousPos();
//wu = glm::dot(w, u);
//wv = glm::dot(w, v);
//D = uv * uv - uu * vv;
//float s, t;
//s = (uv * wv - vv * wu) / D;
//
//if(s < 0.0 || s > 1.0)
//{
// return 0;
//}
//t = (uv * wu - uu * wv) / D;
//if(t < 0.0 || (s + t) > 1.0)
//{
// return 0;
//}
//return 1;
}
bool Triangle::IsPointInTriangle(glm::vec3 p)
{
//glm::vec3 a, b, c;
//a = p1->GetPos();
//b = p2->GetPos();
//c = p3->GetPos();
glm::vec3 u = p2->GetPos() - p1->GetPos();
glm::vec3 v = p3->GetPos() - p1->GetPos();
glm::vec3 w = p - p1->GetPos();
glm::vec3 vCrossW = glm::cross(v, w);
glm::vec3 vCrossU = glm::cross(v, u);
// Test sign of r
if (glm::dot(vCrossW, vCrossU) < 0)
return false;
glm::vec3 uCrossW = glm::cross(u, w);
glm::vec3 uCrossV = glm::cross(u, v);
// Test sign of t
if (glm::dot(uCrossW, uCrossV) < 0)
return false;
// At this point, we know that r and t and both > 0.
// Therefore, as long as their sum is <= 1, each must be less <= 1
float denom = glm::length(uCrossV);
float r = glm::length(vCrossW) / denom;
float t = glm::length(uCrossW) / denom;
return (r + t <= 1);
}
| true |
b4ebc2d907aebb89a60d55dd168f6e03048bc716 | C++ | bramwellandcompanyinc/GitPublic | /Navasim/WaveModel_v10/QuadTree.h | UTF-8 | 7,963 | 3.015625 | 3 | [] | no_license | #include <Geometry/Primitives.h>
class IQuadTreeNode
{
};
//we can implement this class later on to make the parameter passing for the quadtreenode constructor a little cleaner and limit the amount of
//stuff we need to pass on the stack. it will basically have left col, right col, top row, bottom row.
class QuadTreeNodeExtents
{
public:
Int32 L;
Int32 R;
Int32 T;
Int32 B;
QuadTreeNodeExtents& operator = (QuadTreeNodeExtents& qtne)
{
L = qtne.L;
R = qtne.R;
T = qtne.T;
B = qtne.B;
return *this;
}
};
//implements a vertex-centric quad tree. need not be a square quadtree, but should have an odd number of vertices in either dimension.
/*FOR THE TIME BEING WE'RE GOING TO IMPLEMENT A SQUARE QUADTREE (2^n + 1) BUT WE MUST BE ABLE TO HANDLE NO-DATA SITUATIONS */
class QuadTreeRoot
{
public:
Int32 m_i32Width;
Int32 m_i32Height;
Point3f* mp_p3fVertices;
QuadTreeRoot(Int32 a_i32Width, Int32 a_i32Height, Point3f* ap_p3fVertices):m_i32Width(a_i32Width), m_i32Height(a_i32Height), mp_p3fVertices(ap_p3fVertices){}
inline Int32 Width(){return m_i32Width;}
inline Int32 Height(){return m_i32Height;}
inline Point3f* Vertices(){return mp_p3fVertices;}
};
class QuadTreeNode : public IQuadTreeNode
{
private:
bool m_blnHasChildNodes;
// bool m_blnDividesHorizontally;
// bool m_blnDividesVertically;
Int32 m_i32Depth;
QuadTreeRoot* mp_qtrRoot;
//IQuadTreeNode* mp_qtnParent; //for convenience - but lets not store this now so that we keep the size of the qt structure down.
IQuadTreeNode*[4] mp_qtnChildren; //stored clockwise from TL, TR, BR, BL
QuadTreeNodeExtents m_qtne;
//We may even want to map this floating point value into a range of 0..255 to save space in memory - that will probably give sufficient
//accuracy for this purpose.
float m_fltFlatnessFactor;
public:
//we even may be able to get away with loading a flatness quad tree as a staight data struct into memory, and instead of having links
//between a parent and its child nodes, we actually lay it out in memory in a 4-branch extending tree, and based upon our knowledge of which
//node we're dealing with, we can work out its address and just go straight to finding its value there (or the struct that represents the node).
//this will be the approach we'll take when loading a quadtree into memory. addressing would work as follows:
//level 0 (root) = sizeof(the struct)
//level 1 = sizeof(level 0) + (sizeof(the struct) * 4)
//level 2 = sizeof(level 1) + (sizeof(the struct) * 16)
//we can work out how big the structure will be...
//struct size * ((2^n)*(2^n) + (2^(n-1))*(2^(n-1)) + (2^(n-2))*(2^(n-2)).. + 1 )
//so, for a size of 8 polys wide, we'd have n being 3
//so it would be: 8*8 + 4*4 + 2*2 + 1 = 64+16+4+1 = 85*struct size
//if it is 128 polys wide (approx 1280m):
//128*128 + 64*64 + 32*32 + 16*16 + 8*8 + 4*4 + 2*2 + 1
//16384 + 4096 + 1024 + 256 + 64 + 16 + 4 + 1
//= 21845 * struct size
//it would be nice to have a class that can walk the struct, for example: starting from the root node, give me the address of the south-east
//corner at the next level down, and then the address of the north-west corner at the next level down again, and then give me the address of its
//3 sibling nodes, etc. This way we avoid the whole struct of pointers to structs.
//we could lay them out in memory such that each level is contiguous. To navigate around at the root node's children, we start with the address
//of the 2*2 grid, and it will be laid out in column major format.
//but for the sake of generating the initial structure we'll proceed along this path.
QuadTreeNode(QuadTreeRoot* ap_qtrRoot, IQuadTreeNode* ap_qtnParent, QuadTreeNodeExtents& a_qtne);
{
mp_qtrRoot = ap_qtrRoot;
//mp_qtnParent = ap_qtnParent;
mp_p3dVertexArray = ap_p3dVertexArray;
if (ap_qtnParent != nullptr)
m_i32Depth = ap_qtnParent.GetDepth()+1;
else
m_i32Depth = 0;
m_qtne = a_qtne;
//???? Check the extents given to us - if any of the points explained by these extents indicates no data, we won't subdivide.
//Create a new quadtree node now until we get to the point that the vertex array indices are next to each other
//if our extents passed in are 0 to 8 (1 to 9) our midpoint is going to be 4 (5) - ie, look at the difference between incoming indices
//and then halve it. If we have 5 points left, our midpoint is going to be 4-0 = 4, /2 = 2.
//if we have 3 points left, our midpoint is going to be 2-0 = 2, /2 = 1. At this point we stop subdividing.
QuadTreeNodeExtents& e = m_qtne;
//As we're using a square mesh these will always be the same.
Int32 i32DeltaHoriz = e.R-e.L;
//Int32 i32DeltaVert = e.B-e.T;
blnDividesHorizontally = (i32DeltaHoriz>1);
//blnDividesVertically = (i32DeltaVert>1);
m_blnHasChildNodes = !(blnDividesHorizontally);// && blnDividesVertically);
if (m_blnHasChildNodes)
{
mp_qtnChildren[0] = new QuadTreeNode(this, mp_p3dVertexArray, e.L, e.L+i32DeltaHoriz, e.T, e.T+i32DeltaVert)
mp_qtnChildren[1] = new QuadTreeNode(this, mp_p3dVertexArray, e.L+i32DeltaHoriz, a_i32colR, e.T, e.T+i32DeltaVert)
mp_qtnChildren[2] = new QuadTreeNode(this, mp_p3dVertexArray, e.L+i32DeltaHoriz, a_i32ColR, e.T+i32DeltaVert, e.B)
mp_qtnChildren[3] = new QuadTreeNode(this, mp_p3dVertexArray, e.L, e.L+i32DeltaHoriz, e.T+i32DeltaVert, e.B)
}
}
//we somehow need to be aware of where the edge of the coastline is - or do we want to include depth data in each tile? we could keep
//it flexible for the time being.
//if we do this, we should also mark tiles as being all above-water, mixed, or all-below water, so we know that given our current HOE,
//we can exclude submarine tiles from the rendering pipeline if we're above water. this doesn't mean to say that they shouldn't be loaded
//in shallow water conditions, because we will need the depth data to influence water colour and such. deeper tiles that don't affect won't
//affect water colour and may not need to be loaded (unless we're simulating submarine travel).
inline Int32 GetDepth()
{
return m_i32Depth;
}
float CalculateFlatnessFactor()
{
if (m_blnHasChildNodes)
{
//If we have child nodes, recurse down and retrieve their flatness factors, accumulating the results
for (int i=0; i<4; i++)
m_fltFlatnessFactor += mp_qtnChildren[i]->CalculateFlatnessFactor();
}
else
{
//We're going to determine the surface normals for the north-west and south-east triangles, and determine the angle between those
//two normals. (nw = tl, se = br)
Vector3f v3fTL, v3fTR;
FindTopLeftNormalVector(v3fTL);
FindBottomRightNormalVector(v3fTR);
//Knowing that the dot product of the two vectors is the cosine of the
//angle between them, find the angle between the normal vectors.
m_fltFlatnessFactor = acos(v3fTL.DotProduct(v3fTR));
}
return m_fltFlatnessFactor;
}
void FindTopLeftNormalVector(Vector3f& a_v3fTL)
{
//Get our top left, top right, and bottom left points.
Point3f& p3fTL;
Point3f& p3fTR;
Point3f& p3fBL;
//Make a plane from them
Plane pln(p3fTL, p3fTR, p3fBL);
//Return the normal vector
a_v3fTL = pln.m_v3dNormal;
}
void FindBottomRightNormalVector(Vector3f& a_v3fBR)
{
Point3f& p3fTR;
Point3f& p3fBR;
Point3f& p3fBL;
//Make a plane from them
Plane pln(p3fTR, p3fBR, p3fBL);
//Return the normal vector
a_v3fBR = pln.m_v3dNormal;
}
};
//when we build our run-time dynamic quadtree for determining visible vertices and polygons, the tree will only grow as deep as the flatness
//factor dictates. this will be worked out once every x-frames, or even better once the POE has moved far enough away from the point of last
//generation that it is worthwhile re-doing it. Even if we re-gen the quadtree for flatness, we will still need to regen the clipped one because
//the view vector may change considerably, even given the same POE. | true |
e5291e975b32ba86a59595e6708ea6d04c31d33b | C++ | networkit/networkit | /networkit/cpp/centrality/LocalClusteringCoefficient.cpp | UTF-8 | 3,074 | 2.65625 | 3 | [
"MIT"
] | permissive | #include <omp.h>
#include <networkit/centrality/LocalClusteringCoefficient.hpp>
namespace NetworKit {
LocalClusteringCoefficient::LocalClusteringCoefficient(const Graph &G, bool turbo)
: Centrality(G, false, false), turbo(turbo) {
if (G.isDirected())
throw std::runtime_error("Not implemented: Local clustering coefficient is currently not "
"implemented for directed graphs");
if (G.numberOfSelfLoops())
throw std::runtime_error("Local Clustering Coefficient implementation does not support "
"graphs with self-loops. Call Graph.removeSelfLoops() first.");
}
void LocalClusteringCoefficient::run() {
count z = G.upperNodeIdBound();
scoreData.clear();
scoreData.resize(z); // $c(u) := \frac{2 \cdot |E(N(u))| }{\deg(u) \cdot ( \deg(u) - 1)}$
std::vector<index> inBegin;
std::vector<node> inEdges;
if (turbo) {
auto isOutEdge = [&](node u, node v) {
return G.degree(u) > G.degree(v) || (G.degree(u) == G.degree(v) && u < v);
};
inBegin.resize(G.upperNodeIdBound() + 1);
inEdges.resize(G.numberOfEdges());
index pos = 0;
for (index u = 0; u < G.upperNodeIdBound(); ++u) {
inBegin[u] = pos;
if (G.hasNode(u)) {
G.forEdgesOf(u, [&](node v) {
if (isOutEdge(v, u)) {
inEdges[pos++] = v;
}
});
}
}
inBegin[G.upperNodeIdBound()] = pos;
}
std::vector<std::vector<bool>> nodeMarker(omp_get_max_threads());
for (auto &nm : nodeMarker) {
nm.resize(z, false);
}
G.balancedParallelForNodes([&](node u) {
count d = G.degree(u);
if (d < 2) {
scoreData[u] = 0.0;
} else {
size_t tid = omp_get_thread_num();
count triangles = 0;
G.forEdgesOf(u, [&](node v) { nodeMarker[tid][v] = true; });
G.forEdgesOf(u, [&](node, node v) {
if (turbo) {
for (index i = inBegin[v]; i < inBegin[v + 1]; ++i) {
node w = inEdges[i];
if (nodeMarker[tid][w]) {
triangles += 1;
}
}
} else {
G.forEdgesOf(v, [&](node, node w) {
if (nodeMarker[tid][w]) {
triangles += 1;
}
});
}
});
G.forEdgesOf(u, [&](node, node v) { nodeMarker[tid][v] = false; });
// No division by 2 since triangles are counted twice as well!
scoreData[u] = (double)triangles / (double)(d * (d - 1));
if (turbo)
scoreData[u] *= 2; // in turbo mode, we count each triangle only once
}
});
hasRun = true;
}
double LocalClusteringCoefficient::maximum() {
return 1.0;
}
} // namespace NetworKit
| true |
557dc0863ef145ab060b128f2662aef179fbc409 | C++ | leeroun/PS | /NoComment/1339.cpp | UTF-8 | 490 | 3.109375 | 3 | [] | no_license | //±×¸®µð
//Gold 5
#include <iostream>
#include <string>
#include <cmath>
#include <algorithm>
using namespace std;
int main() {
int alphas[26] = { 0, };
string s;
int n;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> s;
for (int j = 0; j < s.size(); j++) {
alphas[s[j] - 'A'] += pow(10, s.size() - j) / 10;
}
}
sort(alphas, alphas + 26);
int num = 9, result = 0;
for (int i = 25; i >= 16; --i) {
result += alphas[i] * num--;
}
cout << result;
return 0;
}
| true |
ef0e982b5aee8a287e88855b32824e085ad0bffb | C++ | webpigeon/miscellany | /ideas/opengl-world/world.cpp | UTF-8 | 2,309 | 2.984375 | 3 | [] | no_license | #include <GL/glut.h>
void setMaterial ( GLfloat ambientR, GLfloat ambientG, GLfloat ambientB,
GLfloat diffuseR, GLfloat diffuseG, GLfloat diffuseB,
GLfloat specularR, GLfloat specularG, GLfloat specularB,
GLfloat shininess ) {
GLfloat ambient[] = { ambientR, ambientG, ambientB };
GLfloat diffuse[] = { diffuseR, diffuseG, diffuseB };
GLfloat specular[] = { specularR, specularG, specularB };
glMaterialfv(GL_FRONT_AND_BACK,GL_AMBIENT,ambient);
glMaterialfv(GL_FRONT_AND_BACK,GL_DIFFUSE,diffuse);
glMaterialfv(GL_FRONT_AND_BACK,GL_SPECULAR,specular);
glMaterialf(GL_FRONT_AND_BACK,GL_SHININESS,shininess);
}
void floorTile(int x, int z){
setMaterial(1.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,0.0,1);
glColor3f(0.2,0.2,0.2);
glBegin(GL_QUADS);
glVertex3f(x, 0.0, z);
glVertex3f(x+1, 0.0, z);
glVertex3f(x+1, 0.0, z+1);
glVertex3f(x, 0.0, z+1);
glEnd();
}
void wallSegmentX(int x, int z){
setMaterial(0.0,0.5,1.0,0.0,0.5,1.0,1.0,1.0,1.0,1);
glColor4f(0.5,0.5,0.5, 0.5);
glBegin(GL_QUADS);
glVertex3f(x, 2.0, z);
glVertex3f(x+1, 2.0, z);
glVertex3f(x+1, 0.0, z);
glVertex3f(x, 0.0, z);
glEnd();
}
void wallSegmentZ(int x, int z){
setMaterial(0.0,0.5,0.5,0.0,0.5,1.0,1.0,1.0,1.0,1);
glColor3f(0.5, 0.5, 0.5);
glBegin(GL_QUADS);
glVertex3f(x, 2.0, z);
glVertex3f(x, 2.0, z+1);
glVertex3f(x, 0.0, z+1);
glVertex3f(x, 0.0, z);
glEnd();
}
void doorX(int x, int z){
setMaterial(1.0,1.0,0.0,1.0,0.0,0.0,0.0,0.0,0.0,0.5);
glColor3f(205/255.0,183/255.0,158/255.0);
glBegin(GL_QUADS);
glVertex3f(x+0.15, 0.0, z+0.01);
glVertex3f(x+0.85, 0.0, z+0.01);
glVertex3f(x+0.85, 1.8, z+0.01);
glVertex3f(x+0.15, 1.8, z+0.01);
glEnd();
}
void render_teapot(int x, int z, float rotation) {
setMaterial(0.5,0.5,0.5,0.9,0.0,0.0,0.0,0.0,0.0,0.5);
glPushMatrix();
glTranslatef(x+0.5, 1, z+0.5);
glRotatef(rotation, 0, 1, 0);
glTranslatef(-(x+0.5), -1, -(z+0.5) );
glTranslatef(x+.5, 1, z);
glColor3f(1, 1, 1);
glutWireTeapot(1);
glPopMatrix();
}
void render_world(int tp_x, int tp_z, float rotation) {
for (int x=0; x<10; x++){
wallSegmentX(x,0);
for(int y=0; y<10; y++){
floorTile(x, y);
}
wallSegmentX(x,10);
}
for (int n=0; n<10; n++){
wallSegmentZ(0, n);
wallSegmentZ(10, n);
}
doorX(5,0);
}
| true |
7341c60f8c5be979447092a51661c4b303e3c581 | C++ | dSyncro/Yac | /Projects/Yac/Yac/Syntax/Statements/WhileStatement.h | UTF-8 | 577 | 2.984375 | 3 | [] | no_license | #pragma once
#include "Statement.h"
#include <Yac/Syntax/Expressions/Expression.h>
namespace Yac {
struct WhileStatement final : Statement {
public:
WhileStatement(Expression* condition, Statement* statement) : Statement(StatementType::While), _condition(condition), _statement(statement) {}
~WhileStatement() { delete _condition; delete _statement; }
const Expression* getCondition() const noexcept { return _condition; }
const Statement* getStatement() const noexcept { return _statement; }
private:
Expression* _condition;
Statement* _statement;
};
} | true |
ad78d98f43ead3b841a0d5d77384cb84af306bd6 | C++ | For-Bob/trunk | /note/design_mode/代码和描述/Observer/Observer/main.cpp | UTF-8 | 532 | 2.578125 | 3 | [] | no_license | #include "concreteobservera.h"
#include "concreteobserverb.h"
int main()
{
shared_ptr<ConcreteObserverA> ObA = make_shared<ConcreteObserverA>();
shared_ptr<ConcreteObserverB> ObB = make_shared<ConcreteObserverB>();
shared_ptr<Subject> sub = make_shared<Subject>();
sub.get()->addObserver(ObA.get());
sub.get()->addObserver(ObB.get());
sub.get()->update("there is subject , do you copy that?");
sub.get()->delObserver(ObA.get());
sub.get()->update("there is subject , revmode A");
return 0;
}
| true |