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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
163a342af809b4cb1121fff92cd00865d9514f9b | C++ | YuhanLiu11/ME759 | /HW10/reduce.cpp | UTF-8 | 260 | 2.609375 | 3 | [] | no_license | #include "reduce.h"
float reduce(const float* arr, const size_t l, const size_t r) {
float local_res = 0;
#pragma omp parallel for simd reduction(+:local_res)
for (size_t i = l; i < r; i++) {
local_res += arr[i];
}
return local_res;
} | true |
8dd5554a57630e64586de971cae98460e5c761c1 | C++ | Jia-Joe/AlgorithmLevel | /HashTable/HashTable/ChainSymbolTable.h | UTF-8 | 1,130 | 3.515625 | 4 | [] | no_license | #pragma once
template<class T1=char,class T2=int>
class ChainSymbolTable
{
private:
class Node
{
public:
T1 key;
T2 val;
Node *next;
Node(){ this->next = NULL; }
Node(T1 key,T2 val)
{
this->key = key;
this->val = val;
this->next = NULL;
}
};
public:
Node *first;
ChainSymbolTable()
{
first = new Node;
first = NULL;
}
ChainSymbolTable(T1 key, T2 val)
{
first = new Node(key,val);
}
T2 get(T1 key)
{
for (Node *x = first; x != NULL; x = x->next)
{
if (key == x->key)
{
return x->val;
}
}
return NULL;
}
void put(T1 key, T2 val)
{
for (Node *x = first; x != NULL; x = x->next)
{
if (key == x->key)
{
x->val = val;
}
}
Node *tmp = new Node(key, val);
tmp->next = first;
this->first = tmp;
}
void printList()
{
for (Node *x = first; x!= NULL; x = x->next)
{
cout << "[" << x->key << "," << x->val << "]--> ";
}
cout << "NULL" << endl;
}
virtual ~ChainSymbolTable()
{
Node *p=first;
while (p != NULL)
{
Node *x = p;
p = p->next;
delete x;
}
delete p;
//cout << "~ChainSymbolTable()" << endl;
}
};
| true |
a64357be66183b63fed87bcc8a50ccb76ccdb597 | C++ | rtodinova/OOP-praktikum | /DArray.cpp | UTF-8 | 1,136 | 3.390625 | 3 | [] | no_license | #include "DArray.h"
#include <iostream>
using namespace std;
DArray::DArray()
{
size = 0;
capacity = 0;
array = NULL;
}
DArray::DArray(DArray const& d)
{
size = d.size;
capacity = d.capacity;
array = new int[capacity];
for (int i = 0; i < size; i++)
array[i] = d.array[i];
}
DArray::~DArray()
{
delete[]array;
}
void DArray::resize()
{
capacity = capacity*1.5 +1;
int* array1 = new int[capacity];
for (int i = 0; i < size; i++)
array1[i] = array[i];
delete[]array;
array = array1;
}
void DArray::setValue(int index, int num)
{
if (index >= capacity)
{
resize();
for (int i = size; i < index; i++)
array[i] = 0;
}
else array[index] = num;
}
void DArray::pushBack(int num1)
{
array[size] = num1;
size++;
}
void DArray::popBack()
{
if (size>0)
size--;
}
void DArray::deleteAt(int index1)
{
for (int i = index1; i < size; i++)
array[i] = array[i + 1];
}
int DArray::getValue(int index2) const
{
return array[index2];
}
int DArray::getSize() const
{
return size;
}
void DArray::print() const
{
for (int i = 0; i < size; i++)
cout << "array[" << i << "]= " << array[i] << endl;
}
| true |
39c7a130926bc91f911a2be68021df075af1691f | C++ | medranSolus/PEA | /PEA/DisjunctiveSet.cpp | UTF-8 | 818 | 2.984375 | 3 | [] | no_license | #include "pch.h"
#include "DisjunctiveSet.h"
DisjunctiveSet::Node::Node(long long upNode, long long nodeRank) : up(upNode), rank(nodeRank) {}
long long DisjunctiveSet::findSet(long long vertex)
{
if (set[vertex].getUpNode() != vertex)
set[vertex].setUpNode(findSet(set[vertex].getUpNode()));
return set[vertex].getUpNode();
}
void DisjunctiveSet::makeSet(long long vertex)
{
set[vertex].setUpNode(vertex);
set[vertex].setRank(0);
}
void DisjunctiveSet::unionSets(unsigned long long start, unsigned long long end)
{
long long first = findSet(start), last = findSet(end);
if (first != last)
{
if (set[first].getRank() > set[last].getRank())
set[last].setUpNode(first);
else
{
set[first].setUpNode(last);
if (set[first].getRank() == set[last].getRank())
set[last].incrementRank();
}
}
} | true |
af9ed4c50d1ca4a3b0b1cb9826b9291495ee78ed | C++ | hal-seiya-yamazaki-0428/2D_Shooting | /sprite.cpp | SHIFT_JIS | 15,987 | 2.734375 | 3 | [] | no_license | #include <d3d9.h>
#include <d3dx9.h>
#include "texture.h"
#include "mydirectx.h"
//=====================================================
//O[oϐ
//=====================================================
static D3DCOLOR g_color = D3DCOLOR_RGBA(255, 255, 255, 255);
//====================================================
//\̐錾
//====================================================
typedef struct
{
D3DXVECTOR4 position; //_W
D3DCOLOR color; //_̐F
D3DXVECTOR2 UV; //uvW(texcoord)
}Vertex2d;
#define FVF_VERTEX2D (D3DFVF_XYZRHW | D3DFVF_DIFFUSE | D3DFVF_TEX1) //x,y,z,RHWĒ_f[^\
//====================================================
//|S`(ʏ)
//====================================================
void Sprite_Draw(int texId, float dx, float dy)
{
//_f[^
int w = Texture_GetWidth(texId);
int h = Texture_GetHeight(texId);
LPDIRECT3DDEVICE9 pDevice = GetDevice();
Vertex2d v[32] =
{
{ D3DXVECTOR4(dx - 0.5f, dy - 0.5f, 0.0f, 1.0f),g_color, D3DXVECTOR2(0, 0) },
{ D3DXVECTOR4(dx + w - 0.5f, dy - 0.5f, 0.0f, 1.0f),g_color, D3DXVECTOR2(1.0f, 0) },
{ D3DXVECTOR4(dx - 0.5f, dy + h - 0.5f, 0.0f, 1.0f),g_color, D3DXVECTOR2(0.0f, 1.0f) },
{ D3DXVECTOR4(dx + w - 0.5f, dy + h - 0.5f, 0.0f, 1.0f),g_color, D3DXVECTOR2(1.0f,1.0f) },
};
pDevice->SetFVF(FVF_VERTEX2D); //foCXɒ_f[^n
pDevice->SetTexture(0, Texture_GetTexture(texId)); //eNX`foCXɓn
pDevice->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, v, sizeof(Vertex2d));//}`̕`(hԂ), }`̐, _f[^̐擪AhX, _f[^̃TCY
//D3DPT_TRIANGLELISTɂƎOp`̕`
//D3DPT_POINTLISTɂƓ_̕`i_1Ő}`1Ƃ݂Ȃj
//D3DPT_LINELISTɂ2_1̕`
//D3DPT_LINESTRIPɂƘAĐ`
//D3DPT_TRIANGLESTRIPɂƎlp``(Op`̐ɓ)
//D3DPT_TRIANGLEFAN`
//~`
}
//====================================================
//|S`(ʏ)(xݒ)
//====================================================
void Sprite_Draw(int texId, float dx, float dy, int alpha)
{
//_f[^
int w = Texture_GetWidth(texId);
int h = Texture_GetHeight(texId);
LPDIRECT3DDEVICE9 pDevice = GetDevice();
Vertex2d v[32] =
{
{ D3DXVECTOR4(dx - 0.5f, dy - 0.5f, 0.0f, 1.0f),D3DCOLOR_RGBA(255, 255, 255, alpha), D3DXVECTOR2(0, 0) },
{ D3DXVECTOR4(dx + w - 0.5f, dy - 0.5f, 0.0f, 1.0f),D3DCOLOR_RGBA(255, 255, 255, alpha), D3DXVECTOR2(1.0f, 0) },
{ D3DXVECTOR4(dx - 0.5f, dy + h - 0.5f, 0.0f, 1.0f),D3DCOLOR_RGBA(255, 255, 255, alpha), D3DXVECTOR2(0.0f, 1.0f) },
{ D3DXVECTOR4(dx + w - 0.5f, dy + h - 0.5f, 0.0f, 1.0f),D3DCOLOR_RGBA(255, 255, 255, alpha), D3DXVECTOR2(1.0f,1.0f) },
};
pDevice->SetFVF(FVF_VERTEX2D); //foCXɒ_f[^n
pDevice->SetTexture(0, Texture_GetTexture(texId)); //eNX`foCXɓn
pDevice->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, v, sizeof(Vertex2d));//}`̕`(hԂ), }`̐, _f[^̐擪AhX, _f[^̃TCY
//D3DPT_TRIANGLELISTɂƎOp`̕`
//D3DPT_POINTLISTɂƓ_̕`i_1Ő}`1Ƃ݂Ȃj
//D3DPT_LINELISTɂ2_1̕`
//D3DPT_LINESTRIPɂƘAĐ`
//D3DPT_TRIANGLESTRIPɂƎlp``(Op`̐ɓ)
//D3DPT_TRIANGLEFAN`
//~`
}
//====================================================
//|S`(UVl)
//====================================================
void Sprite_Draw(int texId, float dx, float dy, int cx, int cy, int cw, int ch)
{
//_f[^
int w = Texture_GetWidth(texId);
int h = Texture_GetHeight(texId);
LPDIRECT3DDEVICE9 pDevice = GetDevice();
float u0 = cx / (float)w;
float v0 = cy / (float)h;
float u1 = (cx + cw) / (float)w;
float v1 = (cy + ch) / (float)h;
Vertex2d v[32] =
{
{ D3DXVECTOR4(dx - 0.5f, dy - 0.5f, 0.0f, 1.0f),g_color, D3DXVECTOR2(u0, v0) },
{ D3DXVECTOR4(dx + cw - 0.5f, dy - 0.5f, 0.0f, 1.0f),g_color, D3DXVECTOR2(u1, v0) },
{ D3DXVECTOR4(dx - 0.5f, dy + ch - 0.5f, 0.0f, 1.0f),g_color, D3DXVECTOR2(u0, v1) },
{ D3DXVECTOR4(dx + cw - 0.5f, dy + ch - 0.5f, 0.0f, 1.0f),g_color, D3DXVECTOR2(u1,v1) },
};
pDevice->SetFVF(FVF_VERTEX2D); //foCXɒ_f[^n
pDevice->SetTexture(0, Texture_GetTexture(texId)); //eNX`foCXɓn
pDevice->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, v, sizeof(Vertex2d));//}`̕`(hԂ), }`̐, _f[^̐擪AhX, _f[^̃TCY
//D3DPT_TRIANGLELISTɂƎOp`̕`
//D3DPT_POINTLISTɂƓ_̕`i_1Ő}`1Ƃ݂Ȃj
//D3DPT_LINELISTɂ2_1̕`
//D3DPT_LINESTRIPɂƘAĐ`
//D3DPT_TRIANGLESTRIPɂƎlp``(Op`̐ɓ)
//D3DPT_TRIANGLEFAN`
//~`
}
//====================================================
//|S`(UVl)(xݒ)
//====================================================
void Sprite_Draw(int texId, float dx, float dy, int cx, int cy, int cw, int ch, int alpha)
{
//_f[^
int w = Texture_GetWidth(texId);
int h = Texture_GetHeight(texId);
LPDIRECT3DDEVICE9 pDevice = GetDevice();
float u0 = cx / (float)w;
float v0 = cy / (float)h;
float u1 = (cx + cw) / (float)w;
float v1 = (cy + ch) / (float)h;
Vertex2d v[32] =
{
{ D3DXVECTOR4(dx - 0.5f, dy - 0.5f, 0.0f, 1.0f),D3DCOLOR_RGBA(255, 255, 255, alpha), D3DXVECTOR2(u0, v0) },
{ D3DXVECTOR4(dx + cw - 0.5f, dy - 0.5f, 0.0f, 1.0f),D3DCOLOR_RGBA(255, 255, 255, alpha), D3DXVECTOR2(u1, v0) },
{ D3DXVECTOR4(dx - 0.5f, dy + ch - 0.5f, 0.0f, 1.0f),D3DCOLOR_RGBA(255, 255, 255, alpha), D3DXVECTOR2(u0, v1) },
{ D3DXVECTOR4(dx + cw - 0.5f, dy + ch - 0.5f, 0.0f, 1.0f),D3DCOLOR_RGBA(255, 255, 255, alpha), D3DXVECTOR2(u1,v1) },
};
pDevice->SetFVF(FVF_VERTEX2D); //foCXɒ_f[^n
pDevice->SetTexture(0, Texture_GetTexture(texId)); //eNX`foCXɓn
pDevice->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, v, sizeof(Vertex2d));//}`̕`(hԂ), }`̐, _f[^̐擪AhX, _f[^̃TCY
//D3DPT_TRIANGLELISTɂƎOp`̕`
//D3DPT_POINTLISTɂƓ_̕`i_1Ő}`1Ƃ݂Ȃj
//D3DPT_LINELISTɂ2_1̕`
//D3DPT_LINESTRIPɂƘAĐ`
//D3DPT_TRIANGLESTRIPɂƎlp``(Op`̐ɓ)
//D3DPT_TRIANGLEFAN`
//~`
}
//====================================================
//|S`(])(g)
//====================================================
void Sprite_Draw(int texId, float dx, float dy, int cx, int cy, int cw, int ch, float angle, float center_x, float center_y, float zoom)
{
//_f[^
int w = Texture_GetWidth(texId);
int h = Texture_GetHeight(texId);
LPDIRECT3DDEVICE9 pDevice = GetDevice();
D3DXMATRIX mtxW, mtxR, mtxT, mtxIT, mtxS;
D3DXMatrixScaling(&mtxS, 1.0f + zoom, 1.0f + zoom, 1.0f + zoom); //s̃|C^,x,y,z
D3DXMatrixTranslation(&mtxT, -center_x - dx, -center_y - dy, 0); //sړ
D3DXMatrixTranslation(&mtxIT, center_x + dx, center_y + dy, 0); //̏ꏊɈړ
D3DXMatrixRotationZ(&mtxR, angle); //]
mtxW = mtxT * mtxS * mtxR * mtxIT;
float u0 = cx / (float)w;
float v0 = cy / (float)h;
float u1 = (cx + cw) / (float)w;
float v1 = (cy + ch) / (float)h;
Vertex2d v[32] =
{
{ D3DXVECTOR4(dx - 0.5f, dy - 0.5f, 0.0f, 1.0f),g_color, D3DXVECTOR2(u0, v0) },
{ D3DXVECTOR4(dx + cw - 0.5f, dy - 0.5f, 0.0f, 1.0f),g_color, D3DXVECTOR2(u1, v0) },
{ D3DXVECTOR4(dx - 0.5f, dy + ch - 0.5f, 0.0f, 1.0f),g_color, D3DXVECTOR2(u0, v1) },
{ D3DXVECTOR4(dx + cw - 0.5f, dy + ch - 0.5f, 0.0f, 1.0f),g_color, D3DXVECTOR2(u1,v1) },
};
for (int i = 0; i < 4; i++)
{
D3DXVec4Transform(&v[i].position, &v[i].position, &mtxW);
}
pDevice->SetFVF(FVF_VERTEX2D); //foCXɒ_f[^n
pDevice->SetTexture(0, Texture_GetTexture(texId)); //eNX`foCXɓn
pDevice->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, v, sizeof(Vertex2d));//}`̕`(hԂ), }`̐, _f[^̐擪AhX, _f[^̃TCY
//D3DPT_TRIANGLELISTɂƎOp`̕`
//D3DPT_POINTLISTɂƓ_̕`i_1Ő}`1Ƃ݂Ȃj
//D3DPT_LINELISTɂ2_1̕`
//D3DPT_LINESTRIPɂƘAĐ`
//D3DPT_TRIANGLESTRIPɂƎlp``(Op`̐ɓ)
//D3DPT_TRIANGLEFAN`
//~`
}
//====================================================
//|S`(])(g)(Fw)
//====================================================
void Sprite_Draw(int texId, float dx, float dy, int cx, int cy, int cw, int ch, float angle, float center_x, float center_y, float zoom, D3DXCOLOR color)
{
//_f[^
int w = Texture_GetWidth(texId);
int h = Texture_GetHeight(texId);
LPDIRECT3DDEVICE9 pDevice = GetDevice();
D3DXMATRIX mtxW, mtxR, mtxT, mtxIT, mtxS;
D3DXMatrixScaling(&mtxS, 1.0f + zoom, 1.0f + zoom, 1.0f + zoom); //s̃|C^,x,y,z
D3DXMatrixTranslation(&mtxT, -center_x - dx, -center_y - dy, 0); //sړ
D3DXMatrixTranslation(&mtxIT, center_x + dx, center_y + dy, 0); //̏ꏊɈړ
D3DXMatrixRotationZ(&mtxR, angle); //]
mtxW = mtxT * mtxS * mtxR * mtxIT;
float u0 = cx / (float)w;
float v0 = cy / (float)h;
float u1 = (cx + cw) / (float)w;
float v1 = (cy + ch) / (float)h;
Vertex2d v[32] =
{
{ D3DXVECTOR4(dx - 0.5f, dy - 0.5f, 0.0f, 1.0f),color, D3DXVECTOR2(u0, v0) },
{ D3DXVECTOR4(dx + cw - 0.5f, dy - 0.5f, 0.0f, 1.0f),color, D3DXVECTOR2(u1, v0) },
{ D3DXVECTOR4(dx - 0.5f, dy + ch - 0.5f, 0.0f, 1.0f),color, D3DXVECTOR2(u0, v1) },
{ D3DXVECTOR4(dx + cw - 0.5f, dy + ch - 0.5f, 0.0f, 1.0f),color, D3DXVECTOR2(u1,v1) },
};
for (int i = 0; i < 4; i++)
{
D3DXVec4Transform(&v[i].position, &v[i].position, &mtxW);
}
pDevice->SetFVF(FVF_VERTEX2D); //foCXɒ_f[^n
pDevice->SetTexture(0, Texture_GetTexture(texId)); //eNX`foCXɓn
pDevice->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, v, sizeof(Vertex2d));//}`̕`(hԂ), }`̐, _f[^̐擪AhX, _f[^̃TCY
//D3DPT_TRIANGLELISTɂƎOp`̕`
//D3DPT_POINTLISTɂƓ_̕`i_1Ő}`1Ƃ݂Ȃj
//D3DPT_LINELISTɂ2_1̕`
//D3DPT_LINESTRIPɂƘAĐ`
//D3DPT_TRIANGLESTRIPɂƎlp``(Op`̐ɓ)
//D3DPT_TRIANGLEFAN`
//~`
}
//====================================================
//|S`(UVl)(E])
//====================================================
void Sprite_Reverse_Draw(int texId, float dx, float dy, int cx, int cy, int cw, int ch)
{
//_f[^
int w = Texture_GetWidth(texId);
int h = Texture_GetHeight(texId);
LPDIRECT3DDEVICE9 pDevice = GetDevice();
float u0 = cx / (float)w;
float v0 = cy / (float)h;
float u1 = (cx + cw) / (float)w;
float v1 = (cy + ch) / (float)h;
Vertex2d v[32] =
{
{ D3DXVECTOR4(dx - 0.5f, dy - 0.5f, 0.0f, 1.0f),g_color, D3DXVECTOR2(u1, v0) },
{ D3DXVECTOR4(dx + cw - 0.5f, dy - 0.5f, 0.0f, 1.0f),g_color, D3DXVECTOR2(u0, v0) },
{ D3DXVECTOR4(dx - 0.5f, dy + ch - 0.5f, 0.0f, 1.0f),g_color, D3DXVECTOR2(u1, v1) },
{ D3DXVECTOR4(dx + cw - 0.5f, dy + ch - 0.5f, 0.0f, 1.0f),g_color, D3DXVECTOR2(u0,v1) },
};
pDevice->SetFVF(FVF_VERTEX2D); //foCXɒ_f[^n
pDevice->SetTexture(0, Texture_GetTexture(texId)); //eNX`foCXɓn
pDevice->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, v, sizeof(Vertex2d));//}`̕`(hԂ), }`̐, _f[^̐擪AhX, _f[^̃TCY
//D3DPT_TRIANGLELISTɂƎOp`̕`
//D3DPT_POINTLISTɂƓ_̕`i_1Ő}`1Ƃ݂Ȃj
//D3DPT_LINELISTɂ2_1̕`
//D3DPT_LINESTRIPɂƘAĐ`
//D3DPT_TRIANGLESTRIPɂƎlp``(Op`̐ɓ)
//D3DPT_TRIANGLEFAN`
//~`
}
//====================================================
//|S`(UVl)(E])
//====================================================
void Sprite_Upside_Draw(int texId, float dx, float dy, int cx, int cy, int cw, int ch)
{
//_f[^
int w = Texture_GetWidth(texId);
int h = Texture_GetHeight(texId);
LPDIRECT3DDEVICE9 pDevice = GetDevice();
float u0 = cx / (float)w;
float v0 = cy / (float)h;
float u1 = (cx + cw) / (float)w;
float v1 = (cy + ch) / (float)h;
Vertex2d v[32] =
{
{ D3DXVECTOR4(dx - 0.5f, dy - 0.5f, 0.0f, 1.0f),g_color, D3DXVECTOR2(u0, v1) },
{ D3DXVECTOR4(dx + cw - 0.5f, dy - 0.5f, 0.0f, 1.0f),g_color, D3DXVECTOR2(u1, v1) },
{ D3DXVECTOR4(dx - 0.5f, dy + ch - 0.5f, 0.0f, 1.0f),g_color, D3DXVECTOR2(u0, v0) },
{ D3DXVECTOR4(dx + cw - 0.5f, dy + ch - 0.5f, 0.0f, 1.0f),g_color, D3DXVECTOR2(u1,v0) },
};
pDevice->SetFVF(FVF_VERTEX2D); //foCXɒ_f[^n
pDevice->SetTexture(0, Texture_GetTexture(texId)); //eNX`foCXɓn
pDevice->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, v, sizeof(Vertex2d));//}`̕`(hԂ), }`̐, _f[^̐擪AhX, _f[^̃TCY
//D3DPT_TRIANGLELISTɂƎOp`̕`
//D3DPT_POINTLISTɂƓ_̕`i_1Ő}`1Ƃ݂Ȃj
//D3DPT_LINELISTɂ2_1̕`
//D3DPT_LINESTRIPɂƘAĐ`
//D3DPT_TRIANGLESTRIPɂƎlp``(Op`̐ɓ)
//D3DPT_TRIANGLEFAN`
//~`
}
void Sprite_SetColor(D3DXCOLOR color)
{
g_color = color;
}
| true |
f9a6df0fb6f00d9e5f8f386499bac3201504c87a | C++ | aukdata/gb7avr | /firmware/src/utils.cpp | UTF-8 | 655 | 2.5625 | 3 | [] | no_license | #include <stdlib.h>
#include <util/delay.h>
#include "utils.hpp"
int __cxa_guard_acquire(__guard* g)
{
return !*reinterpret_cast<char*>(g);
}
void __cxa_guard_release(__guard* g)
{
*reinterpret_cast<char*>(g) = 1;
}
void __cxa_guard_abort(__guard*g ) {}
void __cxa_pure_virtual() {}
void* operator new(size_t size)
{
return malloc(size);
}
void operator delete(void* ptr, size_t size)
{
free(ptr);
}
void* operator new[](size_t size)
{
return malloc(size);
}
void operator delete[](void* ptr, size_t)
{
free(ptr);
}
void delay_ms(int miliseconds) noexcept
{
for (int i = 0; i < miliseconds; i++)
_delay_ms(1);
}
| true |
ee89760b094d2a11a114e9bba88220dbf42ce676 | C++ | tyoma/micro-profiler | /frontend/tests/ProjectionViewTests.cpp | UTF-8 | 4,815 | 2.671875 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | #include <frontend/projection_view.h>
#include "helpers.h"
#include <test-helpers/helpers.h>
#include <ut/assert.h>
#include <ut/test.h>
using namespace std;
namespace micro_profiler
{
namespace tests
{
namespace
{
struct POD
{
int a;
int b;
double c;
};
POD mkpod(int a, int b, double c)
{
POD v = { a,b ,c };
return v;
}
}
begin_test_suite( ProjectionViewTests )
test( ProjectionViewIsAListModel )
{
// INIT
vector< pair<string, POD> > u1;
vector< pair<int, string> > u2;
// INIT / ACT
projection_view<vector< pair<string, POD> >, double> pv1(u1);
projection_view<vector< pair<int, string> >, string> pv2(u2);
// INIT / ACT
wpl::list_model<double> &m1 = pv1;
wpl::list_model<string> &m2 = pv2;
// ASSERT
assert_equal(0u, m1.get_count());
assert_equal(0u, m2.get_count());
}
test( ValueIsProjectedAccordinglyToTheTransform )
{
typedef pair<int, POD> value_type;
// INIT
value_type values[] = {
make_pair(101, mkpod(13, 109, 10.4)),
make_pair(102, mkpod(17, 110, 11.4)),
make_pair(103, mkpod(18, 1109, 10.3)),
make_pair(104, mkpod(19, 11, 19.7)),
};
auto underlying = mkvector(values);
projection_view<vector<value_type>, double> pv1(underlying);
projection_view<vector<value_type>, int> pv2(underlying);
// ACT
pv1.project([] (value_type v) { return v.second.c; });
auto r1 = get_values(pv1);
// ASSERT
double reference1[] = { 10.4, 11.4, 10.3, 19.7, };
assert_equal(reference1, r1);
// ACT
pv2.project([] (value_type v) { return v.second.a; });
auto r2 = get_values(pv2);
// ASSERT
double reference2[] = { 13, 17, 18, 19, };
assert_equal(reference2, r2);
// ACT
pv2.project([] (value_type v) { return v.second.b; });
r2 = get_values(pv2);
// ASSERT
double reference3[] = { 109, 110, 1109, 11, };
assert_equal(reference3, r2);
// ACT
underlying.push_back(make_pair(1000, mkpod(100, 100, 100.1)));
r1 = get_values(pv1);
r2 = get_values(pv2);
// ASSERT
double reference4[] = { 10.4, 11.4, 10.3, 19.7, 100.1, };
double reference5[] = { 109, 110, 1109, 11, 100, };
assert_equal(reference4, r1);
assert_equal(reference5, r2);
}
test( ProjectionBecomesEmptyOnReset )
{
typedef pair<int, POD> value_type;
// INIT
value_type values[] = {
make_pair(101, mkpod(13, 109, 10.4)),
make_pair(102, mkpod(17, 110, 11.4)),
make_pair(103, mkpod(18, 1109, 10.3)),
make_pair(104, mkpod(19, 11, 19.7)),
};
auto underlying = mkvector(values);
projection_view<vector<value_type>, double> pv(underlying);
pv.project([] (value_type v) { return v.second.c; });
// ACT
pv.project();
// ASSERT
assert_equal(0u, pv.get_count());
}
test( ProjectionIsInvalidatedOnMutation )
{
typedef pair<int, POD> value_type;
// INIT
value_type values[] = {
make_pair(101, mkpod(13, 109, 10.4)),
make_pair(102, mkpod(17, 110, 11.4)),
make_pair(103, mkpod(18, 1109, 10.3)),
make_pair(104, mkpod(19, 11, 19.7)),
};
auto underlying = mkvector(values);
projection_view<vector<value_type>, double> pv(underlying);
auto invalidations = 0;
vector<unsigned> log;
auto conn = pv.invalidate += [&] (projection_view<vector<value_type>, double>::index_type item) {
// ACT
invalidations++;
log.push_back(static_cast<unsigned>(pv.get_count()));
// ASSERT
assert_equal(wpl::index_traits::npos(), item);
};
// ACT
pv.fetch();
// ASSERT
assert_equal(1, invalidations);
assert_equal(plural + 0u, log);
// ACT
pv.project([] (value_type v) { return v.second.c; });
pv.fetch();
// ASSERT
assert_equal(3, invalidations);
assert_equal(plural + 0u + 4u + 4u, log);
// ACT
pv.project();
// ASSERT
assert_equal(4, invalidations);
assert_equal(plural + 0u + 4u + 4u + 0u, log);
}
test( ProjectionViewProvidesTrackablesUpdatedOnFetch )
{
typedef pair<int, POD> value_type;
// INIT
value_type values[] = {
make_pair(101, mkpod(13, 109, 10.4)),
make_pair(102, mkpod(17, 110, 11.4)),
make_pair(103, mkpod(18, 1109, 10.3)),
make_pair(104, mkpod(19, 11, 19.7)),
};
auto underlying = mkvector(values);
projection_view<vector<value_type>, double> pv(underlying);
pv.project([] (value_type v) { return v.second.c; });
// INIT / ACT
auto t = pv.track(2);
// ACT / ASSERT
assert_equal(2u, t->index());
// ACT
underlying.insert(underlying.begin(), make_pair(10, mkpod(1, 1, 1)));
pv.fetch();
// ASSERT
assert_equal(3u, t->index());
}
end_test_suite
}
}
| true |
7c58dd4cd230a9b2ea52cf6c06d2000342b1949e | C++ | Luckily777/C- | /C++0c061401.cpp | GB18030 | 5,589 | 3.53125 | 4 | [] | no_license |
//listʵ
#include <iostream>
using namespace std;
//List: ˫ͷѭ
template < class T>
struct ListNode
{
T _value;
ListNode<T>* _next;
ListNode<T>* _prev;
ListNode(const T& val = T())
:_value(val)
, _next(nullptr)
, _prev(nullptr)
{}
};
template <class T, class Ref, class Ptr>
struct ListIterator
{
typedef ListNode<T> Node;
typedef ListIterator<T, Ref, Ptr> Self;
ListIterator(Node* node)
:_node(node)
{}
//ã *iterator ---> ȡڵvalue
Ref operator*()
{
return _node->_value;
}
// ָ->Ա
Ptr operator->()
{
return &_node->_value;
}
// ++: ƶһԪصλ
Self& operator++()
{
_node = _node->_next;
return *this;
}
Self& operator--()
{
_node = _node->_prev;
return *this;
}
bool operator!=(const Self& it)
{
return _node != it._node;
}
Node* _node;
};
/*
template <class T>
struct ConstListIterator
{
typedef ListNode<T> Node;
typedef ConstListIterator<T> Self;
ConstListIterator(Node* node)
:_node(node)
{}
//ã *iterator ---> ȡڵvalue
const T& operator*()
{
return _node->_value;
}
// ָ->Ա
const T* operator->()
{
return &_node->_value;
}
// ++: ƶһԪصλ
Self& operator++()
{
_node = _node->_next;
return *this;
}
Self& operator--()
{
_node = _node->_prev;
return *this;
}
bool operator!=(const Self& it)
{
return _node != it._node;
}
Node* _node;
};
*/
template <class T>
class List
{
public:
typedef ListNode<T> Node;
typedef ListIterator<T, T&, T*> iterator;
//ͨconstηconst
typedef ListIterator<T, const T&, const T*> const_iterator;
iterator begin()
{
//һԪصλ
return iterator(_header->_next);
}
iterator end()
{
//һԪصһλ
return iterator(_header);
}
const_iterator begin() const
{
//һԪصλ
return const_iterator(_header->_next);
}
const_iterator end() const
{
//һԪصһλ
return const_iterator(_header);
}
List()
:_header(new Node)
{
//ѭṹ
_header->_next = _header->_prev = _header;
}
void pushBack(const T& val)
{
//Node* cur = new Node(val);
////
//Node* prev = _header->_prev;
//prev->_next = cur;
//cur->_prev = prev;
//cur->_next = _header;
//_header->_prev = cur;
insert(end(), val);
}
void pushFront(const T& val)
{
insert(begin(), val);
}
void popBack()
{
erase(--end());
}
void popFront()
{
erase(begin());
}
void insert(iterator pos, const T& val)
{
Node* cur = new Node(val);
Node* node = pos._node;
Node* prev = node->_prev;
prev->_next = cur;
cur->_prev = prev;
cur->_next = node;
node->_prev = cur;
}
//ɾposʧЧ
//ֵ һԪصλ
iterator erase(iterator pos)
{
//ɾͷ㣨_header)
if (pos != end())
{
Node* node = pos._node;
Node* prev = node->_prev;
Node* next = node->_next;
delete node;
prev->_next = next;
next->_prev = prev;
return iterator(next);
}
return pos;
}
size_t size() const
{
size_t count = 0;
for (const auto& e : *this)
++count;
return count;
}
~List()
{
if (_header)
{
clear();
delete _header;
_header = nullptr;
}
}
void clear()
{
//зͷ
Node* cur = _header->_next;
while (cur != _header)
{
Node* next = cur->_next;
delete cur;
cur = next;
}
//¹ѭṹ
_header->_next = _header->_prev = _header;
}
List(const List<T>& lst)
:_header(new Node)
{
_header->_next = _header->_prev = _header;
//Ԫ
for (const auto& e : lst)
pushBack(e);
}
//ִд
List<T>& operator=(List<T> lst)
{
swap(_header, lst._header);
return *this;
}
private:
Node* _header;
};
template <class T>
void printList(const List<T>& lst)
{
List<T>::const_iterator it = lst.begin();
while (it != lst.end())
{
cout << *it << " ";
//*it = T();
++it;
}
cout << endl;
}
template <class T>
void printListFor(const List<T>& lst)
{
for (const auto& e : lst)
{
cout << e << " ";
}
cout << endl;
}
class B
{
public:
B(int a = 1, int b = 1)
:_a(a)
, _b(b)
{}
int _a;
int _b;
};
void test()
{
List<int> lst;
lst.pushBack(1);
lst.pushBack(2);
lst.pushBack(3);
lst.pushBack(4);
printList(lst);
printListFor(lst);
}
void test2()
{
List<int> lst;
lst.insert(lst.begin(), 1);
printListFor(lst);
lst.pushBack(2);
printListFor(lst);
lst.pushFront(0);
printListFor(lst);
List<int>::iterator it = ++lst.begin();
lst.insert(it, -1);
printListFor(lst);
it = lst.erase(it);
printListFor(lst);
cout << *it << endl;
}
void test3()
{
List<int> lst;
lst.pushBack(1);
lst.pushBack(2);
lst.pushBack(3);
lst.pushBack(4);
lst.pushBack(5);
lst.pushBack(6);
cout << "size:" << lst.size() << endl;
printListFor(lst);
lst.popBack();
printListFor(lst);
lst.popFront();
printListFor(lst);
lst.popBack();
printListFor(lst);
lst.popFront();
printListFor(lst);
lst.popBack();
printListFor(lst);
lst.popFront();
printListFor(lst);
lst.popFront();
printListFor(lst);
lst.popBack();
printListFor(lst);
}
void test4()
{
List<int> lst;
lst.pushBack(1);
lst.pushBack(2);
lst.pushBack(3);
lst.pushBack(4);
lst.pushBack(5);
lst.pushBack(6);
List<int> copy(lst);
List<int> lst2;
lst2.pushBack(100);
lst2 = copy;
}
//int main()
//{
// //test();
// //test2();
// //test3();
// test4();
// return 0;
//} | true |
e28b63decda0821fdaf2176b4536fc0e64fc219c | C++ | ZeroDestru/meus-pogramas-em-C | /Arvores, listas encadeadas, entre outros/Resta um.cpp | UTF-8 | 1,507 | 2.84375 | 3 | [] | no_license | #include<stdio.h>
#include<stdlib.h>
#include <time.h>
#include <iostream>
struct dados{
struct dados *esq;
int info;
struct dados *dir;
};
typedef struct dados NO;
void cria_LSE(NO ** Inicio, NO **Fim){
*Inicio=NULL;
*Fim=NULL;
}
void Ins_Inicio(NO **Inicio, NO **Fim, int v){
NO *p = (NO *)calloc(1, sizeof(NO));
p->info = v;
p->esq = NULL;
p->dir = *Inicio;
if (*Inicio==NULL) // Se lista vazia
*Fim = p;
else
(*Inicio)->esq = p;
*Inicio = p;
}
void Imprime(NO *Inicio){
NO *p = Inicio;
printf("\nNULL");
while (p!=NULL)
{
printf("<--%d-->", p->info);
p = p->dir;
}
printf("NULL\n\n");
}
void Remove(NO *Inicio, int r, NO *c ){
NO *q = c->dir;
NO *p = c->esq;
p->dir = q;
q->esq = p;
free(c);
}
main(){
printf("Resta UM\n");
int b, n;
NO *Inicio, *Fim, *r;
int op, val, ele;
time_t t;
srand((unsigned) time(&t));
printf("digite qual a quantidade de elementos vai ter: ");
scanf("%d", &ele);
cria_LSE(&Inicio, &Fim);
for(int i=0; i < ele; i++){
b = (rand() % 20);
Ins_Inicio(&Inicio, &Fim, b);
}
printf("digite qual o intervalo para remocao: ");
scanf("%d", &n);
Imprime(Inicio);
ele--;
r = Inicio;
if(n > 1){
n--;
}
while(1){
for(int j=0; j<n; j++){
if(r != Fim){
r = r->dir;
}else{
r = Inicio;
}
}
Remove(Inicio, n, r);
Imprime(Inicio);
}
}
| true |
1908b807705f446d5a03f4f844908132aea81149 | C++ | sooyoungmoon/WSN_Simulation | /DIHA_NEWLKH/DIHA_NEWLKH/Atk_FRA.cpp | UHC | 1,676 | 2.5625 | 3 | [] | no_license |
#include "Atk_FRA.h"
#include <fstream>
using namespace std;
void Atk_FRA::forgeEvntMsg(EvntMsg* msg) // ʿ?
{
int hop = msg->hop;
if (hop == 0) // hop count 0̸ ¥ MAC
{
list<MAC*>::iterator it = msg->macs.begin();
for (it; it != msg->macs.end(); it++)
{
MAC* mac = *it;
// MAC 尡 Ѽ 尡 ƴϸ ߸ CODE (-1)
if (mac->origin->cmprmsd == false)
mac->code = -1;
}
this->numAtk++; // Ƚ +1
msg->falseReport = true; //
}
/*
int hop = rep->hop;
Node* CoS = rep ->CoS;
int cmprmsd = CoS->cmprmsd;
if (hop == 0) // hop count 0̸ ¥ MAC
{
int i;
for(i = 0; i < macsPerRep; i++)
{
if( i < compKeys); // Ѽյ Ű ؼ ڰ Ȯ MAC
else
sec->macs[i][1] = 0; // ڰ Ű ؼ Ʋ MAC Ե
}
this->numAtk++; // Ƚ +1
}
*/
}
void Atk_FRA::initCompNodes (Node nodes[])
{
// Ѽ Ѽ
for (int i =0; i < NUM_NODES; i++)
{
int r = gen1.genRandInt(100);
//int r = gen1.uniformI(0, 100);
if ( r < CNR)
nodes[i].cmprmsd = true;
}
}
void Atk_FRA::testCompNodes (Node nodes[])
{
ofstream out("tst_Atk.txt");
int numCmprmsd = 0;
for (int i =0; i < NUM_NODES; i++)
{
if ( nodes[i].cmprmsd == true)
{
out << "Compromised node " << ++numCmprmsd << ":";
out << "node " << i << endl;
}
}
out.close();
}
Atk_FRA::Atk_FRA() : Atk()
{
}
Atk_FRA::~Atk_FRA()
{
} | true |
202231470b51764318bc4c0061b68dae27872f64 | C++ | Maxinary/Raytracer | /Ray.cpp | UTF-8 | 331 | 2.890625 | 3 | [] | no_license | #include "Ray.h"
Ray::Ray():pos(vectors::vec3(0,0,0)),direction(vectors::vec3(0,0,0)){}
Ray::Ray(const vectors::vec3 pos, const vectors::vec3 direction) : pos(pos), direction(direction){}
vectors::vec3 Ray::posAtDist(double dist){
return vectors::vec3(pos.x+direction.x*dist, pos.y+direction.y*dist, pos.z+direction.z*dist);
}
| true |
1f752e917653e0633bac30b480982b08baad1a27 | C++ | chief-r0cka/poisson-blend | /poisson.cpp | UTF-8 | 4,931 | 3.15625 | 3 | [] | no_license | #include "poisson.h"
// Считаем лапласиан как поток векторного поля через данную точку,
// Аппроксимируя суммой частных производных первого порядка
float Poisson::laplace(cv::Point p, cv::Mat& img){
return 4*img.at<float>(p)
- img.at<float>(p + cv::Point(1,0)) - img.at<float>(p + cv::Point(-1,0))
- img.at<float>(p + cv::Point(0,1)) - img.at<float>(p + cv::Point(0,-1));
}
int Poisson::neighboursCount(cv::Point p){
int N = 0;
for(auto n : neighbours){
bool outOfBorders = (p+n).x < 0 && (p+n).y < 0 && (p+n).x >= Omega.cols && (p+n).y >= Omega.rows;
if( !outOfBorders && Omega.at<float>(p + n) != 0 ) N++;
}
return N;
}
// Вносим в f только точки, входящие во внутренность множества
// Далее запускаем построение системы
void Poisson::updateMatrices(cv::Mat & overlayingImage, cv::Mat & baseImage){
baseImage.convertTo(S, CV_32F);
overlayingImage.convertTo(Omega, CV_32F);
for(int y = 0; y < Omega.rows; ++y){
for(int x = 0; x < Omega.cols; ++x){
cv::Point p(x,y);
if(Omega.at<float>(p) != 0 && neighboursCount(p) == 4) f[p] = Omega.at<float>(p);
}
}
buildSLE();
}
// Система составляется следующим образом
// Итерируем по всем пикселям f_p в f.
// Задаем коэффициенты разреженной матрицы A:
// При f_p стоит 4, при его соседях, если они принадлежат Omega, -1, то есть задаётся аппроксимация лапласиана
// В p-том элементе вектор-столбце b сумма по всем граничным значениям его соседей на границе
// Пройдя всех соседей, добавляем в b_p известное значение лапласиана
// И решаем в численном виде уравнение Пуассона для каждого пикселя: \nabla_d (f_p) - \nabla_b (f) = Sum
// Где nabla_d - дискретный, а nabla_b - известный граничный лапласиан, а Sum - сумма значений на границе
void Poisson::buildSLE(){
A = Eigen::SparseMatrix<double>(f.size(), f.size());
b = Eigen::VectorXd::Zero(f.size());
for(pixelMapIterator f_p = f.begin(); f_p != f.end(); ++f_p){
int p = std::distance<pixelMapIterator> (f.begin(), f_p);
A.insert(p, p) = 4;
for(auto n : neighbours){
if(neighboursCount(f_p->first + n) == 4){
pixelMapIterator f_q = f.find(f_p->first + n);
int q = std::distance<pixelMapIterator>(f.begin(), f_q);
A.insert(p,q) = -1;
}
else b(p) += S.at<float>(f_p->first + n);
}
b(p) += laplace(f_p->first, Omega);
}
std::cout << "SLE has been builded" << std::endl;
}
// Каждая строка матрицы A будет иметь вид (0,...0,-1,0,...,0,-1,4,-1,0,...0,-1,0,...)
// Т.е., A будет очень сильно разреженной.
// Библиотека Eigen предоставляет класс солверов для систем с разреженными матрицами.
// В качестве прямых методов решения - LL^T, LDL^T, QR и LU - разложения.
// LL^T (Холецкий) использует большее количество умножений + корни => потеря в скорости
// QR - сильно замедлено из-за необходимости сжимать матрицу при помощи makeCompressed
// LU - разложение будет проходить по циклу большее количество раз, чем при использовании QR.
// Остаётся LDL^T, обладающий очень хорошей устойчивостью и довольно быстрый.
cv::Mat Poisson::getResult(){
Eigen::SimplicialLDLT<Eigen::SparseMatrix<double>> LDLT(A);
Eigen::VectorXd x = LDLT.solve(b);
std::cout << "Solved: min->" << *(std::min_element(x.data(), x.data()+x.size())) << ", max ->"
<< *(std::max_element(x.data(),x.data()+x.size())) << std::endl;
cv::Mat result = S.clone();
for(pixelMapIterator f_p = f.begin(); f_p != f.end(); ++f_p){
int p = std::distance<pixelMapIterator> (f.begin(), f_p);
float color = x(p);
if (neighboursCount(f_p->first) == 4) result.at<float>(f_p->first) = color;
}
result.convertTo(result, CV_8U);
f.clear();
return result;
}
| true |
e2be1ee730b661a4080232787e5d6cf86d79d41f | C++ | mtfranzen/luci-connect | /test/src/luciconnect/node_test.cc | UTF-8 | 4,326 | 2.625 | 3 | [
"MIT"
] | permissive | #include "luciconnect/node_tests.h"
namespace {
class ServiceMock : luciconnect::Node {
public:
ServiceMock(std::shared_ptr<luciconnect::Connection> connection) : luciconnect::Node(connection) {}
void Run() {
this->Connect();
json register_message = {
{"serviceName", "addingNumbers"},
{"description", "Adds two numbers"},
{"inputs", {
{"arg1", "number"},
{"arg2", "number"}
}},
{"outputs", {
{"sum", "number"}
}},
{"exampleCall", {
{"run", "addingNumbers"},
{"callId", 4386},
{"arg1", 42},
{"arg2", 1337}
}}
};
this->SendRun(0, "RemoteRegister", register_message);
}
json result;
bool canceled = false;
bool error = false;
int64_t progress = -1;
protected:
void HandleRun(int64_t callId, std::string serviceName, json inputs, std::vector<luciconnect::Attachment*> attachments) {
if (inputs.count("arg1") != 1 || inputs.count("arg2") != 1)
throw "Erroneous message";
int64_t arg1 = inputs["arg1"];
int64_t arg2 = inputs["arg2"];
json result = {{"sum", arg1 + arg2}};
this->SendResult(callId, result);
};
void HandleCancel(int64_t callId) {
this->canceled = true;
};
void HandleResult(int64_t callId, json result, std::vector<luciconnect::Attachment*> attachments) {
this->result = result;
LOG(DEBUG) << "result: " << result.dump();
};
void HandleProgress(int64_t callId, int64_t percentage, std::vector<luciconnect::Attachment*> attachments, json intermediateResult) {
this->progress = percentage;
LOG(DEBUG) << "progress";
};
void HandleError(int64_t callId, std::string error) {
LOG(DEBUG) << "error: " << error;
this->error = true;
};
};
// Mock simply sending one message
class ClientMock : luciconnect::Node {
public:
ClientMock(std::shared_ptr<luciconnect::Connection> connection) : luciconnect::Node(connection) {}
void Run() {
this->Connect();
this->SendRun(0, "addingNumbers", {{"arg1", 5}, {"arg2", 7}});
}
json result;
bool canceled = false;
bool error = false;
int64_t progress = -1;
protected:
void HandleRun(int64_t callId, std::string serviceName, json inputs, std::vector<luciconnect::Attachment*> attachments) {
};
void HandleCancel(int64_t callId) {
this->canceled = true;
};
void HandleResult(int64_t callId, json result, std::vector<luciconnect::Attachment*> attachments) {
this->result = result;
};
void HandleProgress(int64_t callId, int64_t percentage, std::vector<luciconnect::Attachment*> attachments, json intermediateResult) {
this->progress = percentage;
};
void HandleError(int64_t callId, std::string error) {
this->error = true;
};
};
TEST_F(AbstractNodeTest, ClientRunWrongService) {
std::shared_ptr<luciconnect::Connection> connection = std::make_shared<luciconnect::Connection>("127.0.0.1", 7654);
ClientMock* node_ = new ClientMock(connection);
node_->Run();
std::this_thread::sleep_for(std::chrono::seconds(1));
ASSERT_EQ(node_->error, true);
}
TEST_F(AbstractNodeTest, ServiceRegister) {
std::shared_ptr<luciconnect::Connection> connection = std::make_shared<luciconnect::Connection>("127.0.0.1", 7654);
ServiceMock* node_ = new ServiceMock(connection);
node_->Run();
std::this_thread::sleep_for(std::chrono::seconds(1));
ASSERT_EQ(node_->result.count("registeredName"), 1);
ASSERT_EQ(node_->result["registeredName"], "addingNumbers");
}
TEST_F(AbstractNodeTest, ClientServiceRun) {
std::shared_ptr<luciconnect::Connection> connection1 = std::make_shared<luciconnect::Connection>("127.0.0.1", 7654);
ServiceMock* service = new ServiceMock(connection1);
service->Run();
std::this_thread::sleep_for(std::chrono::seconds(1));
std::shared_ptr<luciconnect::Connection> connection2 = std::make_shared<luciconnect::Connection>("127.0.0.1", 7654);
ClientMock* client = new ClientMock(connection2);
client->Run();
std::this_thread::sleep_for(std::chrono::seconds(1));
json expected_result = {{"sum", 12}};
ASSERT_EQ(client->result, expected_result);
}
}
| true |
6d1235dbf2bcdc0f0ca47085106b5e09cf6cafe9 | C++ | ragavsachdeva/DynTTP | /Instance/Solution.hpp | UTF-8 | 4,239 | 3.15625 | 3 | [
"MIT"
] | permissive | #ifndef SOLUTION_HPP
#define SOLUTION_HPP
#include <vector>
#include "Instance.hpp"
#include "City.hpp"
#include "Item.hpp"
using namespace std;
#define PRINTALL(arr) for(int i = 0; i < arr.size(); i++) { cout << arr[i] << " "; } cout << endl;
class Solution {
public:
Solution(): tour({}), items({}), objective(-1*numeric_limits<double>::max()) {}
Solution(vector<int> tour, vector <bool> items): tour(tour), items(items), objective(-1*numeric_limits<double>::max()) {}
static int evalCount;
static double calculateObjective(Instance &instance, Solution current) {
evalCount++;
long long collectedWeight = 0;
double objectiveValue = 0.0;
double speedCoef = (instance.maxSpeed - instance.minSpeed) / instance.maxWeight;
auto &tour = current.tour;
auto &items = current.items;
auto nextAvailableCity = [&](int i) -> int {
i = (i+1) % tour.size();
while(!instance.cities[tour[i]].available) i = (i+1) % tour.size();
return i;
};
int start = 0;
int curr = start; int next;
do {
next = nextAvailableCity(curr);
City &currCity = instance.cities[tour[curr]];
City &nextCity = instance.cities[tour[next]];
int nextCityDistance = City::ttp_dist(currCity, nextCity);
for (Item item: currCity.items) {
if (!items[item.index]) continue;
collectedWeight += item.weight;
if (collectedWeight > instance.maxWeight) {
cerr << "Exceeded knapsack weight" << endl;
return numeric_limits<double>::min();
}
objectiveValue += item.value;
}
objectiveValue -= instance.rentingRate * (nextCityDistance / (instance.maxSpeed - speedCoef * collectedWeight));
curr = next;
} while (next != start);
return objectiveValue;
}
long long getWeight(Instance &instance) {
long long weight = 0;
for(int i = 0; i < items.size(); i++) {
weight += (items[i]*instance.items[i].weight);
}
return weight;
}
void dropKItems(Instance &instance, int k) {
if(k > instance.itemCount) {
cout << "Cannot drop more items than available!" << endl;
return;
}
vector<int> indices(instance.itemCount);
for(int i = 0; i < instance.itemCount; ++i) indices[i] = i;
random_shuffle(indices.begin(), indices.begin()+instance.itemCount);
for (int i = 0; i < k; ++i) {
int itemIndex = indices[i];
if (instance.items[itemIndex].available) {
instance.items[itemIndex].available = false;
items[itemIndex] = false;
} else {
instance.items[itemIndex].available = true;
}
}
objective = Solution::calculateObjective(instance, *this);
}
void dropKCities(Instance &instance, int k, string tempFile) {
if(k > instance.cityCount - 1) {
cout << "Cannot drop more cities than available!" << endl;
return;
}
// Cannot drop the first city.
vector<int> indices(instance.cityCount - 1);
for(int i = 0; i < instance.cityCount - 1; ++i) indices[i] = i+1;
random_shuffle(indices.begin(), indices.begin()+instance.cityCount-1);
for (int i = 0; i < k; ++i) {
int cityIndex = indices[i];
if (instance.cities[cityIndex].available) {
instance.cities[cityIndex].available = false;
// NOTE: The cities are not removed from the tour here, for now.
// The calculateObjective function will handle skipping these cities.
// This is done to ensure some sort of ordering in case the city re-appears.
} else {
instance.cities[cityIndex].available = true;
}
}
objective = Solution::calculateObjective(instance, *this);
instance.citiesToFile(tempFile);
}
vector<int> tour;
vector<bool> items;
double objective;
};
int Solution::evalCount = 0;
#endif | true |
7c31d64dfa2ba7bd6e7f0948a065b9306900de50 | C++ | DARKREDHAYABUSA/Unit5_Assignment_Licon | /Transaction.h | UTF-8 | 12,314 | 3.609375 | 4 | [] | no_license | #include <iostream>
#include <string>
#include <vector>
#include <iomanip> //for setw
#include <fstream> //write a file
#include <unistd.h> //for sleep command
#ifndef TRANSACTION_H
#define TRANSACTION_H
using namespace std;
//********Class Style**********/
class MenuItemList
{
private:
string name;
double itemCost;
string desc;
char addLetter;
char removeLetter;
int count = 0;
public:
void setName(string n) { name = n; }
void setItemCost(double iT) { itemCost = iT; }
void setDesc(string d) { desc = d; }
void setAddLetter(char aL) { addLetter = aL; }
void setRemoveLetter(char rL) { removeLetter = rL; }
void setCount(int c) { count += c; }
string getName() const { return name; }
double getItemCost() const { return itemCost; }
string getDesc() const { return desc; }
char getAddLetter() const { return addLetter; }
char getRemoveLetter() const { return removeLetter; }
int getCount() const { return count; }
//void print() { //print menu item data on demad }
};
//*******Class Style*********
//function definitions
void populateObjectMenu(vector<MenuItemList> &entireMenu)
{
//put some default values in our Menu
const int numItems = 7;
MenuItemList Item1; // Item 1 is an object
MenuItemList Item2;
MenuItemList Item3;
MenuItemList Item4;
MenuItemList Item5;
MenuItemList Item6;
MenuItemList Item7;
entireMenu.push_back(Item1); //add to the end of list the Item1
entireMenu.push_back(Item2); //add to the end of list the Item2
entireMenu.push_back(Item3); //add to the end of list the Item3
entireMenu.push_back(Item4); //add to the end of list the Item4
entireMenu.push_back(Item5); //add to the end of list the Item5
entireMenu.push_back(Item6); //add to the end of list the Item6
entireMenu.push_back(Item7); //add to the end of list the Item7
vector<string> defaultMenuNames = {"Green Tea", "Burrito", "Pasta", "Taco", "Burger", "Pizza", "Lasagna"};
vector<char> defaultAddLetters = {'A', 'B', 'C', 'D', 'E', 'F', 'G'};
vector<char> defaultRemoveLetters = {'a', 'b', 'c', 'd', 'e', 'f', 'g'};
for(int i = 0; i < numItems; i++)
{
//add each item to the default list efficiently
entireMenu[i].setName(defaultMenuNames[i]);
entireMenu[i].setAddLetter(defaultAddLetters[i]);
entireMenu[i].setRemoveLetter(defaultRemoveLetters[i]);
entireMenu[i].setItemCost(3.00 + i); //set a random starter cost for each item
entireMenu[i].setCount(0); //initialze all counts to 0
entireMenu[i].setDesc("delicious"); //set all default desc to "delicous"
}
//Menu Description
//Menu Prices
}
//*******Class Style*******
void showObjectMenu(vector<MenuItemList> &m)
{
cout << fixed << setprecision(2);//set doubles to 2 decimal places
cout << "**One Stop Shop**" << endl;
cout << "ADD \tNAME \t COST \tREMOVE\tCOUNT\tDESC"<<endl;
for(int i = 0; i < m.size(); i++)
{
cout << m[i].getAddLetter() << ")" << setw(10)
<< m[i].getName() << setw(5) << "$"
<< m[i].getItemCost() << setw(5) << "("
<< m[i].getRemoveLetter() << ")" << setw(7)
<< m[i].getCount() << setw(13)
<< m[i].getDesc()
<<endl;
}
}
void acceptObjectOrder(vector<MenuItemList> &m)
{
char option = '\0';// the user-selected menu item
double subtotal = 0.0;
double taxRate = 0.0825;
double tax = 0.0;
double tip = 0.0;
double total = 0.0;
double sumTotal = 0.0;
double tipTip = 0.0;
int inputTip;
char payment;
char pay;
double cash;
double card = 0.0;
double change = 0.0;
double cardChange = 0.0;
char printReciept;
do
{
cout << "\nPlease choose an item (x to Exit): ";
cin >> option;
for(int i=0; i < m.size(); i++)
{
if(option == m[i].getAddLetter())
{
cout << "\nMenu Item " << m[i].getAddLetter() << " selected.";
m[i].setCount(1); //increment the count by 1
cout << "\033[2J\033[1;1H"; //clear screen
cout << "\n1 UP on " << m[i].getName() << endl;
subtotal += m[i].getItemCost(); //increment the subtotal by the cost of the item
showObjectMenu(m); //show the updated menu
cout << "\nSubtotal: $" << subtotal << endl;
}
else if(option == m[i].getRemoveLetter())
{
cout << "\nRemove Item " << m[i].getRemoveLetter() << " selected.";
if(m[i].getCount() > 0) //subtract if and only if the count is > 0
{
m[i].setCount(-1); //decrement the count by 1
cout << "\033[2J\033[1;1H"; //clear screen
cout << "\n1 DOWN on " << m[i].getName() << endl;
subtotal -= m[i].getItemCost(); //decrement the subtotal by the cost of the item
showObjectMenu(m); //show the updated menu
cout << "\nSubtotal: $" << subtotal << endl;
}
else //the the user why you blocked item removal
{
cout << "\nItem count must be > 0 to remove: " << m[i].getName() << endl;
}
}
else if(
option != m[i].getAddLetter() &&
option != m[i].getRemoveLetter() &&
option != 'x' &&
option != 'X'
) //test for all of my valid inputs
{
if(i == 0)
{
cout << "\nInvalid input (" << option << "). Please try again." << endl;
}
}
}
}while(option != 'x' && option != 'X');
cout << "\nThank you for placing your order." << endl;
sleep(3);
cout << "\nYour Subtotal for today is: " << "$" << subtotal << endl;
sleep(3);
cout << "\n\nWhat percentage would you like to tip?\n(A 20% tip is suggested): ";
cin >> inputTip;
sleep(2);
tax = subtotal * taxRate;
total = (subtotal + tax);
tipTip = (inputTip * (0.010));
tip = (subtotal * tipTip);
sumTotal = total + tip;
cout << "\nSubtotal = $" << subtotal;
sleep(1);
cout << "\nTax 0.0825 = $" << tax;
sleep(1);
cout << "\nTotal = $" << total;
sleep(1);
cout << "\n\n" << inputTip << "% Tip = $" << tip;
sleep(1);
cout << "\nTotal w/Tip = $" << sumTotal;
sleep(2);
cout << "\n\nWhat payment method would you like to use? "<< endl;
sleep(1);
cout << "(A) Cash or (B) Card: " <<endl;
cin >> payment;
if(payment == 'a' || payment == 'A')
{
cout << "\nPayment Due: $" << sumTotal << endl;
sleep(1);
cout << "\nPlease enter the amount of cash: ";
cin >> cash;
change = cash - sumTotal;
cout << "\nPayment = $" << cash;
sleep(1);
cout << "\nChange Due = $" << change;
sleep(1);
cout << "\nPayment being processed" << endl;
sleep(4);
cout << "\nTransaction was succesful" << endl;
sleep(1);
cout << "\nWould you like a recipt? <Y/N> " << endl;
cin >> printReciept;
if( printReciept == 'y' || printReciept == 'Y')
{
cout << "\nPrinting recipt" << endl;
string color = "";
string reset = "\x1b[0m";
color = "\x1b[91;40m"; // Red/Gray
cout << color << "\n_________________________________________\n" << reset;
sleep(1);
color = "\x1b[32;40m"; // Green/Gray
cout << color << "\n\n\t\t**One Stop Shop**" << endl;
sleep(1);
color = "\x1b[40;1m";
cout << color << "\nSubtotal = $" << subtotal << reset;
sleep(1);
color = "\x1b[40;1m";
cout << color << "\nTax 0.0825 = $" << tax << reset;
sleep(1);
color = "\x1b[40;1m";
cout << color << "\nTotal = $" << total << reset;
sleep(1);
color = "\x1b[40;1m";
cout << color << "\n\n" << inputTip << "% Tip = $" << tip << reset;
sleep(1);
color = "\x1b[40;1m";
cout << color << "\nTotal w/Tip = $" << sumTotal << reset;
sleep(2);
color = "\x1b[40;1m";
cout << color <<"\n\nPayment = $" << cash << reset;
sleep(1);
color = "\x1b[40;1m"; //Green Block (40)
cout << color << "\nChange Due = $" << change << reset;
sleep(1);
color = "\x1b[32;40m"; // Green
cout << color << "\n\nThank You for your business have a nice day" << endl;
sleep(1);
color = "\x1b[91;40m"; // Red/Gray
cout << color << "\n_________________________________________\n" << reset;
sleep(1);
if( printReciept == 'n' || printReciept == 'N')
{ cout << "\n\nThank You for your business have a nice day" << endl; }
//cout << "\nItems Sold = " << m[i].getCount();
//sleep(1);
}
}
else if(payment == 'b' || payment == 'B')
{
cout << "\nPlease swipe card" << endl;
sleep(2);
cout << "\nAmount Due is: $" << sumTotal << endl;
sleep(1);
cout << "\nPay: $" << sumTotal << " <Y/N> ";
cin >> pay;
if ( pay == 'y' || pay == 'Y')
{
card = sumTotal;
cardChange = sumTotal - card;
}
cout << "\nPayment being processed" << endl;
sleep(4);
cout << "\nTransaction was succesful" << endl;
sleep(1);
cout << "\nWould you like a recipt? <Y/N> " << endl;
cin >> printReciept;
if( printReciept == 'y' || printReciept == 'Y')
{
cout << "\nPrinting recipt" << endl;
sleep(2);
string color = "";
string reset = "\x1b[0m";
color = "\x1b[91;1m"; // Red
cout << color << "\n_________________________________________\n" << reset;
sleep(1);
color = "\x1b[31;40m"; // Green/Gray
cout << color << "\n\n\t\t**One Stop Shop**" << endl;
sleep(1);
color = "\x1b[40;1m";
cout << color << "\nSubtotal = $" << subtotal << reset;
sleep(1);
color = "\x1b[40;1m";
cout << color << "\nTax 0.0825 = $" << tax << reset;
sleep(1);
color = "\x1b[40;1m";
cout << color << "\nTotal = $" << total << reset;
sleep(1);
color = "\x1b[40;1m";
cout << color << "\n\n" << inputTip << "% Tip = $" << tip << reset;
sleep(1);
color = "\x1b[40;1m";
cout << color << "\nTotal w/Tip = $" << sumTotal << reset;
sleep(2);
color = "\x1b[40;1m";
cout << color <<"\n\nPayment = $" << card << reset;
sleep(1);
color = "\x1b[40;1m"; //Green Block (40)
cout << color << "\nChange Due = $" << cardChange << reset;
sleep(1);
color = "\x1b[32;40m"; // Green/Gray
cout << color << "\n\nThank You for your business have a nice day" << endl;
sleep(1);
color = "\x1b[91;40m"; // Red/Gray
cout << color << "\n_________________________________________\n" << reset;
sleep(1);
if( printReciept == 'n' || printReciept == 'N')
{ cout << "\n\nThank You for your business have a nice day" << endl; }
if ( pay == 'n' || pay == 'N')
{ cout << "\nTransaction cancled"; }
}
}
//string color = "";
//string reset = "\x1b[0m";
//color = "\x1b[91;1m"; //red
//for(int i = 0; i < 50; i++) { cout << color << "_" << reset; }
//cout << endl;
fstream reciept;
reciept.open("reciept.txt",ios::out);
reciept << fixed << setprecision(2);
for(int i=0; i < m.size(); i++)
{
reciept << "\n_________________________________________\n";
reciept << "\n\t**One Stop Shop**" << endl;
reciept << fixed << setprecision(2);
for(int i=0; i < m.size(); i++)
reciept << m[i].getCount()
<< " - "
<< m[i].getName()
<< " - $"
<< m[i].getItemCost()
<< endl;
reciept << "\nSubtotal = $" << subtotal;
sleep(1);
reciept << "\nTax 0.0825 = $" << tax;
sleep(1);
reciept << "\nTotal = $" << total;
sleep(1);
reciept << "\n\n" << inputTip << "% Tip = $" << tip;
sleep(1);
reciept << "\nTotal w/Tip = $" << sumTotal;
sleep(2);
reciept << "\nPayment = $" << cash;
sleep(1);
reciept << "\nChange Due = $" << change;
sleep(1);
reciept << "\nThank You for your business have a nice day" << endl;
reciept << "\n_________________________________________\n";
reciept.close();
}
}
void printTextReciept(vector<MenuItemList> &m) {}
/*fstream html;
html.open("reciept.html",ios::out);
html << "<html><head><title>cool</title></head>";
html << "<body style=\"background-color:#000000;color:#FFFFFF;\">";
html << "<h1>" << m[0].getName() << "</h1>"<< endl;
html << "</body></html>";
html.close();
*/
#endif | true |
94b63fa2b18e32a69d98daa64d550f7acd36f2c2 | C++ | shivamgohri/ds_codes | /Arrays/merge_2arrays.cpp | UTF-8 | 784 | 3.421875 | 3 | [] | no_license | //https://practice.geeksforgeeks.org/problems/merge-two-sorted-arrays/0
#include <iostream>
#include <vector>
using namespace std;
int main(){
int t;
cin>> t;
while(t--){
int n1, n2;
cin>> n1 >>n2;
vector<long int> arr1(n1,0);
vector<long int> arr2(n2,0);
for(int i=0; i<n1; i++)
cin>> arr1[i];
for(int i=0; i<n2; i++)
cin>> arr2[i];
int i = 0, j = 0;
while( i<n1 && j<n2 ){
if( arr1[i] <= arr2[j] ){
i++;
}
else{
swap( arr1[i], arr2[j] );
int temp = j;
while( arr2[temp] > arr2[temp+1] && temp+1<n2 ){
swap( arr2[temp], arr2[temp+1] );
temp++;
}
i++;
}
}
for(int i=0; i<n1; i++)
cout<< arr1[i] <<" ";
for(int i=0; i<n2; i++)
cout<< arr2[i] <<" ";
cout<<endl;
}
return 0;
} | true |
1a3a799ed373735855a120f969e0cadefc365659 | C++ | mykyusuf/AssemblyReader | /CPUProgram.cpp | UTF-8 | 733 | 2.953125 | 3 | [] | no_license | #include "CPUProgram.h"
//Class constructerı çağrılınca readfile fonk çağırır
CPUProgram::CPUProgram(string myk) {
ReadFile(myk);
}
//Dosya okuma fonksiyonu, okudugunu string arraye atar
CPUProgram::CPUProgram(int option) {
opt=option;
}
CPUProgram::CPUProgram(){}
void CPUProgram::ReadFile(string myk){
ifstream tut;
tut.open(myk);
for(int i=0;tut;i++){
getline(tut,array[i]);
sayz=i;
}
tut.close();
}
//İstenen satıra geri döner
string CPUProgram::getLine(int x){
if(x>0)
return array[x-1];
else
return "wrong command";
}
//Dosya boyutunu tutar
int CPUProgram::size(){
return sayz;
}
| true |
3c2c68d523f56b137c93f5e6d2b5082df651956e | C++ | dmkz/competitive-programming | /codeforces.com/Codeforces Ladder 1500-1599/0363B.cpp | UTF-8 | 719 | 3.15625 | 3 | [] | no_license | /*
Problem: 363B. Fence
Solution: dynamic programming, two pointers, brute force
*/
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::ios_base::sync_with_stdio(false);
std::cin.tie(0); std::cout.tie(0); std::cerr.tie(0);
int n, len;
std::cin >> n >> len;
std::vector<int> h(n);
for (auto& it : h) std::cin >> it;
int sum = 0;
for (int i = 0; i < len; ++i) {
sum += h[i];
}
std::vector<int> s(n-len+1);
s[0] = sum;
for (int i = 1; i+len-1 < n; ++i) {
s[i] = s[i-1] - h[i-1] + h[i+len-1];
}
std::cout << int(std::min_element(s.begin(), s.end()) - s.begin()) + 1;
return 0;
} | true |
7f642dbb0c696a1879bba75d59c0bb2b2d107d22 | C++ | migmartri/slacktronic | /devices/arduino/LEDs/slacktronic_LED.ino | UTF-8 | 1,578 | 3.421875 | 3 | [
"Apache-2.0"
] | permissive | /*
It reads characters from the serial input and sends digital writes or low depending on its value.
Capital leters means HIGH, downcase LOW.
Currently, the actuators are hardcoded to for outputs
*/
char receivedChar;
boolean newData = false;
const int ACTUATOR_A = 2;
const int ACTUATOR_B = 6;
const int ACTUATOR_C = 10;
const int ACTUATOR_D = 12;
int actuator;
int actuatorSignal;
void setup() {
Serial.begin(57600);
Serial.println("<Arduino is ready>");
pinMode(ACTUATOR_A, OUTPUT);
pinMode(ACTUATOR_B, OUTPUT);
pinMode(ACTUATOR_C, OUTPUT);
pinMode(ACTUATOR_D, OUTPUT);
}
void loop() {
recvOneChar();
showNewData();
}
void recvOneChar() {
if (Serial.available() > 0) {
receivedChar = Serial.read();
newData = true;
}
}
void showNewData() {
if (newData == true) {
actuator = 0;
newData = false;
switch(receivedChar) {
case 'A':
actuator = ACTUATOR_A;
actuatorSignal = HIGH;
break;
case 'B':
actuator = ACTUATOR_B;
actuatorSignal = HIGH;
break;
case 'C':
actuator = ACTUATOR_C;
actuatorSignal = HIGH;
break;
case 'D':
actuator = ACTUATOR_D;
actuatorSignal = HIGH;
break;
case 'a':
actuator = ACTUATOR_A;
actuatorSignal = LOW;
break;
case 'b':
actuator = ACTUATOR_B;
actuatorSignal = LOW;
break;
case 'c':
actuator = ACTUATOR_C;
actuatorSignal = LOW;
break;
case 'd':
actuator = ACTUATOR_D;
actuatorSignal = LOW;
break;
}
digitalWrite(actuator, actuatorSignal);
delay(1);
}
}
| true |
b1b518d97db25c7207732a99677a268e8f79f3df | C++ | gpoleszuk/kinematic | /src/Library/Stream/NtripServer.cpp | UTF-8 | 1,383 | 2.546875 | 3 | [] | no_license | #include "NtripServer.h"
#include "Parse.h"
NtripServer::NtripServer(const char* host, const char* port, const char *mount,
const char *user, const char *passwd)
: Socket(host, port)
{
debug("NtripServer::NtripServer(%s, %s, %s, %s, %s) ErrCode=%d\n",
host, port, mount, user, passwd, ErrCode);
if (ErrCode != OK) return;
ErrCode = Printf("SOURCE %s/%s\r\n", passwd, mount)
|| Printf("Source-Agent NTRIP 1.0 Precision-gps.org\r\n")
|| Printf("\r\n")
|| ParseHeader();
if (ErrCode != OK)
Error("NtripServer protocol error starting up\n");
}
bool NtripServer::ParseHeader()
{
// repeat until we read a blank line
char line[256];
forever {
if (ReadLine(line, sizeof(line)) != OK)
return Error("Can't read Ntrip header from Caster\n");
// parse the first token in the line
Parse p(line);
p.Next(" ");
// Look for "ICY 200". Good news.
if (p == "ICY") {
if (p.Next(" ") != "200")
return Error("ParseHeader: Bad code - %s\n", line);
}
// Look for "ERROR - ...." Bad news
else if (p == "ERROR")
return Error("Ntrip Caster says: %s\n", line);
else if (p == "")
break;
}
return OK;
}
NtripServer::~NtripServer()
{
}
| true |
5517cc80c65e111bd48a3a13c77c7cb383c0bb4c | C++ | drusk/scratch | /patch-boundaries/src/patch.cpp | UTF-8 | 1,291 | 3.109375 | 3 | [] | no_license | #include "patch.h"
std::vector<Point> Patch::GetBorderPoints() {
std::vector<Point> borderPoints;
for (int x = minX; x <= maxX; ++x) {
borderPoints.push_back(Point(x, minY));
borderPoints.push_back(Point(x, maxY));
}
/* Don't do corner points twice! */
for (int y = minY + 1; y < maxY; ++y) {
borderPoints.push_back(Point(minX, y));
borderPoints.push_back(Point(maxX, y));
}
return borderPoints;
}
bool Patch::Contains(const Point& point) const {
return point.x <= maxX && point.x >= minX && point.y <= maxY && point.y >= minY;
}
void BoolMap2D::Set(int x, int y) {
map[y][x] = true;
}
bool BoolMap2D::Test(int x, int y) {
return map[y][x];
}
void BoundaryCalculator::AddPatch(Patch patch) {
for (Point& point : patch.GetBorderPoints()) {
if (IsInPatchedArea(point)) {
boundaryPoints.push_back(point);
}
}
AddPatchedArea(patch);
}
bool BoundaryCalculator::IsInPatchedArea(Point point) {
return patchMap.Test(point.x, point.y);
}
void BoundaryCalculator::AddPatchedArea(Patch patch) {
for (int y = patch.GetMinY(); y <= patch.GetMaxY(); ++y) {
for (int x = patch.GetMinX(); x <= patch.GetMaxX(); ++x) {
patchMap.Set(x, y);
}
}
}
| true |
c653b14c7c5a84fe08fdc782073db4d6873fbee8 | C++ | Ypsillonn/PPE | /capteur.ino | UTF-8 | 1,140 | 2.6875 | 3 | [] | no_license | const int pingPin = 7;
const int pin = 2;
int buttonState = 0;
/**************************************************************************/
void setup() {
Serial.begin(9600);
pinMode(pin, INPUT);
}
/**************************************************************************/
void loop() {
float duration, cm; //Valeurs décimales pour plus de précisions
/*****Séquence émission/réception des ultrasons******/
pinMode(pingPin, OUTPUT);
digitalWrite(pingPin, LOW);
delayMicroseconds(2);
digitalWrite(pingPin, HIGH);
delayMicroseconds(5);
digitalWrite(pingPin, LOW);
pinMode(pingPin, INPUT);
duration = pulseIn(pingPin, HIGH);
/************Affichage après activation*************/
buttonState = digitalRead(pin);
if(buttonState == HIGH)
{
cm = microsecondsToCentimeters(duration);
Serial.print(cm);
Serial.print("cm");
Serial.println();
delay(10000000);
}
}
/*****Conversion de l'écart de temps en distance*****/
float microsecondsToCentimeters(float microseconds) {
return microseconds / 29 / 2;
}
| true |
0a217b384bd5a24f29daf1fb3a4b3ee74830c35c | C++ | antautu/CPTR246 | /tree.h | UTF-8 | 13,761 | 3.828125 | 4 | [] | no_license | /************************************************
tree.h - binary tree that holds integers
************************************************/
#ifndef _TREE_H
#define _TREE_H
#include <fstream>
using namespace std;
class BinaryTreeNode{
friend class BinaryTree;
public:
// CONSTRUCTORS
BinaryTreeNode() {data = 0; leftChild = rightChild = 0;}
BinaryTreeNode(int x)
{data = x;
leftChild = rightChild = 0;
}
BinaryTreeNode(int x, BinaryTreeNode * l, BinaryTreeNode * r)
{data = x;
leftChild = l;
rightChild = r;
}
private:
int data; // value at node
BinaryTreeNode * leftChild; // points to left child
BinaryTreeNode * rightChild; // points to right child
};
class BinaryTree{
public:
BinaryTree() {root = 0;} // CONSTRUCTOR
~BinaryTree(); // DESTRUCTOR
int IsEmpty()
{return (root == 0);} // {return !root;}
void MakeTree(ifstream & inFile);
int InTree(int x);
void Preorder();
void Postorder();
void Inorder();
void Largest();
int SumTree();
int Below(int x);
bool DeleteLeaf(int x);
private:
BinaryTreeNode * root; // points to root of tree
// "helper" functions - needed
// when recursion is used!
int InTreeHelper(BinaryTreeNode * root, int x);
void PreorderHelper(BinaryTreeNode * root);
void PostorderHelper(BinaryTreeNode * root);
void InorderHelper(BinaryTreeNode * root);
int LargestHelper(BinaryTreeNode * root);
int SumTreeHelper(BinaryTreeNode * root);
int BelowHelper(BinaryTreeNode * root, int x);
void DestructorHelper(BinaryTreeNode * root);
};
BinaryTree::~BinaryTree(){
// pre: none
// post: all memory utilized by the tree is returned to the free store
DestructorHelper(root);
}
void BinaryTree::DestructorHelper(BinaryTreeNode * root){
// pre: root must be a valid tree node
// post: all memory utilized by the tree is returned to the free store
if (root)
{
if (!root -> leftChild && !root -> rightChild) // If there are no children
{
cout << "Deleting " << root -> data << endl; // Shows what is being deleted
delete root; // Deletes the root
}
else // If there are children
{
if (root -> leftChild) // If there is a leftChild to be deleted
DestructorHelper(root -> leftChild);
if (root -> rightChild) // If there is a rightChild to be deleted
DestructorHelper(root -> rightChild);
cout << "Deleting " << root -> data << endl; // Shows what is being deleted
delete root; // Deletes the root
}
}
}
void BinaryTree::MakeTree(ifstream & inFile){
// pre: inFile is a file containing integers that has been opened
// post: the tree is built, loaded from inFile
BinaryTreeNode * first; // points to root
BinaryTreeNode * current; // used when searching where to insert a node
BinaryTreeNode * thisOne; // points to memory allocated for this node
int value; // value to be inserted
int found; // flag - location to insert found
first = new BinaryTreeNode; // allocate memory for the root node
inFile >> value; // get the first value
first->data = value; // set up root
first->leftChild = 0;
first->rightChild = 0;
inFile >> value; // get next value to insert
while (!inFile.eof()){ // if there are more to insert
thisOne = new BinaryTreeNode; // allocate memory for it
thisOne->data = value; // initialize the values
thisOne->leftChild = 0;
thisOne->rightChild = 0;
current = first; // look for its spot in the tree
found = 0; // set found flag to 0
while (!found){ // found a spot for it yet?
if (value < current->data) // go left if value is less than this node
if (current->leftChild) // is there a node there already?
current = current->leftChild;
else // if not, we've found the spot
found = 1;
else // go right of value is > this node
if (current->rightChild) // is there a node there already?
current = current->rightChild;
else // if not, we've found our spot
found = 1;
}
if (value < current->data) // was is supposed to be the left child
current->leftChild = thisOne;
else // or the right child?
current->rightChild = thisOne;
inFile >> value; // get the next value to insert
}
root = first; // set up root
}
int BinaryTree::InTree(int x){
// pre: none
// post: returns true if x is in the tree, false if not
if (!root) // tree is empty
return 0;
return InTreeHelper(root, x);
}
int BinaryTree::InTreeHelper(BinaryTreeNode * root, int x){
// pre: root is loaded and x is an integer
// post: returns true if x is in the tree, false otherwise
if (root->data == x) // is x at this node?
return 1; // if yes, return true
// if not, is it in either of
// of the "trees" below it?
// first test if there is a child, then if x is in
// the "tree" rooted at that child
if (root->leftChild && InTreeHelper(root->leftChild, x))
return 1;
if (root->rightChild && InTreeHelper(root->rightChild, x))
return 1;
return 0; // if nowhere, return false
}
void BinaryTree::Preorder(){
// pre: none
// post: a preorder listing of the tree is displayed
PreorderHelper(root); // call helper function
cout << endl; // go to a new line
}
void BinaryTree::PreorderHelper(BinaryTreeNode * root){
// pre: root must be a valid tree node
// post: a "preorder" listing is given
if (root){ // if this is not a NULL pointer
cout << root->data << " ";
// print the data in this node
// then print the nodes in the
// "tree" rooted at each child
if (root->leftChild)
PreorderHelper(root->leftChild);
if (root->rightChild)
PreorderHelper(root->rightChild);
}
}
void BinaryTree::Postorder(){
// pre: none
// post: a postorder listing of the tree is displayed
PostorderHelper(root); // call helper function
cout << endl; // go to a new line
}
void BinaryTree::PostorderHelper(BinaryTreeNode * root){
// pre: root must be a valid tree node
// post: a "postorder" listing is given
if (root){ // if this is not a NULL pointer
// then print the nodes in each of the
// children then print this node
if (root->leftChild)
PostorderHelper(root->leftChild);
if (root->rightChild)
PostorderHelper(root->rightChild);
cout << root->data << " ";
}
}
void BinaryTree::Inorder(){
// pre: none
// post: an inorder listing of the tree is displayed
InorderHelper(root); // call helper function
cout << endl; // go to a new line
}
void BinaryTree::InorderHelper(BinaryTreeNode * root){
// pre: root must be a valid tree node
// post: an "inorder" listing is given
if (root){ // if this is not a NULL pointer
// then print the nodes in the left
// child then this node then the
// children in the right node
if (root->leftChild)
InorderHelper(root->leftChild);
cout << root->data << " ";
if (root->rightChild)
InorderHelper(root->rightChild);
}
}
void BinaryTree::Largest(){
// pre: none
// post: the largest value in the tree is displayed
if (!root) // If the list is empty tell the user
cout << "The tree is empty" << endl;
else // Tells the user what the largest value is if the tree is not empty
{
cout << "The largest value is " << LargestHelper(root) << endl;
cout << endl;
}
}
int BinaryTree::LargestHelper(BinaryTreeNode * root){
// pre: root must be a valid tree node
// post: the largest value in the tree is
if (!root -> leftChild && !root -> rightChild) // If there are no children
{
return root -> data;
}
int LargestSoFar = root -> data; // LargestSoFar is set to the root
if (root -> leftChild) // If the root has a leftChild
{
if (LargestSoFar < LargestHelper(root -> leftChild)); // If the leftChild is larger than the root
LargestSoFar = LargestHelper(root -> leftChild); // Set LargestSoFar to the leftChild
}
if (root -> rightChild) // If the root has a rightChild
{
if (LargestSoFar < LargestHelper(root -> rightChild)); // If the rightChild is larger than the root
LargestSoFar = LargestHelper(root -> rightChild); // Set LargestSoFar to the rightChild
}
return LargestSoFar;
}
int BinaryTree::SumTree(){
// pre: none
// post: returns the sum of the values in the tree
if (root) // If there is a root
return SumTreeHelper(root); // Returns the sum of the values
else // If the list is empty
return 0; // The sum is zero because the list is empty
}
int BinaryTree::SumTreeHelper(BinaryTreeNode * root){
// pre: root must be a valid tree node
// post: returns the sum of the values in the tree
if (!root -> leftChild && !root -> rightChild) // If there are no children
{
return root -> data; // The root is equal to the sum
}
if (root -> leftChild) // If the root has a leftChild
{
if (root -> rightChild) // If the root has a rightChild
return root -> data + SumTreeHelper(root -> leftChild) + SumTreeHelper(root -> rightChild); // Adds children to the sum if both exist
return root -> data + SumTreeHelper(root -> leftChild); // Adds leftChild to sum if it exists
}
else
return root -> data + SumTreeHelper(root -> rightChild); // Adds rightChild to sum if it exists
}
int BinaryTree::Below(int x){
// pre: the user enters an integer
// post: returns the number of values in the tree less than the entered value
if (root) // If there is a root check to see if it is less than the value
return BelowHelper(root, x);
else // If there are no roots
return 0; // There are no numbers less then the value
}
int BinaryTree::BelowHelper(BinaryTreeNode * root, int x){
// pre: root must be a valid tree node
// post: returns the number of values in the tree less than the entered value
if (!root -> leftChild && !root -> rightChild) // If there are no children
{
if (root -> data < x) // If the value is less than the root
return 1; // There is one value in the tree less then the value
else // If the value is greater than the root
return 0; // There are no values in the tree less than the value
}
if (root -> leftChild) // If the root has a leftChild
{
if (root -> rightChild) // If the root has a rightChild
{
if (root -> data < x)
return 1 + BelowHelper(root -> leftChild, x) + BelowHelper(root -> rightChild, x); // Adds one to the number of values less than the number
else
return BelowHelper(root -> leftChild, x) + BelowHelper(root -> rightChild, x); // Does not add anything to the number of values less than the number
}
if (root -> data < x)
return 1 + BelowHelper(root -> leftChild, x); // Adds one to the number of values less than the number
else
return BelowHelper(root -> leftChild, x); // Does not add anything to the number of values less than the number
}
else // If there is just a rightChild
{
if (root -> data < x)
return 1 + BelowHelper(root -> rightChild, x); // Adds one to the number of values less than the number
else
return BelowHelper(root -> rightChild, x); // Does not add anything to the number of values less than the number
}
}
bool BinaryTree::DeleteLeaf(int x){
// pre: the user enters an integer of a leaf they wish to delete
// post: returns true if the leaf was deleted and false otherwise
if (!InTree(x)) // If the entered number is not in the tree
return false; // Return false because it could not be deleted
BinaryTreeNode * newRoot;
BinaryTreeNode * current;
current = root; // Sets current to the root we start at
while (current -> data != x) // While the current root is not the number we are looking for
{
if (x > current -> data) // If the value we are looking for is greater than the current root, go to the rightChild
{
newRoot = current; // Updates the root
current = current -> rightChild; // Go to the rightChild
}
if (x < current -> data) // If the value we are looking for is less than the current root, go to the leftChild
{
newRoot = current; // Updates the root
current = current -> leftChild; // Go to the leftChild
}
}
if (current -> leftChild || current -> rightChild) // If the value we were looking for has a child, it is not a leaf
return false; // Return false because the value was not a leaf
if (newRoot -> leftChild == current) // If the value we were looking for is a leftChild and a leaf
{
newRoot -> leftChild = 0; // Gets rid of the pointer
delete current; // Deletes the leaf
return true; // Return true because we deleted the leaf
}
if (newRoot -> rightChild == current) // If the value we were looking for is a rightChild and a leaf
{
newRoot -> rightChild = 0; // Gets rid of the pointer
delete current; // Deletes the leaf
return true; // Return true because we deleted the leaf
}
}
#endif
| true |
bdd1c2c2ea513cffa21857def28746373d14af64 | C++ | jschfflr/hacker.org | /bricolage/object.cpp | UTF-8 | 211 | 2.640625 | 3 | [] | no_license | #include "object.h"
#include <atomic>
std::atomic<long long> count;
Object::Object() {
count.fetch_add(1);
}
Object::Object(const Object&) {
count.fetch_add(1);
}
Object::~Object(){
count.fetch_sub(1);
} | true |
8a770de84160d910d87394153af243eb4682475f | C++ | killbug2004/deianeira | / deianeira --username badteen@sina.com/exe/Deianeira/common/sysmodule.cpp | GB18030 | 1,322 | 2.546875 | 3 | [] | no_license | #include "sysmodule.h"
//ϵͳģб
PSYSTEM_MODULE_LIST GetSystemModuleList()
{
//ָ붨
PNtQuerySystemInformation NtQuerySystemInformation;
HMODULE hModule;
ULONG ulSize;
NTSTATUS status;
PSYSTEM_MODULE_LIST pSystemModuleInfo;
//ģ
if(!(hModule=LoadLibrary(L"ntdll.dll")))
{
return NULL;
}
//úַ
NtQuerySystemInformation=(PNtQuerySystemInformation)GetProcAddress(hModule, "NtQuerySystemInformation");
//ַȡʧ
if(!NtQuerySystemInformation)
{
FreeLibrary(hModule);
return NULL;
}
//һʱѯֽ
NtQuerySystemInformation(SystemModuleInformation,NULL,0, &ulSize);
//ͨصֽڴ
pSystemModuleInfo = (PSYSTEM_MODULE_LIST)malloc(ulSize);
//ڴʧ
if(!pSystemModuleInfo)
{
FreeLibrary(hModule);
return NULL;
}
//ٴλ
status = NtQuerySystemInformation(SystemModuleInformation,pSystemModuleInfo,ulSize,&ulSize);
//ȡʧ
if(!NT_SUCCESS(status))
{
//ͷڴ
free(pSystemModuleInfo);
FreeLibrary(hModule);
return NULL;
}
//ͷڴ
FreeLibrary(hModule);
//ɹ
return pSystemModuleInfo;
} | true |
d84ce153e695bf82d79cc8e1ca6052405838fbe5 | C++ | JessicaALeite/A_lib | /Maths/Diophantine_Linear.cpp | UTF-8 | 1,393 | 3.28125 | 3 | [] | no_license | #include<iostream>
#include<map>
#include<cstdio>
#include<vector>
#include<stack>
#include<set>
#include<algorithm>
using namespace std;
void divide(long long a,long long b,long long &q,long long &r)
{
q=a/b;
r=a%b;
}
long long mod(long long a,long long b)
{
return (a+b)%b;
}
long long ext_euclidean_itr(long long a,long long b,long long &x,long long &y)
{
long long tmp;
long long q,r;
long long lx=y=0;
long long ly=x=1;
while(b)
{
divide(a,b,q,r);
//........ (a,b) <--- (b,a%b)
tmp=b;b=a%b;a=tmp;
// ..... (x,lx) <--- (lx-q*x,x)
tmp=lx;lx=x-q*lx;x=tmp;
// ..... (y,ly) <--- (ly-q*y,y)
tmp=ly;ly=y-q*ly;y=tmp;
}
return a;
}
int gcd_(int a,int b)
{
if(!b)
return a;
return gcd_(b,a%b);
}
int mod_inverse(int a,int b)
{
long long t1,t2;
long long g;
g=ext_euclidean_itr((long long)a,(long long)b,t1,t2);
return mod(t1,b);
}
void linear_dophantine(int a,int b,int c,int &x,int &y)
{
int d=gcd_(a,b);
if(c%d)
{
x=y=-1;
}
else
{
x= (c/d) * mod_inverse(a/d,b/d);
y=(c-a*x)/b;
}
}
int main()
{
int a,b,c;
int x,y;
cout<<"Enter the values of 'a','b'and 'c': for finding solutions of equation:\n\t\t ax + by = c : ";
cin>>a>>b>>c;
linear_dophantine(a,b,c,x,y);
cout<<"solution::\n";
cout<<"x= "<<x<<" y= "<<y<<"\n";
return 0;
}
| true |
81a4d1078ea385238db86b391f942823444c9551 | C++ | Cheese-5040/Comp-2011 | /lab/harrison.cpp | UTF-8 | 14,007 | 3.53125 | 4 | [] | no_license | // pa2.cpp
// COMP2011 (Fall 2020)
// Assignment 2: Subtring Pattern Matching
//
// Name: Shih-heng, LO
// Student ID: 20654493
// Email: sloab@connect.ust.hk
#include <assert.h>
#include <iostream>
#include <limits>
using namespace std;
// C string termination character
const char NULL_CHAR = '\0';
// The "not found" flag
const int NOT_FOUND = -1;
// Single character wildcard
const char DOT = '.';
// Zero or single character wildcard
const char QMARK = '?';
// Zero or more character wildcard
const char PERCENT = '%';
// Matches the beginning of a string
const char CARET = '^';
int matchSub(const char str[], const char pattern[], int &length, int start);
int matchSubWithDot(const char str[], const char pattern[], int &length,
int start);
int matchSubWithQmark(const char str[], const char pattern[], int &length,
int start);
int matchSubWithPercent(const char str[], const char pattern[], int &length,
int start);
int findSubLenAtStrPosWithDot(const char str[], const char pattern[],
int strPos, int patPos);
// Declare additional helper functions below when necessary
void helpPrint(const char *str, int pos) {
for (int i = pos; str[i] != NULL_CHAR; ++i)
cout << str[i];
cout << endl;
}
void Debug(const char *str, int strPos, const char *pattern, int patPos) {
cout << " ------ " << endl;
helpPrint(str, strPos);
helpPrint(pattern, patPos);
}
#define DEBUGMODE 1
int findSubLenAtStrPosWithDot(const char str[], const char pattern[], int strPos = 0, int patPos = 0) {
if (pattern[patPos] != NULL_CHAR && str[strPos] == NULL_CHAR) // the substring is shorter than the pattern to match
return NOT_FOUND;
if (pattern[patPos] == DOT || pattern[patPos] == str[strPos]) {
if (pattern[patPos + 1] == NULL_CHAR) // the entire pattern is matched
return 1;
// otherwise, the match is only part way through
int result = findSubLenAtStrPosWithDot(str, pattern, strPos + 1, patPos + 1); // check if the remaining part of the pattern
if (result != NOT_FOUND) // only return a match when the entire pattern is matched
return 1 + result;
}
return NOT_FOUND;
}
int matchSubWithDot(const char str[], const char pattern[], int &length, int start = 0) {
length = 0;
int *size = &length;
if (str[start] == NULL_CHAR)
return NOT_FOUND;
int testLength = findSubLenAtStrPosWithDot(str, pattern, start);
if (testLength != NOT_FOUND) {
length = testLength;
return start;
}
return matchSubWithDot(str, pattern, length, start + 1);
}
int findSubLenAtStrPosWithQmark(const char str[], const char pattern[], int strPos = 0, int patPos = 0) {
if (DEBUGMODE) Debug(str, strPos, pattern, patPos);
if (pattern[patPos] != NULL_CHAR && str[strPos] == NULL_CHAR) { // the substring is shorter than the pattern to match
return NOT_FOUND;
}
if (pattern[patPos] == QMARK || pattern[patPos] == str[strPos]) {
if (pattern[patPos + 1] == NULL_CHAR) // the entire pattern is matched
return 1;
int result = findSubLenAtStrPosWithQmark(str, pattern, strPos + 1, patPos + 1); // check if the remaining part of the pattern
if (result != NOT_FOUND) // only return a match when the entire pattern is matched
return 1 + result;
result = findSubLenAtStrPosWithQmark(str, pattern, strPos, patPos + 1);
if (result != NOT_FOUND) // only return a match when the entire pattern is matched
return result;
}
return NOT_FOUND;
}
int matchSubWithQmark(const char str[], const char pattern[], int &length, int start = 0) {
length = 0;
if (str[start] == NULL_CHAR)
return NOT_FOUND;
int testLength = findSubLenAtStrPosWithQmark(str, pattern, start);
if (testLength != NOT_FOUND) {
length = testLength;
return start;
}
return matchSubWithQmark(str, pattern, length, start + 1);
}
int getLen(const char *str, int pos = 0) {
if (str[pos] == NULL_CHAR)
return 0;
return 1 + getLen(str, pos + 1);
}
bool PercentOnly(const char *str, int pos = 0) {
if (str[pos] == NULL_CHAR)
return true;
if (str[pos] != PERCENT)
return false;
return true * PercentOnly(str, pos + 1);
}
bool AllKeyword(const char *str, int pos = 0) {
if (str[pos] == NULL_CHAR)
return true;
if (str[pos] != PERCENT && str[pos] != QMARK)
return false;
return true * AllKeyword(str, pos + 1);
}
//task2
int findSubLenAtStrPosWithPercent(const char str[], const char pattern[], int strPos = 0, int patPos = 0) {
char trash[23];
// cin.getline(trash, 4);
if (DEBUGMODE) Debug(str, strPos, pattern, patPos);
if (str[strPos] == NULL_CHAR && AllKeyword(pattern, patPos)) {
return 0;
}
if (str[strPos] != NULL_CHAR && pattern[patPos] == NULL_CHAR) {
if (DEBUGMODE) cout << "BASE4" << endl;
return 0;
}
if (str[strPos] != NULL_CHAR && pattern[patPos] != NULL_CHAR
&& str[strPos + 1] == NULL_CHAR && pattern[patPos + 1] == NULL_CHAR
&& str[strPos] == pattern[patPos]) {
if (DEBUGMODE) cout << "BASE3" << endl;
return 1;
}
if (str[strPos + 1] == NULL_CHAR && pattern[patPos] == NULL_CHAR) {
if (DEBUGMODE) cout << "BASE0" << endl;
return 0;
}
if (str[strPos] == NULL_CHAR && pattern[patPos] == PERCENT && pattern[patPos + 1] == NULL_CHAR) {
if (DEBUGMODE) cout << "BASE1" << endl;
return 0;
}
if (str[strPos] == NULL_CHAR && pattern[patPos] != NULL_CHAR) {
if (DEBUGMODE) cout << "BASE2" << endl;
return NOT_FOUND;
}
//rec
if (pattern[patPos] == PERCENT) {
if (DEBUGMODE) cout << 1 << endl;
int result;
result = findSubLenAtStrPosWithPercent(str, pattern, strPos + 1, patPos) + 1;
if (DEBUGMODE) cout << "RES" << result << endl;
if (result == NOT_FOUND + 1) {
result = findSubLenAtStrPosWithPercent(str, pattern, strPos, patPos + 1);
return result;
} else
return result;
}
if (pattern[patPos] == str[strPos]) {
if (DEBUGMODE) cout << 2 << endl;
int result = findSubLenAtStrPosWithPercent(str, pattern, strPos + 1, patPos) + 1; // check if the remaining part of the pattern
if (result == NOT_FOUND + 1) {
result -= 1;
result = findSubLenAtStrPosWithPercent(str, pattern, strPos + 1, patPos + 1) + 1; // check if the remaining part of the pattern
if (result == NOT_FOUND + 1) {
return result - 1;
} else
return result;
}
return result - 1;
}
return NOT_FOUND;
}
int matchSubWithPercent(const char str[], const char pattern[], int &length, int start = 0) {
length = 0;
if (str[start] == NULL_CHAR)
return NOT_FOUND;
int testLength = findSubLenAtStrPosWithPercent(str, pattern, start);
if (testLength != NOT_FOUND) {
length = testLength;
return start;
}
return matchSubWithPercent(str, pattern, length, start + 1);
}
// Task 3 (25 points)
int findSubLenAtStrPos(const char str[], const char pattern[], int strPos = 0, int patPos = 0) {
if (DEBUGMODE) Debug(str, strPos, pattern, patPos);
if (str[strPos] == NULL_CHAR && AllKeyword(pattern, patPos)) {
if (DEBUGMODE) cout << "BASEE7" << endl;
return 0;
}
if (pattern[patPos] != NULL_CHAR && str[strPos] == NULL_CHAR) { // the substring is shorter than the pattern to match
if (DEBUGMODE) cout << "BASE5" << endl;
return NOT_FOUND;
}
if (str[strPos] != NULL_CHAR && pattern[patPos] == NULL_CHAR) {
if (DEBUGMODE) cout << "BASE4" << endl;
return 0;
}
if (str[strPos] != NULL_CHAR && pattern[patPos] != NULL_CHAR
&& str[strPos + 1] == NULL_CHAR && pattern[patPos + 1] == NULL_CHAR
&& str[strPos] == pattern[patPos]) {
if (DEBUGMODE) cout << "BASE3" << endl;
return 1;
}
if (str[strPos + 1] == NULL_CHAR && pattern[patPos] == NULL_CHAR) {
if (DEBUGMODE) cout << "BASE0" << endl;
return 0;
}
if (str[strPos] == NULL_CHAR && pattern[patPos] == PERCENT && pattern[patPos + 1] == NULL_CHAR) {
if (DEBUGMODE) cout << "BASE1" << endl;
return 0;
}
if (str[strPos] == NULL_CHAR && pattern[patPos] != NULL_CHAR) {
if (DEBUGMODE) cout << "BASE2" << endl;
return NOT_FOUND;
}
if (pattern[patPos] == DOT) {
if (DEBUGMODE) cout << 3 << endl;
if (pattern[patPos + 1] == NULL_CHAR) // the entire pattern is matched
return 1;
// otherwise, the match is only part way through
int result = findSubLenAtStrPos(str, pattern, strPos + 1, patPos + 1); // check if the remaining part of the pattern
if (result != NOT_FOUND) // only return a match when the entire pattern is matched
return 1 + result;
}
if (pattern[patPos] == QMARK) {
if (DEBUGMODE) cout << 3 << endl;
if (pattern[patPos + 1] == NULL_CHAR) // the entire pattern is matched
return 1;
int result = findSubLenAtStrPos(str, pattern, strPos + 1, patPos + 1); // check if the remaining part of the pattern
if (result != NOT_FOUND) // only return a match when the entire pattern is matched
return 1 + result;
result = findSubLenAtStrPos(str, pattern, strPos, patPos + 1);
if (result != NOT_FOUND) // only return a match when the entire pattern is matched
return result;
}
if (pattern[patPos] == PERCENT) {
if (DEBUGMODE) cout << 1 << endl;
int result;
result = findSubLenAtStrPos(str, pattern, strPos + 1, patPos) + 1;
if (DEBUGMODE) cout << "RES" << result << endl;
if (result == NOT_FOUND + 1) {
result = findSubLenAtStrPos(str, pattern, strPos, patPos + 1);
return result;
} else
return result;
}
if (pattern[patPos] == str[strPos]) {
if (DEBUGMODE) cout << 2 << endl;
int result = findSubLenAtStrPos(str, pattern, strPos + 1, patPos) + 1; // check if the remaining part of the pattern
if (result == NOT_FOUND + 1) {
result -= 1;
result = findSubLenAtStrPos(str, pattern, strPos + 1, patPos + 1) + 1; // check if the remaining part of the pattern
if (result == NOT_FOUND + 1) {
return result - 1;
} else
return result;
}
return result - 1;
}
return NOT_FOUND;
}
int matchSub(const char str[], const char pattern[], int &length, int start = 0) {
length = 0;
if (str[start] == NULL_CHAR)
return NOT_FOUND;
if (pattern[0] == CARET) {
int testLength = findSubLenAtStrPos(str, pattern, start, 1);
if (testLength != NOT_FOUND) {
length = testLength;
return start;
} else
return NOT_FOUND;
} else {
int testLength = findSubLenAtStrPos(str, pattern, start);
if (testLength != NOT_FOUND) {
length = testLength;
return start;
}
}
return matchSub(str, pattern, length, start + 1);
}
// DO NOT WRITE ANYTHING AFTER THIS LINE. ANYTHING AFTER THIS LINE WILL BE
// REPLACED
// Given `str`, prints the substring that begins at `start` with length
// `length`. Raises an assertion error when an attempt is made to print beyond
// the available length. You are not allowed to use loops in your solution,
// though we use them here.
void printString(const char str[], const int start, const int length) {
for (int i = start; i < start + length; i++)
assert(str[i] != NULL_CHAR);
for (int i = start; i < start + length; i++)
cout << str[i];
}
// A driver program for testing your solution.
int main() {
const int MAX_LENGTH = 1000;
char pattern[MAX_LENGTH];
char str[MAX_LENGTH];
int option, pos, length;
while (true) {
cout << "Task No. (-1 to exit): ";
// cin >> option;
if (cin.fail()) {
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
continue;
}
if (option == -1)
break;
if (option < 0 || option > 3)
continue;
cout << endl;
cout << "Enter the string to match: ";
cin >> str;
cout << "Enter the pattern to match: ";
cin >> pattern;
length = 0;
// cin >> option;
option = 3;
switch (option) {
case 0:
pos = matchSubWithDot(str, pattern, length);
break;
case 1:
pos = matchSubWithQmark(str, pattern, length);
break;
case 2:
pos = matchSubWithPercent(str, pattern, length);
break;
case 3:
pos = matchSub(str, pattern, length);
break;
}
cout << endl;
if (pos == NOT_FOUND) {
cout << "Pattern is not found." << endl;
} else {
cout << "Pattern's first occurence is at " << pos
<< ", with longest possible length = " << length << "."
<< endl;
cout << "Matched substring is '";
printString(str, pos, length);
cout << "'." << endl;
}
cout << "--------------------------------------------------------------"
"----"
"---"
<< endl;
}
cout << "bye" << endl;
} | true |
56e0af5a79f589bb03d023e27b757b2a555c88d5 | C++ | LM1107/mygit | /workspace/hqyj/c++/day3/const_class.cpp | UTF-8 | 668 | 3.640625 | 4 | [] | no_license | #include <iostream>
using namespace std;
class Demo{
public:
Demo(int ,int );
void setVal(int ,int ) const;
int getVal();
void display(){}
int z;
private:
const int x;
int y;
};
Demo::Demo(int a ,int b):x(a),y(b)
{
}
void Demo::setVal(int a,int b) const
{
}
int Demo::getVal()
{
return y;
}
int main()
{
const Demo obj(10,12); //定义初始化一个只读对象
Demo const obj1(2,4);
obj.setVal(4,5);
//cout<<obj.getVal()<<endl; //const 修饰的对象,不能访问 非const成员函数
cout << obj.z << endl; //cosnt 修饰的对象,能访问类的共有成员变量,但不能修改
} | true |
beae0348680d200effac372f9a6dc9a21687db6a | C++ | vanshsehgal2001/Leetcode | /Leetcode_Arrays_Easy/RelativeSortArray.cpp | UTF-8 | 719 | 3.0625 | 3 | [] | no_license | class Solution {
public:
vector<int> relativeSortArray(vector<int>& arr1, vector<int>& arr2) {
int arr[1001]={0};
for(int i=0;i<arr1.size();i++){
arr[arr1[i]]++;
}
vector<int> output;
for(int i=0;i<arr2.size();i++){
int ele=arr2[i];
// output.push_back(ele);
// arr[ele];
while(arr[ele]){
output.push_back(ele);
arr[ele]--;
}
}
for(int i=0;i<1001;i++){
if(arr[i]>0){
while(arr[i]){
output.push_back(i);
arr[i]--;
}
}
}
return output;
}
};
| true |
f2612aabdea8fdd19c2b0c1cc4bde36f3450a573 | C++ | Blackcat12/Informatica_3 | /E_24_fattoriale con sottoprogrammi.cpp | WINDOWS-1252 | 542 | 3.3125 | 3 | [
"MIT"
] | permissive | #include<stdio.h>
#include<stdlib.h>
/*
program:fattoriale con sottoprogramma
Diego Gattari
3INA
13/09/2017
versione 1.0
*/
int main () {
int r;
int n;
do{//ciclo per rendere l'inserimento del numero corretto
printf("Inserisci un numero: ");
scanf("%d", & n);
}while(n<0);
r=fat_n(int n);//operazione che richiama il sottoprogramma
printf("Il fattoriale : %d", r);
system("PAUSE");
}
int fat_n (int n){//sottoprogramma
int a;
a=1;
if(n>=0){
while(n!=0){
a=a*n;
n--;
}
}
return a;
}
| true |
ad6befce74c7279ca2b3ad07794f002e645cdc7f | C++ | HackEduca/Mixly_Arduino | /mixly_arduino/arduino/portable/sketchbook/libraries/SevenSegmentTM1637/src/SevenSegmentExtended.h | UTF-8 | 1,337 | 2.890625 | 3 | [
"GPL-2.0-only",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | /*
SevenSegmentTM1637 - class to control a 4 digit seven segment display with a TM1636 or TM1637 driver IC
Created by Bram Harmsen, September 25, 2015
Released into the public domain.
Licence: GNU GENERAL PUBLIC LICENSE V2.0
# Changelog
v1.0.0 25-10-2015
* First release
*/
#ifndef SevenSegmentExtended_H
#define SevenSegmentExtended_H
#if ARDUINO >= 100
#include <Arduino.h>
#else
#include <WProgram.h>
#endif
#include "SevenSegmentTM1637.h"
class SevenSegmentExtended : public SevenSegmentTM1637 {
public:
SevenSegmentExtended(uint8_t pinClk, uint8_t pinDIO);
/* Prints given time to the display
@param [in] hour hours or minutes
@param [in] min minutes or seconds
*/
void printTime(uint8_t hour, uint8_t min, bool blink = false);
/* Prints given time to the display
@param [in] t time given as an int, e.g. 1643 prints 16:43
*/
void printTime(uint16_t t, bool blink);
/* Print two one or two digit numbers to the display
* Prints a number to the left and right of the display
*
@param [in] leftCounter the number on the left side of the display
@param [in] rightcounter the numnber on the right side of the display
@param [in] zeroPadding optional: pad counters with zero
*/
void printDualCounter(int8_t leftCounter, int8_t rightCounter, bool zeroPadding = false);
};
#endif
| true |
022f435060b9f64ece2ba235caa212bc1dac040b | C++ | Neology92/complex-test | /src/Statistics.cpp | UTF-8 | 830 | 3.359375 | 3 | [] | no_license | #include <iostream>
#include "Statistics.hh"
/*!
* Plik zawiera definicje metod zawartych w klasie Points
*/
Points::Points(){
count = 0;
pool = 0;
}
void Points::goodAnswer(){
pool++;
count++;
}
void Points::badAnswer(){
pool++;
}
void Points::check(Complex pattern, Complex answer){
if(pattern == answer){
Points::goodAnswer();
std::cout << "\033[1;32mDobrze!\033[0m" << std::endl;
}else{
Points::badAnswer();
std::cout << "\033[1;31mZla odpowiedz.\033[0m Prawidlowy wynik: "<< pattern << std::endl;
}
}
void Points::showResults(){
std::cout << "Ilosc dobrych odpowiedzi: " << count << std::endl;
std::cout << "Ilosc zlych odpowiedzi: " << pool-count << std::endl;
std::cout << "Wynik procentowy: " << (float)(100*count/pool) << "%"<< std::endl;
}
| true |
dd63a923b7fdc940dc63c7293e6d0425fd5f8703 | C++ | kevin-chshen/C-11_exercise | /test/container/IocContainer.h | UTF-8 | 1,800 | 3.109375 | 3 | [] | no_license | #pragma once
#include <unordered_map>
#include <functional>
#include <memory>
#include <string>
#include <iostream>
#include "Any.h"
class IocContainer
{
public:
IocContainer() {};
~IocContainer() {};
public:
template <typename T, typename Denped, typename... Args>
typename std::enable_if<!std::is_base_of<T, Denped>::value>::type
RegisterType(const std::string& key)
{
std::function<T * (Args...)> f = [](Args... args) {
return new T(new Denped(args...));
};
RegisterType(key, f);
}
template <typename T, typename Denped, typename... Args>
typename std::enable_if<std::is_base_of<T, Denped>::value>::type
RegisterType(const std::string& key)
{
std::function<T * (Args...)> f = [](Args... args) {
return new Denped(args...);
};
RegisterType(key, f);
}
template <typename T, typename... Args>
void RegisterSimple(const std::string& key)
{
std::function<T * (Args...)> f = [](Args... args) {
return new T(args...);
};
RegisterType(key, f);
}
template <typename T, typename... Args>
T* Resolve(const std::string& key, Args... args)
{
auto it = _obj_map.find(key);
if (it == _obj_map.end()) {
return nullptr;
}
Any resolver = it->second;
std::function<T * (Args...)> func =
resolver.AnyCast<std::function<T * (Args...)>>();
return func(args...);
}
template <typename T, typename... Args>
std::shared_ptr<T> ResolveShared(const std::string& key, Args... args)
{
T* ptr = Resolve<T>(key, args...);
return std::shared_ptr<T>(ptr);
}
private:
void RegisterType(const std::string& key, Any creator)
{
if (_obj_map.find(key) != _obj_map.end())
throw std::invalid_argument("alread register");
_obj_map.emplace(key, creator);
}
private:
std::unordered_map<std::string, Any> _obj_map;
};
void ioc_container_run();
| true |
84861c5e6bcf32618a13bf0ba28d4fbdd61364ff | C++ | greenfox-zerda-sparta/besszerf | /week-06/Day-3_templates/07.cpp | UTF-8 | 1,036 | 4.125 | 4 | [] | no_license | #include <iostream>
#include <string>
using namespace std;
typedef unsigned int uint;
template<class T, class P>
class Example {
private:
T item1;
P item2;
public:
Example(T i1, P i2);
T get_item1();
P get_item2();
void set_item1(T item);
void set_item2(P item);
};
template<class T, class P>
Example<T, P>::Example(T i1, P i2) {
item1 = i1;
item2 = i2;
}
template<class T, class P>
T Example<T, P>::get_item1() {
return item1;
}
template<class T, class P>
P Example<T, P>::get_item2() {
return item2;
}
template<class T, class P>
void Example<T, P>::set_item1(T item) {
item1 = item;
}
template<class T, class P>
void Example<T, P>::set_item2(P item) {
item2 = item;
}
int main() {
//Create a simple class template which contains 2 item and has both a get and a set method for these!
Example<int, float> my_class(2, 3.1415);
my_class.set_item1(5);
my_class.set_item2(4.8);
cout << my_class.get_item1() << endl;
cout << my_class.get_item2() << endl;
return 0;
}
| true |
8e21c13a2e579a158b75014736e6766ff9c485ff | C++ | Maxime-Tong/Happy_new_year_present | /Characters.cpp | GB18030 | 3,219 | 2.90625 | 3 | [] | no_license | #include "Characters.h"
#include<vector>
#include<queue>
#include<iostream>
#include<conio.h>
#include<windows.h>
using namespace std;
void Put(string c)
{
for (int i = 0; i < c.size(); ++i) {
cout << c[i];
Sleep(10);
}
Sleep(500);
}
bool is_legal(int map[row][column],COORDINATE& node)
{
if (node.x >=column || node.x < 1 || node.y>=row || node.y < 1)return false;//ͼΧ
if (map[node.x][node.y] == 0)return false;//λǽ
return true;
}
Character::Character(int _x, int _y):id(_x, _y), cd(0){}
bool Character::is_coordinate(int _x, int _y) {
if (_x == id.x && _y == id.y)return true;
return false;
}
void Character::bfs(int map[row][column],const COORDINATE& target)
{
if (target.x == id.x && target.y == id.y)return;
struct Situation
{
vector<COORDINATE>trace;
Situation() {};
Situation(vector<COORDINATE> _t) :trace(_t) {};
void add_Node(COORDINATE n) { trace.push_back(n); }
};//trace洢bfs·
Situation road_map[row][column];
queue<COORDINATE>q;
bool visited[row][column] = { 0 };
int direction[4][2] = { {1,0} ,{-1,0},{0,1},{0,-1} };
Situation start;
q.push(id);
visited[id.x][id.y] = true;
road_map[id.x][id.y] = start;
//Ŀ
while (!q.empty())
{
COORDINATE n1 = q.front();
for (int i = 0; i < 4; ++i)
{
COORDINATE new_node;
new_node.x = n1.x + direction[i][0];
new_node.y = n1.y + direction[i][1];
if (!is_legal(map,new_node))continue;//illegal
Situation _l(road_map[n1.x][n1.y]);
_l.add_Node(new_node);
if (!visited[new_node.x][new_node.y])
{
road_map[new_node.x][new_node.y] = _l;
q.push(new_node);
visited[new_node.x][new_node.y] = true;
}
//when we find a better solution
else if (road_map[new_node.x][new_node.y].trace.size() > _l.trace.size())
{
road_map[new_node.x][new_node.y] = _l;
q.push(new_node);
}
}
q.pop();
}
//monster launched to march !
Situation solution = road_map[target.x][target.y];
if (cd == 0 && solution.trace.size() >= 2)
{
id = solution.trace[1];//two steps
//Put("<<<<>>>> ĴϢԶ...........ˣ\n");
cd = 5;
}
else
{
id = solution.trace[0];//one step
--cd;
}
}
const COORDINATE Character::get_coordinate() { return id; }
void Character::March(int map[row][column],int x_offset, int y_offset)
{
COORDINATE tmp = id;
tmp.x += x_offset; tmp.y += y_offset;
if (is_legal(map,tmp))id = tmp;
else cout << "....СΪ\n";
}
void Character::alter_id(const COORDINATE& target) {
id =target;
}
void Voidwalker::cross_wall(int map[row][column], int x_offset, int y_offset)
{
alter_cd(5);
COORDINATE tmp = get_coordinate();
tmp.x += x_offset; tmp.y += y_offset;
if (map[tmp.x][tmp.y] == 0)
{
tmp.x += x_offset; tmp.y += y_offset;
if (map[tmp.x][tmp.y] == 0) {
cout << "....СΪ\n";
return;
}
alter_id(tmp);
return;
}
if (is_legal(map, tmp))alter_id(tmp);
else cout << "....СΪ\n";
}
bool Voidwalker::swimmy(int& stars) {
if (stars == 0)
{
Put("...û֮");
return false;
}
--stars;
return true;
} | true |
8515ab847325264f32434988dfc56d7da251d8d1 | C++ | HaeilSeo/console.h | /main.cpp | UHC | 3,265 | 2.921875 | 3 | [] | no_license | #include<iostream>
#include"DDS.h"
#include"keyboard.h"
#include"graphic.h"
class Player {
public:
/////////÷̾ /////////
DDS_FILE* dds[8]; //DDS κ̹ 迭
float px;
float py;
float Speed;
int imgldx; // κ ̹ 迭 ε
///////÷̾ Լ////////
void init() {
int subImgWidth = 184; //κ ̹ ̿
int subImgHeight = 325;
//8 κ̹ о ´..
dds[0] = readDDSRect("sample.dds", 0 * subImgWidth, 0, subImgWidth, subImgHeight);
dds[1] = readDDSRect("sample.dds", 1 * subImgWidth, 0, subImgWidth, subImgHeight);
dds[2] = readDDSRect("sample.dds", 2 * subImgWidth, 0, subImgWidth, subImgHeight);
dds[3] = readDDSRect("sample.dds", 3 * subImgWidth, 0, subImgWidth, subImgHeight);
dds[4] = readDDSRect("sample.dds", 4 * subImgWidth, 0, subImgWidth, subImgHeight);
dds[5] = readDDSRect("sample.dds", 5 * subImgWidth, 0, subImgWidth, subImgHeight);
dds[6] = readDDSRect("sample.dds", 6 * subImgWidth, 0, subImgWidth, subImgHeight);
dds[7] = readDDSRect("sample.dds", 7 * subImgWidth, 0, subImgWidth, subImgHeight);
px = 0;
py = 0;
imgldx = 0;
Speed = 100;
}
void update() {
Sleep(80);
float dt = getDeltaTime()*Speed;
if (GetKey(VK_UP) == true) {
py -= dt; //ijͰ ϶, pyǥ ϰ
imgldx++; // Ѿϴ.
}
if (GetKey(VK_DOWN) == true) {
py += dt; //ijͰ Ʒ ϶, pyǥ ϰ
imgldx--; // ưϴ.
}
if (GetKey(VK_RIGHT) == true) {
px += dt; //ijͰ ϶, pxǥ ϰ
imgldx++; // Ѿϴ.
}
if (GetKey(VK_LEFT) == true) {
px -= dt; //ijͰ ϶, pxǥ ϰ
imgldx--; // ưϴ.
}
if (imgldx > 7) { //ִ 迭 ȣʰ imgldx þ,
imgldx = 0; //imgldx 0 ʱȭǾ ִϸ̼ ó ưϴ.
}
else if (imgldx < 0) { //ּ 迭 ȣ̴ imgldx پ,
imgldx = 7; //imgldx 7 ʱȭǾ ִϸ̼ ưϴ.
}
}
void render() {
//imgldx ° 迭 ִ... DDS ̹ Ѵ.
BYTE* data = dds[imgldx]->data;
for (int y = 0; y < dds[imgldx]->header.dwHeight; y++) {
for (int x = 0; x < dds[imgldx]->header.dwWidth; x++) {
BYTE a = data[3];
BYTE r = data[2];
BYTE g = data[1];
BYTE b = data[0];
setPixel(px + x, py + y, r, g, b);
data += 4;
}
}
}
};
int main() {
Player player;
///////ʱȭ////////
initGraphic();
initTimer();
initKey();
player.init();
while (true) {
///////Ʈ///////
clear(0, 0, 0);
updateKey();
updateTimer();
player.update();
player.render();
///////////////
render();
}
return 0;
} | true |
1230df5014faae8bcb91bab5c1887c2dcd496383 | C++ | yashasvimisra2798/CodesByYashasvi | /C++/Class.cpp | UTF-8 | 2,876 | 4.4375 | 4 | [] | no_license | // You have to create a class, named Student, representing the student's details, as mentioned above, and store the data of a student.
// Create setter and getter functions for each element; that is, the class should at least have following functions:
// get_age, set_age
// get_first_name, set_first_name
// get_last_name, set_last_name
// get_standard, set_standard
// Also, you have to create another method to_string() which returns the string consisting of the above elements, separated by a comma(,).
// You can refer to stringstream for this.
// Input Format
// Input will consist of four lines.
// The first line will contain an integer, representing the age. The second line will contain a string, consisting of lower-case Latin characters ('a'-'z'),
// representing the first_name of a student.The third line will contain another string, consisting of lower-case Latin characters ('a'-'z'),
// representing the last_name of a student.The fourth line will contain an integer, representing the standard of student.
// Note: The number of characters in first_name and last_name will not exceed 50.
// Output Format
// The code provided by HackerRank will use your class members to set and then get the elements of the Student class.
// Sample Input
// 15
// john
// carmack
// 10
// Sample Output
// 15
// carmack, john
// 10
// 15,john,carmack,10
// CODE:-
#include <iostream>
#include <sstream>
using namespace std;
class Student
{
int age;
int standard;
string first_name;
string last_name;
public:
Student()
{
age=0;
standard=0;
first_name="";
last_name="";
}
void set_age(int newAge)
{
age = newAge;
}
void set_standard(int newStandard)
{
standard = newStandard;
}
void set_first_name(string newFirst_name)
{
first_name = newFirst_name;
}
void set_last_name(string newLast_name)
{
last_name = newLast_name;
}
int get_age() {
return age;
}
int get_standard() {
return standard;
}
string get_first_name() {
return first_name;
}
string get_last_name() {
return last_name;
}
string to_string()
{
stringstream ss;
char c = ',';
ss << age << c << first_name << c << last_name << c << standard;
return ss.str();
}
};
int main() {
int age, standard;
string first_name, last_name;
cin >> age >> first_name >> last_name >> standard;
Student st;
st.set_age(age);
st.set_standard(standard);
st.set_first_name(first_name);
st.set_last_name(last_name);
cout << st.get_age() << "\n";
cout << st.get_last_name() << ", " << st.get_first_name() << "\n";
cout << st.get_standard() << "\n";
cout << "\n";
cout << st.to_string();
return 0;
}
| true |
05070913ce32b9b5f5ce691595d2e48ab5c43a36 | C++ | choupi/puzzle | /leetcode/p1461.cpp | UTF-8 | 406 | 2.765625 | 3 | [] | no_license | class Solution {
public:
bool hasAllCodes(string s, int k) {
unordered_set<string> kset;
int kcnt = 1 << k;
int len = s.size();
//cout << len-k+1<< endl;
for (int i=0;i<len-k+1;i++) {
//cout << s.substr(i, k) << endl;
kset.insert(s.substr(i, k));
if (kset.size() == kcnt) return true;
}
return false;
}
};
| true |
8498efaccba3d19a80ca9b7331be046c2157445d | C++ | elamitie/apex | /engine/graphics/view/Camera.cpp | UTF-8 | 2,781 | 2.796875 | 3 | [] | no_license | #include "Camera.h"
#include <math.h>
#include "utils/Math.h"
#include "input/Keyboard.h"
#include "input/Mouse.h"
#include "utils/Logger.h"
Camera::Camera(glm::vec3 pos, glm::vec3 up) {
Position = pos;
mTargetDistance = mDistance = pos.z;
WorldUp = up;
mScrollDirty = false;
CalculateForward();
}
Camera::~Camera() {
}
void Camera::HandleKeyboard(CameraDirection dir, float dt) {
float vel = Properties.Speed * dt;
if (dir == CamForward)
Position += Front * vel;
if (dir == CamBack)
Position -= Front * vel;
if (dir == CamLeft)
Position -= Right * vel;
if (dir == CamRight)
Position += Right * vel;
}
void Camera::HandleMouse(float deltaX, float deltaY) {
float xmovement = deltaX * Properties.Sensitivity;
float ymovement = deltaY * Properties.Sensitivity;
Properties.Yaw += xmovement;
Properties.Pitch += ymovement;
if (Properties.Yaw == 0.0f) Properties.Yaw = 0.01f;
if (Properties.Pitch == 0.0f) Properties.Pitch = 0.01f;
if (Properties.Pitch > 89.0f) Properties.Pitch = 89.0f;
if (Properties.Pitch < -89.0f) Properties.Pitch = -89.0f;
CalculateForward();
}
void Camera::Update(double dt) {
// "Zoom" in / out with the scroll wheel
float vel = Properties.Speed * dt;
ticks += dt * mRotationRate;
if (mRotate)
{
Position.x = std::cos(ticks) * mDistance;
Position.z = std::sin(ticks) * mDistance;
if (Mouse::GetScrollOffset().y != mPreviousScroll.y) {
mScrollDirty = true;
}
// Only move
if (mScrollDirty) {
mTargetDistance -= Mouse::GetScrollOffset().y * 0.3f;
mScrollDirty = false;
}
mTargetDistance = math::Clamp(mTargetDistance, 1.0f, 6.0f);
mDistance = math::Lerp(mDistance, mTargetDistance, math::Clamp01(dt * DampCoeff));
if (Mouse::GetScrollOffset().y > 0 || Mouse::GetScrollOffset().y < 0) {
mPreviousScroll = Mouse::GetScrollOffset();
}
}
CalculateForward();
}
glm::mat4 Camera::GetView() {
//return glm::lookAt(Position, Position + Front, CameraUp);
return glm::lookAt(Position, glm::vec3(0.0, 0.0, 0.0), CameraUp);
}
glm::mat4 Camera::CreateProjection(uint width, uint height) {
return glm::perspective(Properties.Zoom, (float)width / (float)height, 0.1f, 100.0f);
}
void Camera::CalculateForward() {
glm::vec3 f;
f.x = cos(glm::radians(Properties.Yaw)) * cos(glm::radians(Properties.Pitch));
f.y = sin(glm::radians(Properties.Pitch));
f.z = sin(glm::radians(Properties.Yaw)) * cos(glm::radians(Properties.Pitch));
Front = glm::normalize(f);
Right = glm::normalize(glm::cross(Front, WorldUp));
CameraUp = glm::normalize(glm::cross(Right, Front));
} | true |
649ad58b37d57736b699bd2584b574019421f0e7 | C++ | NerdyCrow/OAP-sem2 | /Лаб 3/Lab №3 v16.2/Lab №3 v16.2/Lab №3 v16.2.cpp | MacCyrillic | 545 | 2.75 | 3 | [] | no_license | #include<iostream>
#include<fstream>
#include<string>
using namespace std;
void search(char str[]) {
ofstream fout;
fout.open("FILE1.txt");
char st;
fout << str;
fout.close();
ifstream fin;
fin.open("FILE1.txt");
char arr[20];
int i = 0;
while (!fin.eof())
{
fin.get(st);
if (st=='2'||st=='4'||st=='6'||st=='8')
{
cout << st<<" ";
}
}
fin.close();
}
int main() {
setlocale(LC_ALL, "rus");
char str[50];
cout << " : ";
gets_s(str);
cout << str;
cout << endl;
search(str);
} | true |
aaec392ba5e6ee04b18ded77ffe60bcdbaa55412 | C++ | adiwang/uvnet | /test/test_pb.cpp | UTF-8 | 1,858 | 3.15625 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include "../pb/netmessage.pb.h"
class Protocol
{
public:
Protocol() {}
virtual ~Protocol() {}
virtual void Process(const char* buf, int length) = 0;
};
class CProtocol1 : public Protocol
{
public:
CProtocol1() {}
virtual ~CProtocol1() {}
static CProtocol1* GetInstance() { static CProtocol1 instance; return &instance; }
virtual void Process(const char *buf, int length)
{
CP1 cp1;
cp1.ParseFromArray(buf, length);
std::cout << "CP1: a = " << cp1.a() << ", b = " << cp1.b() << ", c = " << cp1.c() << std::endl;
}
};
class CProtocol2 : public Protocol
{
public:
CProtocol2() {}
virtual ~CProtocol2() {}
static CProtocol2* GetInstance() { static CProtocol2 instance; return &instance; }
virtual void Process(const char *buf, int length)
{
CP2 cp2;
cp2.ParseFromArray(buf, length);
std::cout << "CP2: a = " << cp2.a() << ", b = " << cp2.b() << ", c = " << cp2.c() << std::endl;
}
};
void HandleProtocol(const char* buf, int length)
{
CProto proto;
proto.ParseFromArray(buf, length);
if(proto.id() == 1)
{
CProtocol1::GetInstance()->Process(proto.body().c_str(), proto.body().size());
}
else if(proto.id() == 2)
{
CProtocol2::GetInstance()->Process(proto.body().c_str(), proto.body().size());
}
else
{
std::cout << "unknown protocol" << std::endl;
}
}
int main(int argc, char **argv)
{
CProto cproto;
std::string data;
CP1 cp1;
cp1.set_a(32);
cp1.set_b(64);
cp1.set_c("this ia a string");
cproto.set_id(1);
cproto.set_body(cp1.SerializeAsString());
cproto.SerializeToString(&data);
HandleProtocol(data.c_str(), data.size());
CP2 cp2;
cp2.set_a("this is cp2 a string");
cp2.set_b("this is cp2 b string");
cp2.set_c(64);
cproto.set_id(2);
cproto.set_body(cp2.SerializeAsString());
cproto.SerializeToString(&data);
HandleProtocol(data.c_str(), data.size());
return 0;
}
| true |
dc483a2942c21f855eecc1cd1803e0b4c233c82a | C++ | dzimbeck/BitBay | /src/qt/qwt/qwt_interval.cpp | UTF-8 | 8,399 | 3 | 3 | [
"MIT"
] | permissive | /* -*- mode: C++ ; c-file-style: "stroustrup" -*- *****************************
* Qwt Widget Library
* Copyright (C) 1997 Josef Wilgen
* Copyright (C) 2002 Uwe Rathmann
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the Qwt License, Version 1.0
*****************************************************************************/
#include "qwt_interval.h"
/*!
\brief Normalize the limits of the interval
If maxValue() < minValue() the limits will be inverted.
\return Normalized interval
\sa isValid(), inverted()
*/
QwtInterval QwtInterval::normalized() const
{
if ( d_minValue > d_maxValue )
{
return inverted();
}
if ( d_minValue == d_maxValue && d_borderFlags == ExcludeMinimum )
{
return inverted();
}
return *this;
}
/*!
Invert the limits of the interval
\return Inverted interval
\sa normalized()
*/
QwtInterval QwtInterval::inverted() const
{
BorderFlags borderFlags = IncludeBorders;
if ( d_borderFlags & ExcludeMinimum )
borderFlags |= ExcludeMaximum;
if ( d_borderFlags & ExcludeMaximum )
borderFlags |= ExcludeMinimum;
return QwtInterval( d_maxValue, d_minValue, borderFlags );
}
/*!
Test if a value is inside an interval
\param value Value
\return true, if value >= minValue() && value <= maxValue()
*/
bool QwtInterval::contains( double value ) const
{
if ( !isValid() )
return false;
if ( value < d_minValue || value > d_maxValue )
return false;
if ( value == d_minValue && d_borderFlags & ExcludeMinimum )
return false;
if ( value == d_maxValue && d_borderFlags & ExcludeMaximum )
return false;
return true;
}
//! Unite 2 intervals
QwtInterval QwtInterval::unite( const QwtInterval &other ) const
{
/*
If one of the intervals is invalid return the other one.
If both are invalid return an invalid default interval
*/
if ( !isValid() )
{
if ( !other.isValid() )
return QwtInterval();
else
return other;
}
if ( !other.isValid() )
return *this;
QwtInterval united;
BorderFlags flags = IncludeBorders;
// minimum
if ( d_minValue < other.minValue() )
{
united.setMinValue( d_minValue );
flags &= d_borderFlags & ExcludeMinimum;
}
else if ( other.minValue() < d_minValue )
{
united.setMinValue( other.minValue() );
flags &= other.borderFlags() & ExcludeMinimum;
}
else // d_minValue == other.minValue()
{
united.setMinValue( d_minValue );
flags &= ( d_borderFlags & other.borderFlags() ) & ExcludeMinimum;
}
// maximum
if ( d_maxValue > other.maxValue() )
{
united.setMaxValue( d_maxValue );
flags &= d_borderFlags & ExcludeMaximum;
}
else if ( other.maxValue() > d_maxValue )
{
united.setMaxValue( other.maxValue() );
flags &= other.borderFlags() & ExcludeMaximum;
}
else // d_maxValue == other.maxValue() )
{
united.setMaxValue( d_maxValue );
flags &= d_borderFlags & other.borderFlags() & ExcludeMaximum;
}
united.setBorderFlags( flags );
return united;
}
/*!
\brief Intersect 2 intervals
\param other Interval to be intersect with
\return Intersection
*/
QwtInterval QwtInterval::intersect( const QwtInterval &other ) const
{
if ( !other.isValid() || !isValid() )
return QwtInterval();
QwtInterval i1 = *this;
QwtInterval i2 = other;
// swap i1/i2, so that the minimum of i1
// is smaller then the minimum of i2
if ( i1.minValue() > i2.minValue() )
{
qSwap( i1, i2 );
}
else if ( i1.minValue() == i2.minValue() )
{
if ( i1.borderFlags() & ExcludeMinimum )
qSwap( i1, i2 );
}
if ( i1.maxValue() < i2.minValue() )
{
return QwtInterval();
}
if ( i1.maxValue() == i2.minValue() )
{
if ( i1.borderFlags() & ExcludeMaximum ||
i2.borderFlags() & ExcludeMinimum )
{
return QwtInterval();
}
}
QwtInterval intersected;
BorderFlags flags = IncludeBorders;
intersected.setMinValue( i2.minValue() );
flags |= i2.borderFlags() & ExcludeMinimum;
if ( i1.maxValue() < i2.maxValue() )
{
intersected.setMaxValue( i1.maxValue() );
flags |= i1.borderFlags() & ExcludeMaximum;
}
else if ( i2.maxValue() < i1.maxValue() )
{
intersected.setMaxValue( i2.maxValue() );
flags |= i2.borderFlags() & ExcludeMaximum;
}
else // i1.maxValue() == i2.maxValue()
{
intersected.setMaxValue( i1.maxValue() );
flags |= i1.borderFlags() & i2.borderFlags() & ExcludeMaximum;
}
intersected.setBorderFlags( flags );
return intersected;
}
/*!
\brief Unite this interval with the given interval.
\param other Interval to be united with
\return This interval
*/
QwtInterval& QwtInterval::operator|=( const QwtInterval &other )
{
*this = *this | other;
return *this;
}
/*!
\brief Intersect this interval with the given interval.
\param other Interval to be intersected with
\return This interval
*/
QwtInterval& QwtInterval::operator&=( const QwtInterval &other )
{
*this = *this & other;
return *this;
}
/*!
\brief Test if two intervals overlap
\param other Interval
\return True, when the intervals are intersecting
*/
bool QwtInterval::intersects( const QwtInterval &other ) const
{
if ( !isValid() || !other.isValid() )
return false;
QwtInterval i1 = *this;
QwtInterval i2 = other;
// swap i1/i2, so that the minimum of i1
// is smaller then the minimum of i2
if ( i1.minValue() > i2.minValue() )
{
qSwap( i1, i2 );
}
else if ( i1.minValue() == i2.minValue() &&
i1.borderFlags() & ExcludeMinimum )
{
qSwap( i1, i2 );
}
if ( i1.maxValue() > i2.minValue() )
{
return true;
}
if ( i1.maxValue() == i2.minValue() )
{
return !( ( i1.borderFlags() & ExcludeMaximum ) ||
( i2.borderFlags() & ExcludeMinimum ) );
}
return false;
}
/*!
Adjust the limit that is closer to value, so that value becomes
the center of the interval.
\param value Center
\return Interval with value as center
*/
QwtInterval QwtInterval::symmetrize( double value ) const
{
if ( !isValid() )
return *this;
const double delta =
qMax( qAbs( value - d_maxValue ), qAbs( value - d_minValue ) );
return QwtInterval( value - delta, value + delta );
}
/*!
Limit the interval, keeping the border modes
\param lowerBound Lower limit
\param upperBound Upper limit
\return Limited interval
*/
QwtInterval QwtInterval::limited( double lowerBound, double upperBound ) const
{
if ( !isValid() || lowerBound > upperBound )
return QwtInterval();
double minValue = qMax( d_minValue, lowerBound );
minValue = qMin( minValue, upperBound );
double maxValue = qMax( d_maxValue, lowerBound );
maxValue = qMin( maxValue, upperBound );
return QwtInterval( minValue, maxValue, d_borderFlags );
}
/*!
\brief Extend the interval
If value is below minValue(), value becomes the lower limit.
If value is above maxValue(), value becomes the upper limit.
extend() has no effect for invalid intervals
\param value Value
\return extended interval
\sa isValid()
*/
QwtInterval QwtInterval::extend( double value ) const
{
if ( !isValid() )
return *this;
return QwtInterval( qMin( value, d_minValue ),
qMax( value, d_maxValue ), d_borderFlags );
}
/*!
Extend an interval
\param value Value
\return Reference of the extended interval
\sa extend()
*/
QwtInterval& QwtInterval::operator|=( double value )
{
*this = *this | value;
return *this;
}
#ifndef QT_NO_DEBUG_STREAM
#include <qdebug.h>
QDebug operator<<( QDebug debug, const QwtInterval &interval )
{
const int flags = interval.borderFlags();
debug.nospace() << "QwtInterval("
<< ( ( flags & QwtInterval::ExcludeMinimum ) ? "]" : "[" )
<< interval.minValue() << "," << interval.maxValue()
<< ( ( flags & QwtInterval::ExcludeMaximum ) ? "[" : "]" )
<< ")";
return debug.space();
}
#endif
| true |
db64ed8876bbe7676f27e7dd336434b32bff8ea6 | C++ | Bekwnn/OpenGLSpring | /source/MayaCamera.cpp | UTF-8 | 4,636 | 2.78125 | 3 | [] | no_license | #include "MayaCamera.hpp"
#include <iostream>
struct MayaCamera::MayaCameraImpl
{
MayaCameraImpl() :
dolly(100.0f),
tumbleVector(45.0f),
trackVector(0.0f),
lastPos(0.0f),
movement(MayaCamera::CameraMovements::IDLE)
{
resetMatrices();
}
void resetAll()
{
dolly = 100.0f;
tumbleVector = atlas::math::Vector(45.0f);
trackVector = atlas::math::Vector(0.0f);
resetMatrices();
}
void resetMatrices()
{
USING_ATLAS_MATH_NS;
USING_GLM_NS;
dollyMatrix = translate(Matrix4(1.0f), Vector(0, 0, -1.0f * dolly));
trackMatrix = Matrix4(1.0f);
tumbleMatrix =
rotate(Matrix4(1.0f), radians(tumbleVector.x), Vector(1, 0, 0)) *
rotate(Matrix4(1.0f), radians(tumbleVector.y), Vector(0, 1, 0));
}
float dolly;
atlas::math::Vector tumbleVector;
atlas::math::Vector trackVector;
atlas::math::Point2 lastPos;
MayaCamera::CameraMovements movement;
atlas::math::Matrix4 dollyMatrix;
atlas::math::Matrix4 tumbleMatrix;
atlas::math::Matrix4 trackMatrix;
// spline movement
atlas::math::Vector position;
glm::quat rotation;
atlas::math::Matrix4 positionMatrix;
atlas::math::Matrix4 rotationMatrix;
};
MayaCamera::MayaCamera() :
mImpl(new MayaCameraImpl),
bIsPlaying(false),
waypointIndex(0),
curCurveTime(0.f)
{ }
MayaCamera::~MayaCamera()
{ }
// update call for spline movement
void MayaCamera::updateCameraRail(atlas::utils::Time const & t)
{
USING_ATLAS_MATH_NS;
USING_GLM_NS;
if (!bIsPlaying) return;
//update time and waypoint parameters
curCurveTime += t.deltaTime;
if (curCurveTime > transitionDurations[waypointIndex])
{
curCurveTime -= transitionDurations[waypointIndex];
waypointIndex++;
if (waypointIndex > waypoints.size() - 1) waypointIndex = 0;
}
Vector lastCameraPos = mImpl->position;
mImpl->position = getHermitePos(waypointIndex, (curCurveTime/transitionDurations[waypointIndex]), 1.f);
mImpl->positionMatrix = translate(Matrix4(1.f), mImpl->position - lastCameraPos);
//camera always looks at the origin
mImpl->rotationMatrix = glm::lookAt(mImpl->position, Vector(0.f, 0.f, 0.f), Vector(0.f, 1.f, 0.f));
}
void MayaCamera::mouseDown(atlas::math::Point2 const& point,
CameraMovements movement)
{
if (bIsPlaying) return;
mImpl->movement = movement;
mImpl->lastPos = point;
}
void MayaCamera::mouseDrag(atlas::math::Point2 const& point)
{
USING_ATLAS_MATH_NS;
USING_GLM_NS;
if (bIsPlaying) return; // lock camera controls if animation is playing
float deltaX = point.x - mImpl->lastPos.x;
float deltaY = point.y - mImpl->lastPos.y;
switch (mImpl->movement)
{
case CameraMovements::DOLLY: // zoom
mImpl->dolly -= 0.0008f * deltaX;
mImpl->dollyMatrix =
translate(Matrix4(1.0), Vector(0, 0, -1.0f * mImpl->dolly));
break;
case CameraMovements::TUMBLE: // rotate around
mImpl->tumbleVector.x += 0.005f * deltaY;
mImpl->tumbleVector.y += 0.005f * deltaX;
mImpl->tumbleMatrix =
rotate(mat4(1.0), radians(mImpl->tumbleVector.x), vec3(1, 0, 0)) *
rotate(mat4(1.0), radians(mImpl->tumbleVector.y), vec3(0, 1, 0));
break;
case CameraMovements::TRACK: // pan
mImpl->trackVector.x += 0.0005f * deltaX;
mImpl->trackVector.y -= 0.0005f * deltaY;
mImpl->trackMatrix = translate(mat4(1.0), mImpl->trackVector);
break;
case CameraMovements::IDLE:
break;
}
}
void MayaCamera::mouseUp()
{
mImpl->movement = CameraMovements::IDLE;
}
void MayaCamera::resetCamera()
{
mImpl->resetAll();
}
atlas::math::Matrix4 MayaCamera::getCameraMatrix()
{
if (bIsPlaying) return mImpl->positionMatrix * mImpl->rotationMatrix;
else return mImpl->dollyMatrix * mImpl->trackMatrix * mImpl->tumbleMatrix;
}
atlas::math::Vector MayaCamera::getHermitePos(int indexStartAt, float t, float tangentSize)
{
USING_ATLAS_MATH_NS;
if (waypoints.size() < 4) return Vector(0.f, 0.f, 0.f);
float t2 = t*t;
float t3 = t2*t;
Vector m0vec = (waypoints[(indexStartAt + 1) % waypoints.size()] - waypoints[(waypoints.size() + indexStartAt - 1) % waypoints.size()]);
Vector m1vec = (waypoints[(indexStartAt + 2) % waypoints.size()] - waypoints[indexStartAt]);
Vector p0 = (2.f*t3 - 3*t2 + 1)*waypoints[indexStartAt];
Vector m0 = (t3 - 2.f*t2 + t)*tangentSize*m0vec;
Vector p1 = (-2.f*t3 + 3.f*t2)*waypoints[(indexStartAt + 1) % waypoints.size()];
Vector m1 = (t3 - t2)*tangentSize*m1vec;
return p0 + m0 + p1 + m1;
}
| true |
e3b1e888a54520dcc72645a06de8dee054392ccb | C++ | Rookiee/CPlusPlus | /C++Primer/8_7.cc | UTF-8 | 951 | 2.859375 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <vector>
using namespace std;
typedef vector<string>::iterator Iterator;
istream &r (istream & is) {
string sval;
while(is >> sval , !is.eof() ) {
if(is.bad() )
throw runtime_error(" IO stream corrupted.");
if(is.fail() ) {
cerr << "Bad data, try agais: ";
is.clear ();
is.setstate(istream::eofbit);
continue;
}
cout << sval << endl;
}
is.clear();
return is;
}
int main() {
vector<string> files;
string name;
while(cin >> name) {
if(name[0] == 'q')
break;
files.push_back(name);
}
Iterator iter = files.begin();
ifstream input;
while(iter != files.end()) {
input.open(iter->c_str());
if(!input) {
cerr << "error continue the next file" << endl;
input.clear();
++iter;
continue;
}
r(input);
input.close();
input.clear();
++iter;
}
return 0;
}
| true |
b3198ed9444119d64b1ff1ce3a48367fbd7c824c | C++ | sahilrastogi25/interview-prep | /leetcode-problems/Recursion/josephusProblem.cpp | UTF-8 | 550 | 2.890625 | 3 | [] | no_license | class Solution {
public:
void solve(int index, int k, vector<int>&v, int&ans) {
int n = v.size();
if (n == 1) {
ans = v[0];
return;
}
index = (index + k) % n;
v.erase(v.begin() + index);
solve(index, k, v, ans);
}
int findTheWinner(int n, int k) {
int ans = -1;
vector<int>v;
for (int i = 1; i <= n; i++) {
v.push_back(i);
}
int index = 0;
k--;
solve(index, k, v, ans);
return ans;
}
}; | true |
04f770b6eb7c7c50dc338f5a049170628ce80d17 | C++ | Dima-Git/RayTracer | /Textures.h | UTF-8 | 2,173 | 2.96875 | 3 | [] | no_license | #pragma once
#ifndef _TEXTURES_H_
#define _TEXTURES_H_
#include "Vec3.h"
#include <math.h>
double noise_function(Vec3 v);
double zoomed_noise(Vec3 p, Vec3 origin, Vec3 size, Vec3 patch_size);
double smooth_noise(Vec3 p, Vec3 origin, Vec3 size, Vec3 patch_size);
double turbulence(Vec3 p, Vec3 origin, Vec3 size, Vec3 patch_size, int depth);
Vec3 noise_vector(Vec3 v);
double vornoi(Vec3 p, Vec3 origin, Vec3 size, Vec3 patch_size);
class NoiseTexture {
public:
NoiseTexture(Vec3 origin, Vec3 size, Vec3 patch_size) {
this->origin = origin;
this->size = size;
this->patch_size = patch_size;
this->color = Vec3(1.0, 1.0, 1.0);
}
Vec3 operator() (Vec3 p, Vec3 n) {
return color * zoomed_noise(p, origin, size, patch_size);
}
NoiseTexture operator * (Vec3 col) {
NoiseTexture clone(*this);
clone.color = clone.color * col;
return clone;
}
private:
Vec3 color;
Vec3 origin;
Vec3 size;
Vec3 patch_size;
};
class SmoothNoiseTexture {
public:
SmoothNoiseTexture(Vec3 origin, Vec3 size, Vec3 patch_size) {
this->origin = origin;
this->size = size;
this->patch_size = patch_size;
this->color = Vec3(1.0, 1.0, 1.0);
}
Vec3 operator() (Vec3 p, Vec3 n) {
return color * smooth_noise(p, origin, size, patch_size);
}
SmoothNoiseTexture operator * (Vec3 col) {
SmoothNoiseTexture clone(*this);
clone.color = clone.color * col;
return clone;
}
private:
Vec3 color;
Vec3 origin;
Vec3 size;
Vec3 patch_size;
};
class TurbulentTexture {
public:
TurbulentTexture(Vec3 origin, Vec3 size, Vec3 patch_size, int depth) {
this->origin = origin;
this->size = size;
this->patch_size = patch_size;
this->color = Vec3(1.0, 1.0, 1.0);
this->depth = depth;
}
Vec3 operator() (Vec3 p, Vec3 n) {
return color * turbulence(p, origin, size, patch_size, depth);
}
TurbulentTexture operator * (Vec3 col) {
TurbulentTexture clone(*this);
clone.color = clone.color * col;
return clone;
}
private:
Vec3 color;
Vec3 origin;
Vec3 size;
Vec3 patch_size;
int depth;
};
#endif // _TEXTURES_H_ | true |
03146d22a40889fdac1832cd5ccb13c271b1d2dc | C++ | ddomovic/PlaneLeveling | /PlaneLevelingSDL2/Plane.cpp | UTF-8 | 1,897 | 2.6875 | 3 | [] | no_license | #include "pch.h"
#include "RandomForceApplier.h"
#include "Game.h"
#include "Component.h"
#include "SpriteComponent.h"
#include "Actor.h"
#include "Plane.h"
//use this one if there's no plane sprite file, otherwise use the second one
Plane::Plane(Game *game, int plane_size, RandomForceApplier *rfa) : Actor(game), _plane_angle(0), _plane_size(plane_size),
_angular_velocity(0), _rfa(rfa), _plane_sprite_file("") {
}
Plane::Plane(Game *game, int plane_size, RandomForceApplier *rfa, std::string plane_sprite_file) : Actor(game), _plane_angle(0),
_plane_size(plane_size), _angular_velocity(0), _rfa(rfa), _plane_sprite_file(plane_sprite_file) {
this->sprite = new SpriteComponent(this);
sprite->SetTexture(this->GetGame()->GetTexture(plane_sprite_file));
}
//applied forces -> (force > 0) for tilting to the left, (force < 0) for tilting to the right
void Plane::calculate_plane_angle(float delta_time, float human_force_applied, float random_force_applied) {
float angular_acceleration = (human_force_applied + random_force_applied) * this->_plane_size / 2.0;
this->_plane_angle += this->_angular_velocity*delta_time + 0.5 * angular_acceleration * pow(delta_time, 2);
this->_angular_velocity += angular_acceleration * delta_time;
}
void Plane::set_plane_size(int plane_size) {
this->_plane_size = plane_size;
}
void Plane::set_plane_angle(float plane_angle) {
this->_plane_angle = plane_angle;
}
void Plane::set_plane_sprite_file(std::string plane_sprite_file) {
this->_plane_sprite_file = plane_sprite_file;
}
void Plane::set_random_force_applier(RandomForceApplier * rfa) {
this->_rfa = rfa;
}
int Plane::get_plane_size() {
return this->_plane_size;
}
float Plane::get_plane_angle() {
return this->_plane_angle;
}
std::string Plane::get_plane_sprite_file() {
return this->_plane_sprite_file;
}
RandomForceApplier * Plane::get_random_force_applier() {
return this->_rfa;
}
| true |
6fd346fbd8a833bd6343e785b1939eff3674f981 | C++ | kumarvis/AlgoPractice | /AlgoMadeEasy/Tree/FindMaxBtree.hpp | UTF-8 | 693 | 3.296875 | 3 | [] | no_license | #ifndef FIND_MAX
#define FIND_MAX
#include<iostream>
#include<stack>
#include<limits>
#include "CreateBST.hpp"
using namespace std;
int findMaxBtree(struct Node* root) {
if (root == NULL)
return numeric_limits<int>::min();
int res = root->data;
int l = findMaxBtree(root->left);
int r = findMaxBtree(root->right);
l = (l > r) ? l : r;
res = (res > l) ? res : r;
return res;
}
void run_findMaxBtree() {
vector<int> vec_arr = { 30, 20, 40, 15, 25, 35, 45 };
struct Node* root = NULL;
for (auto& it : vec_arr) {
root = insertNode(root, it);
}
printInorder(root);
cout << endl;
int ans = findMaxBtree(root);
cout << "Max Element Binary Tree = " << ans << endl;
}
#endif
| true |
03c919444a277411d342708522e55b5c58626143 | C++ | kuronekonano/OJ_Problem | /1087 Leyni, LOLI and Cap.cpp | GB18030 | 747 | 3.140625 | 3 | [] | no_license | #include<stdio.h>
int main()
{
int t,n,a[56];
scanf("%d",&t);//ΪnߵñΪm
while(t--)//ʣµñΪn-mñӵ˿ñΪn-m-1ûñӵ˿ñΪn-m
{
int sum=0;//n-mΪñӵmΪûñӵ(n-m)*(n-m-1)+m*(n-m)=sum
scanf("%d",&n);//(n-m)*(n-1)=sum
for(int i=1;i<=n;i++)//˿ñsumһΪʣñn-1
{
scanf("%d",&a[i]);
sum=sum+a[i];
}
if(sum%(n-1)==0)
{
printf("%d\n",sum/(n-1));
}
else
printf("-1\n");
}
return 0;
}
| true |
463b4d5c11389c56284c30776eae696633dd6c70 | C++ | tomm1990/simpleConsoleForm | /MethodsInSoftwareTask3/NumericBox/NumericBox.h | UTF-8 | 558 | 3.09375 | 3 | [] | no_license | #pragma once
#include "../Panel/Panel.h"
#include "../Label/Label.h"
#include "../Button/Button.h"
class NumericBox : public Panel{
public:
NumericBox(int, const int, const int);
virtual ~NumericBox();
string getValue() const { return to_string(number); }
void setValue(const int);
Label* getLabel() const { return val; }
void SetText(const Label&, string newText) const { val->setValue(newText); }
private:
int min, max , number = 20; // default value
Label *val; // Label object for value
Button *bUP, *bDOWN; // plus and minus buttons
}; | true |
e0dd6a295fed8b672438a46f5b2aab84e135cf3e | C++ | PatrykKudyk/Snake-z-obiekt-wki | /PROJEKT_SNAKE/JedzenieWieksze.cpp | UTF-8 | 523 | 2.75 | 3 | [] | no_license | #include "JedzenieWieksze.h"
JedzenieWieksze::JedzenieWieksze(int szerokosc, int wysokosc)
{
polozenie_x = szerokosc / 2;
polozenie_y = wysokosc / 2;
}
JedzenieWieksze::~JedzenieWieksze()
{
}
int JedzenieWieksze::getPolozenieX()
{
return polozenie_x;
}
int JedzenieWieksze::getPolozenieY()
{
return polozenie_y;
}
int JedzenieWieksze::setPolozenieX(int losowa)
{
return polozenie_x = losowa;
}
int JedzenieWieksze::setPolozenieY(int losowa)
{
return polozenie_y = losowa;
}
| true |
f151de908ca3f9f8aa3ed39cc61379bc0fd7276d | C++ | stoma-siarhei/BinaryTree | /src/BinaryTree.h | UTF-8 | 1,131 | 3.484375 | 3 | [] | no_license | #include <iostream>
#ifndef nullptr
#define nullptr NULL
#endif
template <class K, class D>
class BinaryTree
{
protected:
struct Node {
K key;
D data;
Node *left, *right;
Node(K _key, D _data) : key(_key), data(_data), left(nullptr), right(nullptr) {}
~Node()
{
if (left) {
delete left;
}
if (right) {
delete right;
}
left = right = nullptr;
}
void out(std::ostream &stream, unsigned k)
{
for (int i = 0; i < k; i++) {
stream << " ";
}
stream << "[" << key << "]\n";
if (left) {
left->out(stream, k - 5);
}
if(right){
right->out(stream, k + 5);
}
}
} *root;
public:
BinaryTree() : root(nullptr) {}
~BinaryTree();
void add(K key, D data, bool override = true);
D search(K key);
void remove(K key);
void out(std::ostream &stream, unsigned k = 50)
{
root->out(stream, k);
}
}; | true |
2c7e0bd5082244b1022e2463aa991fd0e4219164 | C++ | awesomeabhi34/cpc-prep | /week 5/first 1 in infinite array.cpp | UTF-8 | 332 | 3 | 3 | [] | no_license | int func(int arr[]){
int lo=0;
int hi=1;
while(arr[h]==0){
l=h;
h=2*h;
}
int ans=myf(arr,l,h);
return ans;
}
int myf(int arr[],int l,int r){
while(l<=r){
int mid=l+(r-l)/2;
if(arr[mid]==1 && (mid==0||arr[mid-1]==0)){
return mid;
}
if(arr[mid]==1){
r=mid-1;
}else{
l=mid+1;
}
}
return -1;
}
| true |
c7279d983dc1aab3a8adc3a2bca7a47c023d5de1 | C++ | HungMingWu/librf | /librf/src/when_v2.h | UTF-8 | 16,049 | 2.703125 | 3 | [
"Apache-2.0"
] | permissive | #pragma once
namespace resumef
{
using any_t = std::any;
using std::any_cast;
}
//纠结过when_any的返回值,是选用index + std::any,还是选用std::variant<>。最终选择了std::any。
//std::variant<>存在第一个元素不能默认构造的问题,需要使用std::monostate来占位,导致下标不是从0开始。
//而且,std::variant<>里面存在类型重复的问题,好几个操作都是病态的
//最最重要的,要统一ranged when_any的返回值,还得做一个运行时通过下标设置std::variant<>的东西
//std::any除了内存布局不太理想,其他方面几乎没缺点(在此应用下)
namespace resumef
{
#ifndef DOXYGEN_SKIP_PROPERTY
using when_any_pair = std::pair<intptr_t, any_t>;
using when_any_pair_ptr = std::shared_ptr<when_any_pair>;
namespace detail
{
struct state_when_t : public state_base_t
{
state_when_t(intptr_t counter_);
void on_cancel() noexcept;
bool on_notify_one();
bool on_timeout();
//将自己加入到通知链表里
template<_PromiseT Promise>
scheduler_t* on_await_suspend(coroutine_handle<Promise> handler) noexcept
{
Promise& promise = handler.promise();
auto* parent_state = promise.get_state();
scheduler_t* sch = parent_state->get_scheduler();
this->_scheduler = sch;
this->_coro = handler;
return sch;
}
spinlock _lock;
std::atomic<intptr_t> _counter;
};
template<class value_type>
struct [[nodiscard]] when_future_t
{
using state_type = detail::state_when_t;
using promise_type = promise_t<value_type>;
using future_type = when_future_t<value_type>;
counted_ptr<state_type> _state;
std::shared_ptr<value_type> _values;
when_future_t(intptr_t count_) noexcept
: _state(new state_type(count_))
, _values(std::make_shared<value_type>())
{
}
bool await_ready() noexcept
{
return _state->_counter.load(std::memory_order_relaxed) == 0;
}
template<_PromiseT Promise>
void await_suspend(coroutine_handle<Promise> handler)
{
_state->on_await_suspend(handler);
}
value_type await_resume() noexcept(std::is_nothrow_move_constructible_v<value_type>)
{
return std::move(*_values);
}
};
using ignore_type = std::remove_const_t<decltype(std::ignore)>;
template<class _Ty>
struct convert_void_2_ignore
{
using type = std::remove_reference_t<_Ty>;
using value_type = type;
};
template<>
struct convert_void_2_ignore<void>
{
using type = void;
using value_type = ignore_type;
};
template<class _Ty, bool = _CallableT<_Ty>>
struct awaitor_result_impl2
{
using value_type = typename convert_void_2_ignore<
typename traits::awaitor_traits<_Ty>::value_type
>::value_type;
};
template<class _Ty>
struct awaitor_result_impl2<_Ty, true> : awaitor_result_impl2<decltype(std::declval<_Ty>()()), false> {};
template<_WhenTaskT _Ty>
using awaitor_result_t = typename awaitor_result_impl2<std::remove_reference_t<_Ty>>::value_type;
template<_WhenTaskT _Awaitable>
decltype(auto) when_real_awaitor(_Awaitable&& awaitor)
{
if constexpr (_CallableT<_Awaitable>)
return awaitor();
else
return std::forward<_Awaitable>(awaitor);
}
template<_WhenTaskT _Awaitable, class _Ty>
future_t<> when_all_connector(state_when_t* state, _Awaitable task, _Ty& value)
{
decltype(auto) awaitor = when_real_awaitor(task);
if constexpr (std::is_same_v<_Ty, ignore_type>)
co_await awaitor;
else
value = co_await awaitor;
state->on_notify_one();
};
template<class _Tup, class _AwaitTuple, std::size_t... I>
inline void when_all_one__(scheduler_t& sch, state_when_t* state, _Tup& values,
_AwaitTuple&& awaitables,
std::index_sequence<I...>)
{
(void)std::initializer_list<int> {
(sch + when_all_connector(state, std::get<I>(awaitables), std::get<I>(values)), 0)...
};
}
template<class _Val, _WhenIterT _Iter>
inline void when_all_range__(scheduler_t& sch, state_when_t* state, std::vector<_Val> & values, _Iter begin, _Iter end)
{
using _Awaitable = std::remove_reference_t<decltype(*begin)>;
intptr_t _Idx = 0;
for (; begin != end; ++begin, ++_Idx)
{
sch + when_all_connector<_Awaitable, _Val>(state, *begin, values[_Idx]);
}
}
//-----------------------------------------------------------------------------------------------------------------------------------------
template<_WhenTaskT _Awaitable>
future_t<> when_any_connector(counted_ptr<state_when_t> state, _Awaitable task, when_any_pair_ptr value, intptr_t idx)
{
assert(idx >= 0);
auto awaitor = when_real_awaitor(task);
using value_type = awaitor_result_t<decltype(awaitor)>;
if constexpr (std::is_same_v<value_type, ignore_type>)
{
co_await awaitor;
intptr_t oldValue = -1;
if (reinterpret_cast<std::atomic<intptr_t>&>(value->first).compare_exchange_strong(oldValue, idx))
{
state->on_notify_one();
}
}
else
{
decltype(auto) result = co_await awaitor;
intptr_t oldValue = -1;
if (reinterpret_cast<std::atomic<intptr_t>&>(value->first).compare_exchange_strong(oldValue, idx))
{
value->second = std::move(result);
state->on_notify_one();
}
}
};
template <class _Awaitable, std::size_t... I>
inline void when_any_one__(scheduler_t& sch, state_when_t* state, when_any_pair_ptr value,
_Awaitable&& awaitable,
std::index_sequence<I...>)
{
(void)std::initializer_list<int> {
(sch + when_any_connector(state, std::get<I>(awaitable), value, I), 0)...
};
}
template<_WhenIterT _Iter>
inline void when_any_range__(scheduler_t& sch, state_when_t* state, when_any_pair_ptr value, _Iter begin, _Iter end)
{
using _Awaitable = std::remove_reference_t<decltype(*begin)>;
intptr_t _Idx = 0;
for (; begin != end; ++begin, ++_Idx)
{
sch + when_any_connector<_Awaitable>(state, *begin, value, static_cast<intptr_t>(_Idx));
}
}
}
#endif //DOXYGEN_SKIP_PROPERTY
#ifndef DOXYGEN_SKIP_PROPERTY
inline namespace when_v2
{
#else
/**
* @brief 目前不知道怎么在doxygen里面能搜集到全局函数的文档。故用一个结构体来欺骗doxygen。
* @details 其下的所有成员函数,均是全局函数。
*/
struct when_{
#endif
/**
* @brief 等待所有的可等待对象完成,不定参数版。
* @param sch 当前协程的调度器。
* @param args... 所有的可等待对象。要么是_AwaitableT<>类型,要么是返回_AwaitableT<>类型的函数(对象)。
* @retval [co_await] std::tuple<...>。每个可等待对象的返回值,逐个存入到std::tuple<...>里面。void 返回值,存的是std::ignore。
*/
template <_WhenTaskT... _Awaitable>
auto when_all(scheduler_t& sch, _Awaitable&&... args)
-> detail::when_future_t<std::tuple<detail::awaitor_result_t<_Awaitable>...> >
{
using tuple_type = std::tuple<detail::awaitor_result_t<_Awaitable>...>;
auto await_tuple = std::make_tuple(std::forward<_Awaitable>(args)...);
detail::when_future_t<tuple_type> awaitor{ sizeof...(_Awaitable) };
detail::when_all_one__<tuple_type>(sch, awaitor._state.get(), *awaitor._values,
await_tuple, std::make_index_sequence<std::tuple_size_v<tuple_type>>());
return awaitor;
}
/**
* @brief 等待所有的可等待对象完成,迭代器版。
* @param sch 当前协程的调度器。
* @param begin 可等待对象容器的起始迭代器。迭代器指向的,要么是_AwaitableT<>类型,要么是返回_AwaitableT<>类型的函数(对象)。
* @param end 可等待对象容器的结束迭代器。
* @retval [co_await] std::vector<>。每个可等待对象的返回值,逐个存入到std::vector<>里面。void 返回值,存的是std::ignore。
*/
template<_WhenIterT _Iter>
auto when_all(scheduler_t& sch, _Iter begin, _Iter end)
-> detail::when_future_t<std::vector<detail::awaitor_result_t<decltype(*std::declval<_Iter>())> > >
{
using value_type = detail::awaitor_result_t<decltype(*std::declval<_Iter>())>;
using vector_type = std::vector<value_type>;
detail::when_future_t<vector_type> awaitor{ std::distance(begin, end) };
awaitor._values->resize(end - begin);
when_all_range__(sch, awaitor._state.get(), *awaitor._values, begin, end);
return awaitor;
}
/**
* @brief 等待所有的可等待对象完成,容器版。
* @param sch 当前协程的调度器。
* @param cont 存访可等待对象的容器。容器内存放的,要么是_AwaitableT<>类型,要么是返回_AwaitableT<>类型的函数(对象)。
* @retval [co_await] std::vector<>。每个可等待对象的返回值,逐个存入到std::vector<>里面。void 返回值,存的是std::ignore。
*/
template<_ContainerT _Cont>
decltype(auto) when_all(scheduler_t& sch, _Cont& cont)
{
return when_all(sch, std::begin(cont), std::end(cont));
}
/**
* @brief 等待所有的可等待对象完成,不定参数版。
* @details 当前协程的调度器通过current_scheduler()宏获得,与带调度器参数的版本相比,多一次resumeable function构造,效率可能低一点。
* @param args... 所有的可等待对象。要么是_AwaitableT<>类型,要么是返回_AwaitableT<>类型的函数(对象)。
* @retval [co_await] std::tuple<...>。每个可等待对象的返回值,逐个存入到std::tuple<...>里面。void 返回值,存的是std::ignore。
*/
template<_WhenTaskT... _Awaitable>
auto when_all(_Awaitable&&... args)
-> future_t<std::tuple<detail::awaitor_result_t<_Awaitable>...>>
{
scheduler_t* sch = current_scheduler();
co_return co_await when_all(*sch, std::forward<_Awaitable>(args)...);
}
/**
* @brief 等待所有的可等待对象完成,迭代器版。
* @details 当前协程的调度器通过current_scheduler()宏获得,与带调度器参数的版本相比,多一次resumeable function构造,效率可能低一点。
* @param begin 可等待对象容器的起始迭代器。迭代器指向的,要么是_AwaitableT<>类型,要么是返回_AwaitableT<>类型的函数(对象)。
* @param end 可等待对象容器的结束迭代器。
* @retval [co_await] std::vector<>。每个可等待对象的返回值,逐个存入到std::vector<>里面。void 返回值,存的是std::ignore。
*/
template<_WhenIterT _Iter>
auto when_all(_Iter begin, _Iter end)
-> future_t<std::vector<detail::awaitor_result_t<decltype(*begin)>>>
{
scheduler_t* sch = current_scheduler();
co_return co_await when_all(*sch, begin, end);
}
/**
* @brief 等待所有的可等待对象完成,容器版。
* @details 当前协程的调度器通过current_scheduler()宏获得,与带调度器参数的版本相比,多一次resumeable function构造,效率可能低一点。
* @param cont 存访可等待对象的容器。容器内存放的,要么是_AwaitableT<>类型,要么是返回_AwaitableT<>类型的函数(对象)。
* @retval [co_await] std::vector<>。每个可等待对象的返回值,逐个存入到std::vector<>里面。void 返回值,存的是std::ignore。
*/
template<_ContainerT _Cont>
auto when_all(_Cont&& cont)
-> future_t<std::vector<detail::awaitor_result_t<decltype(*std::begin(cont))>>>
{
return when_all(std::begin(cont), std::end(cont));
}
/**
* @brief 等待任一的可等待对象完成,不定参数版。
* @param sch 当前协程的调度器。
* @param args... 所有的可等待对象。要么是_AwaitableT<>类型,要么是返回_AwaitableT<>类型的函数(对象)。
* @retval [co_await] std::pair<intptr_t, std::any>。第一个值指示哪个对象完成了,第二个值存访的对应的返回数据。
*/
template<_WhenTaskT... _Awaitable>
auto when_any(scheduler_t& sch, _Awaitable&&... args)
-> detail::when_future_t<when_any_pair>
{
#pragma warning(disable : 6326) //warning C6326: Potential comparison of a constant with another constant.
detail::when_future_t<when_any_pair> awaitor{ sizeof...(_Awaitable) > 0 ? 1 : 0 };
#pragma warning(default : 6326)
auto await_tuple = std::make_tuple(std::forward<_Awaitable>(args)...);
awaitor._values->first = -1;
detail::when_any_one__(sch, awaitor._state.get(), awaitor._values, await_tuple,
std::make_index_sequence<sizeof...(_Awaitable)>());
return awaitor;
}
/**
* @brief 等待任一的可等待对象完成,迭代器版。
* @param sch 当前协程的调度器。
* @param begin 可等待对象容器的起始迭代器。迭代器指向的,要么是_AwaitableT<>类型,要么是返回_AwaitableT<>类型的函数(对象)。
* @param end 可等待对象容器的结束迭代器。
* @retval [co_await] std::pair<intptr_t, std::any>。第一个值指示哪个对象完成了,第二个值存访的对应的返回数据。
*/
template<_WhenIterT _Iter>
auto when_any(scheduler_t& sch, _Iter begin, _Iter end)
-> detail::when_future_t<when_any_pair>
{
detail::when_future_t<when_any_pair> awaitor{ begin == end ? 0 : 1 };
awaitor._values->first = -1;
detail::when_any_range__<_Iter>(sch, awaitor._state.get(), awaitor._values, begin, end);
return awaitor;
}
/**
* @brief 等待任一的可等待对象完成,容器版。
* @param sch 当前协程的调度器。
* @param cont 存访可等待对象的容器。容器内存放的,要么是_AwaitableT<>类型,要么是返回_AwaitableT<>类型的函数(对象)。
* @retval [co_await] std::pair<intptr_t, std::any>。第一个值指示哪个对象完成了,第二个值存访的对应的返回数据。
*/
template<_ContainerT _Cont>
auto when_any(scheduler_t& sch, _Cont& cont)
-> detail::when_future_t<when_any_pair>
{
return when_any(sch, std::begin(cont), std::end(cont));
}
/**
* @brief 等待任一的可等待对象完成,不定参数版。
* @details 当前协程的调度器通过current_scheduler()宏获得,与带调度器参数的版本相比,多一次resumeable function构造,效率可能低一点。
* @param args... 所有的可等待对象。要么是_AwaitableT<>类型,要么是返回_AwaitableT<>类型的函数(对象)。
* @retval [co_await] std::pair<intptr_t, std::any>。第一个值指示哪个对象完成了,第二个值存访的对应的返回数据。
*/
template<_WhenTaskT... _Awaitable>
auto when_any(_Awaitable&&... args)
-> future_t<when_any_pair>
{
scheduler_t* sch = current_scheduler();
co_return co_await when_any(*sch, std::forward<_Awaitable>(args)...);
}
/**
* @brief 等待任一的可等待对象完成,迭代器版。
* @details 当前协程的调度器通过current_scheduler()宏获得,与带调度器参数的版本相比,多一次resumeable function构造,效率可能低一点。
* @param begin 可等待对象容器的起始迭代器。迭代器指向的,要么是_AwaitableT<>类型,要么是返回_AwaitableT<>类型的函数(对象)。
* @param end 可等待对象容器的结束迭代器。
* @retval [co_await] std::pair<intptr_t, std::any>。第一个值指示哪个对象完成了,第二个值存访的对应的返回数据。
*/
template<_WhenIterT _Iter>
auto when_any(_Iter begin, _Iter end)
-> future_t<when_any_pair>
{
scheduler_t* sch = current_scheduler();
co_return co_await when_any(*sch, begin, end);
}
/**
* @brief 等待任一的可等待对象完成,容器版。
* @details 当前协程的调度器通过current_scheduler()宏获得,与带调度器参数的版本相比,多一次resumeable function构造,效率可能低一点。
* @param cont 存访可等待对象的容器。容器内存放的,要么是_AwaitableT<>类型,要么是返回_AwaitableT<>类型的函数(对象)。
* @retval [co_await] std::pair<intptr_t, std::any>。第一个值指示哪个对象完成了,第二个值存访的对应的返回数据。
*/
template <_ContainerT _Cont>
auto when_any(_Cont&& cont)
-> future_t<when_any_pair>
{
return when_any(std::begin(cont), std::end(cont));
}
}
}
| true |
9ee51b9e1f5f3438eefbc3c89930775ff7befb5c | C++ | xiangpeng93/MFCameraPlayer | /TopoBuilder.cpp | UTF-8 | 14,173 | 2.546875 | 3 | [] | no_license | #include "TopoBuilder.h"
//
// Initiates topology building from the file URL by first creating a media source, and then
// adding source and sink nodes for every stream found in the file.
//
HRESULT CTopoBuilder::RenderURL(PCWSTR fileUrl, HWND videoHwnd)
{
HRESULT hr = S_OK;
do
{
m_videoHwnd = videoHwnd;
// first create the media source for the file/stream passed in. Fail and fall out if
// the media source creation fails (e.g. if the file format is not recognized)
hr = CreateMediaSource(fileUrl);
BREAK_ON_FAIL(hr);
hr = CreateTopology();
}
while(false);
return hr;
}
template <class T> void SafeRelease(T **ppT)
{
if (*ppT)
{
(*ppT)->Release();
*ppT = NULL;
}
}
HRESULT CreateVideoDeviceSource(IMFMediaSource **ppSource)
{
*ppSource = NULL;
IMFMediaSource *pSource = NULL;
IMFAttributes *pAttributes = NULL;
IMFActivate **ppDevices = NULL;
// Create an attribute store to specify the enumeration parameters.
HRESULT hr = MFCreateAttributes(&pAttributes, 1);
if (FAILED(hr))
{
goto done;
}
// Source type: video capture devices
hr = pAttributes->SetGUID(
MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE,
MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_GUID
);
if (FAILED(hr))
{
goto done;
}
// Enumerate devices.
UINT32 count;
hr = MFEnumDeviceSources(pAttributes, &ppDevices, &count);
if (FAILED(hr))
{
goto done;
}
if (count == 0)
{
hr = E_FAIL;
goto done;
}
// Create the media source object.
hr = ppDevices[0]->ActivateObject(IID_PPV_ARGS(&pSource));
TCHAR *name;
UINT32 len;
hr = ppDevices[0]->GetAllocatedString(MF_DEVSOURCE_ATTRIBUTE_FRIENDLY_NAME, &name, &len);
if (FAILED(hr))
{
goto done;
}
*ppSource = pSource;
(*ppSource)->AddRef();
done:
SafeRelease(&pAttributes);
for (DWORD i = 0; i < count; i++)
{
SafeRelease(&ppDevices[i]);
}
CoTaskMemFree(ppDevices);
SafeRelease(&pSource);
return hr;
}
//
// Create a media source for the specified URL string. The URL can be a path to a stream,
// or it can be a path to a local file.
//
HRESULT CTopoBuilder::CreateMediaSource(PCWSTR sURL)
{
HRESULT hr = S_OK;
MF_OBJECT_TYPE objectType = MF_OBJECT_INVALID;
CComPtr<IMFSourceResolver> pSourceResolver;
CComPtr<IUnknown> pSource;
IMFMediaSource *ppSource;
CreateVideoDeviceSource(&ppSource);
m_pSource = ppSource;
return hr;
}
//
// Since we created the source, we are responsible for shutting it down.
//
HRESULT CTopoBuilder::ShutdownSource(void)
{
HRESULT hr = S_OK;
if(m_pSource != NULL)
{
// shut down the source
hr = m_pSource->Shutdown();
// release the source, since all subsequent calls to it will fail
m_pSource.Release();
}
else
{
hr = E_UNEXPECTED;
}
return hr;
}
//
// Create a playback topology from the media source by extracting presentation
// and stream descriptors from the source, and creating a sink for each of them.
//
HRESULT CTopoBuilder::CreateTopology(void)
{
HRESULT hr = S_OK;
CComPtr<IMFPresentationDescriptor> pPresDescriptor;
DWORD nSourceStreams = 0;
do
{
// release the old topology if there was one
m_pTopology.Release();
// Create a new topology.
hr = MFCreateTopology(&m_pTopology);
BREAK_ON_FAIL(hr);
// Create the presentation descriptor for the media source - a container object that
// holds a list of the streams and allows selection of streams that will be used.
hr = m_pSource->CreatePresentationDescriptor(&pPresDescriptor);
BREAK_ON_FAIL(hr);
// Get the number of streams in the media source
hr = pPresDescriptor->GetStreamDescriptorCount(&nSourceStreams);
BREAK_ON_FAIL(hr);
// For each stream, create source and sink nodes and add them to the topology.
for (DWORD x = 0; x < nSourceStreams; x++)
{
hr = AddBranchToPartialTopology(pPresDescriptor, x);
// if we failed to build a branch for this stream type, then deselect it
// that will cause the stream to be disabled, and the source will not produce
// any data for it
if(FAILED(hr))
{
hr = pPresDescriptor->DeselectStream(x);
BREAK_ON_FAIL(hr);
}
}
}
while(false);
return hr;
}
#include <guiddef.h>
HRESULT CreateMFTransform(
IMFStreamDescriptor *pSD,
IMFTransform **ppDecoder
)
{
HRESULT hr = S_OK;
UINT32 count = 0;
IMFActivate **ppActivate = NULL;
MFT_REGISTER_TYPE_INFO inInfo = { 0 };
IMFMediaTypeHandler *pTH = NULL;
IMFMediaType *pMT = NULL;
GUID subtype;
pSD->GetMediaTypeHandler(&pTH);
pTH->GetCurrentMediaType(&pMT);
pMT->GetGUID(MF_MT_SUBTYPE, &subtype);
printf("%d",pMT);
SafeRelease(&pTH);
inInfo.guidMajorType = MFMediaType_Video;
inInfo.guidSubtype = subtype;
CLSID sda = { 0xb77014bf, 0x4ac, 0x4b0d, 0x90, 0xbd, 0x52, 0xca, 0x8a, 0xdf, 0x73, 0xed };
IMFAttributes* ppAttributes = NULL;
LPWSTR name;
MFTGetInfo(sda, &name, NULL, NULL, NULL, NULL, &ppAttributes);
//UINT32 unFlags = MFT_ENUM_FLAG_SYNCMFT |
// MFT_ENUM_FLAG_LOCALMFT |
// MFT_ENUM_FLAG_SORTANDFILTER;
UINT32 unFlags = MFT_ENUM_FLAG_ALL;
hr = MFTEnumEx(
MFT_CATEGORY_VIDEO_EFFECT,
//MFT_CATEGORY_VIDEO_DECODER,
MFT_ENUM_FLAG_SYNCMFT,
NULL,
NULL,
&ppActivate,
&count
);
if (SUCCEEDED(hr) && count == 0)
{
hr = MF_E_TOPO_CODEC_NOT_FOUND;
}
IMFTransform *pMFTransform = NULL;
if (SUCCEEDED(hr))
{
hr = ppActivate[4]->ActivateObject(IID_PPV_ARGS(&pMFTransform));
}
//hr = pMFTransform->SetInputType(0, pMT, NULL);
///*hr = pMT->SetGUID(MF_MT_MAJOR_TYPE, MFMediaType_Video);
//hr = pMT->SetGUID(MF_MT_SUBTYPE, MFVideoFormat_YUY2);*/
//hr = pMFTransform->SetOutputType(0, pMT, NULL);
//DWORD inMin, inMax, outMin, outMax,
// inCount, outCount;
//
//hr = pMFTransform->GetStreamLimits(&inMin, &inMax, &outMin, &outMax);
//hr = pMFTransform->GetStreamCount(&inCount, &outCount);
//DWORD *inIDs = new DWORD[inCount], *outIDs = new DWORD[outCount];
//hr = pMFTransform->GetStreamIDs(inCount, inIDs, outCount, outIDs);
//
//IMFMediaType *MFMT = NULL;
//int k = 0;
//hr = S_OK;
//while (SUCCEEDED(hr))
//{
// hr = pMFTransform->GetOutputAvailableType(0, k, &MFMT);
// if(SUCCEEDED(hr))
// LogMediaType(MFMT);
// SafeRelease(&MFMT);
// k++;
//}
//k = 0;
//hr = S_OK;
//while (SUCCEEDED(hr))
//{
// hr = pMFTransform->GetInputAvailableType(0, k, &MFMT);
// if(SUCCEEDED(hr))
// LogMediaType(MFMT);
// SafeRelease(&MFMT);
// k++;
//}
//
//_MFT_INPUT_STREAM_INFO inMFInfo, outMFInfo;
//hr = pMFTransform->GetInputStreamInfo(0, &inMFInfo);
//hr = pMFTransform->GetInputStreamInfo(0, &outMFInfo);
//
//hr = pMFTransform->GetInputCurrentType(0, &pMT);
//if(SUCCEEDED(hr))
// LogMediaType(pMT);
//SafeRelease(&pMT);
//hr = pMFTransform->GetOutputCurrentType(0, &pMT);
//if(SUCCEEDED(hr))
// LogMediaType(pMT);
//SafeRelease(&pMT);
for (UINT32 i = 0; i < count; i++)
{
ppActivate[i]->Release();
}
CoTaskMemFree(ppActivate);
if (SUCCEEDED(hr))
*ppDecoder = pMFTransform;
return hr;
}
HRESULT AddMFTNode(
IMFTopology *pTopology,
IMFTransform *pTransform
)
{
HRESULT hr = S_OK;
// Create the node.
return hr;
}
//
// Adds a topology branch for one stream.
//
// pPresDescriptor: The source's presentation descriptor.
// nStream: Index of the stream to render.
//
// For each stream, we must do the following steps:
// 1. Create a source node associated with the stream.
// 2. Create a sink node for the renderer.
// 3. Connect the two nodes.
// The media session will resolve the topology, inserting intermediate decoder and other
// transform MFTs that will process the data in preparation for consumption by the
// renderers.
//
HRESULT CTopoBuilder::AddBranchToPartialTopology(
IMFPresentationDescriptor* pPresDescriptor,
DWORD nStream)
{
HRESULT hr = S_OK;
CComPtr<IMFStreamDescriptor> pStreamDescriptor;
CComPtr<IMFTopologyNode> pSourceNode;
CComPtr<IMFTopologyNode> pOutputNode;
BOOL streamSelected = FALSE;
IMFTopologyNode *pNode = NULL;
IMFTransform *pImg = NULL;
hr = MFCreateTopologyNode(MF_TOPOLOGY_TRANSFORM_NODE, &pNode);
do
{
BREAK_ON_NULL(m_pTopology, E_UNEXPECTED);
// Get the stream descriptor for this stream (information about stream).
hr = pPresDescriptor->GetStreamDescriptorByIndex(nStream, &streamSelected,
&pStreamDescriptor);
BREAK_ON_FAIL(hr);
// Create the topology branch only if the stream is selected - IE if the user wants
// to play it.
if (streamSelected)
{
// Create a source node for this stream.
hr = CreateSourceStreamNode(pPresDescriptor, pStreamDescriptor, pSourceNode);
BREAK_ON_FAIL(hr);
// Create the sink node for the renderer.
hr = CreateOutputNode(pStreamDescriptor, m_videoHwnd, pOutputNode);
BREAK_ON_FAIL(hr);
hr = CreateMFTransform(pStreamDescriptor, &pImg);
if (SUCCEEDED(hr))
{
hr = pNode->SetObject(pImg);
}
// Add the node to the topology.
if (SUCCEEDED(hr))
{
hr = m_pTopology->AddNode(pNode);
}
// Add the source and sink nodes to the topology.
hr = m_pTopology->AddNode(pSourceNode);
BREAK_ON_FAIL(hr);
hr = m_pTopology->AddNode(pOutputNode);
BREAK_ON_FAIL(hr);
// Connect the source node to the sink node. The resolver will find the
// intermediate nodes needed to convert media types.
hr = pSourceNode->ConnectOutput(0, pNode, 0);
hr = pNode->ConnectOutput(0, pOutputNode, 0);
}
}
while(false);
return hr;
}
//
// Create a source node for the specified stream
//
// pPresDescriptor: Presentation descriptor for the media source.
// pStreamDescriptor: Stream descriptor for the stream.
// pNode: Reference to a pointer to the new node - returns the new node.
//
HRESULT CTopoBuilder::CreateSourceStreamNode(
IMFPresentationDescriptor* pPresDescriptor,
IMFStreamDescriptor* pStreamDescriptor,
CComPtr<IMFTopologyNode> &pNode)
{
HRESULT hr = S_OK;
do
{
BREAK_ON_NULL(pPresDescriptor, E_UNEXPECTED);
BREAK_ON_NULL(pStreamDescriptor, E_UNEXPECTED);
pNode = NULL;
// Create the topology node, indicating that it must be a source node.
hr = MFCreateTopologyNode(MF_TOPOLOGY_SOURCESTREAM_NODE, &pNode);
BREAK_ON_FAIL(hr);
// Associate the node with the source by passing in a pointer to the media source
// and indicating that it is the source
hr = pNode->SetUnknown(MF_TOPONODE_SOURCE, m_pSource);
BREAK_ON_FAIL(hr);
// Set the node presentation descriptor attribute of the node by passing
// in a pointer to the presentation descriptor
hr = pNode->SetUnknown(MF_TOPONODE_PRESENTATION_DESCRIPTOR, pPresDescriptor);
BREAK_ON_FAIL(hr);
// Set the node stream descriptor attribute by passing in a pointer to the stream
// descriptor
hr = pNode->SetUnknown(MF_TOPONODE_STREAM_DESCRIPTOR, pStreamDescriptor);
BREAK_ON_FAIL(hr);
}
while(false);
// if failed, clear the output parameter
if(FAILED(hr))
pNode = NULL;
return hr;
}
//
// This function creates an output node for a stream (sink).
//
HRESULT CTopoBuilder::CreateOutputNode(
IMFStreamDescriptor* pStreamDescriptor,
HWND hwndVideo,
CComPtr<IMFTopologyNode> &pNode)
{
HRESULT hr = S_OK;
CComPtr<IMFMediaTypeHandler> pHandler;
CComPtr<IMFActivate> pRendererActivate;
GUID majorType = GUID_NULL;
do
{
BREAK_ON_NULL(pStreamDescriptor, E_UNEXPECTED);
// Get the media type handler for the stream, which will be used to process
// the media types of the stream. The handler stores the media type.
hr = pStreamDescriptor->GetMediaTypeHandler(&pHandler);
BREAK_ON_FAIL(hr);
// Get the major media type (e.g. video or audio)
hr = pHandler->GetMajorType(&majorType);
BREAK_ON_FAIL(hr);
// Create an IMFActivate controller object for the renderer, based on the media type
// The activation objects are used by the session in order to create the renderers
// only when they are needed - i.e. only right before starting playback. The
// activation objects are also used to shut down the renderers.
if (majorType == MFMediaType_Audio)
{
// if the stream major type is audio, create the audio renderer.
hr = MFCreateAudioRendererActivate(&pRendererActivate);
}
else if (majorType == MFMediaType_Video)
{
// if the stream major type is video, create the video renderer, passing in the
// video window handle - that's where the video will be playing.
hr = MFCreateVideoRendererActivate(hwndVideo, &pRendererActivate);
}
else
{
// fail if the stream type is not video or audio. For example, fail
// if we encounter a CC stream.
hr = E_FAIL;
}
BREAK_ON_FAIL(hr);
pNode = NULL;
// Create the node that will represent the renderer
hr = MFCreateTopologyNode(MF_TOPOLOGY_OUTPUT_NODE, &pNode);
BREAK_ON_FAIL(hr);
// Store the IActivate object in the sink node - it will be extracted later by the
// media session during the topology render phase.
hr = pNode->SetObject(pRendererActivate);
BREAK_ON_FAIL(hr);
}
while(false);
// if failed, clear the output parameter
if(FAILED(hr))
pNode = NULL;
return hr;
}
| true |
9d27bb5e17dedcfca30b118b95e7f1cd43bcd7eb | C++ | MrJiu/eBox_Framework | /component/uGUI/U_GUI.h | WINDOWS-1252 | 3,167 | 2.71875 | 3 | [
"MIT",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | #ifndef __U_GUI_H
#define __U_GUI_H
extern "C" {
#include "ugui.h"
}
//class LCD_DRIVER{
//public:
// UG_RESULT _HW_DrawLine( UG_S16 x1, UG_S16 y1, UG_S16 x2, UG_S16 y2, UG_COLOR c );
// void _HW_DrawPixel( UG_S16 x, UG_S16 y, UG_COLOR c );
// UG_RESULT _HW_FillFrame( UG_S16 x1, UG_S16 y1, UG_S16 x2, UG_S16 y2, UG_COLOR c );
//};
//LCD_DRIVER P;
//void temp_DrawPixel( UG_S16 x, UG_S16 y, UG_COLOR c )
//{
// P._HW_DrawPixel(x,y,c);
//}
//UG_RESULT temp_DrawLine( UG_S16 x1, UG_S16 y1, UG_S16 x2, UG_S16 y2, UG_COLOR c )
//{
// P._HW_DrawLine(x1,y1,x2,y2,c);
// return UG_RESULT_OK;
//}
//UG_RESULT temp_FillFrame( UG_S16 x1, UG_S16 y1, UG_S16 x2, UG_S16 y2, UG_COLOR c )
//{
// P._HW_FillFrame(x1,y1,x2,y2,c);
// return UG_RESULT_OK;
//}
class U_GUI{
public:
U_GUI(){};
// U_GUI(LCD_DRIVER * lcd,uint16_t x,uint16_t y){
// P = *lcd;
// Begin(&temp_DrawPixel,(void*)temp_DrawLine,(void*)temp_FillFrame,x,y);
// };
void Begin(void (*p)(UG_S16,UG_S16,UG_COLOR),void* driverLine,void* driverFill,UG_S16 x, UG_S16 y){
UG_Init(&_gui,p,x,y);
UG_DriverRegister( DRIVER_DRAW_LINE, driverLine);
UG_DriverRegister( DRIVER_FILL_FRAME, driverFill);
UG_DriverEnable( DRIVER_DRAW_LINE );
UG_DriverEnable( DRIVER_FILL_FRAME );
};
//
void FillScreen(UG_COLOR c){UG_FillScreen(c);};
void FillFrame( UG_S16 x1, UG_S16 y1, UG_S16 x2, UG_S16 y2, UG_COLOR c ){UG_FillFrame(x1,y1,x2,y2,c);};
void FillRoundFrame( UG_S16 x1, UG_S16 y1, UG_S16 x2, UG_S16 y2, UG_S16 r, UG_COLOR c ){UG_FillRoundFrame(x1,y1,x2,y2,r,c);};
void FillCircle( UG_S16 x0, UG_S16 y0, UG_S16 r, UG_COLOR c ){UG_FillCircle(x0,y0,r,c);};
// ͼ
void DrawMesh( UG_S16 x1, UG_S16 y1, UG_S16 x2, UG_S16 y2, UG_COLOR c ){UG_DrawMesh(x1,y1,x2,y2,c);};
void DrawFrame( UG_S16 x1, UG_S16 y1, UG_S16 x2, UG_S16 y2, UG_COLOR c ){UG_DrawFrame(x1,y1,x2,y2,c);};
void DrawRoundFrame( UG_S16 x1, UG_S16 y1, UG_S16 x2, UG_S16 y2, UG_S16 r, UG_COLOR c ){UG_DrawRoundFrame(x1,y1,x2,y2,r,c);};
void DrawPixel( UG_S16 x0, UG_S16 y0, UG_COLOR c ){UG_DrawPixel(x0,y0,c);};
void DrawCircle( UG_S16 x0, UG_S16 y0, UG_S16 r, UG_COLOR c ){UG_DrawCircle(x0,y0,r,c);};
void DrawArc( UG_S16 x0, UG_S16 y0, UG_S16 r, UG_U8 s, UG_COLOR c ){UG_DrawArc(x0,y0,r,s,c);};
void DrawLine( UG_S16 x1, UG_S16 y1, UG_S16 x2, UG_S16 y2, UG_COLOR c ){UG_DrawLine(x1,y1,x2,y2,c);};
void DrawBMP( UG_S16 xp, UG_S16 yp, UG_BMP* bmp ){UG_DrawBMP(xp,yp,bmp);};
//
void FontSelect(const UG_FONT* font){UG_FontSelect(font);};
void FontSetHSpace( UG_U16 s ){UG_FontSetHSpace(s);};
void FontSetVSpace( UG_U16 s ){UG_FontSetVSpace(s);};
// ı
void PutString( UG_S16 x, UG_S16 y, char* str ){UG_PutString(x,y,str);};
void PutChar( char chr, UG_S16 x, UG_S16 y, UG_COLOR fc, UG_COLOR bc ){UG_PutChar(chr,x,y,fc,bc);};
void ConsolePutString( char* str ){UG_ConsolePutString(str);};
void ConsoleSetArea( UG_S16 xs, UG_S16 ys, UG_S16 xe, UG_S16 ye ){UG_ConsoleSetArea(xs,ys,xe,ye);};
void ConsoleSetForecolor( UG_COLOR c ){UG_ConsoleSetForecolor(c);};
void ConsoleSetBackcolor( UG_COLOR c ){UG_ConsoleSetBackcolor(c);};
private:
UG_GUI _gui;
};
#endif
| true |
7b5688726f021cb314ad1ff8216d5de50f07836a | C++ | GaryCao97/CodeWarehouse | /C++/dev/try/game2.cpp | GB18030 | 3,986 | 2.828125 | 3 | [] | no_license | #include<iostream>
#include<cstdlib>
#include<conio.h>
#include<ctime>
#include<Windows.h>
using namespace std;
#define KEYDOWN(vk_code) ((GetAsyncKeyState(vk_code) & 0x8000) ? 1 : 0)
#define KEYUP(vk_code) ((GetAsyncKeyState(vk_code) & 0x8000) ? 0 : 1)
#define TOP 1
#define LEFT (2 * TOP)
#define MAX_SIZE 40
#define RANDOM(min, max) ((min) + (rand()%((max) - (min) + 1)))
#define ROAD 0
#define WALL 1
#define END 2
typedef struct PlayerCharacter {
int x, y;
char *PC;
PlayerCharacter() {
PC = "";
x = y = 1;
}
}PlayerCharacter;
typedef struct RandomMap {
int **Map;
int mapW, mapH;
long mapID;
RandomMap() {
mapW = 2 * RANDOM(8, MAX_SIZE / 2) + 1;
mapH = 2 * RANDOM(5, MAX_SIZE / 2) + 1;
Map = (int**)malloc(mapH * sizeof(int*));
for (int i = 0; i < mapH; i++) {
Map[i] = (int*)malloc(mapW * sizeof(int));
for (int j = 0; j < mapW; j++)
Map[i][j] = WALL;
}
}
}RandomMap;
void GotoXY(short x, short y);//ƶ
void HideCursor();
void Create(RandomMap rMap, int m, int n);
void InitMap(RandomMap rMap);
void PaintMapPoint(RandomMap rMap, int x, int y);
void GamePlaying(PlayerCharacter &pc);
void PaintPC(PlayerCharacter pc);
void Move(RandomMap rMap, PlayerCharacter &pc, int x, int y);
int main() {
SYSTEMTIME sys[2];
system("MODE con: COLS=120 LINES=50");
srand((unsigned int)time(0));
HideCursor();
PlayerCharacter pc;
GetLocalTime(&sys[0]);
GamePlaying(pc);
GetLocalTime(&sys[1]);
int mm = sys[1].wMinute - sys[0].wMinute, ss = sys[1].wSecond - sys[0].wSecond;
if (ss < 0) {
ss += 60;
mm -= 1;
}
else if (ss > 59) {
ss -= 60;
mm += 1;
}
printf("\nţư߳Թֻ%2d:%2dʱ䣡\n", mm, ss);
return 0;
}
void GotoXY(short x, short y) {
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), { x,y });
}
void HideCursor() {
CONSOLE_CURSOR_INFO cursor_info = { 1, 0 };
SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cursor_info);
}
bool CheckBorder(RandomMap rMap, int x, int y) {
if (x <= 0 || y <= 0 || x >= rMap.mapW - 1 || y >= rMap.mapH - 1)return true;
else return false;
}
bool CheckOutside(RandomMap rMap, int x, int y) {
if (x < 0 || y < 0 || x > rMap.mapW - 1 || y > rMap.mapH - 1)return false;
else return true;
}
void Create(RandomMap rMap, int m, int n) {
int next[4][2] = {
{ 0,1 },
{ 1,0 },
{ 0,-1 },
{ -1,0 }
};
int i, j, t;
for (i = 0; i<4; i++) {
j = rand() % 4;
t = next[i][0], next[i][0] = next[j][0], next[j][0] = t;
t = next[i][1], next[i][1] = next[j][1], next[j][1] = t;
}
rMap.Map[m][n] = ROAD;
for (i = 0; i<4; i++)
if (!CheckBorder(rMap, n + 2 * next[i][1], m + 2 * next[i][0]) && rMap.Map[m + 2 * next[i][0]][n + 2 * next[i][1]] == WALL) {
rMap.Map[m + next[i][0]][n + next[i][1]] = ROAD;
Create(rMap, m + 2 * next[i][0], n + 2 * next[i][1]);
}
}
void InitMap(RandomMap rMap) {
Create(rMap, 1, 1);
rMap.Map[rMap.mapH - 2][rMap.mapW - 2] = END;
for (int i = 0; i < rMap.mapW; i++) {
for (int j = 0; j < rMap.mapH; j++) {
PaintMapPoint(rMap, i, j);
}
}
}
void PaintMapPoint(RandomMap rMap, int x, int y) {
GotoXY(x * 2 + LEFT, y + TOP);
switch (rMap.Map[y][x]) {
case 0:
printf(" ");
break;
case 1:
printf("");
break;
case 2:
printf(" E");
break;
}
}
void PaintPC(PlayerCharacter pc) {
GotoXY(pc.x * 2 + LEFT, pc.y + TOP);
printf("%s", pc.PC);
}
void Move(RandomMap rMap, PlayerCharacter &pc, int x, int y) {
PaintMapPoint(rMap, pc.x, pc.y);
pc.x += x;
pc.y += y;
PaintPC(pc);
}
void GamePlaying(PlayerCharacter &pc) {
RandomMap rm;
InitMap(rm);
PaintPC(pc);
int x, y;
while (pc.x != rm.mapW - 2 || pc.y != rm.mapH - 2) {
x = 0;
y = 0;
if (KEYDOWN(VK_UP)) {
y--;
}
if (KEYDOWN(VK_DOWN)) {
y++;
}
if (KEYDOWN(VK_LEFT)) {
x--;
}
if (KEYDOWN(VK_RIGHT)) {
x++;
}
if (x || y)
if (CheckOutside(rm, pc.x + x, pc.y + y) && rm.Map[pc.y + y][pc.x + x] != WALL) {
Move(rm, pc, x, y);
}
Sleep(100);
}
GotoXY(LEFT, rm.mapH + TOP);
}
| true |
9f95c55e8ef94465cb1ffe55bc3eaaa561bb3f6a | C++ | WeyrSDev/TouchMIDI | /RotaryEncoder.h | UTF-8 | 717 | 3.015625 | 3 | [] | no_license | #ifndef __ROTARYENCODER_H
#define __ROTARYENCODER_H
#include "Encoder.h"
constexpr bool SWAP = true;
constexpr bool NOSWAP = false;
class RotaryEncoder : public Encoder {
public:
RotaryEncoder(uint8_t pin1, uint8_t pin2, bool swapDirection = false, int divider = 1) : Encoder(pin1,pin2), m_swapDirection(swapDirection), m_divider(divider) {}
int getChange() {
int32_t newPosition = read();
int delta = newPosition - m_lastPosition;
m_lastPosition = newPosition;
if (m_swapDirection) { delta = -delta; }
return delta/m_divider;
}
void setDivider(int divider) {
m_divider = divider;
}
private:
bool m_swapDirection;
int32_t m_lastPosition = 0;
int32_t m_divider;
};
#endif
| true |
2e74268cd135bab8f4d6168d35aca343338a9611 | C++ | feixiangxiaoshu/Leetcode | /208字典树.cpp | UTF-8 | 1,082 | 3.453125 | 3 | [] | no_license | //
// Created by Administrator on 2020/7/12.
//
class Trie {
private:
bool isEnd=0;
Trie* next[26]={nullptr};
public:
/** Initialize your data structure here. */
Trie() {
}
/** Inserts a word into the trie. */
void insert(string word) {//以next存字母
Trie* node=this;
for(char c:word){
if(node->next[c-'a']== nullptr){
node->next[c-'a']=new Trie();
}
node=node->next[c-'a'];
}
node->isEnd= 1;//某个单词到头了
}
/** Returns if the word is in the trie. */
bool search(string word) {
Trie* node=this;
for(char c:word){
node=node->next[c-'a'];
if(node== nullptr) return 0;
}
return node->isEnd;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
bool startsWith(string prefix) {
Trie* node=this;
for(char c:prefix){
node=node->next[c-'a'];
if(node== nullptr) return 0;
}
return 1;
}
}; | true |
5e919a78d29549cb8fcfbec5b4ef9413c905bc91 | C++ | derickfelix/pppucpp_answers | /Part01/09.Technicalities-Classes-etc/Chrono.cpp | UTF-8 | 3,629 | 3.546875 | 4 | [] | no_license | // Chrono.cpp
#include "Chrono.h"
namespace Chrono {
// Member function definitions
Date::Date(int yy, Month mm, int dd)
: y(yy), m(mm), d(dd)
{
if (!is_date(yy, mm, dd)) throw Invalid();
}
const Date& default_date()
{
static Date dd {2001, Month::jan, 1}; // start of 21st century
return dd;
}
Date::Date()
: y(default_date().year()),
m(default_date().month()),
d(default_date().day())
{
}
void Date::add_day(int n)
{
int dim = days_in_month(y, m);
d += n;
if (d > dim) {
d -= dim;
}
}
void Date::add_month(int n)
{
}
void Date::add_year(int n)
{
if (m == Month::feb && d == 29 && !leapyear(y+n)) { // beware of leap years!
m = Month::mar;
d = 1;
}
y += n;
}
// Helper functions:
int days_in_month(int y, Month m)
{
int days_in_month = 31; // most months have 31 days;
switch (m) {
case Month::feb: // the length of Febrary varies
days_in_month = (leapyear(y))?29:28;
break;
case Month::apr: case Month::jun: case Month::sep: case Month::nov:
days_in_month = 30; // the rest have 30 days
break;
}
return days_in_month;
}
bool is_date(int y, Month m, int d)
{
// assume that y is valid
if (d <= 0) return false; // d must be positive
if (m < Month::jan || Month::dec < m) return false;
if (days_in_month(y, m) < d) return false;
return true;
}
bool leapyear(int y)
{
return (y % 4) == 0;
}
bool operator==(const Date& a, const Date& b)
{
return a.year() == b.year()
&& a.month() == b.month()
&& a.day() == b.day();
}
bool operator!=(const Date& a, const Date& b)
{
return !(a == b);
}
ostream& operator<<(ostream& os, const Date& d)
{
return os << '(' << d.year()
<< ", " << int(d.month())
<< ", " << d.day() << ')';
}
istream& operator>>(istream& is, Date& dd)
{
int y, m, d;
char ch1, ch2, ch3, ch4;
is >> ch1 >> y >> ch2 >> m >> ch3 >> d >> ch4;
if (!is) return is;
if (ch1 != '(' || ch2 != ',' || ch3 != ',' || ch4 != ')') {// ops: format error
is.clear(ios_base::failbit); // set the fail bit
return is;
}
dd = Date(y, Month(m), d); // update dd
return is;
}
Day day_of_week(const Date& d)
{
// ...
}
Date next_Sunday(const Date& d)
{
// ...
}
Date next_weekday(const Date& d)
{
// ...
}
void next_day(Day& day) {
if (day == Day::saturday) {
day = Day::sunday;
} else {
day = Day(int(day) + 1);
}
}
Day day_of_week_on_date(const Date& d)
{
Day day = Day::thursday; // 1st, January of 1970 is a thursday
int days = 0;
for (int i = 1970; i <= d.year(); i++) {
int max_month = 12;
if (i == d.year()) {
max_month = int(d.month());
}
for (int m = 1; m <= max_month; m++) {
int daysInMonth = days_in_month(i, Month(m));
if (i == d.year() && m == max_month) {
daysInMonth = d.day()-1;
}
for (int j = 1; j <= daysInMonth; j++) {
next_day(day);
}
days += daysInMonth;
}
}
return day;
}
void next_workday(Date& d)
{
Day day_of_week = day_of_week_on_date(d);
switch (day_of_week) {
case Day::friday:
d.add_day(3);
break;
case Day::saturday:
d.add_day(2);
break;
default:
d.add_day(1);
break;
}
}
} // Chrono
| true |
dbf81cf19977be63481fce0e8d1ab97553121597 | C++ | minghaoPA/hair_utils | /src/XForm.h | UTF-8 | 13,699 | 3.15625 | 3 | [
"MIT"
] | permissive | #ifndef XFORM_H
#define XFORM_H
/*
Szymon Rusinkiewicz
Princeton University
XForm.h
Transformations (represented internally as column-major 4x4 matrices)
Supports the following operations:
xform xf, xf2; // Initialized to the identity
XForm<float> xf3; // Just "xform" is XForm<double>
xf=xform::trans(u,v,w); // An xform that translates
xf=xform::rot(ang,ax); // An xform that rotates
xf=xform::scale(s); // An xform that scales
xf=xform::ortho(l,r,b,t,n,f); // Like GLortho
xf=xform::frustum(l,r,b,t,n,f); // Like GLfrustum
glMultMatrixd(xf); // Conversion to column-major array
bool ok = xf.read("file.xf"); // Read xform from file
xf.write("file.xf"); // Write xform to file
xf=xf * xf2; // Matrix-matrix multiplication
xf=inv(xf2); // Inverse
vec v = xf * vec(1,2,3); // Matrix-vector multiplication
xf2=rot_only(xf); // Just the upper 3x3 of xf
xf2=trans_only(xf); // Just the translation of xf
xf2=norm_xf(xf); // Inverse transpose, no translation
invert(xf); // Inverts xform in place
orthogonalize(xf); // Makes matrix orthogonal
xf(1,2)=3.0; // Access by row/column
xf[4]=5.0; // Access in column-major order
xfname("file.ply") // Returns string("file.xf")
*/
#include <iostream>
#include <fstream>
#include <string>
#include "lineqn.h"
template <class T>
class XForm {
private:
T m[16]; // Column-major (OpenGL) order
public:
// Constructors: defaults to identity
XForm(const T m0 =1, const T m1 =0, const T m2 =0, const T m3 =0,
const T m4 =0, const T m5 =1, const T m6 =0, const T m7 =0,
const T m8 =0, const T m9 =0, const T m10=1, const T m11=0,
const T m12=0, const T m13=0, const T m14=0, const T m15=1)
{
m[0] = m0; m[1] = m1; m[2] = m2; m[3] = m3;
m[4] = m4; m[5] = m5; m[6] = m6; m[7] = m7;
m[8] = m8; m[9] = m9; m[10] = m10; m[11] = m11;
m[12] = m12; m[13] = m13; m[14] = m14; m[15] = m15;
}
template <class S> explicit XForm(const S &x)
{ for (int i = 0; i < 16; i++) m[i] = x[i]; }
// Default destructor, copy constructor, assignment operator
// Array reference and conversion to array - no bounds checking
const T operator [] (int i) const
{ return m[i]; }
T &operator [] (int i)
{ return m[i]; }
operator const T * () const
{ return m; }
operator const T * ()
{ return m; }
operator T * ()
{ return m; }
// Access by row/column
const T operator () (int r, int c) const
{ return m[r + c * 4]; }
T &operator () (int r, int c)
{ return m[r + c * 4]; }
// Some partial compatibility with std::vector
typedef T value_type;
typedef T *pointer;
typedef const T *const_pointer;
typedef T *iterator;
typedef const T *const_iterator;
typedef T &reference;
typedef const T &const_reference;
typedef size_t size_type;
//typedef ptrdiff_t difference_type;
size_t size() const
{ return 16; }
T *begin()
{ return &(m[0]); }
const T *begin() const
{ return &(m[0]); }
T *end()
{ return begin() + size(); }
const T *end() const
{ return begin() + size(); }
// Static members - really just fancy constructors
static XForm<T> identity()
{ return XForm<T>(); }
static XForm<T> trans(const T &tx, const T &ty, const T &tz)
{ return XForm<T>(1,0,0,0,0,1,0,0,0,0,1,0,tx,ty,tz,1); }
template <class S> static XForm<T> trans(const S &t)
{ return XForm<T>::trans(t[0], t[1], t[2]); }
static XForm<T> rot(const T &angle,
const T &rx, const T &ry, const T &rz)
{
// Angle in radians, unlike OpenGL
T l = sqrt(rx*rx+ry*ry+rz*rz);
if (l == T(0))
return XForm<T>();
T l1 = T(1)/l, x = rx*l1, y = ry*l1, z = rz*l1;
T s = sin(angle), c = cos(angle);
T xs = x*s, ys = y*s, zs = z*s, c1 = T(1)-c;
T xx = c1*x*x, yy = c1*y*y, zz = c1*z*z;
T xy = c1*x*y, xz = c1*x*z, yz = c1*y*z;
return XForm<T>(xx+c, xy+zs, xz-ys, 0,
xy-zs, yy+c, yz+xs, 0,
xz+ys, yz-xs, zz+c, 0,
0, 0, 0, 1);
}
template <class S> static XForm<T> rot(const T &angle, const S &axis)
{ return XForm<T>::rot(angle, axis[0], axis[1], axis[2]); }
static XForm<T> scale(const T &s)
{ return XForm<T>(s,0,0,0,0,s,0,0,0,0,s,0,0,0,0,1); }
static XForm<T> scale(const T &sx, const T &sy, const T &sz)
{ return XForm<T>(sx,0,0,0,0,sy,0,0,0,0,sz,0,0,0,0,1); }
static XForm<T> scale(const T &s, const T &dx, const T &dy, const T &dz)
{
T dlen2 = dx*dx + dy*dy + dz*dz;
T s1 = (s - T(1)) / dlen2;
return XForm<T>(T(1) + s1*dx*dx, s1*dx*dy, s1*dx*dz, 0,
s1*dx*dy, T(1) + s1*dy*dy, s1*dy*dz, 0,
s1*dx*dz, s1*dy*dz, T(1) + s1*dz*dz, 0,
0, 0, 0, 1);
}
template <class S> static XForm<T> scale(const T &s, const S &dir)
{ return XForm<T>::scale(s, dir[0], dir[1], dir[2]); }
XForm<T> transpose()
{
XForm<T> dir;
for (int i = 0; i < 4; i++)
for (int j = 0; j < 4; j++)
{
dir[i + 4 * j] = m[j + 4 * i];
}
return dir;
}
static XForm<T> ortho(const T &l, const T &r, const T &b, const T &t,
const T &n, const T &f)
{
T rrl = T(1) / (r-l);
T rtb = T(1) / (t-b);
T rfn = T(1) / (f-n);
return XForm<T>(T(2)*rrl, 0, 0, 0,
0, T(2)*rtb, 0, 0,
0, 0, T(-2)*rfn, 0,
-(r+l)*rrl, -(t+b)*rtb, -(f+n)*rfn, 1);
}
static XForm<T> frustum(const T &l, const T &r, const T &b, const T &t,
const T &n, const T &f)
{
T rrl = T(1) / (r-l);
T rtb = T(1) / (t-b);
T rfn = T(1) / (f-n);
return XForm<T>(T(2)*n*rrl, 0, 0, 0,
0, T(2)*n*rtb, 0, 0,
(r+l)*rrl, (t+b)*rtb, -(f+n)*rfn, -1,
0, 0, T(-2)*f*n*rfn, 0);
}
// Returns y*x^T, thinking of y and x as column 3-vectors
template <class S> static XForm<T> outer(const S &y, const S &x)
{
XForm<T> result;
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
result[4*i+j] = x[i]*y[j];
return result;
}
// Read an XForm from a file.
bool read(const std::string &filename)
{
//cout << filename << endl;
std::ifstream f(filename.c_str());
//std::ifstream f(filename);
//ifstream f("F:\\HAIR\\HairSAHM\\Yi\\Yi\\trans\\extrinsic_00008.txt");
XForm<T> M;
f >> M;
if (f.good()) {
*this = M;
f.close();
return true;
}
return false;
}
// Write an XForm to a file
bool write(const std::string &filename) const
{
std::ofstream f(filename.c_str());
f << *this;
f.close();
return f.good();
}
};
typedef XForm<double> xform;
typedef XForm<float> fxform;
// Binary operations
template <class T>
static inline XForm<T> operator + (const XForm<T> &xf1, const XForm<T> &xf2)
{
return XForm<T>(
xf1[ 0] + xf2[ 0], xf1[ 1] + xf2[ 1],
xf1[ 2] + xf2[ 2], xf1[ 3] + xf2[ 3],
xf1[ 4] + xf2[ 4], xf1[ 5] + xf2[ 5],
xf1[ 6] + xf2[ 6], xf1[ 7] + xf2[ 7],
xf1[ 8] + xf2[ 8], xf1[ 9] + xf2[ 9],
xf1[10] + xf2[10], xf1[11] + xf2[11],
xf1[12] + xf2[12], xf1[13] + xf2[13],
xf1[14] + xf2[14], xf1[15] + xf2[15]
);
}
template <class T>
static inline XForm<T> operator - (const XForm<T> &xf1, const XForm<T> &xf2)
{
return XForm<T>(
xf1[ 0] - xf2[ 0], xf1[ 1] - xf2[ 1],
xf1[ 2] - xf2[ 2], xf1[ 3] - xf2[ 3],
xf1[ 4] - xf2[ 4], xf1[ 5] - xf2[ 5],
xf1[ 6] - xf2[ 6], xf1[ 7] - xf2[ 7],
xf1[ 8] - xf2[ 8], xf1[ 9] - xf2[ 9],
xf1[10] - xf2[10], xf1[11] - xf2[11],
xf1[12] - xf2[12], xf1[13] - xf2[13],
xf1[14] - xf2[14], xf1[15] - xf2[15]
);
}
template <class T>
static inline XForm<T> operator * (const XForm<T> &xf1, const XForm<T> &xf2)
{
return XForm<T>(
xf1[ 0]*xf2[ 0]+xf1[ 4]*xf2[ 1]+xf1[ 8]*xf2[ 2]+xf1[12]*xf2[ 3],
xf1[ 1]*xf2[ 0]+xf1[ 5]*xf2[ 1]+xf1[ 9]*xf2[ 2]+xf1[13]*xf2[ 3],
xf1[ 2]*xf2[ 0]+xf1[ 6]*xf2[ 1]+xf1[10]*xf2[ 2]+xf1[14]*xf2[ 3],
xf1[ 3]*xf2[ 0]+xf1[ 7]*xf2[ 1]+xf1[11]*xf2[ 2]+xf1[15]*xf2[ 3],
xf1[ 0]*xf2[ 4]+xf1[ 4]*xf2[ 5]+xf1[ 8]*xf2[ 6]+xf1[12]*xf2[ 7],
xf1[ 1]*xf2[ 4]+xf1[ 5]*xf2[ 5]+xf1[ 9]*xf2[ 6]+xf1[13]*xf2[ 7],
xf1[ 2]*xf2[ 4]+xf1[ 6]*xf2[ 5]+xf1[10]*xf2[ 6]+xf1[14]*xf2[ 7],
xf1[ 3]*xf2[ 4]+xf1[ 7]*xf2[ 5]+xf1[11]*xf2[ 6]+xf1[15]*xf2[ 7],
xf1[ 0]*xf2[ 8]+xf1[ 4]*xf2[ 9]+xf1[ 8]*xf2[10]+xf1[12]*xf2[11],
xf1[ 1]*xf2[ 8]+xf1[ 5]*xf2[ 9]+xf1[ 9]*xf2[10]+xf1[13]*xf2[11],
xf1[ 2]*xf2[ 8]+xf1[ 6]*xf2[ 9]+xf1[10]*xf2[10]+xf1[14]*xf2[11],
xf1[ 3]*xf2[ 8]+xf1[ 7]*xf2[ 9]+xf1[11]*xf2[10]+xf1[15]*xf2[11],
xf1[ 0]*xf2[12]+xf1[ 4]*xf2[13]+xf1[ 8]*xf2[14]+xf1[12]*xf2[15],
xf1[ 1]*xf2[12]+xf1[ 5]*xf2[13]+xf1[ 9]*xf2[14]+xf1[13]*xf2[15],
xf1[ 2]*xf2[12]+xf1[ 6]*xf2[13]+xf1[10]*xf2[14]+xf1[14]*xf2[15],
xf1[ 3]*xf2[12]+xf1[ 7]*xf2[13]+xf1[11]*xf2[14]+xf1[15]*xf2[15]
);
}
// Component-wise equality and inequality (#include the usual caveats
// about comparing floats for equality...)
template <class T>
static inline bool operator == (const XForm<T> &xf1, const XForm<T> &xf2)
{
for (int i = 0; i < 16; i++)
if (xf1[i] != xf2[i])
return false;
return true;
}
template <class T>
static inline bool operator != (const XForm<T> &xf1, const XForm<T> &xf2)
{
for (int i = 0; i < 16; i++)
if (xf1[i] != xf2[i])
return true;
return false;
}
template<class T>
static inline XForm<T> transpose(const XForm<T> &xf)
{
return XForm<T>(xf[0], xf[4], xf[8 ], xf[12],
xf[1], xf[5], xf[9 ], xf[13],
xf[2], xf[6], xf[10], xf[14],
xf[3], xf[7], xf[11], xf[15]);
}
// Inverse
template <class T>
static inline XForm<T> inv(const XForm<T> &xf)
{
T A[4][4] = { { xf[0], xf[4], xf[8], xf[12] },
{ xf[1], xf[5], xf[9], xf[13] },
{ xf[2], xf[6], xf[10], xf[14] },
{ xf[3], xf[7], xf[11], xf[15] } };
int ind[4];
bool ok = ludcmp<T,4>(A, ind);
if (!ok)
return XForm<T>();
T B[4][4] = { { 1, 0, 0, 0 },
{ 0, 1, 0, 0 },
{ 0, 0, 1, 0 },
{ 0, 0, 0, 1 } };
for (int i = 0; i < 4; i++)
lubksb<T,4>(A, ind, B[i]);
return XForm<T>(B[0][0], B[0][1], B[0][2], B[0][3],
B[1][0], B[1][1], B[1][2], B[1][3],
B[2][0], B[2][1], B[2][2], B[2][3],
B[3][0], B[3][1], B[3][2], B[3][3]);
}
template <class T>
static inline void invert(XForm<T> &xf)
{
xf = inv(xf);
}
template <class T>
static inline XForm<T> rot_only(const XForm<T> &xf)
{
return XForm<T>(xf[0], xf[1], xf[2], 0,
xf[4], xf[5], xf[6], 0,
xf[8], xf[9], xf[10], 0,
0, 0, 0, 1);
}
template <class T>
static inline XForm<T> trans_only(const XForm<T> &xf)
{
return XForm<T>(1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
xf[12], xf[13], xf[14], 1);
}
template <class T>
static inline XForm<T> norm_xf(const XForm<T> &xf)
{
XForm<T> M = inv(xf);
M[12] = M[13] = M[14] = T(0);
std::swap(M[1], M[4]);
std::swap(M[2], M[8]);
std::swap(M[6], M[9]);
return M;
}
template <class T>
static inline void orthogonalize(XForm<T> &xf)
{
if (xf[15] == T(0)) // Yuck. Doesn't make sense...
xf[15] = T(1);
T q0 = xf[0] + xf[5] + xf[10] + xf[15];
T q1 = xf[6] - xf[9];
T q2 = xf[8] - xf[2];
T q3 = xf[1] - xf[4];
T l = sqrt(q0*q0+q1*q1+q2*q2+q3*q3);
XForm<T> M = XForm<T>::rot(T(2)*acos(q0/l), q1, q2, q3);
M[12] = xf[12]/xf[15];
M[13] = xf[13]/xf[15];
M[14] = xf[14]/xf[15];
xf = M;
}
// Matrix-vector multiplication
template <class S, class T>
static inline const S operator * (const XForm<T> &xf, const S &v)
{
T h = xf[3]*v[0] + xf[7]*v[1] + xf[11]*v[2] + xf[15];
h = T(1) / h;
return S(T(h*(xf[0]*v[0] + xf[4]*v[1] + xf[8]*v[2] + xf[12])),
T(h*(xf[1]*v[0] + xf[5]*v[1] + xf[9]*v[2] + xf[13])),
T(h*(xf[2]*v[0] + xf[6]*v[1] + xf[10]*v[2] + xf[14])));
}
// iostream operators
template <class T>
static inline std::ostream &operator << (std::ostream &os, const XForm<T> &m)
{
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
os << m[i+4*j];
if (j == 3)
os << std::endl;
else
os << " ";
}
}
return os;
}
template <class T>
static inline std::istream &operator >> (std::istream &is, XForm<T> &m)
{
for (int i = 0; i < 3; i++)
for (int j = 0; j < 4; j++) {
float mm;
is >> mm;
m[i + 4 * j]=mm;
//cout << mm << " ";
}
if (!is.good()) {
m = xform::identity();
return is;
}
// 4th row is allowed to fail
for (int j = 0; j < 4; j++)
is >> m[3+4*j];
if (!is.good()) {
m[3] = m[7] = m[11] = T(0);
m[15] = T(1);
is.clear();
return is;
}
return is;
}
#endif
| true |
9e970ad25f36eb2464b59bff6281802754a58fef | C++ | fiorentinogiuseppe/curso_cpp | /secao_8/VariavelEstatica.cpp | UTF-8 | 284 | 2.6875 | 3 | [] | no_license | //
// Created by giuseppe on 16/04/2020.
//
#include<iostream>
int ContadorChamadas(){
static int NumChamadasDaFuncao = 0;
return ++NumChamadasDaFuncao;
}
int main(){
for(int i = 0; i<5; i++){
std::cout << ContadorChamadas() << std::endl;
}
return 0;
} | true |
885f0cc6ab391a8a2d346685137e4a81b6e1b8ba | C++ | CindyKXLiu/LifeGUI | /cell.h | UTF-8 | 1,502 | 3.234375 | 3 | [] | no_license | #ifndef CELL_H
#define CELL_H
#include <cstddef> // defines size_t i.e. an unsigned int
#include <iostream>
#include <string>
#include "subject.h"
#include "observer.h"
#include "info.h"
class Cell : public Subject, public Observer {
const int LOWER_BOUND = 2;
const int UPPER_BOUND = 3;
const int REVIVAL = 3;
const int DEFAULT_ALIVE = 0;
const size_t r, c; // coordinates of cell
int numAliveNeighbours; // current number of neighbours who are alive
State state; // dead/alive
public:
Cell(size_t r, size_t c); // Cell is at row r and column c of the grid
void setLiving(); // Marks cell as alive. Called by Grid::turnOn.
void reset(); // Resets neighbour count to 0.
// Return a string consisting of "(r,c)" where r and c are the data fields.
virtual std::string getName() override;
// Grid calls this to start the process whereby a cell notifies its neighbours if it
// is alive.
void broadcastIfAlive();
// My neighbours will call this to let me know if they're alive. Also needs
// to be called when state is set to be alive so display(s) are notified.
void notify( Subject & whoNotified ) override;
// Reassess my living-or-dead status, based on information from neighbours.
void recalculate();
// Observer calls this to get information about cell.
virtual Info getInfo() const override;
};
#endif
| true |
922f2ec08b38e6222dbcc4c02a406fe22c05ccd5 | C++ | Lee-DongWon/Baekjoon_Problems | /11170.cpp | UTF-8 | 433 | 3.125 | 3 | [] | no_license | #include <stdio.h>
int count(int n) {
int cnt = 0;
if (n == 0) {
return 1;
}
else {
while (n > 0) {
if (n % 10 == 0) {
cnt++;
}
n /= 10;
}
return cnt;
}
}
int main() {
int t;
int sum = 0;
scanf("%d", &t);
while (t--) {
int a, b;
sum = 0;
scanf("%d %d", &a, &b);
for (int i = a; i <= b; i++) {
sum += count(i);
}
printf("%d\n", sum);
}
return 0;
} | true |
377c3ae6ec9d73d0ac8eb48fe664a579a1507932 | C++ | joraojr/trabalhoed2 | /001/main.cpp | UTF-8 | 1,625 | 2.625 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <string>
#include "SplayTree.h"
#include "Trie_RW.h"
using namespace std;
int main()
{
Trie_RW Trie;
string line;
ifstream myfile ("/home/jorao/Documentos/trabalhoed2/001/Dicionarios/novos/dic2"); // ifstream = padrão ios:in
if (myfile.is_open())
{
while (! myfile.eof() ) //enquanto end of file for false continua
{
getline (myfile,line); // como foi aberto em modo texto(padrão)
//e não binário(ios::bin) pega cada linha
//string x ="abcèé";
unsigned int x =line[0];
//cout << line <<" "<<x<<" "<< line.size()<<endl;
//string z =line;
if(line.size() > 0)
{
//int x =line[1];
//cout <<x;
Trie.inserePalavra(line);
}
//cout << Arvore.busca(line)<<endl;
}
myfile.close();
}
cout<<"TAqui"<<Trie.buscaPalavra("abcde");
/********************************************************************
cout << Arvore.raiz->getDir()->getDir()->getPai()->getPalavra();
Arvore.imprimeArvore();
return 0;
/*
Trie_RW Trie;
char c[] ={'a','b'};
char x[] ={'ç','x','a'};
unsigned char a[] = {'Ç','à','ç'};
unsigned char h = a[0];
string m = "aaaàrè";
int z= a[0];
int y=a[1];
int b=a[2];
//if(h == 'è')
cout<<z<<endl;
cout<<y<<endl;
cout<<b<<endl;
cout<<m.size()<<endl;
// cout<<
Trie.inserePalavra(x);
cout<<Trie.buscaPalavra(x);
*/
}
| true |
ed7657b37a07a2d4d4598d7c8bce3785a9851a70 | C++ | MattMorris1996/GameOfLife | /main.cpp | UTF-8 | 1,314 | 3.125 | 3 | [] | no_license | #include <iostream>
#include <stdlib.h>
#include <vector>
#include "life.h"
#include "display_sdl.h"
using namespace std;
int main(void)
{
const int COLUMNS = 500;
const int ROWS = 500;
const int WINDOW_WIDTH = 1000;
const int WINDOW_HEIGHT = 1000;
Display display(WINDOW_WIDTH, WINDOW_HEIGHT);
Life board(COLUMNS, ROWS, RANDOM);
display.load_menu();
//tell the display where the pixels are
display.load_pixels(board.get_vector());
//randomly generate board
if (display.generateGrid(COLUMNS, ROWS))
{
cout << "Error" << endl;
}
SDL_Event event;
int start = 0;
while (1)
{
SDL_PumpEvents();
if (SDL_PollEvent(&event) && event.type == SDL_QUIT)
{
std::cout << "Quiting.." << std::endl;
return EXIT_SUCCESS;
}
if (SDL_GetMouseState(NULL, NULL) & SDL_BUTTON(SDL_BUTTON_LEFT))
{
std::cout << "Mouse Button 1 (left) is pressed." << std::endl;
display.destroy_menu();
start = 1;
}
if (start)
{
board.update_neighbours();
board.cells_update();
display.clear_screen();
display.generateGrid(COLUMNS, ROWS);
display.Update();
}
}
}
| true |
82b0c12a1120b0169bca40e327ab59feb46e60d7 | C++ | huiaidan/WebServer | /base/Socket.h | UTF-8 | 489 | 2.671875 | 3 | [] | no_license |
#include<sys/socket.h>
#include<arpa/inet.h>
#include"Data.h"
using namespace std;
class Socket
{
public:
Socket(int lifd=-1):listenfd(lifd)
{}
~Socket()
{}
void socket_init();//初始化socket结构体serv_addr
void listenfd_create();//创建listenfd;一个eventloop只有一个
void socket_bind();//绑定listenfd到socket结构体
void socket_listen();//设置listenfd的最大监听数量
void do_listen(int& lfd);
private:
int listenfd;
struct sockaddr_in serv_addr;
};
| true |
258b28d8b157042c885fb7ed137c27fc0ae63090 | C++ | ThouCheese/floating_n | /f/floor.cpp | UTF-8 | 544 | 2.609375 | 3 | [] | no_license | template<size_t M, size_t E>
F<M, E> constexpr F<M, E>::floor() const
{
// will do nothing if the last digit of the mantissa has value less than
// one.
if (this->abs() < ONE)
return ZERO;
BitArray<s_bits> exp = get_exp() - s_exponent_bias;
// make sure that the exponent is not greater than 2^(2^64)
assert(exp.leading_zeros() - s_bits < 64);
size_t exp_word = exp.d_data[0];
// now shift of the rightmost `exp` bits.
man >>= exp_word;
man <<= exp_word;
return F<M, E>(*this).set_man(man);
} | true |
2019638e7fc99b1c221b0509bcf43be294f89a45 | C++ | ailyanlu/ACM_LeetCode | /ACM_Programfan/[LeetCode]Convert Sorted List to Binary Search Tree/[LeetCode]Convert Sorted List to Binary Search Tree.cpp | UTF-8 | 1,715 | 3.484375 | 3 | [] | no_license | // [LeetCode]Convert Sorted List to Binary Search Tree.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
// [LeetCode]Invert Binary Tree.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;
/*
Input:{3,9,20,#,#,15,7}
Output:{3,20,9,15,7}
*/
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
TreeNode* sortedListToBST(ListNode* head,int len) {
if (len <= 0)
return NULL;
int mid = 1 + (len - 1) / 2, k = mid;
ListNode* pnext = head;
while (--k)
pnext = pnext->next;
TreeNode* root = new TreeNode(pnext->val);
root->left = sortedListToBST(head, mid - 1);
root->right = sortedListToBST(pnext->next, len - mid);
return root;
}
TreeNode* sortedListToBST(ListNode* head) {
if (head == NULL)
return NULL;
int len = 0;
ListNode* pnext = head;
while (pnext){
len++;
pnext = pnext->next;
}
pnext = head;
return sortedListToBST(pnext, len);
}
};
int main(void){
Solution answer;
int a[] = { 1, 2, 3, 4, 5, 6, 7, 8 };
ListNode* pHead = new ListNode(1), *pNext=pHead;
for (size_t i = 1; i < 8; ++i){
ListNode* pNode = new ListNode(a[i]);
pNext->next = pNode;
pNext = pNext->next;
}
TreeNode *root = answer.sortedListToBST(pHead);
while (root != NULL){
cout << root->val << " ";
if (root->left)
cout << root->left->val << " ";
if (root->right)
cout << root->right->val << " ";
cout<< endl;
root = root->right;
}
system("Pause");
return 0;
}
| true |
5e3e73a3e62c1bb7b30bc4e6e878ec140c2a2ce8 | C++ | sand0636/RFID | /RFID-Network-Build-master/tests/Power consumption tests/RF24MeshPowerUse/RF24MeshPowerUse.ino | UTF-8 | 1,881 | 2.75 | 3 | [
"MIT"
] | permissive |
/*
* Code to test the actual data rate and number of packets dropped using the RF24Mesh. This is largely taken from the transfer example for the RF24 library
* Ben Duggan
* 9/16/18
*/
#include "RF24.h"
#include "RF24Network.h"
#include "RF24Mesh.h"
#include "printf.h"
#include <SPI.h>
/*** Variables to change ***/
#define cs 8 //Pin connected to the ce (chip enable)
#define csn 9 //Pin connected to the cs (chip select)
uint8_t channel = 10; //Channel the radios are using 0-124
#define thisID 0 //This nodes ID 0 for master(giving data rate) 1-127 for other
uint8_t powerLevel = RF24_PA_MIN; //Power level of this node (RF24_PA_MIN, RF24_PA_LOW, RF24_PA_HIGH, or RF24_PA_MAX)
rf24_datarate_e dataRate = RF24_250KBPS; //Data rate of this node (RF24_250KBPS, RF24_1MBPS or RF24_2MBPS)
#define ledPin LED_BUILTIN //What pin is the led connected to
//#define Serial SerialUSB // Uncomment this line if you are testing with a SAMD based board
/*** ***/
RF24 radio(cs, csn);
RF24Network network(radio);
RF24Mesh mesh(radio, network);
void setup() {
Serial.begin(9600);
printf_begin();
Serial.println("Begin: This may take a minute if you just changed the settings...");
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, HIGH);
delay(500);
digitalWrite(ledPin, LOW);
mesh.setNodeID(thisID);
mesh.begin(channel, dataRate); //Start mesh using this channel and data rate
radio.setPALevel(powerLevel); //Set the PA level of the radio
radio.printDetails(); //Prints all the details of the radio. Usefull to double check that you set things correctly
for(int i=0; i<5; i++) {
digitalWrite(ledPin, HIGH);
delay(100);
digitalWrite(ledPin, LOW);
}
Serial.println("Starting main loop...");
delay(3000);
radio.powerDown();
delay(5000);
//radio.powerUp();
}
void loop() {
mesh.update();
if(thisID == 0) {
mesh.DHCP();
}
}
| true |
8d70005c6a1f8edd93c24c57c5a89a878435d761 | C++ | maqalaqil/swag-c- | /Examples/lua/embed3/embed3.cpp | UTF-8 | 5,127 | 2.703125 | 3 | [] | no_license | /* embed3.cpp A C++ embedded interpreter
This will register a C++ class with Lua, and then call a Lua function
passing C++ objects to this function.
*/
/* Deal with Microsoft's attempt at deprecating C standard runtime functions */
#if !defined(alaqil_NO_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER) && !defined(_CRT_SECURE_NO_DEPRECATE)
# define _CRT_SECURE_NO_DEPRECATE
#endif
/* Deal with Microsoft's attempt at deprecating methods in the standard C++ library */
#if !defined(alaqil_NO_SCL_SECURE_NO_DEPRECATE) && defined(_MSC_VER) && !defined(_SCL_SECURE_NO_DEPRECATE)
# define _SCL_SECURE_NO_DEPRECATE
#endif
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdarg.h>
extern "C" {
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
}
#if LUA_VERSION_NUM > 501
#define lua_open luaL_newstate
#endif
/* The alaqil external runtime is generated by using.
alaqil -lua -externalruntime alaqilluarun.h
It contains useful function used by alaqil in its wrapper
alaqil_TypeQuery() alaqil_NewPointerObj()
*/
#include "alaqilluarun.h" // the alaqil external runtime
/* the alaqil wrapped library */
extern "C" int luaopen_example(lua_State*L);
// the code itself
#include "example.h"
// this code pushes a C++ pointer as well as the alaqil type onto the Lua stack
bool push_pointer(lua_State*L, void* ptr, const char* type_name, int owned = 0) {
// task 1: get the object 'type' which is registered with alaqil
// you need to call alaqil_TypeQuery() with the class name
// (normally, just look in the wrapper file to get this)
alaqil_type_info * pTypeInfo = alaqil_TypeQuery(L, type_name);
if (pTypeInfo == 0)
return false; // error
// task 2: push the pointer to the Lua stack
// this requires a pointer & the type
// the last param specifies if Lua is responsible for deleting the object
alaqil_NewPointerObj(L, ptr, pTypeInfo, owned);
return true;
}
/* This is an example of how to call the Lua function
void onEvent(Event e)
its very tedious, but gives you an idea of the issues involed.
*/
int call_onEvent(lua_State *L, Event e) {
int top;
/* ok, here we go:
push a, push b, call 'add' check & return res
*/
top = lua_gettop(L); /* for later */
lua_getglobal(L, "onEvent"); /* function to be called */
if (!lua_isfunction(L, -1)) {
printf("[C++] error: cannot find function 'OnEvent'\n");
lua_settop(L, top); // reset
return 0;
}
// push the event object
push_pointer(L, &e, "Event *", 0);
if (lua_pcall(L, 1, 0, 0) != 0) /* call function with 1 arguments and no result */
{
printf("[C++] error running function `OnEvent': %s\n", lua_tostring(L, -1));
lua_settop(L, top); // reset
return 0;
}
lua_settop(L, top); /* reset stack */
return 1; // ok
}
int main(int argc, char* argv[]) {
printf("[C++] Welcome to the simple embedded Lua example v3\n");
printf("[C++] We are in C++\n");
printf("[C++] opening a Lua state & loading the libraries\n");
lua_State *L = lua_open();
luaopen_base(L);
luaopen_string(L);
luaopen_math(L);
printf("[C++] now loading the alaqil wrappered library\n");
luaopen_example(L);
printf("[C++] all looks ok\n");
printf("\n");
printf("[C++] let's create an Engine and pass a pointer to Lua\n");
Engine engine;
/* this code will pass a pointer into lua, but C++ still owns the object
this is a little tedious, to do, but let's do it
we need to pass the pointer (obviously), the type name
and a flag which states if Lua should delete the pointer once its finished with it
The type name is a class name string which is registered with alaqil
(normally, just look in the wrapper file to get this)
in this case we don't want Lua to delete the pointer so the ownership flag is 0
*/
push_pointer(L,&engine,"Engine *",0);
lua_setglobal(L, "pEngine"); // set as global variable
if (argc != 2 || argv[1] == NULL || strlen(argv[1]) == 0) {
printf("[C++] ERROR: no lua file given on command line\n");
exit(3);
}
printf("[C++] now let's load the file '%s'\n", argv[1]);
printf("[C++] any lua code in this file will be executed\n");
if (luaL_loadfile(L, argv[1]) || lua_pcall(L, 0, 0, 0)) {
printf("[C++] ERROR: cannot run lua file: %s",lua_tostring(L, -1));
exit(3);
}
printf("[C++] We are now back in C++, all looks ok\n");
printf("\n");
printf("[C++] Let's call the Lua function onEvent(e)\n");
printf("[C++] We will give it different events, as we wish\n");
printf("[C++] Starting with STARTUP\n");
Event ev;
ev.mType = Event::STARTUP;
call_onEvent(L, ev);
printf("[C++] ok\n");
printf("[C++] now we will try MOUSEPRESS,KEYPRESS,MOUSEPRESS\n");
ev.mType = Event::MOUSEPRESS;
call_onEvent(L, ev);
ev.mType = Event::KEYPRESS;
call_onEvent(L, ev);
ev.mType = Event::MOUSEPRESS;
call_onEvent(L, ev);
printf("[C++] ok\n");
printf("[C++] Finally we will SHUTDOWN\n");
ev.mType = Event::SHUTDOWN;
call_onEvent(L, ev);
printf("[C++] ok\n");
printf("\n");
printf("[C++] all finished, closing the lua state\n");
lua_close(L);
return 0;
}
| true |
489314ebdc67a5f20a9960c633293c8f317a5b0f | C++ | fsilvestrim/cpp-tweenlib | /src/Animation.h | UTF-8 | 986 | 2.828125 | 3 | [
"MIT"
] | permissive | /*
* Animation.h
* AnimationProject
*
* Created by Filipe Silvestrim on 4/29/09.
* Copyright 2009 __MyCompanyName__. All rights reserved.
*
*/
#include "Object.h"
class Animation
{
public:
static const int TRANSLATE = 0;
static const int LOOKAT = 1;
static const int ROTATE = 2;
static const int SCALE = 3;
static const int UP = 4;
Animation(Object *target, int animationType, map<int, float> endValues, int startFrame, int endFrame, int easeType = 0);
void run(int currentFrame);
int getStartFrame();
int getEndFrame();
int getId();
void setAuxValues(map<int, float> auxValues);
private:
static int instCount;
Object *target;
int id;
int startFrame;
int endFrame;
int totalFrames;
int easeType;
int animationType;
map<int, float> auxValues;
map<int, float> startValues;
map<int, float> endValues;
void translate(float u);
void lookat(float u);
void rotate(float u);
void scale(float u);
void up(float u);
float ease(int index, float u);
};
| true |
4e5daa6f3eb88691d0de9447d9f0cb7739352ce4 | C++ | accessmvsk/CodingPractice | /BinaryToDecimal.cc | UTF-8 | 1,190 | 3.6875 | 4 | [] | no_license | #include <iostream>
#include <string>
#include <cmath>
#include <cstring>
// Program to convert decimal to binary and again binary to decimal
// XXX what if number is signed ?
int main()
{
std::string inputNumber;
std::cout<<"please enter the input number "<<std::endl;
std::cin>>inputNumber;
int decimal = 0;
int length = inputNumber.size();
for (int i = 0; i < length; i++)
{
if (inputNumber.c_str()[i] == '1') {
decimal += pow(2,(length -1 -i));
}
}
std::cout<<"decimal value: "<<decimal<<std::endl;
char binary[33];
memset(binary, '0', 33);
binary[32] = '\0';
for (int i = 0; decimal > 0 ; i++)
{
// get the right most bit
int rightMostBit = decimal & 1;
// set the corresponding bit in binary string
if (rightMostBit == 1) {
binary[(31-i)] = '1';
} else {
binary[(31-i)] = '0';
}
// knock off the right most bit.
decimal = decimal >> 1;
}
// print in human readable form
std::string binaryString(binary);
std::cout<<"binary: "<<binaryString<<std::endl;
return 0;
}
| true |
41ec7e6749799dcbde7843535c035817210b0e9a | C++ | andyryan/Volume-Renderer | /Volume Renderer/Volume Renderer/Colour.h | UTF-8 | 5,320 | 3.171875 | 3 | [] | no_license | #pragma once
#include <ostream>
#define RGB 3
#define RGBA 4
#define GREYSCALE 1
#define COMPRGB 6
#define COMPGREY 2
class Colour
{
public:
Colour(void)
{
_nbChannels = 3;
_intensities = new float[3];
for (int i = 0; i < _nbChannels; i++){
_intensities[i] = 0;
}
}
Colour(const int nbChannels, const float intensities[])
{
_nbChannels = nbChannels;
_intensities = new float[nbChannels];
for (int i = 0; i < nbChannels; i++){
_intensities[i] = intensities[i];
}
}
Colour(const Colour& original) {*this = original;}
~Colour(void)
{
delete _intensities;
}
bool isRGB() const{return _nbChannels == RGB;}
bool isRGBA() const{return _nbChannels == RGBA;};
bool isGreyscale() const{return _nbChannels == GREYSCALE;};
bool isCOMPRGB() const{return _nbChannels == COMPRGB;};
bool isCOMPGREY() const{return _nbChannels == COMPGREY;};
bool isZero() const;
int nbChannels() const {return _nbChannels;}
float intensity(int c) const {return _intensities[c];}
float operator[](int c){return _intensities[c];}
void setIntensity(int c, float i) {_intensities[c] = i;}
Colour& operator=(const Colour & right_op);
Colour& operator+=(const Colour & right_op);
Colour& operator*=(const Colour & right_op);
Colour& operator/=(const Colour & right_op);
Colour& operator*(float right_op);
Colour& operator/(float right_op);
Colour operator+() const{return *this;}
Colour operator-()const{
Colour newC(_nbChannels, _intensities);
for (int i = 0; i < _nbChannels; i++) newC._intensities[i] = -_intensities[i];
return newC;}
friend std::ostream& operator<<( std::ostream & out, const Colour & theColour);
friend Colour operator*(const Colour& c, float f);
friend Colour operator*(float f, const Colour& c);
friend Colour operator/(const Colour& c, float f);
friend Colour operator*(const Colour& c1, const Colour& c2);
friend Colour operator/(const Colour& c1, const Colour& c2);
friend Colour operator+(const Colour& c1, const Colour& c2);
void clamp();
int _nbChannels;
float *_intensities;
};
inline Colour& Colour::operator=(const Colour & right_op) {
_nbChannels = right_op._nbChannels;
if (_intensities != NULL)
delete _intensities;
_intensities = new float[_nbChannels];
for (int i = 0; i < _nbChannels; i++){
_intensities[i] = right_op._intensities[i];
}
return *this;
}
inline Colour& Colour::operator+=(const Colour & right_op){
if (_nbChannels != right_op._nbChannels)
throw "incompatible colours";
for (int i = 0; i < _nbChannels; i++)
_intensities[i] += right_op._intensities[i];
return *this;
}
inline Colour& Colour::operator*=(const Colour & right_op){
if (_nbChannels != right_op._nbChannels)
throw "incompatible colours";
for (int i = 0; i < _nbChannels; i++)
_intensities[i] *= right_op._intensities[i];
return *this;
}
inline Colour& Colour::operator/=(const Colour & right_op){
if (_nbChannels != right_op._nbChannels)
throw "incompatible colours";
for (int i = 0; i < _nbChannels; i++)
_intensities[i] /= right_op._intensities[i];
return *this;
}
inline Colour& Colour::operator*(float right_op){
for (int i = 0; i < _nbChannels; i++)
_intensities[i] *= right_op;
return *this;
}
inline Colour& Colour::operator/(float right_op){
for (int i = 0; i < _nbChannels; i++)
_intensities[i] /= right_op;
return *this;
}
inline std::ostream& operator<<( std::ostream & out, const Colour & theColour){
for (int i = 0; i < theColour._nbChannels; i++){
out << theColour._intensities[i] << ' ';
}
out << '/n';
return out;
}
inline Colour operator*(const Colour& c, float f){
Colour newC(c._nbChannels, c._intensities);
for (int i = 0; i < newC._nbChannels; i++)
newC._intensities[i] *= f ;
return newC;
}
inline Colour operator*(float f, const Colour& c){
Colour newC(c._nbChannels, c._intensities);
for (int i = 0; i < newC._nbChannels; i++)
newC._intensities[i] *= f ;
return newC;
}
inline Colour operator/(const Colour& c, float f){
Colour newC(c._nbChannels, c._intensities);
for (int i = 0; i < newC._nbChannels; i++)
newC._intensities[i] /= f ;
return newC;
}
inline Colour operator*(const Colour& c1, const Colour& c2){
if (c1._nbChannels != c2._nbChannels)
throw "incompatible colours";
Colour newC(c1._nbChannels, c1._intensities);
for (int i = 0; i < newC._nbChannels; i++)
newC._intensities[i] *= c2._intensities[i] ;
return newC;
}
inline Colour operator/(const Colour& c1, const Colour& c2){
if (c1._nbChannels != c2._nbChannels)
throw "incompatible colours";
Colour newC(c1._nbChannels, c1._intensities);
for (int i = 0; i < newC._nbChannels; i++)
newC._intensities[i] /= c2._intensities[i] ;
return newC;
}
inline Colour operator+(const Colour& c1, const Colour& c2){
if (c1._nbChannels != c2._nbChannels)
throw "incompatible colours";
Colour newC(c1._nbChannels, c1._intensities);
for (int i = 0; i < newC._nbChannels; i++)
newC._intensities[i] += c2._intensities[i] ;
return newC;
}
inline void Colour::clamp(){
for (int i = 0; i < _nbChannels; i++){
if (_intensities[i] >1.0f)
_intensities[i] = 1.0f;
if (_intensities[i] < 0.0f)
_intensities[i] = 0.0f;
}
}
inline bool Colour::isZero()const{
bool isZero = true;
for (int k = 0; k < _nbChannels; k++)
if (_intensities[k] != 0.0f)
isZero = false;
return isZero;
}
| true |
e5a1c2f9c6cec870e64855aa40b93b2fc2e47e48 | C++ | EliiFlipz/prueba1 | /Suma2Numeros.cpp | UTF-8 | 187 | 2.78125 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main(){
int n1, n2, resp;
cout<<"Ingrese dos numeros: "<<endl;
cin>>n1;
cin>>n2;
resp=n1+n2;
cout<<"La respuesta es: "<<resp;
}
| true |
49b0f29f0880956b0b9fcdbc3242cb8923336f65 | C++ | hkaushalya/CDFPhoJets | /PhoFlat/PhoFlat/NewJetList.hh | UTF-8 | 1,857 | 2.5625 | 3 | [] | no_license | #ifndef NEWJETLIST_HH
#define NEWJETLIST_HH
#include "Stuple.hh"
#include <string>
#include <vector>
#include "FreeFunctions.hh"
#include "PhotonList.hh"
#include "ElectronList.hh"
#include "JetList.hh"
class NewJetList
{
public:
NewJetList();
void AddUnused(Stuple& stuple, std::vector<int>UsedPho, std::vector<int>UsedEle);
void AddUnusedCentral(Stuple& stuple, std::vector<int>UsedPho, std::vector<int>UsedEle); //add unused central em objs back to central jet list
void AddUnusedUp(Stuple& stuple, std::vector<int>UsedPho, std::vector<int>UsedEle); //add unused em/jes up em objs back to jes up jet list
void AddUnusedDown(Stuple& stuple, std::vector<int>UsedPho, std::vector<int>UsedEle); //add unused em/jes down em objs back to jes down jet list
NewJetList(Stuple&, int iObjType); // ObjType == 0 (photon), 1 (electron)
bool IsUsed(int, std::vector<int>);
void AddEleToJetList(Stuple&, std::vector<int> EleNoMatch);
void AddPhoToJetList(Stuple&, std::vector<int> PhoNoMatch);
void ReorderJets(Stuple&);
void AddEleToCentralJetList(Stuple&, std::vector<int> EleNoMatch);
void AddPhoToCentralJetList(Stuple&, std::vector<int> PhoNoMatch);
void ReorderCentralJets(Stuple&);
void AddUpEleToUpJetList(Stuple&, std::vector<int> EleNoMatch);
void AddUpPhoToUpJetList(Stuple&, std::vector<int> PhoNoMatch);
void ReorderUpJets(Stuple&);
void AddDownEleToDownJetList(Stuple&, std::vector<int> EleNoMatch);
void AddDownPhoToDownJetList(Stuple&, std::vector<int> PhoNoMatch);
void ReorderDownJets(Stuple&);
void AddUnused(PhotonList& phos, ElectronList& eles, JetList& jets,
const std::vector<int>UsedPho, const std::vector<int>UsedEle,
const float fMinJetEt, const float fMaxJetEta); //add unused central em objs back to central jet list
void ReorderJets(JetList& jets);
};
#endif
| true |
2f2a2e4fddcc283a223c6e8247da253339f1e3ed | C++ | beta382/Tetris | /src/Screen/PauseScreen.h | UTF-8 | 3,828 | 2.8125 | 3 | [] | no_license | /*
* Authors: Wes Cossick, Evan Green, Austin Hash, Taylor Jones
* Assignment name: Tetris: Spring 2014 Group Project
* Assignment description: Write an awesome Tetris clone
* Due date: Apr 30, 2014
* Date created: Apr 27, 2014
* Date last modified: Apr 27, 2014
*/
#ifndef PAUSESCREEN_H_
#define PAUSESCREEN_H_
#include "Screen.h"
#include "GameScreen.h"
#include "MenuScreen.h"
#include "ConfirmScreen.h"
#include "../Shape/BlockString.h"
// Forward declaration of destination screens, due to potential for an inclusion loop
class GameScreen;
class MenuScreen;
class ConfirmScreen;
/*
* PauseScreen:
*
* Inherits from Screen.
*
* PauseScreen is intended to represent a paused screen, and be a wrapper for everything that the
* pause screen contains. PauseScreen IS NOT intended to be inherited from.
*/
class PauseScreen: public Screen {
_registerForLeakcheckWithID(PauseScreen)
public:
/*
* Instantiates a PauseScreen object using the passed Games* to return to.
*
* Parameters:
* Game* bgScreen: A pointer to the screen object to return to
*/
PauseScreen(GameScreen* bgScreen);
/*
* Destructs this PauseScreen object.
*/
~PauseScreen();
/* ---------- Implemented from Screen ---------- */
/*
* Performs an action based on the passed key.
*
* Parameters:
* int key: The value of the key to perform an action based upon
*
* Returns: A pointer to the Screen object control should shift to after this function
* exits, or NULL if control should not shift to another Screen object
*/
void respondToKey(int) throw (QUIT, NEW_SCREEN);
/*
* Performs an action based on the passed Click.
*
* Parameters:
* Click: The value of the Click to perform an action based upon
*
* Returns: A pointer to the Screen object control should shift to after this function
* exits, or NULL if control should not shift to another Screen object
*/
void respondToClick(Click) throw (QUIT, NEW_SCREEN);
/*
* Performs actions that should happen continuously in the background on this Screen.
*
* Returns: A pointer to the Screen object control should shift to after this function
* exits, or NULL if control should not shift to another Screen object
*/
void doBackground() throw (QUIT, NEW_SCREEN);
/*
* Sets Drawable member data width's, height's, and/or locations according to the size of
* the screen as reported by GLUT_Plotter. Useful to dynamically move/scale objects when
* the screen size changes.
*/
void applyLayout();
/* ---------- Implemented from Drawable ---------- */
/*
* Draws all Drawable member data to the screen in an order that preserves view heiarchy.
*/
void draw();
/*
* Erases all Drawable member data from the screen in an order that preserves view
* heiarchy.
*/
void erase();
private:
/*
* Prevent default instantiation; we need to know where to return to.
*/
PauseScreen();
void doResume() throw (NEW_SCREEN);
void doExit() throw (NEW_SCREEN);
/*
* The game to return control to once this screen exits
*/
GameScreen* bgScreen;
BlockString title;
BlockString resume;
BlockString exit;
};
#endif /* PAUSESCREEN_H_ */
| true |
63843542787dd057997e474721ac79ec37fde9a2 | C++ | w0lker/ACM | /leetcode/Two sum.cpp | GB18030 | 851 | 3.453125 | 3 | [] | no_license | #include <vector>
using namespace std;
//ӶO(nlog(n)) hashmapԴﵽO(n)Ӷȡ
class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target) {
vector<int> vec(numbers);
//òȽ
for(int i=1;i<vec.size();++i){
int tmp = vec[i];
int j = i - 1;
while(j>=0 && vec[j]>tmp){
vec[j+1] = vec[j];
--j;
}
vec[j+1] = tmp;
}
//Ϊtarget
int begin = 0,end = vec.size() - 1;
vector<int> ans;
while(true){
int sum = vec[begin] + vec[end];
if(sum>target){
--end;
continue;
}else if(sum<target){
++begin;
continue;
}
else{
for(int i=0;i<vec.size();++i){
if(numbers[i]==vec[begin]) {ans.push_back(++i);}
if(numbers[i]==vec[end]) {ans.push_back(++i);}
}
return ans;
}
}
}
}; | true |
bb39a579689aa5452375f336425f9abf5faa6962 | C++ | MasterMaxLi/TemplateStudy | /普通函数与函数模板调用优先权.cpp | GB18030 | 593 | 3.5 | 4 | [
"Apache-2.0"
] | permissive | #include<iostream>
using namespace std;
//1.ͨͺģ嶼Եãȵͨ
void myPrint(int a, int b)
{
cout << "ͨ\n";
}
template<class T>
void myPrint(T a, T b)
{
cout << "úģ\n";
}
template<class T>
void myPrint(T a, T b,T c)
{
cout << "غģ\n";
}
void test01()
{
//ͨģIJбǿƵúģ
//myPrint<>(1, 2);
char a = 'a';
char b = 'b';
//иƥ»ȵúģ
myPrint(a, b);
}
int main()
{
test01();
return 0;
} | true |
45b70f0622a4f93ca2a62e69157915cece25f05c | C++ | Ogimle/ne | /src/Game/gamemap.h | UTF-8 | 3,064 | 2.6875 | 3 | [] | no_license | #ifndef GAMEMAP_H_INCLUDED
#define GAMEMAP_H_INCLUDED
#include <vector>
#include "../Utils/micropather.h"
#include "editor.h"
class C_GameMap : public micropather::Graph
{
private:
int MAPX, MAPY;
int maxDir;
public:
std::vector<void*> path;
micropather::MicroPather* aStar;
float totalCost;
C_GameMap()
{
aStar = NULL;
}
virtual ~C_GameMap()
{
if (aStar) delete aStar;
}
void init()
{
MAPX = Editor->getWordlWidth();
MAPY = Editor->getWordlHeigh();
if (aStar) delete aStar;
aStar = new micropather::MicroPather( this, MAPX*MAPY/4, 6 );
maxDir = 8;
}
bool getPath(int sx, int sy, int ex, int ey)
{
int result = aStar->Solve( XYToNode( sx, sy ), XYToNode( ex, ey ), &path, &totalCost );
if ( result == micropather::MicroPather::SOLVED ) return true;
return false;
}
int Passable( int x, int y, int nx, int ny )
{
if ( nx >= 0 && nx < MAPX
&& ny >= 0 && ny < MAPY )
{
int dx=nx-x, dy=ny-y;
if ( abs(dx)+abs(dy)==2 ) //ход по диагонали
{
if ( Editor->getTile(nx,ny)->isPassable //доступна целевая клетка
&& Editor->getTile(x+dx, y)->isPassable // и пересекаемая диагональ
&& Editor->getTile(x, y+dy)->isPassable // свободна
) return 1;
return 0;
}
else
if ( Editor->getTile(nx,ny)->isPassable ) return 1;
}
return 0;
}
void NodeToXY( void* node, int* x, int* y )
{
int index = (int)node;
*y = index / MAPX;
*x = index - *y * MAPX;
}
void* XYToNode( int x, int y )
{
return (void*) ( y*MAPX + x );
}
virtual float LeastCostEstimate( void* nodeStart, void* nodeEnd )
{
int xStart, yStart, xEnd, yEnd;
NodeToXY( nodeStart, &xStart, &yStart );
NodeToXY( nodeEnd, &xEnd, &yEnd );
int dx = xStart - xEnd;
int dy = yStart - yEnd;
return (float) sqrt( (double)(dx*dx) + (double)(dy*dy) );
}
virtual void AdjacentCost( void* node, std::vector< micropather::StateCost > *neighbors )
{
int x, y;
// E N W S NE NW SW SE
const int dx[8] = { 1, 0, -1, 0, 1, -1, -1, 1 };
const int dy[8] = { 0, -1, 0, 1, -1, -1, 1, 1 };
const float cost[8] = { 1.0f, 1.0f, 1.0f, 1.0f,
1.41f, 1.41f, 1.41f, 1.41f };
NodeToXY( node, &x, &y );
for( int i=0; i<maxDir; ++i )
{
int nx = x + dx[i];
int ny = y + dy[i];
int pass = Passable( x, y, nx, ny );
if ( pass > 0 ) {
// Normal floor
micropather::StateCost nodeCost = { XYToNode( nx, ny ), cost[i] * (float)(pass) };
neighbors->push_back( nodeCost );
}
}
}
virtual void PrintStateInfo( void* node )
{
int x, y;
NodeToXY( node, &x, &y );
printf( "(%2d,%2d)", x, y );
}
void PrintPath()
{
printf("path: \n");
for(int i=0, imax=path.size(); i<imax; ++i)
{
PrintStateInfo( path[i] );
}
printf("\n");
}
};
#endif // GAMEMAP_H_INCLUDED
| true |
e1107b2b3d10bb5f3da7d57129629ef1817e893c | C++ | aminallam/algorithms | /solutions/028_Crystal_dp.cpp | UTF-8 | 1,195 | 2.90625 | 3 | [] | no_license | // Problem: http://icpcres.ecs.baylor.edu/onlinejudge/index.php?option=com_onlinejudge&page=show_problem&problem=1955
// Submit: Same As Previous
// Problem Number: 11014
#include <iostream>
#include <cstdio>
#include <cmath>
using namespace std;
typedef long long LL;
/////////////////////////////////////////////////////////////////////
#define MAX_N 200000
LL s[MAX_N+1];
LL p[MAX_N+1];
LL r[MAX_N+1];
int n;
void Initialize()
{
int i,j;
s[0]=1; p[0]=0;
for(i=1;i<=MAX_N;i++)
{
LL a=2*i+1, b=2*(i-1)+1;
s[i]=a*a*a-b*b*b;
p[i]=s[i];
}
for(i=1;i<=MAX_N;i++)
{
for(j=2;j<=MAX_N/i;j++) p[i*j]-=p[i];
}
r[0]=p[0];
for(i=1;i<=MAX_N;i++)
{
r[i]=r[i-1]+p[i];
}
}
LL Compute()
{
return r[n];
}
/////////////////////////////////////////////////////////////////////
int main()
{
//freopen("Crystal.in", "r", stdin);
int icase=0;
Initialize();
while(true)
{
scanf("%d ", &n);
if(n==0) break;
n=n/2; // We need only +ve part
icase++;
cout << "Crystal " << icase << ": " << Compute() << "\n";
}
return 0;
}
/*
Crystal 1: 98
Crystal 2: 26
Crystal 3: 1144243350562754
*/
| true |
b0383c20add6cb2828aca774376a05c8eb035c6d | C++ | MargaritaCastro/dd-cut-and-lift | /src/bdd_conic_diag.cpp | UTF-8 | 54,582 | 3.015625 | 3 | [] | no_license | //
// Created by Margarita Castro on 2019-08-09.
//
#include "bdd_conic_diag.h"
#include <fstream>
#include <algorithm>
#include <queue>
using namespace std;
// Construct BDD from scratch
void bdd_diag::construct_bdd() {
if (is_constructed){
cout << "BDD is already constructed" << endl;
return;
}
clock_t start_constr = clock();
//Initialize space and all necessary variable
initialize_bdd_space();
// Create initial bdd
width_one_bdd();
// Include GUB constraints
if (cqd->gub && max_width > 1) gub_bdd();
procedure_bottom_up(0);
int i = 1;
int num_it = 10;
bdd_has_change = true;
if (cqd->gub) num_it = 10;
// Iterative procedures
while (bdd_has_change && i <= num_it) {
bdd_has_change = false;
procedure_top_down(i);
if (!bdd_has_change) break;
bdd_has_change = false;
procedure_bottom_up(i);
i++;
}
//Reduce final BDD
reduce_bdd();
is_constructed = true;
clock_t end_constr = clock();
constr_time = double(end_constr - start_constr) / CLOCKS_PER_SEC;
}
// Initialize the space of the BDD
void bdd_diag::initialize_bdd_space() {
int size = 0;
// Create and initialize nodes
nodes.resize(num_vars + 1, vector<bdd_node*>());
for (int l=0 ; l < num_vars + 1; l++) {
if (l == 0 || l == num_vars) {
nodes[l].resize(1, nullptr);
nodes[l][0] = new bdd_node();
}
else {
size = 2*nodes[l-1].size();
size = min(size, max_width);
nodes[l].resize(size, nullptr);
for (int i = 0; i < size ; i ++){
nodes[l][i] = new bdd_node();
}
}
}
// Create and initialize arcs
arcs.resize(num_vars, vector<bdd_arc*>());
for (int l=0 ; l < num_vars; l++) {
if (l == 0){
arcs[l].resize(2, nullptr);
arcs[l][0] = new bdd_arc(l, 0, 0);
arcs[l][1] = new bdd_arc(l, 0, 1);
}
else{
size = 2*nodes[l].size();
arcs[l].resize(size, nullptr);
for (int i = 0; i < size ; i ++) {
arcs[l][i] = new bdd_arc(l, (int)floor(i/2), i%2);
}
}
}
// Initialize nodes available
nodes_available.resize(num_vars + 1,max_width);
for (int l=0 ; l < num_vars + 1; l++) {
nodes_available[l] = nodes[l].size();
}
first_node_available.resize(num_vars + 1, 0);
// Initialize arc & node candidate
candidate_arcs.resize(max_width*2, make_tuple(-1,-1,-1));
candidate_nodes.resize(max_width, -1);
// Initialize exact layer
is_layer_exact.resize(num_vars + 1, false);
// Initialize edge cost vector (for slack computation)
cost_edge.resize(2);
}
//Create initial BDD
void bdd_diag::width_one_bdd() {
// Update root node
nodes[0][0]->is_exact = true;
nodes[0][0]->is_free = false;
nodes_available[0] = 0;
first_node_available[0] = -1;
// Update every layer - one node and two arcs per layer
for (int l = 0; l < num_vars ; l++) {
//Direct arcs of first node
arcs[l][0]->target = 0;
arcs[l][1]->target = 0;
// Activate first node in next layer
nodes[l+1][0]->is_free = false;
nodes[l+1][0]->in_arcs.push_back(0);
nodes[l+1][0]->in_arcs.push_back(1);
update_node_top_down(l+1, 0);
//Update nodes available
nodes_available[l+1]--;
first_node_available[l+1] = 1;
}
//Update terminal node
nodes[num_vars][0]->lin_min_bottom = 0;
nodes[num_vars][0]->lin_max_bottom = 0;
nodes[num_vars][0]->diag_min_bottom = 0;
nodes[num_vars][0]->diag_max_bottom = 0;
first_node_available[num_vars] = -1;
is_layer_exact[0] = true;
if (debug) {
char name[256];
sprintf(name, "graphs/bdd%d_width0.gml", bdd_id);
export_graph(name);
}
}
// Include GUB constraints to BDD
void bdd_diag::gub_bdd() {
int count = 1;
int group_id = 0;
//Iterate over each layer
for (int l = 1; l < num_vars; l++) {
if (count < cqd->gub_groups[group_id]) {
// Refine layer
refine_gub(l);
count++;
}
else {
//No need to refine this layer
//Update group id
group_id++;
count = 1;
}
}
bdd_has_change = true;
if (debug) {
char name[256];
sprintf(name, "graphs/bdd%d_gub.gml", bdd_id);
export_graph(name);
}
}
//refine layer following GUB constraint
void bdd_diag::refine_gub(int layer) {
int original_id = 0;
//Create new node
int new_node_id = first_node_available[layer];
bdd_node* new_node = nodes[layer][new_node_id];
assert(new_node->is_free && new_node->in_arcs.empty());
//Activate new node
new_node->is_free = false;
//Arcs for new node
new_node->in_arcs.push_back(1);
if (nodes[layer][original_id]->in_arcs.size() == 3) new_node->in_arcs.push_back(2);
for (int i: new_node->in_arcs) arcs[layer - 1][i]->target = new_node_id;
//Set up outgoing arcs of new node
arcs[layer][2*new_node_id]->target = 0;
nodes[layer + 1][0]->in_arcs.push_back(2*new_node_id);
if (debug)
cout << "Adding arc " << 2*new_node_id << " to node " << 0 << " in layer " << layer + 1 << endl;
//Update available nodes
update_first_node_available(layer);
nodes_available[layer]--;
//Update arcs in original node
nodes[layer][original_id]->in_arcs.clear();
nodes[layer][original_id]->in_arcs.push_back(0);
}
// Top-down procedure
void bdd_diag::procedure_top_down(int round) {
int size = 0;
if (debug) {
cout << "\n== Starting top-down procedure "<< round <<" ==\n";
}
for (int l = 0; l < num_vars; l++) {
size = arcs[l].size();
//Filter arcs in current layer
for (int i = 0; i < size; i++) {
if (arcs[l][i]->target == -1) continue;
if (is_arc_infeasible(arcs[l][i])) {
remove_arc(arcs[l][i]);
if (debug) cout << "Filter arc " << i << " in layer " << l << endl;
}
}
// Check nodes and see if there is any available
size = nodes[l + 1].size();
for (int i = 0; i < size; i++) {
if (nodes[l + 1][i]->is_free) continue;
if (nodes[l + 1][i]->in_arcs.empty() ) {
remove_node(l + 1, i);
continue;
}
if (l + 1 < num_vars && arcs[l + 1][2*i]->target == -1 && arcs[l + 1][2*i+1]->target == -1) {
remove_node(l + 1, i);
continue;
}
}
// Refine nodes in next layer
if (!is_layer_exact[l+1] && nodes_available[l + 1] >= 1) refine(l + 1);
// Update nodes in next layer
for (int i = 0; i < size; i++) {
if (nodes[l+1][i]->is_free || nodes[l+1][i]->is_exact) continue;
if (nodes[l+1][i]->in_arcs.empty() ) {
remove_node(l + 1, i);
continue;
}
update_node_top_down(l+1, i);
}
check_exact_layer(l+1);
}
if (debug){
cout << "\n== End top-down procedure "<< round <<" ==\n";
char name[256];
sprintf(name, "graphs/bdd%d_top%d.gml", bdd_id,round);
export_graph(name);
}
}
//Bottom-up procedure
void bdd_diag::procedure_bottom_up(int round) {
if (debug){
cout << "\n== Starting bottom-up procedure "<< round <<" ==\n";
}
int size = 0;
bdd_stop_reducing = false;
for (int l = num_vars-1; l >= 0; l--) {
size = arcs[l].size();
//Filter arcs is the current layer
for (int i = 0; i < size; i++) {
if (arcs[l][i]->target == -1) continue;
if (is_arc_infeasible(arcs[l][i])) {
remove_arc(arcs[l][i]);
if(debug) cout << "Filter arc " << i << " in layer " << l << endl;
}
}
//Reduce nodes in the layer
if(!bdd_stop_reducing) reduce_layer(l, false);
// Update nodes in the current layer
size = nodes[l].size();
for (int i = 0; i < size; i++) {
if (nodes[l][i]->is_free) continue;
if (arcs[l][2*i]->target == -1 && arcs[l][2*i+1]->target == -1){
remove_node(l, i);
continue;
}
if (l > 0 && nodes[l][i]->in_arcs.empty()) {
remove_node(l, i);
continue;
}
update_node_bottom_up(l, i);
}
}
if (debug){
cout << "\n== End bottom-up procedure "<< round <<" ==\n";
char name[256];
sprintf(name, "graphs/bdd%d_bottom%d.gml", bdd_id, round);
export_graph(name);
}
}
//Update node top_down
void bdd_diag::update_node_top_down(int layer, int node_id) {
bdd_node* node = nodes[layer][node_id];
bdd_node* source = nullptr;
bdd_arc* arc = nullptr;
int lin_value = 0;
int diag_value = 0;
node->lin_min_top = int_max;
node->lin_max_top = int_min;
node->diag_min_top = int_max;
node->diag_max_top = int_min;
assert(!node->in_arcs.empty());
for (int i : node->in_arcs) {
arc = arcs[layer - 1][i];
source = nodes[layer - 1][arc->source];
assert(!source->is_free);
diag_value = arc->value*cqd->diag2[layer - 1];
lin_value = arc->value*cqd->linear[layer - 1];
// Update linear values
if (lin_value + source->lin_min_top < node->lin_min_top)
node->lin_min_top = lin_value + source->lin_min_top ;
if (lin_value + source->lin_max_top > node->lin_max_top)
node->lin_max_top = lin_value + source->lin_max_top ;
// Update diagonal values
if (diag_value + source->diag_min_top < node->diag_min_top)
node->diag_min_top = diag_value + source->diag_min_top;
if (diag_value + source->diag_max_top > node->diag_max_top)
node->diag_max_top = diag_value + source->diag_max_top;
}
node->is_exact = false;
node->is_feasible = false;
// Check if node is exact or not
if (node->lin_min_top == node->lin_max_top && node->diag_min_top == node->diag_max_top)
node->is_exact = true;
//Check if all the solutions are feasible or not
if (node->is_reduce) {
node->is_feasible = true; // Reduce nodes always have only fesible paths
}
else if (node->lin_max_top + node->lin_max_bottom +
cqd->omega*sqrt( node->diag_max_top + node->diag_max_bottom) <= cqd->rhs) {
node->is_feasible = true;
}
else{
// Check each incoming arcs for feasibility
node->is_feasible = true;
for (int i : node->in_arcs) {
if( !is_arc_feasible(arcs[layer-1][i]) ){
node->is_feasible = false;
break;
}
}
}
if (debug){
//Print node top-down information
cout << "\nNode " << node_id << " in layer " << layer << " -- top-down" << endl;
cout << "\tin_arcs = ";
for (int i : node->in_arcs) {
cout << i << " ";
}
cout << "\n\tlinear = [" << node->lin_min_top << " , " << node->lin_max_top << "]"<< endl;
cout << "\tdiagonal = [" << node->diag_min_top << " , " << node->diag_max_top << "]"<< endl;
if (node->is_exact)
cout <<"\tNode is exact" << endl;
if (node->is_feasible)
cout <<"\tNode has only feasible paths" << endl;
}
}
void bdd_diag::update_node_bottom_up(int layer, int node_id) {
bdd_node* node = nodes[layer][node_id];
//Outgoing arcs
bdd_arc* arc0 = arcs[layer][node_id*2];
bdd_arc* arc1 = arcs[layer][node_id*2+1];
if (arc0->target != -1) {
node->lin_min_bottom = nodes[layer + 1][arc0->target]->lin_min_bottom;
node->diag_min_bottom = nodes[layer + 1][arc0->target]->diag_min_bottom;
node->lin_max_bottom = nodes[layer + 1][arc0->target]->lin_max_bottom;
node->diag_max_bottom = nodes[layer + 1][arc0->target]->diag_max_bottom;
if (arc1->target != -1){
node->lin_min_bottom = min(node->lin_min_bottom,
nodes[layer + 1][arc1->target]->lin_min_bottom + cqd->linear[layer] );
node->diag_min_bottom = min(node->diag_min_bottom,
nodes[layer + 1][arc1->target]->diag_min_bottom + cqd->diag2[layer]);
node->lin_max_bottom = max(node->lin_max_bottom,
nodes[layer + 1][arc1->target]->lin_max_bottom + cqd->linear[layer] );
node->diag_max_bottom = max(node->diag_max_bottom,
nodes[layer + 1][arc1->target]->diag_max_bottom + cqd->diag2[layer]);
}
}
else {
node->lin_min_bottom = nodes[layer + 1][arc1->target]->lin_min_bottom + cqd->linear[layer];
node->diag_min_bottom = nodes[layer + 1][arc1->target]->diag_min_bottom + cqd->diag2[layer];
node->lin_max_bottom = nodes[layer + 1][arc1->target]->lin_max_bottom + cqd->linear[layer];
node->diag_max_bottom = nodes[layer + 1][arc1->target]->diag_max_bottom + cqd->diag2[layer];
}
if (debug){
//Print node top-down information
cout << "\nNode " << node_id << " in layer " << layer << " -- bottom-up" << endl;
cout << "\tout_arcs = ";
if (arc0->target != -1) cout << node_id*2 << " ";
if (arc1->target != -1) cout << node_id*2 + 1 << " ";
cout << "\n\tlinear = [" << node->lin_min_bottom << " , " << node->lin_max_bottom << "]"<< endl;
cout << "\tdiagonal = [" << node->diag_min_bottom << " , " << node->diag_max_bottom << "]"<< endl;
}
}
// Filter arcs
bool bdd_diag::is_arc_infeasible(bdd_arc* arc) {
if (is_arc_infeasible_qcd(arc)){
return true;
}
return false;
}
//Filter arc w.r.t to QCD constraint
bool bdd_diag::is_arc_infeasible_qcd(bdd_arc* arc){
const int layer = arc->layer;
int linear = nodes[layer][arc->source]->lin_min_top + arc->value*cqd->linear[layer]
+ nodes[layer + 1][arc->target]->lin_min_bottom;
double diag = nodes[layer][arc->source]->diag_min_top + arc->value*cqd->diag2[layer]
+ nodes[layer + 1][arc->target]->diag_min_bottom;
if (linear + cqd->omega*sqrt(diag) >= epsilon + cqd->rhs) {
return true;
}
return false;
}
//Check if all paths over an arc are feasible or not
bool bdd_diag::is_arc_feasible(bdd_arc* arc){
const int layer = arc->layer;
int linear = nodes[layer][arc->source]->lin_max_top + arc->value*cqd->linear[layer]
+ nodes[layer + 1][arc->target]->lin_max_bottom;
double diag = nodes[layer][arc->source]->diag_max_top + arc->value*cqd->diag2[layer]
+ nodes[layer + 1][arc->target]->diag_max_bottom;
if (linear + cqd->omega*sqrt(diag) <= cqd->rhs) {
return true;
}
return false;
}
void bdd_diag::refine(int layer) {
if (debug) cout << "\n= Refining layer " << layer << " =" << endl;
// Get candidate arcs (lhs, linear, arc_id)
int total = 0;
int arc_id = 0;
get_candidate_arcs(layer, total);
int old_target_id = 0;
list<int> in_arcs;
// Iterate over arcs and create new nodes (until we reach max_width)
for (int i = 0; i < total; i++) {
if (get<0>(candidate_arcs[i]) == -1) continue;
arc_id = get<2>(candidate_arcs[i]);
old_target_id = arcs[layer - 1][arc_id]->target;
// Skip arc if it is the last in the node
if (nodes[layer][old_target_id]->in_arcs.size() == 1) continue;
in_arcs.clear();
in_arcs.push_back(get<2>(candidate_arcs[i]));
// Get other arcs with similar value
for (int j = i+1; j< total; j++) {
if (get<0>(candidate_arcs[i]) == get<0>(candidate_arcs[j]) &&
get<1>(candidate_arcs[i]) == get<1>(candidate_arcs[j])) {
in_arcs.push_back(get<2>(candidate_arcs[j]));
get<0>(candidate_arcs[j]) = -1;
}
else {
break;
}
}
// Remove edges from old_target nodes
for (int j : in_arcs) remove_arc(arcs[layer - 1][j]);
// Create new node for the arcs
create_new_node(layer,old_target_id, in_arcs);
// Check availability
if (nodes_available[layer] == 0) break;
}
}
void bdd_diag::get_candidate_arcs(int layer, int& total) {
int size = nodes[layer].size();
double value = 0;
int linear_value = 0;
int diag_value = 0;
bdd_arc* arc = nullptr;
candidate_arcs.assign(max_width*2, make_tuple(-1,-1,-1));
total = 0;
// Iterate over nodes in the layer
for (int i = 0; i < size; i++) {
if (nodes[layer][i]->is_free || nodes[layer][i]->is_exact || nodes[layer][i]->is_feasible ) continue;
// No refinement for nodes with one incoming arc
if (nodes[layer][i]->in_arcs.size() == 1) continue;
// Skip nodes that have all arcs equal (w.r.t. min value)
if(are_in_arcs_min_equal(layer, i)) continue;
// Iterate over their incoming arcs
for (auto j: nodes[layer][i]->in_arcs) {
arc = arcs[layer - 1 ][j];
//Ignore arcs that are always feasible
if (is_arc_feasible(arc)) continue;
linear_value = arc->value*cqd->linear[layer - 1] + nodes[layer - 1][ arc->source]->lin_min_top;
diag_value = arc->value*cqd->diag2[layer - 1] + nodes[layer - 1][ arc->source]->diag_min_top;
value = linear_value + cqd->omega*sqrt(diag_value);
//Add arc to the candidate list
get<0>(candidate_arcs[total]) = value;
get<1>(candidate_arcs[total]) = linear_value;
get<2>(candidate_arcs[total]) = j;
total++;
}
}
//Sort the vector in decreasing order
sort(candidate_arcs.begin(), candidate_arcs.begin() + total, greater<>() );
}
bool bdd_diag::are_in_arcs_min_equal(int layer, int id) {
bdd_arc* arc = nullptr;
double first_value = int_min;
double first_linear = int_min;
double value = 0;
int linear_value = 0;
int diag_value = 0;
for (int j: nodes[layer][id]->in_arcs) {
arc = arcs[layer - 1 ][j];
linear_value = arc->value*cqd->linear[layer - 1] + nodes[layer - 1][ arc->source]->lin_min_top;
diag_value = arc->value*cqd->diag2[layer - 1] + nodes[layer - 1][ arc->source]->diag_min_top;
value = linear_value + cqd->omega*sqrt(diag_value);
if (first_value == int_min) {
first_value = value;
first_linear = linear_value;
}
if ( first_linear != linear_value || abs(first_value - value) > epsilon ) return false;
}
return true;
}
void bdd_diag::reduce_bdd() {
//Procedure to reduce the final BDD
for (int l = num_vars-1; l >= 0; l--) {
//Reduce nodes in the layer
reduce_layer(l, true);
}
if (debug){
cout << "\n== End final BDD reduction ==\n";
char name[256];
sprintf(name, "graphs/bdd%d_reduced.gml", bdd_id);
export_graph(name);
}
}
void bdd_diag::reduce_layer(int layer, bool final_bdd){
int total = 0;
if(final_bdd) total = get_nodes_to_reduce_final(layer);
else total = get_nodes_to_reduce(layer);
if (total == 0) {
if (layer < num_vars-1) bdd_stop_reducing = true;
return;
}
list<int> similar;
int last_skip = total;
int first_skip = 0;
bool first = true;
bool has_reduced = false;
//Iterate over the list add
for (int i =0; i < total; i++) {
if (candidate_nodes[i] == -1) continue;
similar.clear();
last_skip = i+1;
first_skip = i;
first = true;
//Find similar nodes
for (int j = i+1; j < total; j++) {
if (candidate_nodes[j] == -1) continue;
if (arcs[layer][2*candidate_nodes[i] ]->target == arcs[layer][2*candidate_nodes[j] ]->target &&
arcs[layer][2*candidate_nodes[i] +1 ]->target == arcs[layer][2*candidate_nodes[j] +1 ]->target) {
similar.push_back(candidate_nodes[j]);
candidate_nodes[j] = - 1;
}
else {
if(first){
first_skip = j;
first = false;
}
last_skip = j + 1;
}
}
//Reduce nodes
if (!similar.empty()) {
reduce_nodes(layer,candidate_nodes[i], similar);
has_reduced=true;
}
//update indices
total = last_skip;
if (!first) {
i = first_skip -1;
}
}
if(!has_reduced) bdd_stop_reducing = true;
}
void bdd_diag::reduce_nodes(int layer, int node_id, list<int>& similar) {
bdd_node* node = nodes[layer][node_id];
for (auto i: similar) {
// Redirect arcs
for (auto arc_id : nodes[layer][i]->in_arcs) {
node->in_arcs.push_back(arc_id);
arcs[layer-1][arc_id]->target = node_id;
}
// Remove node
nodes[layer][i]->in_arcs.clear();
remove_node(layer, i);
}
bdd_has_change = true;
node->is_reduce = true;
node->is_feasible = true;
node->is_exact = false;
if (debug){
cout << "Merge nodes: ";
for (auto i: similar) cout << i << " ";
cout << "in layer "<< layer <<" into node " << node_id << endl;
}
}
int bdd_diag::get_nodes_to_reduce(int layer) {
//Get list of possible nodes to reduce
//i.e., exact/feasible nodes that have exact/feasible target nodes (or terminal node)
int size = nodes[layer].size();
int total = 0;
candidate_nodes.assign(max_width, -1);
for (int i = 0; i < size; i++) {
if (nodes[layer][i]->is_free) continue;
//Remove nodes that are disconnect
if (arcs[layer][2*i]->target == -1 && arcs[layer][2*i+1]->target == -1){
remove_node(layer, i);
continue;
}
if (layer > 0 && nodes[layer][i]->in_arcs.empty()) {
remove_node(layer, i);
continue;
}
// Check that node is either exact or feasible
if (!nodes[layer][i]->is_exact && !nodes[layer][i]->is_feasible) continue;
// Check that node have exact or feasible targets
if (layer == num_vars - 1) {
candidate_nodes[total] = i;
total++;
}
//OLD
// else if (arcs[layer][2*i]->target == -1 ||
// (nodes[layer+1][arcs[layer][2*i]->target]->is_exact || nodes[layer+1][arcs[layer][2*i]->target]->is_feasible)) {
// if(arcs[layer][2*i+1]->target == -1 ||
// (nodes[layer+1][arcs[layer][2*i+1]->target]->is_exact || nodes[layer+1][arcs[layer][2*i+1]->target]->is_feasible)){
// candidate_nodes[total] = i;
// total++;
// }
// }
else {
bool add = true;
for ( int j = 0; j < 2; j++){
if (arcs[layer][2*i + j]->target != -1) {
if (nodes[layer+1][arcs[layer][2*i + j]->target]->in_arcs.size() == 1 ) {
add = false;
break;
}
if(!nodes[layer+1][arcs[layer][2*i + j]->target]->is_exact && !nodes[layer+1][arcs[layer][2*i + j]->target]->is_feasible){
add = false;
break;
}
}
}
if (add){
candidate_nodes[total] = i;
total++;
}
}
}
return total;
}
int bdd_diag::get_nodes_to_reduce_final(int layer) {
//Get list of possible nodes to reduce
//In this case we don't care about the status of the target nodes
int size = nodes[layer].size();
int total = 0;
candidate_nodes.assign(max_width, -1);
for (int i = 0; i < size; i++) {
if (nodes[layer][i]->is_free) continue;
//Remove nodes that are disconnect
if (arcs[layer][2*i]->target == -1 && arcs[layer][2*i+1]->target == -1){
remove_node(layer, i);
continue;
}
if (layer > 0 && nodes[layer][i]->in_arcs.empty()) {
remove_node(layer, i);
continue;
}
candidate_nodes[total] = i;
total++;
}
return total;
}
void bdd_diag::check_exact_layer(int layer){
int size = nodes[layer].size();
//Check if layer is exact or not
if (!is_layer_exact[layer]) {
is_layer_exact[layer] = true;
for (int i = 0; i < size; i++) {
if (nodes[layer][i]->is_free) continue;
if (!nodes[layer][i]->is_exact) {
is_layer_exact[layer] = false;
break;
}
}
}
}
void bdd_diag::update_first_node_available(int layer){
//Find new first node available
for (int i =first_node_available[layer]; i < nodes[layer].size(); i++){
if (nodes[layer][i]->is_free){
first_node_available[layer] = i;
return;
}
}
first_node_available[layer] = -1;
assert(nodes_available[layer] <= 1);
}
//Create new node and duplicate outgoing arcs following old_target node
void bdd_diag::create_new_node(int layer, int old_id, list<int>& in_arcs) {
int new_node_id = first_node_available[layer];
if (debug) {
cout << "Create new node " << new_node_id << " in layer " << layer <<" in_arcs = ";
for (int i : in_arcs) {
cout << i << " ";
}
cout << endl;
}
assert(new_node_id >= 0);
bdd_node* new_node = nodes[layer][new_node_id];
assert(new_node->is_free && new_node->in_arcs.empty());
//Activate new node
new_node->is_free = false;
new_node->in_arcs.assign( in_arcs.begin(), in_arcs.end());
for (int i: in_arcs) arcs[layer - 1][i]->target = new_node_id;
//Set up outgoing arcs of new node
int new_target = 0;
for(int j =0; j < 2; j++){
new_target = arcs[layer][2*old_id + j]->target;
if (new_target >= 0) {
arcs[layer][2*new_node_id + j]->target = new_target;
nodes[layer + 1][new_target]->in_arcs.push_back(2*new_node_id + j);
if (debug) cout << "Adding arc " << 2*new_node_id + j << " to node " << new_target << " in layer " << layer + 1 << endl;
}
}
//Update available nodes
update_first_node_available(layer);
nodes_available[layer]--;
bdd_has_change = true;
}
//Remove arc from BDD
void bdd_diag::remove_arc(bdd_arc* arc) {
if (arc->target == -1) return;
//Remove arc from target node
int id = 2*arc->source + arc->value;
list<int>::iterator it = nodes[arc->layer + 1][arc->target]->in_arcs.begin();
list<int>::iterator end = nodes[arc->layer + 1][arc->target]->in_arcs.end();
while( it != end){
if( *it == id ){
it = nodes[arc->layer + 1][arc->target]->in_arcs.erase(it);
break;
}
it++;
}
// Desactivate arc
arc->target = -1;
bdd_has_change = true;
if (debug) {
cout << "Removing arc "<< 2*arc->source + arc->value << " in layer " << arc->layer << endl;
}
}
//Remove node
void bdd_diag::remove_node(int layer, int node_id) {
if (debug) {
cout << "Removing node "<< node_id << " in layer " << layer << endl;
}
bdd_node* node = nodes[layer][node_id];
//Reset node values
node->is_feasible = false;
node->is_free = true;
node->is_exact = false;
node->is_reduce = false;
node->lin_min_top = 0;
node->lin_max_top = 0;
node->diag_min_top = 0;
node->diag_max_top = 0;
node->lin_min_bottom = int_min;
node->lin_max_bottom = int_max;
node->diag_min_bottom = 0;
node->diag_max_bottom = int_max;
//Reset incoming arcs (if any)
for (int i : node->in_arcs) {
arcs[layer - 1][i]->target = -1;
}
node->in_arcs.clear();
// Reset outgoing arcs
remove_arc(arcs[layer][node_id*2]);
remove_arc(arcs[layer][node_id*2 +1 ]);
//Update available nodes
nodes_available[layer]++;
if (node_id < first_node_available[layer] || first_node_available[layer] == -1 ){
first_node_available[layer] = node_id;
}
bdd_has_change = true;
}
// =============== SLACK FUNCTIONS - BEGIN
bool bdd_diag::get_bdd_slacks(double* _cost, double* _slack, double& rhs){
if (!is_constructed){
cout << "Error: Need to construct BDD before getting slacks. Use method construct_bdd()" << endl;
exit(1);
}
if (debug) {
cout << "= Computing BDD slacks =" << endl;
}
// Set values
cost = _cost;
slack = _slack;
// Compute top-down cost
compute_cost_top();
//Check if rhs is correct or not
if (rhs > nodes[num_vars][0]->cost_top) {
if(debug) cout << "Improve rhs of the inequality form " << rhs << " to " <<nodes[num_vars][0]->cost_top <<endl;
rhs = nodes[num_vars][0]->cost_top;
}
else if(rhs < nodes[num_vars][0]->cost_top) {
if(debug) cout << "Can't improve inequality with BDD " << bdd_id << endl;
return false;
}
// Compute bottom-up cost
compute_cost_bottom();
// Compute slacks
compute_slacks();
if (debug){
cout << "slacks = ";
for (int i = 0; i < num_vars; i++) {
cout << slack[i] << " ";
}
cout << "\n";
}
return true;
}
void bdd_diag::compute_cost_top() {
// if (debug) {
// cout << "\n== Computing BDD cost - top ==" <<endl;
// }
int size = 0;
// Iterate over all node layers (expect the first)
for (int l = 1; l < num_vars + 1; l++) {
size = nodes[l].size();
for (int i = 0; i < size; i++){
if (nodes[l][i]->is_free) continue;
compute_cost_node_top(l, i);
}
}
}
void bdd_diag::compute_cost_bottom() {
// if (debug) {
// cout << "\n== Computing BDD cost - bottom ==" <<endl;
// }
int size = 0;
// Iterate over all node layers
for (int l = num_vars - 1; l >= 0; l--) {
size = nodes[l].size();
for (int i = 0; i < size; i++){
if (nodes[l][i]->is_free) continue;
compute_cost_node_bottom(l, i);
}
}
}
void bdd_diag::compute_slacks() {
int size = 0;
double value = 0;
int removable = 0;
// Iterate over all the edge layers
for (int l = 0; l < num_vars; l++) {
size = arcs[l].size();
//Iterate over 0-edges (even) first and then 1-edges (odd)
for (int j = 0; j < 2; j++) {
cost_edge[j] = int_min;
for (int i = j; i < size; i += 2) {
if (arcs[l][i]->target == -1) continue;
value = nodes[l][arcs[l][i]->source]->cost_top + j*cost[l]
+ nodes[l+1][arcs[l][i]->target]->cost_bottom;
// cout << "edge["<<l<<"]["<<i<<"] = " << value << endl;
if (cost_edge[j] < value)
cost_edge[j] = value;
}
// cout << "- cost_edge["<<l<<"]["<<j<<"] = " << cost_edge[j] <<endl;
}
if (cost_edge[0] == int_min || cost_edge[1] == int_min) {
slack[l] = 0;
removable++;
//cout << "remove var:" << cqd->vars[l] << endl;
}
else {
slack[l] = cost_edge[0] - cost_edge[1];
}
// cout << "- slack["<<l<<"] = " << slack[l] << endl;
}
}
void bdd_diag::compute_cost_node_top(int layer, int id) {
bdd_node* node = nodes[layer][id];
double value = 0;
node->cost_top = int_min;
// Iterate over incoming arcs to get maximum cost
for (int i : node->in_arcs) {
value = nodes[layer - 1][arcs[layer - 1][i]->source]->cost_top
+ arcs[layer - 1][i]->value*cost[layer - 1];
if (node->cost_top < value) {
node->cost_top = value;
node->cost_arc_id = i;
}
}
// if (debug) {
// cout << "\nNode " << id << " in layer " << layer << " -- top-down" << endl;
// cout << "\tin_arcs = ";
// for (int i : node->in_arcs) {
// cout << i << " ";
// }
// cout<<"\n\tcost = " << node->cost_top << endl;
// cout<<"\tarc = " << node->cost_arc_id << endl;
// }
}
void bdd_diag::compute_cost_node_bottom(int layer, int id) {
bdd_node* node = nodes[layer][id];
double value = 0;
node->cost_bottom = int_min;
// Iterate over outgoing arcs
for (int i = 0; i < 2; i++) {
if (arcs[layer][2*id + i]->target == -1) continue;
value = nodes[layer +1][arcs[layer][2*id + i]->target]->cost_bottom
+ arcs[layer][2*id + i]->value*cost[layer];
if (node->cost_bottom < value) {
node->cost_bottom = value;
}
}
// if (debug){
// cout << "\nNode " << id << " in layer " << layer << " -- bottom-up" << endl;
// cout << "\tout_arcs = ";
// for (int i = 0; i < 2; i++) {
// if (arcs[layer][2*id + i]->target == -1) continue;
// cout << 2*id + i << " ";
// }
// cout<<"\n\tcost = " << node->cost_bottom << endl;
// }
}
// =============== SLACK FUNCTIONS - END
// =============== LONGEST PATH - BEGIN
void bdd_diag::compute_longest_path(double* _cost, int* path) {
if (!is_constructed){
cout << "Error: Need to construct BDD before getting slacks. Use method construct_bdd()" << endl;
exit(1);
}
if (debug) {
cout << "= Computing Shortest path =" << endl;
}
// Set values
cost = _cost;
// Compute top-down cost
compute_cost_top();
// Extract Longest path
extract_longest_path(path);
}
void bdd_diag::extract_longest_path(int* path) {
bdd_arc* arc = nullptr;
bdd_node* current_node = nodes[num_vars][0]; // start with target node
for (int l = num_vars; l > 0; l--) {
assert(current_node->cost_arc_id >= 0);
arc = arcs[l-1][current_node->cost_arc_id];
path[l-1] = arc->value;
current_node = nodes[l-1][arc->source];
}
if (debug){
cout << "Longest path = ";
for (int i =0 ; i < num_vars; i++) {
cout << path[i] << " ";
}
cout << endl;
}
}
// =============== LONGEST PATH - END
// =============== MIN-CUT SEPARATION FUNCTIONS - BEGIN
bool bdd_diag::separate_min_cut(double* _cost, double* pi, double& pi0) {
//Get active nodes
get_active_nodes();
// Set values
cost = _cost;
set_values_max_flow();
if(debug){
cout << "Capacity values: ";
for(int i = 0; i < cqd->vars.size(); i++){
cout << cost[i] << " ";
}
cout << endl;
}
// Compute max-flow
double max_flow = 0;
compute_max_flow(max_flow);
// cout << "Weak cut val: " << max_flow << endl;
if (max_flow >= 1 - epsilon) {
//is_max_flow_feasible();
return false;
}
// Get min-cut
get_min_cut_arcs(pi, pi0);
// Double check that point violates constraint (to avoid precision errors)
return is_constraint_violated(pi, pi0);
}
void bdd_diag::get_active_nodes(){
if (!active_nodes.empty()) return;
active_nodes.resize(num_vars + 1, vector<int>() );
int n = 0;
int count = 0;
for (int l = 0; l < num_vars + 1; l++ ) {
n = nodes[l].size();
count = 0;
active_nodes[l].resize(nodes[l].size(), -1);
for (int i = 0; i < n; i++) {
if (nodes[l][i]->is_free) continue;
active_nodes[l][count] = i;
count++;
}
active_nodes[l].resize(count);
}
//check_incoming_arcs();
}
void bdd_diag::check_incoming_arcs() {
int num_nodes = 0;
int node_id = 0;
int count_zero = 0;
int count_one = 0;
for (int l = 1; l <= num_vars; l++ ) {
num_nodes = active_nodes[l].size();
for (int i = 0; i < num_nodes; i++) {
node_id = active_nodes[l][i];
count_zero = 0;
count_one = 0;
for (int j: nodes[l][node_id]->in_arcs) {
if (j%2 == 0) count_zero++;
else count_one++;
}
if((count_zero > 1 && count_one == 0) || (count_zero == 0 && count_one > 1) ){
cout << "Candidate node " << node_id << " layer" << l << " - " << count_zero << " " << count_one << endl;
}
}
}
}
void bdd_diag::set_values_max_flow() {
// Iterate over nodes and outgoing arcs
int num_nodes = 0;
int node_id = 0;
bdd_node* node = nullptr;
for (int layer = 0; layer <= num_vars; layer++) {
num_nodes = active_nodes[layer].size();
for (int i = 0; i < num_nodes; i++) {
node_id = active_nodes[layer][i];
node = nodes[layer][node_id];
node-> visited = false;
node->parent.first = -1;
node->parent.second = -1;
if (layer == num_vars) break;
// Update outgoing arcs
for (int j = 0; j < 2; j++) {
if (arcs[layer][2*node_id +j]->target == -1) continue;
if (j == 0) arcs[layer][2*node_id +j]->res_value = 1 - cost[layer];
else arcs[layer][2*node_id +j]->res_value = cost[layer];
arcs[layer][2*node_id +j]->res_rev_value = 0.0;
}
}
}
}
//Ford-Fulkerson algorithm for max_flow
void bdd_diag::compute_max_flow(double& max_flow) {
double path_flow = 0;
double edge_flow = 0;
int layer = -1;
int node_id = -1;
bool found_path = true;
bool found_edge = true;
bdd_node* node = nullptr;
max_flow = 0;
while(found_path) {
// Find augmentation path
found_path = find_augmenting_path();
if(!found_path) break;
//Get flow in the path
path_flow = 2;
node = nodes[num_vars][0]; //terminal node
layer = num_vars;
node_id = 0;
while ( !(layer == 0 && node_id == 0) ) {
found_edge = false;
if (node->parent.first == layer -1) {
//First cases: layer of parent is previous layer
// Check which outgoing arc of the parent points to the node_id
for (int j =0; j < 2; j++) {
edge_flow = arcs[layer - 1][2*node->parent.second +j]->res_value;
if (arcs[layer - 1][2*node->parent.second +j]->target == node_id && edge_flow >= epsilon ) {
path_flow = min(path_flow, edge_flow);
found_edge = true;
break;
}
}
}
else {
//Second case: layer of parent is next layer
assert(node->parent.first == layer + 1);
// Check which outgoing arc of the parent (new_node) points to new node_id
for (int j =0; j < 2; j++) {
edge_flow = arcs[layer][2*node_id +j]->res_rev_value;
if (arcs[layer][2*node_id +j]->target == node->parent.second && edge_flow >= epsilon) {
path_flow = min(path_flow, edge_flow);
found_edge = true;
break;
}
}
}
assert(found_edge);
//Update values of next node
layer = node->parent.first;
node_id = node->parent.second;
node= nodes[layer][node_id];
}
//Update residual values
node = nodes[num_vars][0]; //terminal node
layer = num_vars;
while ( !(layer == 0 && node_id == 0) ) {
if (node->parent.first == layer -1) {
//First cases: layer of parent is previous layer
// Check which outgoing arc of the parent points to the node_id
for (int j =0; j < 2; j++) {
edge_flow = arcs[layer - 1][2*node->parent.second +j]->res_value;
if (arcs[layer - 1][2*node->parent.second +j]->target == node_id && edge_flow >= epsilon ) {
arcs[layer - 1][2*node->parent.second +j]->res_value -= path_flow;
arcs[layer - 1][2*node->parent.second +j]->res_rev_value += path_flow;
break;
}
}
}
else {
//Second case: layer of parent is next layer
// Check which outgoing arc of the current node that points to new node_id
for (int j =0; j < 2; j++) {
edge_flow = arcs[layer][2*node_id +j]->res_rev_value;
if (arcs[layer][2*node_id +j]->target == node->parent.second && edge_flow >= epsilon) {
arcs[layer][2*node_id +j]->res_rev_value -= path_flow;
arcs[layer][2*node_id +j]->res_value += path_flow;
break;
}
}
}
//Update values of next node
layer = node->parent.first;
node_id = node->parent.second;
node= nodes[layer][node_id];
}
//Update max_flow
max_flow += path_flow;
if (max_flow >= 1 - epsilon) break;
}
if (debug) {
cout << "\t max_flow = "<< max_flow << endl;
}
}
bool bdd_diag::find_augmenting_path() {
// Reset visited nodes
reset_visited_nodes();
queue <pair<int,int> > q_nodes; //(layer, node_id);
q_nodes.push(make_pair(0,0));
nodes[0][0]->visited = true;
int layer = -1;
int node_id = -1;
int target = -1;
int source = -1;
bool found_target = false;
while(!q_nodes.empty()) {
layer = q_nodes.front().first;
node_id = q_nodes.front().second;
q_nodes.pop();
// Iterate over outgoing arcs
for (int j = 0; j< 2; j++) {
target = arcs[layer][node_id*2 + j]->target;
if (target == -1) continue;
if (arcs[layer][node_id*2 + j]->res_value <= epsilon) continue; // residual value is "0"
if (nodes[layer + 1][target]->visited) continue; //target already visited
//Add node to the queue
nodes[layer + 1][target]->visited = true;
nodes[layer + 1][target]->parent.first = layer;
nodes[layer + 1][target]->parent.second = node_id;
q_nodes.push(make_pair(layer + 1, target));
if (layer == num_vars - 1){
found_target = true;
break;
}
}
if (found_target) break;
// Iterate over incoming arcs (for reversible edges)
for (int j : nodes[layer][node_id]->in_arcs) {
if (arcs[layer - 1][j]->res_rev_value <= epsilon) continue; // residual value is "0"
source = arcs[layer - 1][j]->source;
if (nodes[layer - 1][source]->visited) continue; //source already visited
//Add node to the queue
nodes[layer - 1][source]->visited = true;
nodes[layer - 1][source]->parent.first = layer;
nodes[layer - 1][source]->parent.second = node_id;
q_nodes.push(make_pair(layer - 1, source));
}
}
if (found_target) return true;
return false;
}
void bdd_diag::reset_visited_nodes(){
int num_nodes = 0;
int node_id = 0;
bdd_node* node = nullptr;
for (int layer = 0; layer <= num_vars; layer++) {
num_nodes = active_nodes[layer].size();
for (int i = 0; i < num_nodes; i++) {
node_id = active_nodes[layer][i];
node = nodes[layer][node_id];
node->visited = false;
node->parent.first = -1;
node->parent.second = -1;
}
}
}
void bdd_diag::get_min_cut_arcs(double* pi, double& pi0) {
// Reset visited nodes
reset_visited_nodes();
// Compute Visited nodes in residual graph
compute_visited_nodes();
//Get min-cut edges in original graph
int num_nodes = 0;
bdd_node* node = nullptr;
double min_cut = 0;
pi0 = -1;
for (int layer = 0; layer < num_vars; layer++) {
num_nodes = nodes[layer].size();
for (int i = 0; i < num_nodes; i++) {
node = nodes[layer][i];
if (node->is_free || !node->visited) continue;
//Iterate over outgoing arcs
for (int j=0; j < 2; j++) {
if (arcs[layer][2*i+j]->target == -1) continue;
if (nodes[layer + 1][arcs[layer][2*i+j]->target]->visited ) continue;
// Found arc that is part of the min_cut!
if (j == 0) {
min_cut += 1 - cost[layer];
pi[layer] += 1;
pi0 +=1;
}
else {
min_cut += cost[layer];
pi[layer] -= 1;
}
}
}
}
if (debug) {
cout << "\t min_cut = "<< min_cut << endl;
}
}
void bdd_diag::compute_visited_nodes() {
queue <pair<int,int> > q_nodes; //(layer, node_id);
q_nodes.push(make_pair(0,0));
nodes[0][0]->visited = true;
int layer = -1;
int node_id = -1;
int target = -1;
int source = -1;
while(!q_nodes.empty()) {
layer = q_nodes.front().first;
node_id = q_nodes.front().second;
q_nodes.pop();
// Iterate over outgoing arcs
for (int j = 0; j< 2; j++) {
target = arcs[layer][node_id*2 + j]->target;
if (target == -1) continue;
if (arcs[layer][node_id*2 + j]->res_value <= epsilon) continue; // residual value is "0"
if (nodes[layer + 1][target]->visited) continue; //target already visited
//Add node to the queue
nodes[layer + 1][target]->visited = true;
q_nodes.push(make_pair(layer + 1, target));
}
// Iterate over incoming arcs (for reversible edges)
for (int j : nodes[layer][node_id]->in_arcs) {
if (arcs[layer - 1][j]->res_rev_value <= epsilon) continue; // residual value is "0"
source = arcs[layer - 1][j]->source;
if (nodes[layer - 1][source]->visited) continue; //source already visited
//Add node to the queue
nodes[layer - 1][source]->visited = true;
q_nodes.push(make_pair(layer - 1, source));
}
}
}
bool bdd_diag::is_constraint_violated(double* pi, double& pi0) {
double lhs = 0;
for (int i = 0; i < num_vars; i++) {
lhs +=pi[i]*cost[i];
}
return (lhs - pi0 >= epsilon);
}
void bdd_diag::is_max_flow_feasible() {
int num_nodes = 0;
int node_id = 0;
double zero_value = 0.0;
double one_value = 0.0;
bool feasible = true;
for (int layer = 0; layer < num_vars; layer++) {
num_nodes = active_nodes[layer].size();
zero_value = 0.0;
one_value = 0.0;
for (int i = 0; i < num_nodes; i++) {
node_id = active_nodes[layer][i];
//sum_up zero value
if (arcs[layer][node_id*2]->target != -1) {
zero_value += arcs[layer][node_id*2]->res_rev_value;
if (zero_value >= (1 - cost[layer] + epsilon) ){
//cout << 1 - cost[layer] << endl;
feasible = false;
}
}
//sum_up one value
if (arcs[layer][node_id*2 + 1]->target != -1) {
one_value += arcs[layer][node_id*2 + 1]->res_rev_value;
if (one_value >= (cost[layer] + epsilon) ) {
//cout << 1 - cost[layer] << endl;
feasible = false;
}
}
if (!feasible) break;
}
if (!feasible) break;
}
if (feasible) cout << "feasible" << endl;
}
// =============== MIN-CUT SEPARATION FUNCTIONS - END
// =============== TARGET CUTS FUNCTIONS - BEGIN
void bdd_diag::compute_center_point() {
if (overflow) return;
//Initialize structure
count_paths_top.resize(num_vars + 1, vector<long long>() );
count_paths_bottom.resize(num_vars + 1, vector<long long>() );
for (int l = 0; l < num_vars + 1; l++ ) {
count_paths_top[l].resize(nodes[l].size(), 0);
count_paths_bottom[l].resize(nodes[l].size(), 0);
}
//Count paths top & bottom
count_path_top();
if (overflow) return;
count_path_bottom();
assert(count_paths_bottom[0][0] == count_paths_top[num_vars][0] );
//Calculate center point
center_point.resize(num_vars, 0);
int num_nodes = 0;
double num_zero = 0;
double num_one = 0;
int arc_id = 0;
bdd_node* node = nullptr;
for (int l = 0; l < num_vars; l ++) {
num_nodes = nodes[l].size();
num_zero = 0;
num_one = 0;
//Count number of zero and one paths in each layer
for (int i = 0; i < num_nodes; i++) {
if (nodes[l][i]->is_free) continue;
node = nodes[l][i];
//Iterate over outgoing arcs
for (int j = 0; j< 2; j++) {
arc_id = 2*i + j;
if(arcs[l][arc_id]->target == -1) continue;
if (j == 0) {
num_zero += count_paths_top[l][i] * count_paths_bottom[l+1][arcs[l][arc_id]->target];
}
else{
num_one += count_paths_top[l][i] * count_paths_bottom[l+1][arcs[l][arc_id]->target];
}
}
}
center_point[l] = num_one/count_paths_bottom[0][0];
}
}
void bdd_diag::count_path_top() {
int num_nodes = 0;
bdd_node* node = nullptr;
count_paths_top[0][0] = 1;
for (int l = 1; l < num_vars + 1; l++ ) {
num_nodes = nodes[l].size();
for (int i = 0; i < num_nodes; i++) {
node = nodes[l][i];
if (node->is_free) continue;
//Iterate over incoming arcs
for (int arc_id : node->in_arcs) {
count_paths_top[l][i] += count_paths_top[l-1][ arcs[l-1][arc_id]->source ];
if (count_paths_top[l][i] < 0 || count_paths_top[l][i] < count_paths_top[l-1][ arcs[l-1][arc_id]->source ] ) {
cout << " Long overflow - cannot compute center point" << endl;
overflow = true;
return;
}
}
}
}
}
void bdd_diag::count_path_bottom() {
int arc_id = 0;
int num_nodes = 0;
bdd_node* node = nullptr;
count_paths_bottom[num_vars][0] = 1;
for (int l = num_vars - 1; l >= 0; l--) {
num_nodes = nodes[l].size();
for (int i = 0; i < num_nodes; i++) {
node = nodes[l][i];
if (node->is_free) continue;
//Iterate over outgoing arcs
for (int j = 0; j< 2; j++) {
arc_id = 2*i + j;
if(arcs[l][arc_id]->target == -1) continue;
count_paths_bottom[l][i] += count_paths_bottom[l+1][ arcs[l][arc_id]->target ];
}
}
}
}
// =============== TARGET CUTS FUNCTIONS - ENDS
// Export BDD graph
void bdd_diag::export_graph(const char* filename){
cout << "Exporting graph in gml format " << endl;
cout << "\t max_width = " << max_width << "\t,\tmax_layer = "<< num_vars + 1 << endl;
//create file
ofstream bdd_file(filename);
bdd_file << "graph [\n";
bdd_file << "\t directed 1\n";
bdd_file << "\t hierarchic 1\n";
//Print nodes
for (int l = 0; l < num_vars + 1; ++l) {
for (int i = 0; i < nodes[l].size(); i++) {
if (nodes[l][i]->is_free) continue;
bdd_file << "node [ \n";
bdd_file << "\t id " << l * max_width + i << "\n";
bdd_file << "\t label \"" << l << "," << i << "\n";
bdd_file << "\n\tlin = [" << nodes[l][i]->lin_min_top << " , " << nodes[l][i]->lin_max_top << "]"<< endl;
bdd_file << "\tdia = [" << nodes[l][i]->diag_min_top << " , " << nodes[l][i]->diag_max_top << "]"<< endl;
bdd_file << "\"\n";
bdd_file << "\t graphics [ \n";
bdd_file << "\t\t type \"rectangle\"\n";
if (nodes[l][i]->is_exact) {
bdd_file << "\t\t fill \"#cce5ff\" \n"; // light blue -> exact node
}
else if(nodes[l][i]->is_feasible) {
bdd_file << "\t\t fill \"#d8ffcc\" \n"; // light green -> feasible node
}
else{
bdd_file << "\t\t hasFill 0 \n";
}
bdd_file << "\t\tw 110.0";
bdd_file << "\t\th 80.0";
bdd_file << "\t\t ] \n";
bdd_file << "\t ]\n";
}
}
//Print Edges
for (int l = 0; l < num_vars; ++l) {
for (int i = 0; i < arcs[l].size(); i++) {
if(arcs[l][i]->target == -1) continue;
bdd_file << "edge [ \n";
bdd_file << "\t source " << l*max_width + arcs[l][i]->source << "\n";
bdd_file << "\t target " << (l+1)*max_width + arcs[l][i]->target << "\n";
bdd_file << "\t label \"" << arcs[l][i]->value;
if (arcs[l][i]->value == 1)
bdd_file<< " (" << cqd->vars[l] <<") ";
bdd_file << "\"\n";
bdd_file << "\t graphics [ \n";
bdd_file << "\t \t fill \"#000000\" "; //give color to an edge
bdd_file << "\t\ttargetArrow \"diamond\"";
bdd_file << "\t \t ]\n";
bdd_file << "\t ]\n";
}
}
}
//Destructor
bdd_diag::~bdd_diag() {
for (int l = 0; l < num_vars; ++l) {
for (auto & i : arcs[l]) {
delete i;
}
}
for (int l = 0; l < num_vars + 1; ++l) {
for (auto & i : nodes[l]) {
delete i;
}
}
}
| true |
d1ad4edc0a9ee987e5f54a4232733cea5c745bee | C++ | zqnnn/coding-note | /practice/130_maxSlidingWindow.cpp | UTF-8 | 3,299 | 3.734375 | 4 | [] | no_license | //
// Created by zqn on 2019/9/4.
//
#include <vector>
#include <algorithm>
#include <set>
#include <queue>
using namespace std;
//简单粗暴型。。竟然过了
class Solution {
public:
int max_num(vector<int>& nums, int i, int j){
int max_res = 0;
for(int q = i; q < j; q++){
max_res = max(max_res, nums[q]);
}
return max_res;
}
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
if(nums.empty() || k == 0)
return {};
if(k == 1)
return nums;
vector<int> res;
int i = 0, size = nums.size();
while (i <= size - k){
int max = max_num(nums, i, i+k);
res.push_back(max);
i++;
}
return res;
}
};
//我们希望窗口内的数字是有序的,但是每次给新窗口排序又太费时了,所以最好能有一种类似二叉搜索树的结构,
// 可以在 lgn 的时间复杂度内完成插入和删除操作,
// 那么使用 STL 自带的 multiset 就能满足我们的需求,这是一种基于红黑树的数据结构,
// 可以自动对元素进行排序,又允许有重复值,完美契合。
//遍历每个数字,即窗口右移,若超过了k,则需要把左边界值删除,这里不能直接删除 nums[i-k],
// 因为集合中可能有重复数字,我们只想删除一个,而 erase 默认是将所有和目标值相同的元素都删掉,
// 所以我们只能提供一个 iterator,代表一个确定的删除位置,先通过 find() 函数找到左边界 nums[i-k] 在集合中的位置,
// 再删除即可。然后将当前数字插入到集合中,此时看若 i >= k-1,说明窗口大小正好是k,
// 就需要将最大值加入结果 res 中,而由于 multiset 是按升序排列的,最大值在最后一个元素,我们可以通过rbegin() 来取出
vector<int> maxSlidingwindow(vector<int> &nums, int k){
vector<int> res;
multiset<int> st;
for(int i = 0; i < nums.size(); i++){
if(i >= k) st.erase(st.find(nums[i-k]));
st.insert(nums[i]);
if(i >= k-1) res.push_back(*st.rbegin());
}
return res;
}
//我们也可以使用优先队列来做,即最大堆,不过此时我们里面放一个 pair 对儿,由数字和其所在位置组成的,
// 这样我们就可以知道每个数字的位置了,而不用再进行搜索了。在遍历每个数字时,进行 while 循环,
// 假如优先队列中最大的数字此时不在窗口中了,就要移除,判断方法就是将队首元素的 pair 对儿中的 second(位置坐标)跟 i-k 对比,
// 小于等于就移除。然后将当前数字和其位置组成 pair 对儿加入优先队列中。
// 此时看若 i >= k-1,说明窗口大小正好是k,就将最大值加入结果 res 中即可,参见代码如下:
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
vector<int> res;
priority_queue<pair<int, int>> q; //默认是大顶堆
for(int i = 0; i < nums.size(); i++){
while (!q.empty() && q.top().second <= i-k) q.pop();
q.push({nums[i], i});
if(i >= k-1) res.push_back(q.top().first);
}
return res;
}
int main(){
vector<int> num = {1,-1};
maxSlidingwindow(num, 1);
} | true |
d0ff0740373f6827403ef1d5f9f8603b20aa7e47 | C++ | CZ-CE3004-MDP-Group10/MDP-Group-10 | /Arduino/Libraries/Sensors/Sensors_Read_Sensor_Analog.cpp | UTF-8 | 1,623 | 3.609375 | 4 | [] | no_license | // MULTIDISCIPLINARY DESIGN PROJECT SEMESTER 2 YEAR 20-21 GROUP 10 SENSORS READ ANALOG VALUES FROM SENSORS FILE.
// Include the sensors header file.
#include "Sensors.h"
// Read and obtain the average of all sensor's analog values.
void Sensors::readSensor()
{
sensorA0_avg = 0;
sensorA1_avg = 0;
sensorA2_avg = 0;
sensorA3_avg = 0;
sensorA4_avg = 0;
sensorA5_avg = 0;
// Take 20 readings from each sensor.
for(int count = 0; count < 20; count++)
{
// Read the analog value of each sensor and accumulate them for averaging.
sensorA0_list[count] = analogRead(A0);
sensorA1_list[count] = analogRead(A1);
sensorA2_list[count] = analogRead(A2);
sensorA3_list[count] = analogRead(A3);
sensorA4_list[count] = analogRead(A4);
sensorA5_list[count] = analogRead(A5);
}
// Sort the sensor analog readings from lowest to highest.
sortReadings(sensorA0_list);
sortReadings(sensorA1_list);
sortReadings(sensorA2_list);
sortReadings(sensorA3_list);
sortReadings(sensorA4_list);
sortReadings(sensorA5_list);
// Take only the middle 10 readings out of the 20 samples for each sensor.
for(int i = 5; i < 15; i++)
{
sensorA0_avg += sensorA0_list[i];
sensorA1_avg += sensorA1_list[i];
sensorA2_avg += sensorA2_list[i];
sensorA3_avg += sensorA3_list[i];
sensorA4_avg += sensorA4_list[i];
sensorA5_avg += sensorA5_list[i];
}
// Obtain the average of the values of each sensor.
sensorA0_avg /= 10;
sensorA1_avg /= 10;
sensorA2_avg /= 10;
sensorA3_avg /= 10;
sensorA4_avg /= 10;
sensorA5_avg /= 10;
// Perform analog values to distance in cm conversion.
calculateDistance();
}
| true |
2f436eb7ca64e3f00e572e255a280af7a7d0d0a9 | C++ | YavuzSelimGugen/BusCardSystem | /kod/main.cpp | UTF-8 | 7,425 | 2.671875 | 3 | [] | no_license | #include <iostream>
#include "person.h"
#include "admin.h"
#include "user.h"
using namespace std;
//Ön tanımlar.
void menu(person *dizi[10]);
void adminPanel(int i, person *dizi[10]);
void adminGiris(person *dizi[10]);
void userPanel(int i, person *dizi[10]);
//Admin panelinde işlemler yapıldıktan sonra y/n işlemini yapar.
void admingecis(int i,person *dizi[10]){
char cevap;
cout<<"Ana menuye devam etmek icin y/n";
cin>>cevap;
if(cevap == 'y'){
menu(dizi);
} else if (cevap == 'n'){
adminPanel(i,dizi);
}
}
//User panelinde işlemler yapıldıktan sonra anamenüye gidilip gidilmeyeceğini kontrol eder.
void usergecis(int i,person *dizi[10]){
char cevap;
cout<<"Anamenuye devam etmek icin y/n";
cin>>cevap;
if(cevap == 'y'){
menu(dizi);
} else if (cevap == 'n'){
userPanel(i,dizi);
}
}
//Admin işlemlerinin yapıldığı panel.
void adminPanel(int i, person *dizi[10]){
system("cls");
int girdi;
admin *admin1 = (admin *)dizi[i];
cout<< "1) Kullanici olustur."<<endl;
cout<< "2) Kullanici sil."<<endl;
cout<< "3) Kullanici durumunu goster."<<endl;
cout<< "4) Kullanici bul."<<endl;
cout<< "5) Kullanici kartlarini birlestir."<<endl;
cout<< "6) Kullanici bilgilerini degistir."<<endl;
cout<< "7) Ana menuye don."<<endl;
cin>>girdi;
string ad,soyad;
int tc;
user *u1 = new user();
if(girdi == 1){
system("cls");
cout<<"Kullanici adini giriniz:";
cin>>ad;
cout<<"Kullanici soyadini giriniz: ";
cin>>soyad;
cout<<"Tc girniz: ";
cin>>tc;
admin1->CreateUser(ad,soyad,tc,dizi);
admingecis(i,dizi);
} else if( girdi == 2){
system("cls");
cout<<"Silinecek kullanicinin Tc nosunu giriniz: ";
cin>>tc;
admin1->DeleteUser(tc, dizi);
admingecis(i,dizi);
} else if (girdi == 3){
system("cls");
cout<<"aragidin tc yi gir: ";
cin>>tc;
u1 = admin1->FindUser(tc,dizi);
admin1->ShowUserState(u1);
admingecis(i,dizi);
} else if (girdi == 4){
system("cls");
cout<<"aragidin tc yi gir: ";
cin>>tc;
u1 = admin1->FindUser(tc,dizi);
admin1->ShowPersonState(u1);
admingecis(i,dizi);
} else if (girdi == 5) {
system("cls");
cout<<"Kullanici tc yi gir: ";
cin>>tc;
u1 = admin1->FindUser(tc,dizi);
admin1->CombineUserCards(u1);
admingecis(i,dizi);
} else if (girdi == 6) {
system("cls");
cout<<"Kullanici tc yi gir: ";
cin>>tc;
u1 = admin1->FindUser(tc,dizi);
cout<<u1->getName()<<u1->getSurname()<<" isimli kullancinin degistirmek istediginiz Adini giriniz:"<<endl;
cin>>ad;
u1->setName(ad);
cout<<u1->getName()<<u1->getSurname()<<" isimli kullancinin degistirmek istediginiz Soyadini giriniz:"<<endl;
cin>>soyad;
u1->setSurname(soyad);
cout<<"Guncellenmis ad, soyad: "<<u1->getName()<<u1->getSurname();
admingecis(i,dizi);
} else if (girdi == 7) {
menu(dizi);
} else {
cout<< "Yanlis girdi!"<<endl;
adminPanel(i,dizi);
}
}
//Ana menüden gelen kullanıcının admin olup olmadığını kontrol eder.
void adminGiris(person *dizi[10]){
system("cls");
int tc,i,boo=0;
cout<<"Yonetici TC giriniz:"<<endl;
cin>>tc;
for (i = 0; i < 10; ++i) {
if (dizi[i]->getTc()==tc && dizi[i]->getPersonType()==Admin){
cout<<"Yonetici girisi basarili"<<endl;
adminPanel(i,dizi);
boo = 1;
break;
}
}
if(boo == 0){
cout<<"Araginiz Tc de bir yonetici bulunmamaktadir."<<endl;
menu(dizi);
}
}
//Kullanıcı işlemlerinin yapıldığı sekme.
void userPanel(int i, person *dizi[10]){
system("cls");
int girdi;
user *user1 = (user *)dizi[i];
cout<< "1) Bakiye yukle."<<endl;
cout<< "2) Kart okut."<<endl;
cout<< "3) Kart durumunu goster."<<endl;
cout<< "4) Ana Menu."<<endl;
cin>>girdi;
if(girdi == 1){
int bakiye,k;
cout<<"Hangi kart ? 1/2"<<endl;
cin>>k;
if(k == 1){
cout<<"yuklemek istediginiz miktari giriniz:";
cin>>bakiye;
user1->LoadBalance((user1->getCard1()),bakiye);
cout<<"yukleme islemi basarili yeni bakiyeniz: "<<user1->getCard1()->getBalance()<<endl;
} else if (k == 2){
cout<<"yuklemek istediginiz miktari giriniz:";
cin>>bakiye;
user1->LoadBalance((user1->getCard2()),bakiye);
cout<<"yukleme islemi basarili yeni bakiyeniz: "<<user1->getCard2()->getBalance()<<endl;
} else {
cout<<"Yanlis girdi!!!"<<endl;
menu(dizi);
}
usergecis(i,dizi);
} else if (girdi == 2){
int k;
cout<<"Hangi kart ? 1/2"<<endl;
cin>>k;
if(k == 1){
user1->ReadCard((user1->getCard1()));
} else if (k == 2) {
user1->ReadCard((user1->getCard2()));
} else {
cout<<"Yanlis girid!!!"<<endl;
menu(dizi);
}
usergecis(i,dizi);
} else if (girdi == 3){
user1->ShowCardState();
usergecis(i,dizi);
} else if (girdi ==4){
menu(dizi);
} else {
cout<<"yanlis girdi!!!"<<endl;
userPanel(i,dizi);
}
}
//Girilen tc nin kullanıcı olup olmadığını kontrol eder.
void userGiris(person *dizi[10]){
system("cls");
int tc,i,boo=0;
cout<<"Kullanici TC giriniz:"<<endl;
cin>>tc;
for (i = 0; i < 10; ++i) {
if (dizi[i]->getTc()==tc && dizi[i]->getPersonType()==User){
cout<<"Kullanici girisi basarili"<<endl;
userPanel(i,dizi);
boo = 1;
break;
}
}
if(boo == 0){
cout<<"Araginiz Tc de bir kullanici bulunmamaktadir."<<endl;
menu(dizi);
}
}
//Menu akışını sağlar.
void menu(person *dizi[10]){
system("cls");
puts("<<GidereGidere Turizm>>");
int secim;
printf("1)\tYonetici islemleri.\n");
printf("2)\tKullanici islemleri.\n");
printf("3)\tCikis.\n");
cin>>secim;
printf("seciminiz %d\n",secim);
if(secim == 1){
adminGiris(dizi);
} else if (secim == 2) {
userGiris(dizi);
} else if (secim == 3) {
return;
} else {
puts("Gecersiz girdi.");
menu(dizi);
}
}
//Program başlangıcındaki diziyi doldurur.
void fillPersons(person *dizi[10]){
for (int i = 0; i <10 ; i++) {
person *p = new person();
dizi[i] = p ;
dizi[i]->setTc(0);
}
admin *admin1 = new admin();
admin1->setName("Hakki");
admin1->setSurname("Hakili");
admin1->setPersonType(1);
admin1->setTc(1234);
user *user1 = new user();
user1->setName("Selin");
user1->setSurname("sakli");
user1->setTc(4321);
user1->setPersonType(0);
card *card1 = new card();
card1->setBalance(10000);
card1->setCardType(1);
card *card2 = new card();
card2->setBalance(200);
card2->setCardType(1);
user1->setCard1(card1);
user1->setCard2(card2);
dizi[0] = admin1;
dizi[1] = user1;
}
int main() {
person *dizi[10];
fillPersons(dizi);
menu(dizi);
return 0;
} | true |
b6ca66b03b4731779437bf7d49f611d51552fc18 | C++ | AlexeiRubin/CDAC_ACTS | /ADS/15_JUL_2020/Assignment_3_Bitset.cpp | UTF-8 | 385 | 2.625 | 3 | [] | no_license | #include <bits/stdc++.h>
#define MAX_OF_RANGE 100
using namespace std;
int main()
{
int N;
bitset<MAX_OF_RANGE> arr;
cin >> N;
while(N != 0)
{
if(arr[N - 1] != 0)
cout << "Duplicate Entry of : " << N << endl;
else
arr[N - 1] = 1;
cin >> N;
}
return 0;
} | true |
5d227cff0972339fbbee33d5ff866b5e6da7efaa | C++ | Wayne-Zen/practice | /basket/basket.hh | UTF-8 | 1,331 | 3.359375 | 3 | [] | no_license | #ifndef BASKET_HH
#define BASKET_HH
#include <memory>
#include <set>
#include <iostream>
#include "quote.hh"
#include "print_total.hh"
namespace {
class Basket {
public:
void AddItem(const Quote& sale) {
items_.insert(std::shared_ptr<Quote>(sale.clone()));
}
void AddItem(Quote&& sale) {
items_.insert(std::shared_ptr<Quote>(std::move(sale).clone()));
}
// prints the total price for each book and the overall total for all items in the basket
double TotalReceipt(std::ostream& os) const {
double sum{0.0};
// upper_bound returns an iterator to the element just past the end of that batch
// skip over all the elements that match the current key
for (auto iter = items_.cbegin(); iter != items_.cend();
iter = items_.upper_bound(*iter)) {
sum += PrintTotal(os, **iter, items_.count(*iter));
}
os << "Total Sale: " << sum << std::endl;
return sum;
}
private:
// function to compare shared_ptrs needed by the multiset member
static bool compare(const std::shared_ptr<Quote>& lhs,
const std::shared_ptr<Quote>& rhs) {
return lhs->isbn() < rhs->isbn();
}
// multiset to hold nultiple quotes, ordered by the compare member
// pass compare function for initializing
std::multiset<std::shared_ptr<Quote>, decltype(compare)*> items_{compare};
};
}
#endif | true |
734ea2b7db7d80cdbf21d3dde2a794ecdeb38511 | C++ | Saragimaru/ipol_cpp | /src_test/test_polsym.cpp | UTF-8 | 3,247 | 2.8125 | 3 | [] | no_license | #include <stdio.h> /* printf */
#include <time.h>
#include <iostream>
#include <math.h>
void polleg(int const, double const *, int const, double *);
void polqkm(int const, int const, double const *, int const, double *);
void polrtm(int const, int const, double const *, int const, double *, double *);
void main()
{
double *px, *mx, *pk_plus, *pk_minus, *r_plus, *r_minus, *t_plus, *t_minus;
int ix, ik, nx, nk, im, m;
double dx, p_plus, p_minus, dp, csym, csymR, csymT,
sum_dPk, sum_dQkm, sum_dRkm, sum_dTkm;
//
double start = (double)clock() / (double)CLOCKS_PER_SEC;
//
nk = 21;
nx = 5;
dx = 0.2;
pk_plus = new double[nk*nx];
pk_minus = new double[nk*nx];
r_plus = new double[nk*nx];
r_minus = new double[nk*nx];
t_plus = new double[nk*nx];
t_minus = new double[nk*nx];
//
px = new double[nx];
mx = new double[nx];
//
px[0] = 1.0;
mx[0] = -1.0;
printf("ix = %i +x =%5.2f -x = %5.2f \n", 1, px[0], mx[0]);
for (ix = 1; ix < nx; ix++) {
px[ix] = px[ix - 1] - dx;
mx[ix] = mx[ix - 1] + dx;
printf("ix = %i +x =%5.2f -x = %5.2f \n", ix+1, px[ix], mx[ix]);
}
printf("\n \n");
//------------------------------------------------------------------------------
//
polleg(nk-1, px, nx, pk_plus);
polleg(nk-1, mx, nx, pk_minus);
sum_dPk = 0.0;
for (ix = 0; ix < nx; ix++) {
for (ik = 0; ik < nk; ik++) {
p_plus = pk_plus[ix*nk+ik];
p_minus = pk_minus[ix*nk+ik];
csym = pow(-1.0, ik);
sum_dPk += fabs(p_plus - csym * p_minus);
}
}
printf("Pk(x), k = 0:%i, sum_dp = %10.1e \n", nk - 1, sum_dPk);
//------------------------------------------------------------------------------
//
sum_dQkm = 0.0;
m = 19;
for (im = 1; im < m; im++) {
polqkm(im, nk - 1, px, nx, pk_plus);
polqkm(im, nk - 1, mx, nx, pk_minus);
for (ix = 0; ix < nx; ix++) {
for (ik = 0; ik < nk; ik++) {
p_plus = pk_plus[ix*nk + ik];
p_minus = pk_minus[ix*nk + ik];
csym = pow(-1.0, ik + im);
sum_dQkm += fabs(p_plus - csym * p_minus);
}
}
}
printf("Qkm(x), k = 0:%i, m = 1:%i, sum_dq = %10.1e \n", nk - 1, m, sum_dQkm);
//------------------------------------------------------------------------------
//
sum_dRkm = 0.0;
sum_dTkm = 0.0;
m = 19;
for (im = 1; im < m; im++) {
polrtm(im, nk - 1, px, nx, r_plus, t_plus);
polrtm(im, nk - 1, mx, nx, r_minus, t_minus);
for (ix = 0; ix < nx; ix++) {
for (ik = 0; ik < nk; ik++) {
// Rkm(x)
p_plus = r_plus[ix*nk + ik];
p_minus = r_minus[ix*nk + ik];
csymR = pow(-1.0, ik + im);
sum_dRkm += fabs(p_plus - csymR * p_minus);
// Tkm(x)
p_plus = t_plus[ix*nk + ik];
p_minus = t_minus[ix*nk + ik];
csymT = -pow(-1.0, ik + im);
sum_dTkm += fabs(p_plus - csymT * p_minus);
}
}
}
printf("Rkm(x), k = 0:%i, m = 1:%i, sum_dr = %10.1e \n", nk - 1, m, sum_dRkm);
printf("Tkm(x), k = 0:%i, m = 1:%i, sum_dt = %10.1e \n", nk - 1, m, sum_dTkm);
//------------------------------------------------------------------------------
//
double end = (double)clock() / (double) CLOCKS_PER_SEC;
//
printf("\n");
printf("cpu time %fs \n", end - start);
printf("Done! \n");
system("pause");
} | true |
9c3f8c5fadd5720915a4707845b47a329f7ad621 | C++ | Barbuseries/IAJV_TP1 | /EntityNames.h | UTF-8 | 449 | 2.9375 | 3 | [] | no_license | #ifndef NAMES_H
#define NAMES_H
#include <string>
enum
{
ent_Nobody,
ent_Miner_Bob,
ent_Elsa,
ent_Drunkard_Clay,
ent_Barman,
MAX_ENTITY_INDEX
};
inline std::string GetNameOfEntity(int n)
{
switch(n)
{
case ent_Miner_Bob:
return "Miner Bob";
case ent_Elsa:
return "Elsa";
case ent_Drunkard_Clay:
return "Clay";
case ent_Barman:
return "Barman";
default:
return "UNKNOWN!";
}
}
#endif | true |
1bc8a37293c05cc615ac8f3e8e968306cc84468e | C++ | inmatarian/freezzt | /src/fileListModel.cpp | UTF-8 | 4,681 | 2.84375 | 3 | [
"MIT"
] | permissive | /**
* @file
* @author Inmatarian <inmatarian@gmail.com>
* @section LICENSE
* Insert copyright and license information here.
*/
#include <string>
#include <vector>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <algorithm>
#include <cassert>
#include "debug.h"
#include "zstring.h"
#include "fileListModel.h"
struct FileTuple
{
ZString name;
ZString data;
bool isDirectory;
FileTuple( const ZString &n, const ZString d, bool i )
: name(n), data(d), isDirectory(i) {/* */};
bool operator<( const FileTuple &other ) const
{
if ( this->isDirectory && !other.isDirectory ) return true;
if ( !this->isDirectory && other.isDirectory ) return false;
return ( (this->name.lower()) < (other.name.lower()) );
};
};
// -------------------------------------
class DirList
{
public:
DirList( const ZString &dirpath );
~DirList();
bool next();
const ZString & currentName() const;
const ZString & currentPath() const;
bool currentIsDirectory() const;
bool currentIsValid() const;
private:
DIR *dir;
struct dirent *ent;
ZString path;
ZString c_fullpath;
ZString c_shortname;
bool c_valid;
bool c_dir;
};
DirList::DirList( const ZString &dirpath )
: dir(0), ent(0), path(dirpath), c_valid(false), c_dir(false)
{
dir = opendir( path.c_str() );
if ( !dir ) zwarn() << "Error listing" << dir;
}
DirList::~DirList()
{
if ( dir ) closedir( dir );
}
bool DirList::next()
{
if ( !dir ) return false;
ent = readdir( dir );
if ( ent )
{
struct stat inode;
c_shortname = ZString(ent->d_name);
c_fullpath = path + "/" + ZString(ent->d_name);
if ( stat(c_fullpath.c_str(), &inode) == 0 &&
c_shortname != "." )
{
if ( S_ISDIR(inode.st_mode) ) {
c_valid = true;
c_dir = true;
c_shortname += "/";
}
else if ( S_ISREG(inode.st_mode) ) {
c_valid = true;
c_dir = false;
}
else {
c_valid = false;
c_dir = false;
}
}
else {
c_valid = false;
c_dir = false;
}
return true;
}
return false;
}
const ZString & DirList::currentName() const
{
return c_shortname;
}
const ZString & DirList::currentPath() const
{
return c_fullpath;
}
bool DirList::currentIsDirectory() const
{
return c_dir;
}
bool DirList::currentIsValid() const
{
return c_valid;
}
// -------------------------------------
class FileListModelPrivate
{
public:
FileListModelPrivate( FileListModel *pSelf );
void makeDirList( const ZString &dir );
static ZString cwd();
public:
std::vector<FileTuple> fileList;
private:
FileListModel *self;
};
FileListModelPrivate::FileListModelPrivate( FileListModel *pSelf )
: self( pSelf )
{
/* */
}
void FileListModelPrivate::makeDirList( const ZString &dir )
{
fileList.clear();
DirList dirlist(dir);
while ( dirlist.next() )
{
if ( !dirlist.currentIsValid() ) continue;
fileList.push_back( FileTuple( dirlist.currentName(),
dirlist.currentPath(),
dirlist.currentIsDirectory() ) );
}
sort( fileList.begin(), fileList.end() );
}
ZString FileListModelPrivate::cwd()
{
char *c = new char[PATH_MAX];
c[0] = 0;
char *r = getcwd(c, PATH_MAX);
assert(r);
ZString d(c);
delete[] c;
return d;
}
// -------------------------------------
FileListModel::FileListModel()
: d( new FileListModelPrivate(this) )
{
d->makeDirList( d->cwd() );
}
FileListModel::~FileListModel()
{
delete d;
d = 0;
}
ZString FileListModel::getTitleMessage() const
{
return ZString("Load World");
}
ZString FileListModel::getLineMessage( int line ) const
{
if ( line < 0 || line >= lineCount() ) {
return ZString();
}
return d->fileList.at(line).name;
}
ZString FileListModel::getLineData( int line ) const
{
if ( line < 0 || line >= lineCount() ) {
return ZString();
}
return d->fileList.at(line).data;
}
bool FileListModel::isCentered( int line ) const
{
return false;
}
bool FileListModel::isHighlighted( int line ) const
{
if ( line < 0 || line >= lineCount() ) return false;
return d->fileList.at(line).isDirectory;
}
AbstractScrollModel::Action FileListModel::getAction( int line ) const
{
if ( line < 0 || line >= lineCount() ) {
return None;
}
return d->fileList.at(line).isDirectory
? ChangeDirectory
: LoadFile;
}
int FileListModel::lineCount() const
{
return d->fileList.size();
}
void FileListModel::setDirectory( const ZString &dir )
{
if ( dir.empty() ) return;
d->makeDirList( dir );
}
| true |
b404c93a59bfc2fe44a727f27a01524d5ce90801 | C++ | avast/retdec | /include/retdec/llvmir2hll/hll/output_manager.h | UTF-8 | 3,640 | 2.546875 | 3 | [
"MIT",
"Zlib",
"JSON",
"LicenseRef-scancode-unknown-license-reference",
"MPL-2.0",
"BSD-3-Clause",
"GPL-2.0-only",
"NCSA",
"WTFPL",
"BSL-1.0",
"LicenseRef-scancode-proprietary-license",
"Apache-2.0"
] | permissive | /**
* @file include/retdec/llvmir2hll/hll/output_manager.h
* @brief A base class of all output managers.
* @copyright (c) 2019 Avast Software, licensed under the MIT license
*/
#ifndef RETDEC_LLVMIR2HLL_HLL_OUTPUT_MANAGER_H
#define RETDEC_LLVMIR2HLL_HLL_OUTPUT_MANAGER_H
#include <string>
#include "retdec/llvmir2hll/support/types.h"
namespace retdec {
namespace llvmir2hll {
/**
*
*/
class OutputManager
{
// Ctors, dtros.
public:
virtual ~OutputManager();
virtual void finalize();
// Configuration methods.
//
public:
void setCommentPrefix(const std::string& prefix);
const std::string& getCommentPrefix() const;
void setOutputLanguage(const std::string& lang);
const std::string& getOutputLanguage() const;
// Tokens.
//
public:
// new line
virtual void newLine() = 0;
// any whitespace
virtual void space(const std::string& space = " ") = 0;
// e.g. (){}[];
virtual void punctuation(char p) = 0;
// e.g. == - + * -> .
virtual void operatorX(const std::string& op) = 0;
// identifiers
virtual void globalVariableId(const std::string& id) = 0;
virtual void localVariableId(const std::string& id) = 0;
virtual void memberId(const std::string& id) = 0;
virtual void labelId(const std::string& id) = 0;
virtual void functionId(const std::string& id) = 0;
virtual void parameterId(const std::string& id) = 0;
// other
virtual void keyword(const std::string& k) = 0;
virtual void dataType(const std::string& t) = 0;
virtual void preprocessor(const std::string& p) = 0;
virtual void include(const std::string& i) = 0;
// constants
virtual void constantBool(const std::string& c) = 0;
virtual void constantInt(const std::string& c) = 0;
virtual void constantFloat(const std::string& c) = 0;
virtual void constantString(const std::string& c) = 0;
virtual void constantSymbol(const std::string& c) = 0;
virtual void constantPointer(const std::string& c) = 0;
// comment_prefix comment
virtual void comment(
const std::string& comment) = 0;
// Special methods.
//
public:
// Any token added to the end of the line is going to be a comment.
virtual void commentModifier() = 0;
/// Associates all subsequently added tokens with the passed address.
/// Intended to be used in pair with \c addressPop().
/// Every addressPush() must have a corresponding addressPop() that
/// always gets executed (e.g. cannot be skipped because of early
/// function return or similar).
/// Together, these methods are designed to recursively encapsulate
/// token blocks with the same address.
virtual void addressPush(Address a) = 0;
/// Associates all subsequently added tokens with address that was used
/// before the last addressPush(addr).
virtual void addressPop() = 0;
// Helpers to create more complex token sequences.
//
public:
// [space]op[space]
virtual void operatorX(
const std::string& op,
bool spaceBefore,
bool spaceAfter);
// indent// comment
virtual void comment(
const std::string& comment,
const std::string& indent);
// [indent]// comment\n
virtual void commentLine(
const std::string& comment,
const std::string& indent = "");
// [indent]#include <include>[ // comment]
virtual void includeLine(
const std::string& header,
const std::string& indent = "",
const std::string& comment = "");
// [indent]typedef t1 t2;
virtual void typedefLine(
const std::string& indent,
const std::string& t1,
const std::string& t2);
// Data.
//
private:
std::string _commentPrefix;
std::string _outLanguage;
};
} // namespace llvmir2hll
} // namespace retdec
#endif
| true |
1c5b4f37eb4f3c5414e54c5362e39228a28b3619 | C++ | nandohdc/INF1010 | /T7 - Grafos/maze.cpp | UTF-8 | 3,326 | 3.046875 | 3 | [] | no_license | #include "maze.h"
#include <fstream>
#include <random>
#include <iostream>
#include <algorithm>
#include "unionfind.h"
#include "graph.h"
int randomInt( int from, int to )
{
std::random_device rand_dev;
std::mt19937 generator(rand_dev());
std::uniform_int_distribution<int> distr(from, to);
return distr(generator);
}
void createMaze( int m, int n, std::vector< bool >& maze )
{
int nElementsWall = 0;
//Calculo do numero de paredes uteis.
nElementsWall = (2 * (m*n)) - 1;
//Criando o vetor de paredes uteis
std::vector<int> walls = std::vector<int>(nElementsWall, 1);
//Criando union que representas as celulas, com tamanho MxN
UnionFind *_union = new UnionFind(m*n);
while (_union->getNumSets() != 1) {
int selectedWall = randomInt(0, nElementsWall);
if (selectedWall % 2 == 0) { // eh par
if ((selectedWall + 2) % m != 0) {// nao eh borda
if (_union->find((selectedWall / 2) - 1) != _union->find(selectedWall / 2) + 1 && (maze[selectedWall] != true)) {
maze[selectedWall] = !maze[selectedWall];
_union->makeUnion(((selectedWall / 2) - 1), ((selectedWall / 2) + 1));
}
}
}
else {
if (selectedWall <= ((m*n * 2) - (m * 2))) {// nao eh borda
if (_union->find((selectedWall / 2) - 1) != _union->find((selectedWall / 2) + 1) && maze[selectedWall] != true) {
maze[selectedWall] = !maze[selectedWall];
_union->makeUnion(((selectedWall / 2) - 1), ((selectedWall / 2) + 1));
}
}
}
}
}
void drawMaze( const std::vector< bool >& maze, int m, int n )
{
//Linha de cima
std::cout << "+";
for( int j = 0; j < m; j++ )
std::cout << "---+";
for( int i = 0; i < n; i++ )
{
int pos = i*2*m;
std::cout << std::endl << "|";
for( int j = 0; j < m; j++ )
{
std::cout << " ";
std::cout << (maze[pos] ? "|" : " ");
pos+=2;
}
std::cout << std::endl << "+";
pos=i*2*m+1;
for( int j = 0; j < m; j++ )
{
std::cout << (maze[pos] ? "---" : " ") << "+";
pos+=2;
}
}
std::cout<< std::endl;
}
void printMaze( const std::vector< bool >& maze )
{
if( !maze.empty() )
{
for( size_t i = 0; i < maze.size()-1; i+=2 )
{
std::cout << i/2 << " "
<< (maze[i+0] ? 1 : 0) << " "
<< (maze[i+1] ? 1 : 0) << std::endl;
}
}
}
Graph createGraph( const std::vector<bool>& maze, int m, int n )
{
int size = m*n;
Graph mazeGraph(size);
for( int i = 0; i < n; i++ )
{
for( int j = 0; j < m; j++ )
{
int cell1 = i*m+j;
if( !maze[cell1*2] && (cell1+1)%m!=0 )
mazeGraph.insertEdge(cell1,cell1+1);
if( !maze[cell1*2+1] && cell1<(size-m) )
mazeGraph.insertEdge(cell1,cell1+m);
}
}
return mazeGraph;
}
void findStartEnd(const std::vector<bool>& maze, int m, int n, int& start, int& end)
{
//Cria o grafo que representa o labirinto
Graph mazeGraph = createGraph(maze, m, n);
//TODO: Encontrar entrada e saida
/*Eu sei que para resolver o labirinto deveriamos usar o algoritmo de BFS,
porem eu fiquei em duvida e nao soube como aplica-lo aqui.
*/
start = 13;
end = 1;
}
| true |
bc8b7875f2bf2fecaac80d60a84baaf4a505bdff | C++ | thtfive/USACO_Training | /pancakes/pancakes.cpp | UTF-8 | 2,026 | 2.71875 | 3 | [] | no_license | /*
ID:thtfive
LANG:C++
*/
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int partition(int *array,int p,int q)
{
int i=p-1;
for (int j=p;j<q;j++)
{
if(array[j]>array[q])
{
i++;
int tmp=array[j];
array[j]=array[i];
array[i]=tmp;
}
}
int tmp=array[q];
array[q]=array[i+1];
array[i+1]=tmp;
return i+1;
}
void quick_sort(int *array,int start,int end)///descend sort
{
if (start<end)
{
int mid=partition(array,start,end);
quick_sort(array,start,mid-1);
quick_sort(array,mid+1,end);
}
}
int main()
{
ifstream fin("B-small-attempt0.in");
ofstream fout("B-small-attempt0.out");
int T;
fin>>T;
for (int Test=1;Test<=T;Test++)
{
int D;
fin>>D;
int Pan[1001];
int record[1001];
for (int i=0;i<=1000;i++)
{
Pan[i]=0;
}
int tmp;
int maxnum=0;
for (int i=0;i<D;i++)
{
fin>>tmp;
Pan[tmp]++;
if(maxnum<tmp)maxnum=tmp;
}
int min_time=maxnum;///the upper bound of eating time is maxnum
int punish_time=0;///punish_time initial is 0
int idx=3;
while(idx<maxnum)
{
punish_time+=Pan[maxnum];
if(maxnum%2==0)
{
Pan[maxnum/2]+=Pan[maxnum]*2;
}
else
{
Pan[maxnum/2]+=Pan[maxnum];
Pan[maxnum/2+1]+=Pan[maxnum];
}
Pan[maxnum]=0;
while(Pan[maxnum]==0)maxnum--;
// cout<<"maxnum: "<<maxnum<<" punish_time:"<<punish_time<<" min_time:"<<punish_time+maxnum<<endl;
// cout<< "punish_time:"<<punish_time<<" maxnum: "<<maxnum<<endl;
min_time=min_time<punish_time+maxnum?min_time:punish_time+maxnum;
}
cout<<"Case #"<<Test<<": "<<min_time<<"\n";
}
return 0;
}
| true |
811362aec054ad24b20bc858e5451e02bd4e1e44 | C++ | akkk12/CodingQuestions | /recursion/PhoneKeypad.cpp | UTF-8 | 674 | 3.28125 | 3 | [] | no_license | #include<iostream>
using namespace std ;
char keypad[][10] = {" ", " ","ABC","DEF","GHI","JKL","MNO","PQRS","TUV","WXYZ"};
void generateNames(char *in , char *out , int i , int j ){
if(in[i] =='\0'){
out[i] ='\0';
cout<<out<<endl;
return ;
}
int digit = in[i] - '0';
if(digit == 0 || digit == 1){
generateNames(in,out,i+1,j);
}
for(int k = 0 ;keypad[digit][k] !='\0' ; k++){
out[i] = keypad[digit][k] ;
generateNames(in,out,i+1,j+1);
}
return ;
}
int main(){
int n ;
char input[1000];
cin>>input ;
n = sizeof(input)/sizeof(char);
char output[1000];
generateNames(input,output,0,0);
}
| true |
a5897c7ab3f89fabf45e4d6d9c7545be46448e56 | C++ | oknashar/Problem-Solving | /CodeFights Challenges/roadsBuilding.cpp | UTF-8 | 832 | 2.71875 | 3 | [] | no_license | // problem link : https://codefights.com/arcade/graphs-arcade/kingdom-roads/nCMisf4ZKpDLdHevE/
// solution by : youssef_ali
// codefights profile : https://codefights.com/profile/youssef_ali
std::vector<std::vector<int>> roadsBuilding(int cities, std::vector<std::vector<int>> roads) {
std::vector<std::vector<int>> ret;
bool adjMat[cities][cities];
// initialize idjMat
memset(adjMat, false, sizeof adjMat);
for(int i = 0; i < roads.size(); i++) {
adjMat[roads[i][0]][roads[i][1]] = true;
adjMat[roads[i][1]][roads[i][0]] = true;
}
for(int i = 0; i < cities; i++) for(int j = i+1; j < cities; j++)
if(adjMat[i][j] == 0){
std::vector<int> v(2);
v[0] = i;
v[1] = j;
ret.push_back(v);
}
return ret;
}
| true |
d369f3ab187dc1dab84c9dcf8dfb530dbc6f964b | C++ | dinhtuyen3011/cpp | /OOP Concepts/1. Sources/Exceptions_DAO_02.cpp | UTF-8 | 392 | 3.375 | 3 | [] | no_license | /* Trying to delete pointer to a local stack allocated variable. */
#include <bits/stdc++.h>
using namespace std;
int main()
{
int x;
int* ptr1 = &x;
// x is present on stack frame as
// local variable, only dynamically
// allocated variables can be destroyed
// using delete operator
delete ptr1;
return 0;
}
/* Output */
Runtime error
| true |
826446a555742e8bbeebac83b8723411b4300bcf | C++ | vtil-project/VTIL-Core | /VTIL-Common/util/task.hpp | UTF-8 | 3,383 | 2.921875 | 3 | [] | permissive | #pragma once
#include <thread>
#include <future>
#include <optional>
#include <memory>
#include "type_helpers.hpp"
// [Configuration]
// Determine whether or not to use thread pooling for tasks.
//
#ifndef VTIL_USE_THREAD_POOLING
#ifdef _DEBUG
#define VTIL_USE_THREAD_POOLING false
#else
#define VTIL_USE_THREAD_POOLING true
#endif
#endif
namespace vtil::task
{
// Declare task controller.
//
struct task_controller
{
inline static thread_local std::vector<std::function<void( bool make_or_break )>> callbacks = {};
// Simple ::begin and ::end helpers that go through all callbacks.
//
static void begin()
{
for ( auto& cb : callbacks )
cb( true );
}
static void end()
{
for ( auto& cb : callbacks )
cb( false );
}
};
// Declare task local, must always have the following signature:
//
template<typename T>
struct alignas( T ) local_variable
{
// Hold the value.
//
union
{
T value;
uint8_t raw[ sizeof( T ) ];
};
// Whether variable is initialized or not.
//
bool init = false;
// Holds the default value.
//
const std::optional<T> default_value;
// Adds a callback to the task controller.
//
local_variable( std::optional<T> default_value = std::nullopt )
: raw{ 0 }, default_value( std::move( default_value ) )
{
task_controller::callbacks.emplace_back( [ this ] ( bool make )
{
if ( make ) get();
else reset();
} );
}
// Initializes / deinitializes where necessary.
//
T* get()
{
if ( !std::exchange( init, true ) )
{
if ( default_value )
{
if constexpr ( std::is_copy_constructible_v<T> )
return new ( &value ) T( default_value.value() );
}
else
{
if constexpr ( std::is_default_constructible_v<T> )
return new ( &value ) T();
}
unreachable();
}
return &value;
}
void reset()
{
if ( std::exchange( init, false ) )
std::destroy_at( &value );
}
// Steals current state.
//
T steal()
{
T x = std::move( *get() );
reset();
return x;
}
// Simple accessors.
//
T& operator*() { return *get(); }
T* operator->() { return get(); }
// Deinitialize on destroy.
//
~local_variable() { reset(); }
};
#define task_local( ... ) thread_local vtil::task::local_variable<__VA_ARGS__>
// Declare handle type.
//
#if VTIL_USE_THREAD_POOLING
using handle_type = std::future<void>;
#else
using handle_type = std::thread;
#endif
// Task instance.
//
struct instance
{
handle_type handle;
// Construct by invocable.
//
template<typename T> requires Invocable<T, void>
instance( T&& fn )
{
// Wrap around task markers.
//
auto f = [ fn = std::forward<T>( fn ) ]()
{
task_controller::begin();
fn();
task_controller::end();
};
#if VTIL_USE_THREAD_POOLING
handle = std::async( std::launch::async, std::move( f ) );
#else
handle = { f };
#endif
}
// Default move / copy.
//
instance( instance&& ) = default;
instance( const instance& ) = default;
instance& operator=( instance&& ) = default;
instance& operator=( const instance& ) = default;
// Destruction calls ::get if pooling is enabled to
// propagate exceptions from std::future.
//
~instance()
{
#if VTIL_USE_THREAD_POOLING
handle.get();
#else
handle.join();
#endif
}
};
}; | true |
403bd90c6f6d5971a7b472a5a66edff907ac7669 | C++ | Chickking-Website/SomeFile | /201801/test002.cpp | GB18030 | 765 | 3.546875 | 4 | [] | no_license | #include <cstdio>
int n, arr[100 + 1];
bool visited[100 + 1];
void print() {
for (int i = 1; i <= n; i++) {
printf("%5d", arr[i]);
}
putchar('\n');
}
void dfs(int start) {
if (start == n) {
print();
return;
} // ʼ±ڽ±꣬ȫɣ˳
for (int i = 1; i <= n; i++) {
if (!visited[i]) { // ĿǰҪʵλδʹ
visited[i] = true; //
arr[start + 1] = i; //
dfs(start + 1); // ݹ飬һ·ߵ
visited[i] = false; // ϣݣ visited[i] Ϊ falseΪһѭ
}
}
}
int main() {
scanf("%d", &n);
dfs(0); // 0 Ϊʼ±
return 0;
}
| true |
420514b30b60a629c7a8a02be27577aefe072aa0 | C++ | thejoggeli/matrix-raspi-3d | /Ledlib/Remote/Keys.cpp | UTF-8 | 931 | 2.890625 | 3 | [] | no_license | #include "Keys.h"
namespace Ledlib {
std::string KeyCodeToString(KeyCode KeyCode){
switch(KeyCode){
case KeyCode::A: return "A";
case KeyCode::B: return "B";
case KeyCode::X: return "X";
case KeyCode::Y: return "Y";
case KeyCode::Up: return "Up";
case KeyCode::Down: return "Down";
case KeyCode::Left: return "Left";
case KeyCode::Right: return "Right";
case KeyCode::Start: return "Start";
case KeyCode::Select: return "Select";
case KeyCode::LeftJoystick: return "LeftJoystick";
case KeyCode::RightJoystick: return "RightJoystick";
default: return "KeyCode(" + std::to_string(static_cast<int>(KeyCode)) + ")";
}
}
std::string KeyStateToString(KeyState keyState){
switch(keyState){
case KeyState::Pressed: return "Pressed";
case KeyState::Released: return "Released";
case KeyState::JoystickMove: return "JoystickMove";
default: return "KeyState(" + std::to_string(static_cast<int>(keyState)) + ")";
}
}
}
| true |
0a2d31c65d72a6cf2c76f4679791ac3df4000616 | C++ | pfe1223/error-code | /Wordrange/AVL.h | UTF-8 | 1,947 | 3.84375 | 4 | [] | no_license | #ifndef AVL_h
#define AVL_h
#include<iostream>
#include <string>
using namespace std;
// node struct to hold data
class Node
{
public:
string key;
int tree_size = 0;
Node *left, *right, *parent;
Node() // default constructor
{
left = right = parent = NULL; // setting everything to NULL
}
Node(string val) // constructor that sets key to val
{
key = val;
left = right = parent = NULL; // setting everything to NULL
}
};
class AVL
{
private:
Node *root; // Stores root of tree
public:
AVL(); // Default constructor sets root to null
void insert(string); // insert string into list
void insert(Node*, Node*); // recursive version that inserts a node
Node* find(string); // find string in tree, and return pointer to node with that string
Node* find(Node*, string); // recursive version that finds in a rooted subtree
Node* minNode(Node*); // gets minimum node in rooted subtree
Node* maxNode(Node*); // gets maximum node in rooted subtree
Node* deleteKey(string); // remove a node with string (if it exists), and return pointer to deleted node. This does not delete all nodes with the value.
Node* deleteNode(Node*); // try to delete node pointed by argument. This also returns the node, isolated from the tree.
void deleteAVL(); // deletes every node to prevent memory leaks, and frees memory
void deleteAVL(Node* start); // deletes every Node in subtree rooted at start to prevent memory leaks.
Node* lca(string, string); // calls reccursive lca method
Node* lca(Node*, string, string); // recursive method that finds the least common ancestor
int range(string, string); // calls recursive range method
int range(Node*, string, string); // finds the amount of nodes with keys between the given range
};
#endif
| true |