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 |
---|---|---|---|---|---|---|---|---|---|---|---|
c63c9c61b09e278c7b22d3be08ebd04cd2c864f2
|
C++
|
pmontalb/CudaLight
|
/CudaLight/Vector.tpp
|
UTF-8
| 7,600 | 2.6875 | 3 |
[
"MIT"
] |
permissive
|
#pragma once
#include <type_traits>
#include <Types.h>
#include <Exception.h>
#include <Vector.h>
#include <HostRoutines/ForgeHelpers.h>
namespace cl
{
template<MemorySpace ms, MathDomain md>
Vector<ms, md>::Vector(const unsigned size)
: Buffer<Vector < ms, md>, ms, md>(true), _buffer(0, size, ms, md)
{
this->ctor(_buffer);
}
template<MemorySpace ms, MathDomain md>
Vector<ms, md>::Vector(const unsigned size, const typename Traits<md>::stdType value)
: Vector(size)
{
if (ms == MemorySpace::Host || ms == MemorySpace::Device)
dm::detail::Initialize(_buffer, static_cast<double>(value));
else
routines::Initialize(_buffer, static_cast<double>(value));
}
template<MemorySpace ms, MathDomain md>
Vector<ms, md>::Vector(const Vector& rhs)
: Vector(rhs.size())
{
this->ReadFrom(rhs);
}
template<MemorySpace ms, MathDomain md>
Vector<ms, md>::Vector(const Vector& rhs, const size_t start, const size_t end) noexcept
: Buffer<Vector < ms, md>, ms, md>(false), // this is a no-copy operation, this instance doesn't own the original memory!
_buffer(0, static_cast<unsigned>(end - start), ms, md)
{
assert(end > start);
assert(end <= rhs.size());
_buffer.pointer = rhs._buffer.pointer + start * rhs._buffer.ElementarySize();
}
template<MemorySpace ms, MathDomain md>
Vector<ms, md>::Vector(Vector&& rhs) noexcept
: Buffer<Vector < ms, md>, ms, md>(std::move(rhs)), _buffer(rhs._buffer)
{
}
template<MemorySpace ms, MathDomain md>
Vector<ms, md>::Vector(const std::vector<typename Traits<md>::stdType>& rhs)
: Vector(static_cast<unsigned>(rhs.size()))
{
this->ReadFrom(rhs);
}
template<MemorySpace ms, MathDomain md>
Vector<ms, md>::Vector(const std::string& fileName, bool useMemoryMapping)
{
std::vector<typename Traits<md>::stdType> v;
cl::VectorFromBinaryFile(v, fileName, useMemoryMapping);
this->ReadFrom(v);
}
template<MemorySpace ms, MathDomain md>
Vector<ms, md>::Vector(const MemoryBuffer& buffer)
: Buffer<Vector < ms, md>, ms, md>(false), _buffer(buffer)
{
}
template<MemorySpace ms, MathDomain md>
void Vector<ms, md>::RandomShuffle(const unsigned seed)
{
assert(_buffer.pointer != 0);
if (ms == MemorySpace::Host || ms == MemorySpace::Device)
dm::detail::RandShuffle(_buffer, seed);
else
routines::RandShuffle(_buffer, seed);
}
template<MemorySpace ms, MathDomain md>
void Vector<ms, md>::Print(const std::string& label) const
{
auto v = this->Get();
cl::Print(v, label);
}
template<MemorySpace ms, MathDomain md>
std::ostream& Vector<ms, md>::ToOutputStream(std::ostream& os) const
{
cl::VectorToOutputStream(this->Get(), os);
return os;
}
template<MemorySpace ms, MathDomain md>
void Vector<ms, md>::ToBinaryFile(const std::string& fileName, const bool compressed, const std::string mode) const
{
cl::VectorToBinaryFile(this->Get(), fileName, compressed, mode);
}
template<MemorySpace ms, MathDomain md>
std::ostream& operator<<(std::ostream& os, const Vector<ms, md>& buffer)
{
buffer.ToOutputStream(os);
return os;
}
template<MemorySpace ms, MathDomain md>
std::istream& operator>>(std::istream& is, const Vector<ms, md>& buffer)
{
return buffer.Deserialize(is);
}
#pragma region Linear Algebra
template<MemorySpace ms, MathDomain md>
Vector<ms, md> Vector<ms, md>::operator +(const Vector& rhs) const
{
Vector ret(*this);
ret += rhs;
return ret;
}
template<MemorySpace ms, MathDomain md>
Vector<ms, md> Vector<ms, md>::operator -(const Vector& rhs) const
{
Vector ret(*this);
ret -= rhs;
return ret;
}
template<MemorySpace ms, MathDomain md>
Vector<ms, md> Vector<ms, md>::operator %(const Vector& rhs) const
{
Vector ret(*this);
ret %= rhs;
return ret;
}
template<MemorySpace ms, MathDomain md>
Vector<ms, md> Vector<ms, md>::Add(const Vector& rhs, const double alpha) const
{
Vector ret(*this);
ret.AddEqual(rhs, alpha);
return ret;
}
#pragma endregion
template<MemorySpace ms, MathDomain md>
Vector<ms, md> Vector<ms, md>::Copy(const Vector<ms, md>& source)
{
Vector<ms, md> ret(source);
return ret;
}
template<MemorySpace ms, MathDomain md>
Vector<ms, md> Vector<ms, md>::LinSpace(const stdType x0, const stdType x1, const unsigned size)
{
Vector<ms, md> ret(size);
ret.LinSpace(x0, x1);
return ret;
}
template<MemorySpace ms, MathDomain md>
Vector<ms, md> Vector<ms, md>::RandomUniform(const unsigned size, const unsigned seed)
{
Vector<ms, md> ret(size);
ret.RandomUniform(seed);
return ret;
}
template<MemorySpace ms, MathDomain md>
Vector<ms, md> Vector<ms, md>::RandomGaussian(const unsigned size, const unsigned seed)
{
Vector<ms, md> ret(size);
ret.RandomGaussian(seed);
return ret;
}
template<MemorySpace ms, MathDomain md>
void Vector<ms, md>::RandomShuffle(Vector<ms, md>& v, const unsigned seed)
{
v.RandomShuffle(seed);
}
template<MemorySpace ms, MathDomain md>
void Vector<ms, md>::RandomShufflePair(Vector<ms, md>& v1, Vector<ms, md>& v2, const unsigned seed)
{
if (ms == MemorySpace::Host || ms == MemorySpace::Device)
dm::detail::RandShufflePair(v1.GetBuffer(), v2.GetBuffer(), seed);
else
routines::RandShufflePair(v1.GetBuffer(), v2.GetBuffer(), seed);
}
template<MemorySpace ms, MathDomain md>
void Vector<ms, md>::Print(const Vector<ms, md>& v, const std::string& label)
{
v.Print(label);
}
template<MemorySpace ms, MathDomain md>
std::ostream& Vector<ms, md>::VectorToOutputStream(const Vector<ms, md>& v, std::ostream& os)
{
os << cl::VectorToOutputStream(v.Get(), os);
return os;
}
template<MemorySpace ms, MathDomain md>
void Vector<ms, md>::VectorToBinaryFile(const Vector<ms, md>& v, const std::string& fileName, const bool compressed, const std::string mode)
{
const auto& _vec = v.Get();
cl::VectorToBinaryFile(_vec, fileName, compressed, mode);
}
template<MemorySpace ms, MathDomain md>
Vector<ms, md> Vector<ms, md>::VectorFromInputStream(std::istream& is)
{
std::vector<typename Vector<ms, md>::stdType> _vec;
cl::VectorFromInputStream(_vec, is);
Vector<ms, md> ret(static_cast<unsigned>(_vec.size()));
ret.ReadFrom(_vec);
return ret;
}
template<MemorySpace ms, MathDomain md>
Vector<ms, md> Vector<ms, md>::VectorFromBinaryFile(const std::string& fileName, const bool compressed, const bool useMemoryMapping)
{
std::vector<typename Vector<ms, md>::stdType> _vec {};
cl::VectorFromBinaryFile(_vec, fileName, compressed, useMemoryMapping);
Vector<ms, md> ret(static_cast<unsigned>(_vec.size()));
ret.ReadFrom(_vec);
return ret;
}
template<MemorySpace ms, MathDomain md>
Vector<ms, md> Vector<ms, md>::Add(const Vector<ms, md>& lhs, const Vector<ms, md>& rhs, const double alpha)
{
return lhs.Add(rhs, alpha);
}
template<MemorySpace ms, MathDomain md>
void Vector<ms, md>::Scale(Vector<ms, md>& lhs, const double alpha)
{
lhs.Scale(alpha);
}
template<MemorySpace ms, MathDomain md>
Vector<ms, MathDomain::Float> Vector<ms, md>::MakePair(const Vector<ms, md>& x, const Vector<ms, md>& y)
{
assert(x.size() == y.size());
Vector<ms, MathDomain::Float> pair(2 * x.size());
MakePair(pair, x, y);
return pair;
}
template<MemorySpace ms, MathDomain md>
void Vector<ms, md>::MakePair(Vector<ms, MathDomain::Float>& pair, const Vector<ms, md>& x, const Vector<ms, md>& y)
{
if (ms == MemorySpace::Host || ms == MemorySpace::Device)
dm::detail::MakePair(pair.GetBuffer(), x.GetBuffer(), y.GetBuffer());
else
routines::MakePair(pair.GetBuffer(), x.GetBuffer(), y.GetBuffer());
}
}
| true |
7572ff9aee94ce8ecf754e8386ed5f64eb7611d8
|
C++
|
kc345ws/Data
|
/数据结构上机题/第一次上机第二题.cpp
|
GB18030
| 2,420 | 3.859375 | 4 |
[] |
no_license
|
#include<iostream>
#include"һϻڶ.h"
using namespace std;
AStack<int> *astcktest;
void Menu();
int main()
{
Menu();
}
void Menu()
{
cout << "1.˳ջ" << endl;
cout << "2." << endl;
cout << "3.ɾ" << endl;
cout << "4.ȡ" << endl;
cout << "5.ӡջԪ" << endl;
int select;
int item;
cin >> select;
switch (select)
{
case 1:
cout << "ջĴС" << endl;
int size;
cin >> size;
astcktest = new AStack<int>(size);
cout << endl;
Menu();
break;
case 2:
cout << "ѹջԪصֵ" << endl;
cin >> item;
if (astcktest->Push(item))
{
cout << "ѹջɹ" << endl;
}
else
{
cout << "ջѹ" << endl;
}
cout << endl;
Menu();
break;
case 3:
if (astcktest->Pop(item))
{
cout << "ɹջԪ" << item << endl;
}
else
{
cout << "ջյʧ" << endl;
}
cout << endl;
Menu();
break;
case 4:
if (astcktest->Peek(item))
{
cout << "ջԪΪ:" << item <<endl;
}
else
{
cout << "ջ" << endl;
}
cout << endl;
Menu();
break;
case 5:
astcktest->Show();
cout << endl;
Menu();
break;
default:
cout << endl;
Menu();
break;
}
}
template<typename T>
AStack<T>::AStack(int maxsize)
{
size = maxsize;
AStackArray = new T[size];
top = -1;
}
template<typename T>
AStack<T>::~AStack()
{
delete[]AStackArray;
}
template<typename T>
bool AStack<T>::Push(const T &item)
{
if (!isFull())//ջ
{
AStackArray[top + 1] = item;
top++;
return true;
}
return false;
}
template<typename T>
bool AStack<T>::Pop(T &item)
{
if (!IsEmpty())//ջ
{
item = AStackArray[top];
top--;
return true;
}
return false;
}
template<typename T>
bool AStack<T>::Peek(T &item)const
{
if (!IsEmpty())
{
item = AStackArray[top];
return true;
}
return false;
}
template<typename T>
bool AStack<T>::IsEmpty()const
{
if (top == -1)
{
return true;
}
else
{
return false;
}
}
template<typename T>
bool AStack<T>::isFull()const
{
if (top == size - 1)
{
return true;
}
else
{
return false;
}
}
template<typename T>
void AStack<T>::Clear()
{
delete[]AStackArray;
}
template<typename T>
void AStack<T>::Show()
{
cout << "ջԪΪ" << endl;
for (int i = 0; i <= top; i++)
{
cout << AStackArray[i] << " ";
}
cout << endl;
}
| true |
8054202aba8ef9b40752a9d7342dcdc69ab8fc53
|
C++
|
clayh7/Thesis
|
/Engine/RenderSystem/Uniform.hpp
|
UTF-8
| 936 | 2.890625 | 3 |
[] |
no_license
|
#pragma once
#include <string>
//-------------------------------------------------------------------------------------------------
class Uniform
{
//-------------------------------------------------------------------------------------------------
// Members
//-------------------------------------------------------------------------------------------------
public:
int m_bindPoint;
int m_length;
int m_size;
unsigned int m_type;
std::string m_name;
void * const m_data;
//-------------------------------------------------------------------------------------------------
// Functions
//-------------------------------------------------------------------------------------------------
public:
Uniform( Uniform const & copy, void * const data );
Uniform( int bindPoint, int length, int size, unsigned int type, std::string const & name, void * const data );
~Uniform( );
int GetBindPoint( ) const { return m_bindPoint; }
};
| true |
ed0e588eb979c6448169ccccc1cff6de1dfe92ea
|
C++
|
haozx1997/C
|
/宣讲/函数 指针/指针/变量地址.cpp
|
GB18030
| 288 | 2.625 | 3 |
[] |
no_license
|
#include<stdio.h>
int main()
{
int a = 1;
int c = 2;
int e = 3;
printf("aַ %lld\n",&a);
printf("cַ %lld\n",&c);
printf("eַ %lld\n",&e);
int *a_p = &a;
printf("a_p ֵָ%d a_pֵ %lld\n",*a_p,a_p);
printf("%lld\n",a_p-1);
printf("%d\n",*(a_p-1));
}
| true |
aa89696d43d40f40d8aa996163efa4223397c190
|
C++
|
IAM-WK/GCodePores
|
/src/GCodeTransform.cpp
|
WINDOWS-1252
| 6,596 | 2.796875 | 3 |
[
"MIT"
] |
permissive
|
#include "GCodeTransform.h"
GCodeTransform::GCodeTransform()
{
}
void GCodeTransform::setOrigin(const std::vector<float>& ImageOriginVal) noexcept
{
this->ImageOrigin = ImageOriginVal;
}
void GCodeTransform::setAngles(const float & ImageAngleGammaVal, const float & ImageAngleBetaVal, const float & ImageAngleAlphaVal) noexcept
{
this->ImageAngleGamma = ImageAngleGammaVal;
this->ImageAngleBeta = ImageAngleBetaVal;
this->ImageAngleAlpha = ImageAngleAlphaVal;
}
void GCodeTransform::setImagedimensions(const float & y_image_lengthVal, const float & z_image_lengthVal) noexcept
{
this->y_image_length = y_image_lengthVal;
this->z_image_length = z_image_lengthVal;
}
void GCodeTransform::setInput(const PathBase::PathVector &GCodeVector) noexcept
{
this->ImageCoordinateGCode = GCodeVector; // copy values to new vector
}
void GCodeTransform::Execute()
{
// make vector relative: start with 0,0,0 and subtract first entry from every entry
std::array<float, 3> printpathbegin = { this->ImageCoordinateGCode.front().front()[0], this->ImageCoordinateGCode.front().front()[1] ,this->ImageCoordinateGCode.front().front()[2] };
for (auto &chunkitem : this->ImageCoordinateGCode) {
for (auto &coorditem : chunkitem) {
for (std::size_t k = 0; k < 3; ++k) {
coorditem[k] = coorditem[k] - printpathbegin[k] ; // make vector relative to first printing point
}
}
}
// first do an transformation of KOS : Roation and translation (Alias transform)
// GCodeKOS to ImageKOS --> 180 rotation about x-axis ----------> always like this?
// --> invert y-axis and z-axis
for (auto &chunkitem : this->ImageCoordinateGCode) {
for (auto &coorditem : chunkitem) {
coorditem[1] = (-1)*coorditem[1]; // invert y
coorditem[2] = (-1)*coorditem[2]; // invert z
}
}
// GCodeKOS to ImageKOS --> translate z about h_image; y about length_image
for (auto &chunkitem : this->ImageCoordinateGCode) {
for (auto &coorditem : chunkitem) {
coorditem[1] = coorditem[1] + this->y_image_length; // translate y
coorditem[2] = coorditem[2] + this->z_image_length; // translate z
}
}
// then rotate+translate object accordingly
std::array<float, 3> DifferenceVector;
// translate GCode to imageorigin
// GCodeOrigin = PrintVector[0][0]
// DifferenceVector = ImageOrigin - GCodeOrigin
// loop: PrintVector[i][j] + DifferenceVector
DifferenceVector[0] = this->ImageOrigin[0] - this->ImageCoordinateGCode.front().front()[0];
DifferenceVector[1] = this->ImageOrigin[1] - this->ImageCoordinateGCode.front().front()[1];
DifferenceVector[2] = this->ImageOrigin[2] - this->ImageCoordinateGCode.front().front()[2];
for (auto &pathitem : this->ImageCoordinateGCode) {
for (auto &coorditem : pathitem) {
for (std::size_t k = 0; k < 3; ++k) {
coorditem[k] = coorditem[k] + DifferenceVector[k]; // use ImageCoordinateGCode
}
}
}
// rotate GCode with angle
// rotate XYZ
// rotate dxdydz or recalculate
// x' = xursp + cos * (x - x1) - sin * (y - y1)
// y' = yursp + sin * (x - x1) + cos * (y - y1)
// rotation about z-axis
float tempx, tempy, tempz;
for (auto &pathitem : this->ImageCoordinateGCode) {
for (auto &coorditem : pathitem) {
tempx = this->ImageOrigin[0] + (coorditem[0] - this->ImageOrigin[0]) * cos(this->ImageAngleGamma) - (coorditem[1] - this->ImageOrigin[1]) * sin(this->ImageAngleGamma);
tempy = this->ImageOrigin[1] + (coorditem[0] - this->ImageOrigin[0]) * sin(this->ImageAngleGamma) + (coorditem[1] - this->ImageOrigin[1]) * cos(this->ImageAngleGamma);
coorditem[0] = tempx;
coorditem[1] = tempy;
}
}
// rotation about y-axis
for (auto &pathitem : this->ImageCoordinateGCode) {
for (auto &coorditem : pathitem) {
tempx = this->ImageOrigin[0] + (coorditem[0] - this->ImageOrigin[0]) * cos(this->ImageAngleBeta) + (coorditem[2] - this->ImageOrigin[2]) * sin(this->ImageAngleBeta);
tempz = this->ImageOrigin[2] - (coorditem[0] - this->ImageOrigin[0]) * sin(this->ImageAngleBeta) + (coorditem[2] - this->ImageOrigin[2]) * cos(this->ImageAngleBeta);
coorditem[0] = tempx;
coorditem[2] = tempz;
}
}
// rotation about x-axis
for (auto &pathitem : this->ImageCoordinateGCode) {
for (auto &coorditem : pathitem) {
tempy = this->ImageOrigin[1] + (coorditem[1] - this->ImageOrigin[1]) * cos(this->ImageAngleAlpha) - (coorditem[2] - this->ImageOrigin[2]) * sin(this->ImageAngleAlpha);
tempz = this->ImageOrigin[2] + (coorditem[1] - this->ImageOrigin[1]) * sin(this->ImageAngleAlpha) + (coorditem[2] - this->ImageOrigin[2]) * cos(this->ImageAngleAlpha);
coorditem[1] = tempy;
coorditem[2] = tempz;
}
}
// now we need to regenerate the directions
float dx, dy, dz, disttonext;
for (auto &chunkitem : this->ImageCoordinateGCode) {
for (std::size_t i = 0; i < chunkitem.size() - 1; ++i) {
dx = chunkitem[i + 1][0] - chunkitem[i][0];
dy = chunkitem[i + 1][1] - chunkitem[i][1];
dz = chunkitem[i + 1][2] - chunkitem[i][2];
disttonext = sqrt(dx * dx + dy * dy + dz * dz);
dx = dx / disttonext; dy = dy / disttonext; dz = dz / disttonext; //norm direction
chunkitem[i][3] = dx; chunkitem[i][4] = dy; chunkitem[i][5] = dz; chunkitem[i][6] = disttonext;
// prints out extracted object printing coords
//std::cout << " -- X: " << pathitem[i][0] << " -- Y: " << pathitem[i][1] << " -- Z: " << pathitem[i][2] << " -- disttonext " << pathitem[i][6] << std::endl;
}
}
for (std::size_t i = 0; i < this->ImageCoordinateGCode.size(); ++i) { // update last elements
if (this->ImageCoordinateGCode[i].size() >= 2) {
dx = this->ImageCoordinateGCode[i][this->ImageCoordinateGCode[i].size() - 2][3];
dy = this->ImageCoordinateGCode[i][this->ImageCoordinateGCode[i].size() - 2][4]; //caution with double travels !!!!!!
dz = this->ImageCoordinateGCode[i][this->ImageCoordinateGCode[i].size() - 2][5];
}
else { // take last direction of -1 -1 -1 as fallback ----> Todo!
dx = -1;
dy = -1;
dz = -1;
}
// disttonext is 0 by definition
this->ImageCoordinateGCode[i].back()[3] = dx; this->ImageCoordinateGCode[i].back()[4] = dy; this->ImageCoordinateGCode[i].back()[5] = dz; this->ImageCoordinateGCode[i].back()[6] = 0;
}
return;
}
PathBase::PathVector GCodeTransform::GetOutput() const
{
if (this->ImageCoordinateGCode.size() == 0) {
throw std::runtime_error("Error after path transformation: Transformed coordinate vector is empty!");
}
return this->ImageCoordinateGCode;
}
| true |
2aab4ac13df4f5c74ef1487d81de5a33e184ad34
|
C++
|
itachi1101/Graphs_documented
|
/Directed Graph/isCyclic.cpp
|
UTF-8
| 1,027 | 2.578125 | 3 |
[] |
no_license
|
#include<bits/stdc++.h>
using namespace std;
vector<int>gr[100];
int cycle = 0;
void dfs(int src, set<int>s, vector<bool>&visited) {
visited[src] = true;
s.insert(src);
for (auto child : gr[src]) {
if (!visited[child]) {
dfs(child, s, visited);
}
else if (visited[child] == true && s.find(child) != s.end()) {
cycle = 1;
}
}
s.erase(s.find(src));
return ;
}
int main() {
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
int i, j, k, n, m, ans = 0, cnt = 0, sum = 0;
cin >> n >> m;
for (int i = 0; i < m; i++) {
int x, y;
cin >> x >> y;
gr[x].push_back(y);
}
vector<bool>visited;
visited.assign(n, false);
set<int>s;
for (int i = 0; i < n; i++) {
if (!visited[i])
dfs(i, s, visited);
}
if (cycle == 1)cout << "cycle\n";
else cout << "no cycle\n";
}
| true |
4fa3e7d3518a21d90920cf3be4e5f0b3bb7ed67a
|
C++
|
michellibera/Cplusplus
|
/19/main.cpp
|
UTF-8
| 1,620 | 3.296875 | 3 |
[] |
no_license
|
#include <iostream>
using namespace std;
float A[100];
float B[100];
void wczyt(int n);
void wypis (int n);
float iloczynab(int n);
float iloczynaa(int n);
float iloczynbb(int n);
float wyrazenia(int n);
int main()
{
int n;
float wyrazenie;
cout<<"podaj ilosc elementow wektorow A i B";
cin>>n;
wczyt(n);
wypis(n);
wyrazenie=wyrazenia(n);
cout<<"aa"<<iloczynaa(n)<<endl;
cout<<"bb"<<iloczynbb(n)<<endl;
cout<<"ab"<<iloczynab(n)<<endl;
cout<<wyrazenie;
return 0;
}
void wczyt(int n)
{
int i;
for(i=0;i<n;i++)
{
cout<<"Podaj "<<i+1<<" element wektora A";
cin>>A[i];
}
for(i=0;i<n;i++)
{
cout<<"Podaj "<<i+1<<" element wektora B";
cin>>B[i];
}
}
void wypis(int n)
{
int i;
cout<<"A"<<endl;
for(i=0;i<n;i++)
{
cout<<A[i]<<endl;
}
cout<<"B"<<endl;
for(i=0;i<n;i++)
{
cout<<B[i]<<endl;
}
}
float iloczynab(int n)
{ int i;
float suma=0;
for(i=0;i<n;i++)
{
suma+=A[i]*B[i];
}
return suma;
}
float iloczynaa(int n)
{ int i;
float suma=0;
for(i=0;i<n;i++)
{
suma+=A[i]*A[i];
}
return suma;
}
float iloczynbb(int n)
{ int i;
float suma=0;
for(i=0;i<n;i++)
{
suma+=B[i]*B[i];
}
return suma;
}
float wyrazenia(int n)
{
float suma=0;
suma=(((iloczynaa(n))+(iloczynbb(n)))/(iloczynab(n)));
return suma;
}
| true |
3ad660d058dd4352936668b1cc35ecd1540443a2
|
C++
|
ujdcodr/Parallel-Data-Compression
|
/final/serial/vafle_compress.cpp
|
UTF-8
| 3,225 | 2.6875 | 3 |
[] |
no_license
|
/*
This program is for compressing the file using the VaFLe algorithm
*/
#include"readfile.cpp"
#include"writefile.cpp"
using namespace std;
string comp(char* rFile,char* wFile)
{
float start=omp_get_wtime(),tim=0;
int minLength = 1;
string s1,s2;
string value,flag,length,interStr,zeroes;
int iStr,iRun,header,sizeOfValue,sizeOfLength,maxBits,bitsRepresentingLength,numZeroes;
int count,i,j;
tim+=omp_get_wtime()-start;
tim+=readfile(rFile,s1);
//s1 = "1001110000111110000001111111000000001111111110000000000111111111110000000000001111111111111000000000000001111111111111110000000000000000";
cout<<"\nInitial size = "<<s1.size()<<endl;
start=omp_get_wtime();
//Header of the compressed file, which is 1 byte long, containing the min length of a run that can be compressed
header = minLength;
for(int q=128 ; q>0 ; q/=2)
{
if(header/q == 1)
s2.push_back('1');
else
s2.push_back('0');
header %= q;
}
//Compression of file
for(iStr=iRun=0,count=1;iRun<s1.size();iRun++)
{
if(iRun<s1.size()-1 && s1.at(iRun+1) == s1.at(iRun))
count++;
else
{
//if(iStr<(10*8))
//cout<<count<<" -> "<<s1.substr(iStr,count)<<" - ";// <-
if(count<=minLength){
s2 += (s1.substr(iStr,count));
//if(iStr<(10*8))
//cout<<s1.substr(iStr,count)<<endl;// <-
iStr = iStr+count;
}
else{
value=flag=length="";
value += (s1.substr(iStr,minLength));
sizeOfValue = (int)log2( count - (minLength-1) );
for(j = 0;j<sizeOfValue;j++)
{
flag += (s1.substr(iStr,1));
}
if(flag[0]-'0' == 0)
flag += "1";
else
flag += "0";
sizeOfLength = (count-(minLength-1)) - (int)pow(2,sizeOfValue);
maxBits = sizeOfValue;
interStr="";
while(sizeOfValue>0)
{
bitsRepresentingLength = (int)sizeOfLength/pow(2,--sizeOfValue);
sizeOfLength %= (int)pow(2,sizeOfValue);
if(bitsRepresentingLength == 1)
interStr += "1";
else
interStr += "0";
}
if(maxBits-interStr.size()>0) {
numZeroes = maxBits-interStr.size();
zeroes = "0";
while(numZeroes>1){
zeroes += "0";
numZeroes--;
}
length += zeroes;
}
length += interStr;
s2 += (value+flag+length);
//if(iStr<(10*8))
//cout<<value<<' '<<flag<<' '<<length<<endl;// <-
iStr = iStr+count;
}
count = 1;
}
}
tim+=omp_get_wtime()-start;
cout<<"\nCompressed length = "<<s2.size()<<endl;
cout<<"Compression rate = "<<((float)s1.size()/s2.size())<<endl;
tim+=writefile(wFile,s2);
cout<<"Time taken = "<<tim<<" s\n";
return s2;
}
main(int argc,char **argv)
{
comp(argv[1],argv[2]);
}
| true |
27d3c0bb03ad5a92c0eaf523e658a6c2e39cc939
|
C++
|
hieule22/truc
|
/src/scanner.cc
|
UTF-8
| 29,727 | 2.8125 | 3 |
[] |
no_license
|
// Implementation of Scanner class.
// @author Hieu Le
// @version September 30th, 2016
#include "scanner.h"
#include <vector>
Scanner::Scanner(char *filename) : buffer_(new Buffer(filename)) {}
Scanner::Scanner(Buffer *buffer) : buffer_(buffer) {}
Scanner::~Scanner() {
delete buffer_;
}
void Scanner::scanner_fatal_error(const string& message) const {
cerr << "Exiting on Scanner Fatal Error: " << message << endl;
exit(EXIT_FAILURE);
}
// Placing declarations inside an anonymous namespace make them visible only
// to this compilation unit and not polluting the global namespace.
namespace {
// Set of states for the deterministic finite automaton that recognizes all
// valid lexemes from TruPL.
const int START = 0;
const int DONE = 999;
const int IDENTIFIER = 1;
const int NUMBER = 24;
const int END_OF_FILE = 25;
const int A = 2;
const int AN = 40;
const int AND = 41;
const int B = 3;
const int BE = 42;
const int BEG = 44;
const int BEGI = 45;
const int BEGIN = 46;
const int BO = 43;
const int BOO = 47;
const int BOOL = 48;
const int E = 4;
const int EL = 49;
const int ELS = 50;
const int ELSE = 51;
const int EN = 52;
const int END = 53;
const int I = 5;
const int IF = 54;
const int IN = 55;
const int INT = 56;
const int L = 6;
const int LO = 57;
const int LOO = 58;
const int LOOP = 59;
const int N = 7;
const int NO = 60;
const int NOT = 61;
const int O = 8;
const int OR = 62;
const int P = 9;
const int PR = 63;
const int PRI = 64;
const int PRIN = 65;
const int PRINT = 66;
const int PRO = 67;
const int PROC = 68;
const int PROCE = 69;
const int PROCED = 70;
const int PROCEDU = 71;
const int PROCEDUR = 72;
const int PROCEDURE = 73;
const int PROG = 74;
const int PROGR = 75;
const int PROGRA = 76;
const int PROGRAM = 77;
const int T = 10;
const int TH = 78;
const int THE = 79;
const int THEN = 80;
const int W = 11;
const int WH = 81;
const int WHI = 82;
const int WHIL = 83;
const int WHILE = 84;
const int SEMICOLON = 12;
const int COLON = 13;
const int COMMA = 14;
const int OPENBRACKET = 15;
const int CLOSEBRACKET = 16;
const int EQUAL = 17;
const int LESS = 18;
const int LESSEQUAL = 34;
const int NOTEQUAL = 35;
const int GREATER = 19;
const int GREATEREQUAL = 36;
const int ADD = 20;
const int SUBTRACT = 21;
const int MULTIPLY = 22;
const int DIVIDE = 32;
const int ASSIGN = 33;
// Checks if a target character is a member of a given set of characters.
bool is_member_of(const char target, const vector<char>& collection) {
for (const char c : collection) {
if (target == c) {
return true;
}
}
return false;
}
} // namespace
Token *Scanner::next_token() {
int state = START;
string attribute;
Token* token = nullptr;
while (state != DONE) {
// Always read a char from buffer before each transition.
const char c = buffer_->next_char();
switch (state) {
case START:
if (is_alpha(c) && !is_member_of(c, {
'a', 'b', 'e', 'i', 'l', 'n', 'o', 'p', 't', 'w'})) {
state = IDENTIFIER;
attribute.push_back(c);
} else if (c == 'a') {
state = A;
attribute.push_back(c);
} else if (c == 'b') {
state = B;
attribute.push_back(c);
} else if (c == 'e') {
state = E;
attribute.push_back(c);
} else if (c == 'i') {
state = I;
attribute.push_back(c);
} else if (c == 'l') {
state = L;
attribute.push_back(c);
} else if (c == 'n') {
state = N;
attribute.push_back(c);
} else if (c == 'o') {
state = O;
attribute.push_back(c);
} else if (c == 'p') {
state = P;
attribute.push_back(c);
} else if (c == 't') {
state = T;
attribute.push_back(c);
} else if (c == 'w') {
state = W;
attribute.push_back(c);
} else if (c == ';') {
state = SEMICOLON;
} else if (c == ':') {
state = COLON;
} else if (c == ',') {
state = COMMA;
} else if (c == '(') {
state = OPENBRACKET;
} else if (c == ')') {
state = CLOSEBRACKET;
} else if (c == '=') {
state = EQUAL;
} else if (c == '<') {
state = LESS;
} else if (c == '>') {
state = GREATER;
} else if (c == '+') {
state = ADD;
} else if (c == '-') {
state = SUBTRACT;
} else if (c == '*') {
state = MULTIPLY;
} else if (c == '/') {
state = DIVIDE;
} else if (is_digit(c)) {
state = NUMBER;
attribute.push_back(c);
} else if (c == EOF_MARKER) {
state = END_OF_FILE;
} else {
scanner_fatal_error(string("Illegal character: ") + c);
}
break;
case IDENTIFIER:
if (is_alphanum(c)) {
state = IDENTIFIER;
attribute.push_back(c);
} else {
state = DONE;
token = new IdToken(attribute);
if (!is_space(c)) {
buffer_->unread_char(c);
}
}
break;
case A:
if (c == 'n') {
state = AN;
attribute.push_back(c);
} else if (is_alphanum(c)) {
state = IDENTIFIER;
attribute.push_back(c);
} else {
state = DONE;
token = new IdToken(attribute);
if (!is_space(c)) {
buffer_->unread_char(c);
}
}
break;
case AN:
if (c == 'd') {
state = AND;
attribute.push_back(c);
} else if (is_alphanum(c)) {
state = IDENTIFIER;
attribute.push_back(c);
} else {
state = DONE;
token = new IdToken(attribute);
if (!is_space(c)) {
buffer_->unread_char(c);
}
}
break;
case AND:
if (is_alphanum(c)) {
state = IDENTIFIER;
attribute.push_back(c);
} else {
state = DONE;
token = new MulopToken(mulop_attr_type::MULOP_AND);
if (!is_space(c)) {
buffer_->unread_char(c);
}
}
break;
case B:
if (c == 'e') {
state = BE;
attribute.push_back(c);
} else if (c == 'o') {
state = BO;
attribute.push_back(c);
} else if (is_alphanum(c)) {
state = IDENTIFIER;
attribute.push_back(c);
} else {
state = DONE;
token = new IdToken(attribute);
if (!is_space(c)) {
buffer_->unread_char(c);
}
}
break;
case BE:
if (c == 'g') {
state = BEG;
attribute.push_back(c);
} else if (is_alphanum(c)) {
state = IDENTIFIER;
attribute.push_back(c);
} else {
state = DONE;
token = new IdToken(attribute);
if (!is_space(c)) {
buffer_->unread_char(c);
}
}
break;
case BEG:
if (c == 'i') {
state = BEGI;
attribute.push_back(c);
} else if (is_alphanum(c)) {
state = IDENTIFIER;
attribute.push_back(c);
} else {
state = DONE;
token = new IdToken(attribute);
if (!is_space(c)) {
buffer_->unread_char(c);
}
}
break;
case BEGI:
if (c == 'n') {
state = BEGIN;
attribute.push_back(c);
} else if (is_alphanum(c)) {
state = IDENTIFIER;
attribute.push_back(c);
} else {
state = DONE;
token = new IdToken(attribute);
if (!is_space(c)) {
buffer_->unread_char(c);
}
}
break;
case BEGIN:
if (is_alphanum(c)) {
state = IDENTIFIER;
attribute.push_back(c);
} else {
state = DONE;
token = new KeywordToken(keyword_attr_type::KW_BEGIN);
if (!is_space(c)) {
buffer_->unread_char(c);
}
}
break;
case BO:
if (c == 'o') {
state = BOO;
attribute.push_back(c);
} else if (is_alphanum(c)) {
state = IDENTIFIER;
attribute.push_back(c);
} else {
state = DONE;
token = new IdToken(attribute);
if (!is_space(c)) {
buffer_->unread_char(c);
}
}
break;
case BOO:
if (c == 'l') {
state = BOOL;
attribute.push_back(c);
} else if (is_alphanum(c)) {
state = IDENTIFIER;
attribute.push_back(c);
} else {
state = DONE;
token = new IdToken(attribute);
if (!is_space(c)) {
buffer_->unread_char(c);
}
}
break;
case BOOL:
if (is_alphanum(c)) {
state = IDENTIFIER;
attribute.push_back(c);
} else {
state = DONE;
token = new KeywordToken(keyword_attr_type::KW_BOOL);
if (!is_space(c)) {
buffer_->unread_char(c);
}
}
break;
case E:
if (c == 'l') {
state = EL;
attribute.push_back(c);
} else if (c == 'n') {
state = EN;
attribute.push_back(c);
} else if (is_alphanum(c)) {
state = IDENTIFIER;
attribute.push_back(c);
} else {
state = DONE;
token = new IdToken(attribute);
if (!is_space(c)) {
buffer_->unread_char(c);
}
}
break;
case EL:
if (c == 's') {
state = ELS;
attribute.push_back(c);
} else if (is_alphanum(c)) {
state = IDENTIFIER;
attribute.push_back(c);
} else {
state = DONE;
token = new IdToken(attribute);
if (!is_space(c)) {
buffer_->unread_char(c);
}
}
break;
case ELS:
if (c == 'e') {
state = ELSE;
attribute.push_back(c);
} else if (is_alphanum(c)) {
state = IDENTIFIER;
attribute.push_back(c);
} else {
state = DONE;
token = new IdToken(attribute);
if (!is_space(c)) {
buffer_->unread_char(c);
}
}
break;
case ELSE:
if (is_alphanum(c)) {
state = IDENTIFIER;
attribute.push_back(c);
} else {
state = DONE;
token = new KeywordToken(keyword_attr_type::KW_ELSE);
if (!is_space(c)) {
buffer_->unread_char(c);
}
}
break;
case EN:
if (c == 'd') {
state = END;
attribute.push_back(c);
} else if (is_alphanum(c)) {
state = IDENTIFIER;
attribute.push_back(c);
} else {
state = DONE;
token = new IdToken(attribute);
if (!is_space(c)) {
buffer_->unread_char(c);
}
}
break;
case END:
if (is_alphanum(c)) {
state = IDENTIFIER;
attribute.push_back(c);
} else {
state = DONE;
token = new KeywordToken(keyword_attr_type::KW_END);
if (!is_space(c)) {
buffer_->unread_char(c);
}
}
break;
case I:
if (c == 'f') {
state = IF;
attribute.push_back(c);
} else if (c == 'n') {
state = IN;
attribute.push_back(c);
} else if (is_alphanum(c)) {
state = IDENTIFIER;
attribute.push_back(c);
} else {
state = DONE;
token = new IdToken(attribute);
if (!is_space(c)) {
buffer_->unread_char(c);
}
}
break;
case IF:
if (is_alphanum(c)) {
state = IDENTIFIER;
attribute.push_back(c);
} else {
state = DONE;
token = new KeywordToken(keyword_attr_type::KW_IF);
if (!is_space(c)) {
buffer_->unread_char(c);
}
}
break;
case IN:
if (c == 't') {
state = INT;
attribute.push_back(c);
} else if (is_alphanum(c)) {
state = IDENTIFIER;
attribute.push_back(c);
} else {
state = DONE;
token = new IdToken(attribute);
if (!is_space(c)) {
buffer_->unread_char(c);
}
}
break;
case INT:
if (is_alphanum(c)) {
state = IDENTIFIER;
attribute.push_back(c);
} else {
state = DONE;
token = new KeywordToken(keyword_attr_type::KW_INT);
if (!is_space(c)) {
buffer_->unread_char(c);
}
}
break;
case L:
if (c == 'o') {
state = LO;
attribute.push_back(c);
} else if (is_alphanum(c)) {
state = IDENTIFIER;
attribute.push_back(c);
} else {
state = DONE;
token = new IdToken(attribute);
if (!is_space(c)) {
buffer_->unread_char(c);
}
}
break;
case LO:
if (c == 'o') {
state = LOO;
attribute.push_back(c);
} else if (is_alphanum(c)) {
state = IDENTIFIER;
attribute.push_back(c);
} else {
state = DONE;
token = new IdToken(attribute);
if (!is_space(c)) {
buffer_->unread_char(c);
}
}
break;
case LOO:
if (c == 'p') {
state = LOOP;
attribute.push_back(c);
} else if (is_alphanum(c)) {
state = IDENTIFIER;
attribute.push_back(c);
} else {
state = DONE;
token = new IdToken(attribute);
if (!is_space(c)) {
buffer_->unread_char(c);
}
}
break;
case LOOP:
if (is_alphanum(c)) {
state = IDENTIFIER;
attribute.push_back(c);
} else {
state = DONE;
token = new KeywordToken(keyword_attr_type::KW_LOOP);
if (!is_space(c)) {
buffer_->unread_char(c);
}
}
break;
case N:
if (c == 'o') {
state = NO;
attribute.push_back(c);
} else if (is_alphanum(c)) {
state = IDENTIFIER;
attribute.push_back(c);
} else {
state = DONE;
token = new IdToken(attribute);
if (!is_space(c)) {
buffer_->unread_char(c);
}
}
break;
case NO:
if (c == 't') {
state = NOT;
attribute.push_back(c);
} else if (is_alphanum(c)) {
state = IDENTIFIER;
attribute.push_back(c);
} else {
state = DONE;
token = new IdToken(attribute);
if (!is_space(c)) {
buffer_->unread_char(c);
}
}
break;
case NOT:
if (is_alphanum(c)) {
state = IDENTIFIER;
attribute.push_back(c);
} else {
state = DONE;
token = new KeywordToken(keyword_attr_type::KW_NOT);
if (!is_space(c)) {
buffer_->unread_char(c);
}
}
break;
case O:
if (c == 'r') {
state = OR;
attribute.push_back(c);
} else if (is_alphanum(c)) {
state = IDENTIFIER;
attribute.push_back(c);
} else {
state = DONE;
token = new IdToken(attribute);
if (!is_space(c)) {
buffer_->unread_char(c);
}
}
break;
case OR:
if (is_alphanum(c)) {
state = IDENTIFIER;
attribute.push_back(c);
} else {
state = DONE;
token = new AddopToken(addop_attr_type::ADDOP_OR);
if (!is_space(c)) {
buffer_->unread_char(c);
}
}
break;
case P:
if (c == 'r') {
state = PR;
attribute.push_back(c);
} else if (is_alphanum(c)) {
state = IDENTIFIER;
attribute.push_back(c);
} else {
state = DONE;
token = new IdToken(attribute);
if (!is_space(c)) {
buffer_->unread_char(c);
}
}
break;
case PR:
if (c == 'i') {
state = PRI;
attribute.push_back(c);
} else if (c == 'o') {
state = PRO;
attribute.push_back(c);
} else if (is_alphanum(c)) {
state = IDENTIFIER;
attribute.push_back(c);
} else {
state = DONE;
token = new IdToken(attribute);
if (!is_space(c)) {
buffer_->unread_char(c);
}
}
break;
case PRI:
if (c == 'n') {
state = PRIN;
attribute.push_back(c);
} else if (is_alphanum(c)) {
state = IDENTIFIER;
attribute.push_back(c);
} else {
state = DONE;
token = new IdToken(attribute);
if (!is_space(c)) {
buffer_->unread_char(c);
}
}
break;
case PRIN:
if (c == 't') {
state = PRINT;
attribute.push_back(c);
} else if (is_alphanum(c)) {
state = IDENTIFIER;
attribute.push_back(c);
} else {
state = DONE;
token = new IdToken(attribute);
if (!is_space(c)) {
buffer_->unread_char(c);
}
}
break;
case PRINT:
if (is_alphanum(c)) {
state = IDENTIFIER;
attribute.push_back(c);
} else {
state = DONE;
token = new KeywordToken(keyword_attr_type::KW_PRINT);
if (!is_space(c)) {
buffer_->unread_char(c);
}
}
break;
case PRO:
if (c == 'c') {
state = PROC;
attribute.push_back(c);
} else if (c == 'g') {
state = PROG;
attribute.push_back(c);
} else if (is_alphanum(c)) {
state = IDENTIFIER;
attribute.push_back(c);
} else {
state = DONE;
token = new IdToken(attribute);
if (!is_space(c)) {
buffer_->unread_char(c);
}
}
break;
case PROC:
if (c == 'e') {
state = PROCE;
attribute.push_back(c);
} else if (is_alphanum(c)) {
state = IDENTIFIER;
attribute.push_back(c);
} else {
state = DONE;
token = new IdToken(attribute);
if (!is_space(c)) {
buffer_->unread_char(c);
}
}
break;
case PROCE:
if (c == 'd') {
state = PROCED;
attribute.push_back(c);
} else if (is_alphanum(c)) {
state = IDENTIFIER;
attribute.push_back(c);
} else {
state = DONE;
token = new IdToken(attribute);
if (!is_space(c)) {
buffer_->unread_char(c);
}
}
break;
case PROCED:
if (c == 'u') {
state = PROCEDU;
attribute.push_back(c);
} else if (is_alphanum(c)) {
state = IDENTIFIER;
attribute.push_back(c);
} else {
state = DONE;
token = new IdToken(attribute);
if (!is_space(c)) {
buffer_->unread_char(c);
}
}
break;
case PROCEDU:
if (c == 'r') {
state = PROCEDUR;
attribute.push_back(c);
} else if (is_alphanum(c)) {
state = IDENTIFIER;
attribute.push_back(c);
} else {
state = DONE;
token = new IdToken(attribute);
if (!is_space(c)) {
buffer_->unread_char(c);
}
}
break;
case PROCEDUR:
if (c == 'e') {
state = PROCEDURE;
attribute.push_back(c);
} else if (is_alphanum(c)) {
state = IDENTIFIER;
attribute.push_back(c);
} else {
state = DONE;
token = new IdToken(attribute);
if (!is_space(c)) {
buffer_->unread_char(c);
}
}
break;
case PROCEDURE:
if (is_alphanum(c)) {
state = IDENTIFIER;
attribute.push_back(c);
} else {
state = DONE;
token = new KeywordToken(keyword_attr_type::KW_PROCEDURE);
if (!is_space(c)) {
buffer_->unread_char(c);
}
}
break;
case PROG:
if (c == 'r') {
state = PROGR;
attribute.push_back(c);
} else if (is_alphanum(c)) {
state = IDENTIFIER;
attribute.push_back(c);
} else {
state = DONE;
token = new IdToken(attribute);
if (!is_space(c)) {
buffer_->unread_char(c);
}
}
break;
case PROGR:
if (c == 'a') {
state = PROGRA;
attribute.push_back(c);
} else if (is_alphanum(c)) {
state = IDENTIFIER;
attribute.push_back(c);
} else {
state = DONE;
token = new IdToken(attribute);
if (!is_space(c)) {
buffer_->unread_char(c);
}
}
break;
case PROGRA:
if (c == 'm') {
state = PROGRAM;
attribute.push_back(c);
} else if (is_alphanum(c)) {
state = IDENTIFIER;
attribute.push_back(c);
} else {
state = DONE;
token = new IdToken(attribute);
if (!is_space(c)) {
buffer_->unread_char(c);
}
}
break;
case PROGRAM:
if (is_alphanum(c)) {
state = IDENTIFIER;
attribute.push_back(c);
} else {
state = DONE;
token = new KeywordToken(keyword_attr_type::KW_PROGRAM);
if (!is_space(c)) {
buffer_->unread_char(c);
}
}
break;
case T:
if (c == 'h') {
state = TH;
attribute.push_back(c);
} else if (is_alphanum(c)) {
state = IDENTIFIER;
attribute.push_back(c);
} else {
state = DONE;
token = new IdToken(attribute);
if (!is_space(c)) {
buffer_->unread_char(c);
}
}
break;
case TH:
if (c == 'e') {
state = THE;
attribute.push_back(c);
} else if (is_alphanum(c)) {
state = IDENTIFIER;
attribute.push_back(c);
} else {
state = DONE;
token = new IdToken(attribute);
if (!is_space(c)) {
buffer_->unread_char(c);
}
}
break;
case THE:
if (c == 'n') {
state = THEN;
attribute.push_back(c);
} else if (is_alphanum(c)) {
state = IDENTIFIER;
attribute.push_back(c);
} else {
state = DONE;
token = new IdToken(attribute);
if (!is_space(c)) {
buffer_->unread_char(c);
}
}
break;
case THEN:
if (is_alphanum(c)) {
state = IDENTIFIER;
attribute.push_back(c);
} else {
state = DONE;
token = new KeywordToken(keyword_attr_type::KW_THEN);
if (!is_space(c)) {
buffer_->unread_char(c);
}
}
break;
case W:
if (c == 'h') {
state = WH;
attribute.push_back(c);
} else if (is_alphanum(c)) {
state = IDENTIFIER;
attribute.push_back(c);
} else {
state = DONE;
token = new IdToken(attribute);
if (!is_space(c)) {
buffer_->unread_char(c);
}
}
break;
case WH:
if (c == 'i') {
state = WHI;
attribute.push_back(c);
} else if (is_alphanum(c)) {
state = IDENTIFIER;
attribute.push_back(c);
} else {
state = DONE;
token = new IdToken(attribute);
if (!is_space(c)) {
buffer_->unread_char(c);
}
}
break;
case WHI:
if (c == 'l') {
state = WHIL;
attribute.push_back(c);
} else if (is_alphanum(c)) {
state = IDENTIFIER;
attribute.push_back(c);
} else {
state = DONE;
token = new IdToken(attribute);
if (!is_space(c)) {
buffer_->unread_char(c);
}
}
break;
case WHIL:
if (c == 'e') {
state = WHILE;
attribute.push_back(c);
} else if (is_alphanum(c)) {
state = IDENTIFIER;
attribute.push_back(c);
} else {
state = DONE;
token = new IdToken(attribute);
if (!is_space(c)) {
buffer_->unread_char(c);
}
}
break;
case WHILE:
if (is_alphanum(c)) {
state = IDENTIFIER;
attribute.push_back(c);
} else {
state = DONE;
token = new KeywordToken(keyword_attr_type::KW_WHILE);
if (!is_space(c)) {
buffer_->unread_char(c);
}
}
break;
case SEMICOLON:
state = DONE;
token = new PuncToken(punc_attr_type::PUNC_SEMI);
if (!is_space(c)) {
buffer_->unread_char(c);
}
break;
case COLON:
if (c == '=') {
state = ASSIGN;
} else {
state = DONE;
token = new PuncToken(punc_attr_type::PUNC_COLON);
if (!is_space(c)) {
buffer_->unread_char(c);
}
}
break;
case ASSIGN:
state = DONE;
token = new PuncToken(punc_attr_type::PUNC_ASSIGN);
if (!is_space(c)) {
buffer_->unread_char(c);
}
break;
case COMMA:
state = DONE;
token = new PuncToken(punc_attr_type::PUNC_COMMA);
if (!is_space(c)) {
buffer_->unread_char(c);
}
break;
case OPENBRACKET:
state = DONE;
token = new PuncToken(punc_attr_type::PUNC_OPEN);
if (!is_space(c)) {
buffer_->unread_char(c);
}
break;
case CLOSEBRACKET:
state = DONE;
token = new PuncToken(punc_attr_type::PUNC_CLOSE);
if (!is_space(c)) {
buffer_->unread_char(c);
}
break;
case EQUAL:
state = DONE;
token = new RelopToken(relop_attr_type::RELOP_EQ);
if (!is_space(c)) {
buffer_->unread_char(c);
}
break;
case LESS:
if (c == '=') {
state = LESSEQUAL;
} else if (c == '>') {
state = NOTEQUAL;
} else {
state = DONE;
token = new RelopToken(relop_attr_type::RELOP_LT);
if (!is_space(c)) {
buffer_->unread_char(c);
}
}
break;
case LESSEQUAL:
state = DONE;
token = new RelopToken(relop_attr_type::RELOP_LE);
if (!is_space(c)) {
buffer_->unread_char(c);
}
break;
case NOTEQUAL:
state = DONE;
token = new RelopToken(relop_attr_type::RELOP_NE);
if (!is_space(c)) {
buffer_->unread_char(c);
}
break;
case GREATER:
if (c == '=') {
state = GREATEREQUAL;
} else {
state = DONE;
token = new RelopToken(relop_attr_type::RELOP_GT);
if (!is_space(c)) {
buffer_->unread_char(c);
}
}
break;
case GREATEREQUAL:
state = DONE;
token = new RelopToken(relop_attr_type::RELOP_GE);
if (!is_space(c)) {
buffer_->unread_char(c);
}
break;
case ADD:
state = DONE;
token = new AddopToken(addop_attr_type::ADDOP_ADD);
if (!is_space(c)) {
buffer_->unread_char(c);
}
break;
case SUBTRACT:
state = DONE;
token = new AddopToken(addop_attr_type::ADDOP_SUB);
if (!is_space(c)) {
buffer_->unread_char(c);
}
break;
case MULTIPLY:
state = DONE;
token = new MulopToken(mulop_attr_type::MULOP_MUL);
if (!is_space(c)) {
buffer_->unread_char(c);
}
break;
case DIVIDE:
state = DONE;
token = new MulopToken(mulop_attr_type::MULOP_DIV);
if (!is_space(c)) {
buffer_->unread_char(c);
}
break;
case NUMBER:
if (is_digit(c)) {
state = NUMBER;
attribute.push_back(c);
} else {
state = DONE;
token = new NumToken(attribute);
if (!is_space(c)) {
buffer_->unread_char(c);
}
}
break;
case END_OF_FILE:
state = DONE;
token = new EofToken();
break;
default:
break;
}
}
return token;
}
| true |
fbdab31baad20920cb085d764b2f81e921f51eef
|
C++
|
EDRappaport/DSA
|
/Program 2/DSA_Proj2_firstAttmpt.cpp
|
UTF-8
| 5,638 | 3.0625 | 3 |
[] |
no_license
|
// THIS IS THE PROVIDED CODE FOR PROGRAM #2, DSA 1, SPRING 2012
#include <iostream>
#include <fstream>
#include <sstream>
#include <list>
#include <vector>
#include <string>
#include <algorithm>
#include <ctime>
#include <cmath>
#include <cstring>
#include <cctype>
#include <cstdlib>
using namespace std;
// A simple class; each object holds one string
class Data {
public:
string data;
Data(const string &s) { data = s; }
};
// Load the data from a specified input file
void loadDataList(list<Data *> &l) {
string filename;
cout << "Enter name of input file: ";
cin >> filename;
ifstream input(filename.c_str());
if (!input) {
cerr << "Error: could not open " << filename << endl;
exit(1);
}
// The first line indicates the size
string line;
getline(input, line);
stringstream ss(line);
int size;
ss >> size;
// Load the data
for (int i = 0; i < size; i++) {
string line;
getline(input, line);
l.push_back(new Data(line));
}
input.close();
}
// Output the data to a specified input file
void writeDataList(const list<Data *> &l) {
string filename;
cout << "Enter name of output file: ";
cin >> filename;
ofstream output(filename.c_str());
if (!output) {
cerr << "Error: could not open " << filename << endl;
exit(1);
}
// Write the size first
int size = l.size();
output << size << endl;
// Write the data
for (list<Data *>::const_iterator ipD = l.begin(); ipD != l.end(); ipD++) {
output << (*ipD)->data << endl;
}
output.close();
}
void sortDataList(list<Data *> &);
// The main function calls routines to get the data, sort the data,
// and output the data. The sort is timed according to CPU time.
int main() {
list<Data *> theList;
loadDataList(theList);
cout << "Data loaded. Executing sort..." << endl;
clock_t t1 = clock();
sortDataList(theList);
clock_t t2 = clock();
double timeDiff = ((double) (t2 - t1)) / CLOCKS_PER_SEC;
cout << "Sort finished. CPU time was " << timeDiff << " seconds." << endl;
writeDataList(theList);
}
// -------------------------------------------------
// YOU MAY NOT CHANGE OR ADD ANY CODE ABOVE HERE !!!
// -------------------------------------------------
// You may add global variables, functions, and/or
// class defintions here if you wish.
Data* buckets[11][26][1010000];
int ind[11][33];
int kk =99;
int hh = 4;
bool compare (Data* first, Data* second);
void T1_2sort(list<Data *> &l);
void T3sort(list<Data *> &l);
void T4sort(list<Data *> &l);
void identify(list<Data *> &l);
Data* newvec[11][1010000];
unsigned long n;
int here=0;
string temp;
list<Data *>::iterator i_1;
list<Data *>::iterator i;
list<Data *>::iterator it;
list<Data *>::iterator itb;
int ii, jj, ww, newn, tot, yy;
bool swapped;
int id [7] = {0, 0, 0, 0, 0, 0, 0};
void sortDataList(list<Data *> &l) {
if (l.size() < 200000){
//cout<<"This guy is T1"<<endl;
T1_2sort(l);}
else identify(l);
}
bool compare (Data* first, Data* second){
if (((first)->data)<((second)->data)) return true;
else if (((first)->data)>((second)->data)) return false;
}
void identify(list<Data *> &l) {
itb = l.begin();
if ((((*itb)->data)[0])<65){
//cout<<"This guy is T2"<<endl;
T1_2sort(l);}
else{
for (itb = l.begin(), yy=0; yy<6; itb++, yy++){
if ((((*itb)->data)[0])>64 && (((*itb)->data)[0])<91){
id[yy] = 1;}
else if ((((*itb)->data)[0])>96 && (((*itb)->data)[0])<123){
id [yy] = 2;}
else id[yy] =3;}
if (id[0] == 1 && id[1] ==1 && id[2] ==1 && id[3] ==1 && id[4] ==1 && id[5] ==1){
//cout<<"This guy is T4"<<endl;
T4sort(l);}
else if (id[0] == 2 && id[1] ==2 && id[2] ==2 && id[3] ==2 && id[4] ==2 && id[5] ==2){
//cout<<"This guy is T3"<<endl;
T3sort(l);}
else{
//cout<<"This guy is T2"<<endl;
T1_2sort(l);}
}}
void T1_2sort(list<Data *> &l) {
for (itb = l.begin(); itb!=l.end(); itb++){
buckets[0][((((*itb)->data)[0])/10)-3][ind[0][((((*itb)->data)[0])/10)-3]++] = *itb;}
//tot=0;
for (ii = 0; ii<13; ii++){
if (ind[0][ii]!=0){
sort(&buckets[0][ii][0], &buckets[0][ii][ind[0][ii]], compare);
/*for (jj = 0; jj<ind[0][ii]; jj++, tot++)
newvec[0][tot] = buckets[0][ii][jj];*/
}}
itb = l.begin();
for(ii=0; ii<13; ii++)
for (jj=0; jj<ind[0][ii]; jj++, itb++)
*itb = buckets[0][ii][jj];
//l.assign(newvec[0], newvec[0]+l.size());
}
void T3sort(list<Data *> &l) {
it = l.begin();
for (itb = l.begin(); itb!=l.end(); itb++){
buckets[here][(((*itb)->data)[hh])-97][ind[here][(((*itb)->data)[hh])-97]++] = *itb;}
tot=0;
for (ii = 0; ii<26; ii++){
if (ind[here][ii]!=0){
for (jj = 0; jj<ind[here][ii]; jj++, tot++)
newvec[here][tot] = buckets[here][ii][jj];
}}
l.assign(newvec[here], newvec[here]+l.size());
hh--;
if (hh>=0){
here++;
T3sort(l);}}
void T4sort(list<Data *> &l) {
it = l.begin();
for (itb = l.begin(); itb!=l.end(); itb++){
buckets[here][(((*itb)->data)[kk])-65][ind[here][(((*itb)->data)[kk])-65]++] = *itb;}
tot=0;
for (ii = 0; ii<26; ii++){
if (ind[here][ii]!=0){
for (jj = 0; jj<ind[here][ii]; jj++, tot++)
newvec[here][tot] = buckets[here][ii][jj];
}}
l.assign(newvec[here], newvec[here]+l.size());
kk--;
if (kk>=90){
here++;
T4sort(l);}
else{
n =l.size();
newn = 0;
swapped = true;
while(n!=0){
while (swapped ==true){
for (ww =1; ww < n ; ww++){
i_1 = it;
i = ++it;
if ((*i_1)->data > (*i)->data){
temp = (*i_1)->data;
(*i_1)->data = (*i)->data;
(*i)->data = (*i_1)->data;
newn = ww;
swapped = true;}
else swapped = false;}
n = newn;}}
}}
| true |
b9b7201677d4d48f9b6eb46467d7e84901124f54
|
C++
|
BaherAbdelfatah/Object-Oriented-Programming-with-Cplusplus-
|
/OOP_MD_1/OOP_MD_1/Student.cpp
|
UTF-8
| 611 | 3.375 | 3 |
[] |
no_license
|
#include "Student.h"
Student::Student(string n, string g, float a, int l, float gp, string d):Person(n, g, a)
{
level = l;
GPA = gp;
depart = d;
}
void Student::set_level(int l)
{
level = l;
}
void Student::set_GPA(float g)
{
GPA = g;
}
void Student::set_depart(string d)
{
depart = d;
}
int Student::get_level()
{
return level;
}
float Student::get_GPA()
{
return GPA;
}
string Student::get_depart()
{
return depart;
}
void Student::display()
{
Person::display();
cout << "Depart= " << depart << " ,Level= " << level << " ,GPA= "<< GPA << endl;
}
| true |
afd99bbe8c6efa07e6d2475109f4a6ec7b7d20b4
|
C++
|
fantasia85/MyRPC
|
/myrpc/network/UThreadRuntime.h
|
UTF-8
| 1,260 | 2.78125 | 3 |
[] |
no_license
|
/* 封装了协程的调度,并用一个context_list_保存所有协程上下文 ,
* 每一个上下文被封装成一个ContextSlot.
* */
#pragma once
#include "UThreadContextBase.h"
#include <vector>
namespace myrpc {
class UThreadRuntime {
public:
UThreadRuntime(size_t stack_size, const bool need_stack_protect);
~UThreadRuntime();
//创建一个上下文
int Create(UThreadFunc_t func, void *args);
int GetCurrUThread();
//封装了UThreadContext的对应操作
bool Yield();
//封装了UThreadContext的对应操作
bool Resume(size_t index);
bool IsAllDone();
int GetUnfinishedItemCount() const;
void UThreadDoneCallback();
private:
//把每个上下文封装成一个ContextSlot的结构
struct ContextSlot {
ContextSlot() {
context = nullptr;
next_done_item = -1;
}
UThreadContext *context;
//保存下一个可用的Slot下标
int next_done_item;
int status;
};
size_t stack_size_;
std::vector<ContextSlot> context_list_;
//保存上一个已经完成的上下文下标
int first_done_item_;
int current_uthread_;
int unfinished_item_count_;
bool need_stack_protect_;
};
}
| true |
267e9e8e8772f512569f071c8b40ad41a4af26d4
|
C++
|
daniellemersch/libants
|
/statistics.h
|
UTF-8
| 2,514 | 3.375 | 3 |
[] |
no_license
|
/*
* statistics.h
*
* Created by Danielle Mersch
* Copyright Unil. All rights reserved.
*
*/
#ifndef __statistics__
#define __statistics__
#include <cmath>
#include <iostream>
#include <list>
#include <cstdlib>
using namespace std;
const double MAX_DOUBLE = 1.7e308; //< maximum value that can be expressed in a double
const double MIN_DOUBLE = 4.94e-324; //< minimum value that can be expressed in a double
class Stats{
public:
Stats();
~Stats();
/**\brief Reset all the values and clears the lists
*/
void reset();
/**\brief Adds a value to the sum, counter, sum of square and to the list
*\param value The element to be added
*/
void add_element(double value);
/**\brief Adds an angle to the sums, counters and to the list
*\param value The element to be added
*/
void add_angle(double angle);
/**\brief Calculates the arithmetric mean of the values
*\return The mean
*/
double calculate_mean();
/**\brief Calculates the geometric mean of the values
*\return The geometric mean
*/
double calculate_geometric_mean();
/**\brief Calculates the harmonic mean of the values
*\return The harmonic mean
*/
double calculate_harmonic_mean();
/**\brief Calculates the standard deviation of the values
*\return The standard deviation
*/
double calculate_stdev();
/**\brief Finds the median of the values
* \return The value of the median
*/
double find_median();
/**\brief Calculates the arithmetric mean of the angles
*\return The mean angle in degrees
*/
double calculate_mean_angle();
/**\brief Finds the median angle
* \return The median angle in degrees
*/
double find_median_angle();
protected:
private:
double sum_square; ///< sum of square of elements
double sum; //< sum of elements
unsigned int ctr; //< number of elements
list <double> value_list; //< list of elements
double produit; // product of values
bool produit_flag; //< flag to indicate if the product of values can be used and if mean is valid. Goal: prevent usage of inf or zeros
double rapport; //< sum of ratios of values
bool rapport_flag; //< flag to indicate if the sum of ratios can be used and if the mean is valid. Goal: prevent usage of zero values.
double sum_sin; //< sum of sine of angles
double sum_cos; //< sum of cosine of angles
unsigned int actr; //< counter of angles
list <double> angle_list; //< list of angles
};
#endif // --statistics__
| true |
69ab12cd92b6c6f3c16187a6edd0e363c0b0e2f7
|
C++
|
ashn01/algorithm
|
/MaximumBinaryTree.cpp
|
UTF-8
| 2,513 | 3.859375 | 4 |
[] |
no_license
|
//https://leetcode.com/problems/maximum-binary-tree/description/
//Given an integer array with no duplicates. A maximum tree building on this array is defined as follow:
//
//The root is the maximum number in the array.
//The left subtree is the maximum tree constructed from left part subarray divided by the maximum number.
//The right subtree is the maximum tree constructed from right part subarray divided by the maximum number.
//Construct the maximum tree by the given array and output the root node of this tree.
//
//Example 1:
//Input: [3,2,1,6,0,5]
//Output: return the tree root node representing the following tree:
//
// 6
// / \
// 3 5
// \ /
// 2 0
// \
// 1
//Note:
//The size of the given array will be in the range [1,1000].
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
int max = 0;
int idx=0;
for(int i=0;i<nums.size();i++)
if(nums[i] > max)
{
max = nums[i];
idx=i;
}
TreeNode* ret = new TreeNode(nums[idx]);
make(nums, ret->left, 0, idx);
make(nums, ret->right, idx+1, nums.size());
return ret;
}
void make(vector<int>& nums, TreeNode*& subRoot, int from, int to)
{
if(from == to)
return;
int max = -1;
int idx=-1;
for(int i=from;i<to;i++)
if(nums[i] > max)
{
max = nums[i];
idx=i;
}
subRoot = new TreeNode(nums[idx]);
if(from != idx)
make(nums, subRoot->left, from, idx);
if(idx+1 != to)
make(nums, subRoot->right, idx+1, to);
}
/*void deletion(TreeNode*& ohs)
{
if(ohs != nullptr)
{
if(ohs->left != nullptr)
{
deletion(ohs->left);
}
if(ohs->right != nullptr)
{
deletion(ohs->right);
}
if(ohs->left == nullptr && ohs->right == nullptr)
{
cout << "delete : " << ohs->val<<endl;
delete ohs;
ohs = nullptr;
}
}
}
~Solution()
{
deletion(ret);
}*/
};
| true |
f9f402420ea6277f1242617387a74a2fcb1acad3
|
C++
|
ElderSix/my_leetcode
|
/tree/513_Find_Bottom_Left_Tree_Value.cpp
|
UTF-8
| 2,766 | 4.125 | 4 |
[] |
no_license
|
/*
Given a binary tree, find the leftmost value in the last row of the tree.
Example 1:
Input:
2
/ \
1 3
Output:
1
Example 2:
Input:
1
/ \
2 3
/ / \
4 5 6
/
7
Output:
7
*/
#include <iostream>
#include <vector>
using std::cin;
using std::cout;
using std::endl;
using std::vector;
/**
* Definition for binary tree
*/
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
explicit TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
class Solution {
public:
int findBottomLeftValue(TreeNode* root) {
if(!root) {
return 0;
}
int val = root->val;
int max_level = 0;
travel(root, 0, &max_level, &val);
return val;
}
private:
void travel(TreeNode *root, int level, int *max_level, int *val) {
if((!root->left)&&(!root->right)) {
if(level > *max_level) {
*max_level = level;
*val = root->val;
}
return;
}
if(root->left) {
travel(root->left, level+1, max_level, val);
}
if(root->right) {
travel(root->right, level+1, max_level, val);
}
}
};
class BSTree {
public:
BSTree():size(0),root(nullptr) {}
int insert(int d);
TreeNode* search(int d, TreeNode** parent);
int deleteNode(TreeNode* node);
void print();
TreeNode* root;
private:
int size;
void do_print(TreeNode* begin);
};
int BSTree::insert(int d) {
TreeNode* pnode = nullptr;
TreeNode* new_node = new TreeNode(d);
TreeNode* node = search(d, &pnode);
if(!pnode) {
root = new_node;
return 0;
}
if(!node) {
if(d <= pnode->val) {
pnode->left = new_node;
}else {
pnode->right = new_node;
}
}else {
new_node->left = node->left;
node->left = new_node;
}
return 0;
}
TreeNode* BSTree::search(int d, TreeNode** parent) {
TreeNode *begin = root;
while((begin != nullptr) && (begin->val != d)) {
*parent = begin;
begin = (begin->val < d) ? begin->right : begin->left;
} //Find the first one
return begin;
}
void BSTree::print() {
do_print(root);
}
void BSTree::do_print(TreeNode* begin) {
if(!begin) {
return;
}
cout<<"[";
do_print(begin->left);
cout<<" "<<begin->val<<" ";
do_print(begin->right);
cout<<"]";
return;
}
int main() {
BSTree tree;
vector<int> input = {9,2,1,6,3,5,8};
for(auto x : input) {
tree.insert(x);
}
tree.print();
cout<<endl;
Solution slt;
int result = slt.findBottomLeftValue(tree.root);
cout<<result<<endl;
}
| true |
dcf1cd7fdce9ea336958d5d22f301fa95abfb439
|
C++
|
tomerr1212/MasterMindGame
|
/SmartGuesser.hpp
|
UTF-8
| 520 | 2.515625 | 3 |
[] |
no_license
|
#pragma once
#include "calculate.hpp"
#include "Guesser.hpp"
#include <string>
#include <list>
#include<iterator>
using std::string;
namespace bullpgia{
class SmartGuesser:public bullpgia::Guesser{
public:
string firstGuess="";
list <string> combination;
uint length;
int counterGuess=0;
int sumOf=0;
void learn(string calculate)override;
void startNewGame(uint length)override;
string guess() override;
};
}
| true |
d9cf9bb35a5ab9380c52e3fb44a677e62e4aa217
|
C++
|
rootid/fft
|
/2d/set-matrix-zeroes.cpp
|
UTF-8
| 4,785 | 3.59375 | 4 |
[] |
no_license
|
//Set Matrix Zeroes
//Given a m x n matrix, if an element is 0, set its entire row and column to 0.
//Do it in place.
//######################################### 2 traversals (L-R),(R-L) #########################################
public void setZeroes(int[][] matrix) {
int m = matrix.length, n = matrix[0].length, k = 0;
// First row has zero?
while (k < n && matrix[0][k] != 0) ++k;
// Use first row/column as marker, scan the matrix
for (int i = 1; i < m; ++i)
for (int j = 0; j < n; ++j)
if (matrix[i][j] == 0)
matrix[0][j] = matrix[i][0] = 0;
// Set the zeros
for (int i = 1; i < m; ++i)
for (int j = n - 1; j >= 0; --j)
if (matrix[0][j] == 0 || matrix[i][0] == 0)
matrix[i][j] = 0;
// Set the zeros for the first row
if (k < n) Arrays.fill(matrix[0], 0);
}
//######################################### 2 traversals (L-R),(R-L) #########################################
//store states of each row in the first of that row, and store states of each
//column in the first
//of that column. Because the state of row0 and the state of column0 would
//occupy the same cell, I
//let it be the state of row0,
//and use another variable "col0" for column0. In the first phase, use matrix
//elements to set states
//in a top-down way. In the second phase, use states to set matrix elements in
//a bottom-up way.
void setZeroes(vector<vector<int> > &matrix) {
int col0 = 1, rows = matrix.size(), cols = matrix[0].size();
for (int i = 0; i < rows; i++) { //L-R
if (matrix[i][0] == 0) col0 = 0;
for (int j = 1; j < cols; j++)
if (matrix[i][j] == 0)
matrix[i][0] = matrix[0][j] = 0;
}
for (int i = rows - 1; i >= 0; i--) {
for (int j = cols - 1; j >= 1; j--)
if (matrix[i][0] == 0 || matrix[0][j] == 0)
matrix[i][j] = 0;
if (col0 == 0) matrix[i][0] = 0;
}
}
//######################################### 2 traversals (L-R),(R-L) #########################################
void setZeroes(vector<vector<int> >& matrix) {
int m = matrix.size();
int n = matrix[0].size();
bool is_col_zero = false;
for(int i=0;i<m;i++) {
if(matrix[i][0] == 0) {
is_col_zero = true;
}
for(int j=1;j<n;j++) {
if(matrix[i][j] == 0) {
matrix[i][0] = 0;
matrix[0][j] = 0;
}
}
}
for(int i=m-1;i>=0;i--) {
for(int j=n-1;j>=1;j--) {
if(matrix[i][0] == 0 || matrix[0][j] == 0) {
matrix[i][j] = 0;
}
}
}
if(is_col_zero) {
for(int i=0;i<m;i++) {
matrix[i][0] = 0;
}
}
}
//######################################### Ugly solution #########################################
class Solution {
public void setZeroes(int[][] matrix) {
int m = matrix.length;
int n = matrix[0].length;
boolean isRowZero = false;
boolean isColZero = false;
if(isRowZero == false) {
int i=0, j=0;
while(i<m) if(matrix[i++][0] == 0) isRowZero = true;
while(j<n) if(matrix[0][j++] == 0) isColZero = true;
}
for(int i=0;i<m;i++) {
for(int j=1;j<n;j++) {
if(matrix[i][j] == 0) {
matrix[0][j] = 0;
matrix[i][0] = 0;
}
}
}
for(int i=1;i<m;i++) {
if(matrix[i][0] == 0) {
int j = 0;
while(j<n) matrix[i][j++] = 0;
}
}
for(int j=1;j<n;j++) {
if(matrix[0][j] == 0) {
int i = 0;
while(i<m) matrix[i++][j] = 0;
}
}
if(isRowZero == true) {
int i=0;
while(i<m) matrix[i++][0] = 0;
}
if(isColZero == true) {
int j =0;
while(j<n) matrix[0][j++] = 0;
}
}
}
//######################################### 2 traversals (L-R),(R-L) python #########################################
def setZeroes(self, matrix):
# First row has zero?
m, n, firstRowHasZero = len(matrix), len(matrix[0]), not all(matrix[0])
# Use first row/column as marker, scan the matrix
for i in xrange(1, m):
for j in xrange(n):
if matrix[i][j] == 0:
matrix[0][j] = matrix[i][0] = 0
# Set the zeros
for i in xrange(1, m):
for j in xrange(n - 1, -1, -1):
if matrix[i][0] == 0 or matrix[0][j] == 0:
matrix[i][j] = 0
# Set the zeros for the first row
if firstRowHasZero:
matrix[0] = [0] * n
| true |
518db8626b7c9df97afe536aa49339a50c8cd738
|
C++
|
zsq001/oi-code
|
/7.20/source/Stu-12-张荣国/massage.cpp
|
UTF-8
| 1,280 | 2.546875 | 3 |
[] |
no_license
|
#include<stdio.h>
#include<algorithm>
#include<string.h>
#include<math.h>
using namespace std;
int n,q,f[10][10][10][10],a[205][5],tot;
void read(int &x){
int t=0;x=0;char s=getchar();
while(s<'0'||s>'9') { if(s=='0') t=1; s=getchar();}
while(s>='0'&&s<='9') { x=(x<<3)+(x<<1)+(s^48);s=getchar();}
x=t?-x:x;
}
bool is_prime(int p){
for(int i=2;i<=sqrt(p)+1;i++)
if(p%i==0) return 0;
return 1;
}
void div(int x){
tot++;
int tmp=x;
a[tot][1]=x/1000;
a[tot][2]=x/100%10;
a[tot][3]=x/10%10;
a[tot][4]=x%10;
}
int main(){
freopen("massage.in","r",stdin);
freopen("massage.out","w",stdout);
read(n),read(q);
int x,y;
for(int o=1;o<=n;o++){
memset(f,0x3f,sizeof(f));
read(x),read(y);
div(x);
div(y);
int I=a[o*2-1][1],J=a[o*2-1][2],K=a[o*2-1][3],L=a[o*2-1][4];
f[a[o*2][1]][a[o*2][2]][a[o*2][3]][a[o*2][4]]=0;
for(int i=-9;i<=9;i++){
for(int j=-9;j<=9;j++){
for(int k=-9;k<=9;k++){
for(int l=-9;l<=9;l++){
if(I+i<=9&&J+j<=9&&K+k<=9&&L+l<=9&&I+i>=1&&J+j>=0&&K+k>=0&&L+l>=0&&is_prime((I+i)*1000+(J+j)*100+(K+k)*10+(L+l)))
f[I][J][K][L]=min(f[I+i][J+j][K+k][L+l]+abs(i)+abs(j)+abs(k)+abs(l),f[I][J][K][L]);
}
}
}
}
printf("%d\n",f[I][J][K][L]);
}
return 0;
}
| true |
b3da0dee7858cceee9ee90ab16f3ab1f736cb72b
|
C++
|
alvas/ms_interview_100
|
/leetcode/PowerOfTwo.cpp
|
UTF-8
| 366 | 3.390625 | 3 |
[] |
no_license
|
#include <iostream>
using namespace std;
class Solution {
public:
bool isPowerOfTwo(int n) {
if (n <= 0)
{
return 0;
}
return (n & (n - 1)) == 0;
}
};
int main()
{
Solution sln;
int n = 0;
std::cout << "Please enter n: ";
cin >> n;
std::cout << sln.isPowerOfTwo(n) << endl;
return 0;
}
| true |
26cd4c3e21d18b86e414df382617554166592664
|
C++
|
mulenatic/arduino
|
/arduinoAdventures/challenge1/challenge1.ino
|
UTF-8
| 384 | 2.6875 | 3 |
[] |
no_license
|
void setup() {
// setup serial port
Serial.begin(9600);
}
void loop() {
// set sensorValue to the reading on analog input 0
int sensorValue = analogRead(A0);
// set the mappedSensorValue to the value of the map() function
int mappedSensorValue = map(sensorValue, 0, 1023, 0, 9);
// send mappedSensorValue to the serial port.
Serial.println(mappedSensorValue, DEC);
}
| true |
70e6b94c70f6065960b065bc5503c66258d1e985
|
C++
|
chiahsun/problem_solving
|
/UVA/APOAPC_2nd/12325 - Zombie's Treasure Chest/solve1.cc.not_clean.cxx
|
UTF-8
| 2,399 | 2.84375 | 3 |
[] |
no_license
|
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <utility>
#include <algorithm>
const bool debug = false;
bool double_equal(double d1, double d2) {
return fabs(d1 - d2) < 1E-9;
}
long long solve(long long N, long long S1, long long V1, long long S2, long long V2) {
double per_value_s1 = double(V1)/S1;
double per_value_s2 = double(V2)/S2;
// XXX: if equal value put large to s2
if (per_value_s1 > per_value_s2 or (double_equal(per_value_s1, per_value_s2) and S1 > S2)) {
std::swap(per_value_s1, per_value_s2);
std::swap(S1, S2);
std::swap(V1, V2);
}
if (debug) {
printf("N : %lld (S1, V1) : (%lld, %lld) (S2, V2) : (%lld, %lld)\n", N, S1, V1, S2, V2);
printf("per value s1 : %f, per value s2 : %f\n", per_value_s1, per_value_s2);
}
long long max_num_s2 = N/S2;
double per_waste = per_value_s2 - per_value_s1;
long long left_num = N - max_num_s2 * S2;
long long min_num_s1 = left_num / S1;
long long left_left_num = left_num - min_num_s1 * S1;
double max_regain = left_left_num * per_value_s1;
long long max_value = max_num_s2 * V2 + min_num_s1 * V1;
if (max_regain == 0)
return max_value;
if (debug)
printf("init ns1(%lld) ns2(%lld) max_value(%lld)\n", min_num_s1, max_num_s2, max_value);
for (long long i = max_num_s2-1; i >= 0; --i) {
double waste = (max_num_s2 - i) * S2 * per_waste;
long long k = (N - i * S2)/S1;
long long value = i * V2 + k * V1;
max_value = std::max(max_value, value);
if (debug)
printf("ns1(%lld) ns2(%lld) value(%lld) max_value(%lld) waste(%f) max_regain(%f)\n", k, i, value, max_value, waste, max_regain);
if (waste > max_regain) {
// if (debug)
printf("break at waste(%f) > max_regain(%f)\n", waste, max_regain);
break;
}
if (k > 0 and (k * S1) % S2 == 0) {
// if (debug)
printf("break at (ns1 * s1) %% s2 == 0, (%lld * %lld) %% %lld == \n", k, S1, S2);
break;
}
}
return max_value;
}
int main() {
int nCase, posCase = 1;
scanf("%d", &nCase);
int N, S1, V1, S2, V2;
while (nCase--) {
scanf("%d%d%d%d%d", &N, &S1, &V1, &S2, &V2);
printf("Case #%d: %lld\n", posCase++, solve(N, S1, V1, S2, V2));
}
return 0;
}
| true |
76fbdbb3af5b8feb24ada4acf8c575c9829e0438
|
C++
|
modern-cmake/buildit
|
/src/blocks/rce.cpp
|
UTF-8
| 3,553 | 2.578125 | 3 |
[
"MIT"
] |
permissive
|
#include "blocks/rce.h"
namespace block {
void check_side_effects::visit(assign_expr::Ptr) {
has_side_effects = true;
}
void check_side_effects::visit(function_call_expr::Ptr) {
has_side_effects = true;
}
void check_side_effects::visit(addr_of_expr::Ptr) {
has_side_effects = true;
}
void use_counter::visit(var_expr::Ptr a) {
if (a->var1 == to_find)
total_uses++;
}
void gather_redundant_decls::visit(decl_stmt::Ptr decl) {
if (decl->init_expr == nullptr)
return;
// Let us only replace those variables that are either simple variables on the RHS
// Or are used exactly once
if (isa<var_expr>(decl->init_expr)) {
//current_decl = decl;
gathered_decls.push_back(decl);
return;
}
use_counter counter;
counter.to_find = decl->decl_var;
ast->accept(&counter);
if (counter.total_uses <= 1) {
check_side_effects checker;
decl->init_expr->accept(&checker);
if (counter.total_uses == 0 || checker.has_side_effects == false) {
gathered_decls.push_back(decl);
}
}
}
void gather_redundant_decls::visit(assign_expr::Ptr assign) {
std::vector<decl_stmt::Ptr> new_gathers;
if (!isa<var_expr>(assign->var1))
return;
var_expr::Ptr var1 = to<var_expr>(assign->var1);
for (auto a: gathered_decls) {
if (a->decl_var == var1->var1)
continue;
new_gathers.push_back(a);
}
gathered_decls = new_gathers;
}
void replace_redundant_vars::visit(var_expr::Ptr e) {
if (!decl_found) {
node = e;
return;
}
if (e->var1 == to_replace->decl_var) {
node = to_replace->init_expr;
has_replaced = true;
} else {
node = e;
}
}
void replace_redundant_vars::visit(decl_stmt::Ptr decl) {
if (decl->init_expr)
decl->init_expr = rewrite(decl->init_expr);
if (decl->decl_var == to_replace->decl_var)
decl_found = true;
node = decl;
}
void replace_redundant_vars::visit(assign_expr::Ptr assign) {
assign->expr1 = rewrite(assign->expr1);
assign->var1 = rewrite(assign->var1);
if (!isa<var_expr>(to_replace->init_expr))
decl_found = false;
node = assign;
}
void replace_redundant_vars::visit(addr_of_expr::Ptr addr) {
addr->expr1 = rewrite(addr->expr1);
if (!isa<var_expr>(to_replace->init_expr))
decl_found = false;
node = addr;
}
void replace_redundant_vars::visit(function_call_expr::Ptr f) {
for (unsigned int i = 0; i < f->args.size(); i++) {
f->args[i] = rewrite(f->args[i]);
}
if (!isa<var_expr>(to_replace->init_expr))
decl_found = false;
node = f;
}
void decl_eraser::visit(stmt_block::Ptr block) {
std::vector<stmt::Ptr> new_stmts;
for (auto s: block->stmts) {
if (s == to_erase)
continue;
s->accept(this);
new_stmts.push_back(s);
}
block->stmts = new_stmts;
}
void eliminate_redundant_vars(block::Ptr ast) {
gather_redundant_decls gather;
gather.ast = ast;
ast->accept(&gather);
while (gather.gathered_decls.size()) {
decl_stmt::Ptr to_replace = gather.gathered_decls.back();
gather.gathered_decls.pop_back();
if (!isa<var_expr>(to_replace->init_expr)) {
use_counter pre_counter;
pre_counter.to_find = to_replace->decl_var;
ast->accept(&pre_counter);
if (pre_counter.total_uses != 1) {
continue;
}
}
replace_redundant_vars replacer;
replacer.to_replace = to_replace;
ast->accept(&replacer);
// Now that replacing has been done
// Count the number of occurences
// If zero, delete
use_counter counter;
counter.to_find = to_replace->decl_var;
ast->accept(&counter);
if (counter.total_uses == 0) {
decl_eraser eraser;
eraser.to_erase = to_replace;
ast->accept(&eraser);
}
}
}
}
| true |
ea7f87bcd995ff7bf002a1eede3ea299ec73c72c
|
C++
|
chaithubk/qt_tcpserver
|
/mytcpserver.cpp
|
UTF-8
| 2,679 | 2.703125 | 3 |
[] |
no_license
|
#include "mytcpserver.h"
#include <QTime>
QString MyTcpServer::simData[VS_ID_LAST] =
{
"60", // 0 - Heart rate
"27" // 1 - Temperature
};
MyTcpServer::MyTcpServer(QObject *parent) :
QObject(parent)
, m_server()
, m_socket(NULL)
, m_delayTimer()
{
connect(&m_delayTimer, SIGNAL(timeout()), this, SLOT(delayTimeoutHanlder()));
m_server = new QTcpServer(this);
// whenever a user connects, it will emit signal
connect(m_server, SIGNAL(newConnection()),
this, SLOT(newConnection()));
if(!m_server->listen(QHostAddress::Any, 2346))
qDebug() << "Server could not start";
else
qDebug() << "Server started!";
if(m_server->isListening())
qDebug() << "Server is listening";
m_delayTimer.start(200);
for(int i = VS_ID_HR; i < VS_ID_LAST; i++)
m_vsData[i] = "---";
}
MyTcpServer::~MyTcpServer()
{
}
void MyTcpServer::delayTimeoutHanlder()
{
writeToSocket();
}
// This function will get called everytime a new telnet connection is established
void MyTcpServer::newConnection()
{
// If there are no pending connections, bail
if(m_server->hasPendingConnections())
{
m_socket = m_server->nextPendingConnection();
if(m_socket)
{
qDebug() << "New connection established: " << m_socket;
for(int i = VS_ID_HR; i < VS_ID_LAST; i++)
m_vsData[i] = simData[i];
}
else
qDebug() << "Failed to establish new connection: " << m_socket;
}
else
{
qDebug() << "No Pending Connections";
return;
}
}
void MyTcpServer::writeToSocket()
{
char data[100];
static int index = VS_ID_HR;
if(!m_socket)
return;
if(m_socket)
{
sprintf(data, "%d^%s", index, m_vsData[index].toStdString().data());
if(++index >= VS_ID_LAST)
index = VS_ID_HR;
if( -1 == m_socket->write(data) )
{
qDebug() << "Socket Write error: " << m_socket->localAddress() << "Port: " << m_socket->localPort();
if(m_socket != NULL)
{
m_socket->close();
delete m_socket;
m_socket = NULL;
for(int i = VS_ID_HR; i < VS_ID_LAST; i++)
m_vsData[i] = "---";
}
return;
}
qDebug() << "Writing to socket: " << m_socket->localAddress() << "Port: " << m_socket->localPort();
m_socket->flush();
// m_socket->waitForBytesWritten(500);
}
}
| true |
f882fc31cddb286e09f1c9aafe612d25b70073d1
|
C++
|
carlostule/ESCOM
|
/Desarrollo de Sistemas Distribuidos/Practica5/PoligonoIrregular.cpp
|
UTF-8
| 859 | 2.640625 | 3 |
[
"Apache-2.0"
] |
permissive
|
/*
IPN - ESCOM
Desarrollo de Sistemas Distribuidos
4CM1
Equipo 5
=> Hernández Jiménez Enrique
=> Ortega Ortuño Eder
=> Fernandez Eduardo
multiaportes.com/sistemasdistribuidos
*/
#include <iostream>
#include "PoligonoIrregular.hpp"
int PoligonoIrregular::contadorVertices = 0;
PoligonoIrregular::PoligonoIrregular()
{
}
void PoligonoIrregular::agregarVertice(Coordenada c, bool benchmarking)
{
if(benchmarking)
{
this->coords.reserve(this->coords.size() + 10);
this->coords.push_back(c); // Aumenta su capacidad en uno si no hay más espacio disponible
}
else
{
this->coords.push_back(c);
}
contadorVertices++;
}
void PoligonoIrregular::imprimirVertices()
{
int i;
for(i = 0; i < this->coords.size(); i++)
std::cout << "X = " << this->coords[i].getX() << "\tY = " << this->coords[i].getY() << std::endl;
}
int PoligonoIrregular::getContador()
{
return contadorVertices;
}
| true |
ab3c67b61db3c40c9b1902e665bcedcfbc547bc0
|
C++
|
polatory/polatory
|
/include/polatory/point_cloud/sdf_data_generator.hpp
|
UTF-8
| 806 | 2.71875 | 3 |
[
"MIT"
] |
permissive
|
#pragma once
#include <polatory/geometry/point3d.hpp>
#include <polatory/types.hpp>
namespace polatory::point_cloud {
// Generates signed distance function data from given points and normals.
class sdf_data_generator {
public:
sdf_data_generator(const geometry::points3d& points, const geometry::vectors3d& normals,
double min_distance, double max_distance, double multiplication = 2.0);
const geometry::points3d& sdf_points() const;
const common::valuesd& sdf_values() const;
private:
const geometry::points3d points_; // Do not hold a reference to a temporary object.
const geometry::vectors3d normals_; // Do not hold a reference to a temporary object.
geometry::points3d sdf_points_;
common::valuesd sdf_values_;
};
} // namespace polatory::point_cloud
| true |
5ba8a8e0df8838f4c094da989b6a3e7c1121840f
|
C++
|
kennethpham/DungeonGameCpp
|
/assassin.h
|
UTF-8
| 459 | 3.078125 | 3 |
[] |
no_license
|
#include <string>
#include <vector>
#include "character.h"
class Assassin : public Character // A character that can critically strike for bonus damage, and evade attacks
{
private:
int critChance = 10; // % chance of critting
int critDamage = 2; // Factor that an attack increases in damage by when critting
int evadeChance = 15; // % chance of dodging an attack
public:
Assassin();
int attack() const;
bool takeDamage(int dmg);
};
| true |
3f95026fe404515e189f5f472deaea37d2c3279c
|
C++
|
KalahariKanga/ooImages
|
/Expression.cpp
|
UTF-8
| 2,007 | 2.765625 | 3 |
[] |
no_license
|
#include "Expression.h"
ImageStore* const Expression::store = ImageStore::get();
Expression::Expression()
{
}
Expression::~Expression()
{
}
Variable Expression::getResult()
{
if (!constancyOptimisation)
return evaluate();
if (isConstant && optimisable)
{
if (!hasConstantValue)
{
hasConstantValue = 1;
constantValue = evaluate();
}
return constantValue;
}
else
return evaluate();
}
bool Expression::calculateConstancy()
{
isConstant = 1;
for (auto a : arguments)
{
if (!a->calculateConstancy())
{
isConstant = 0;
}
}
return isConstant;
}
void Expression::setLocalVariable(std::string name, Variable var)
{
auto exp = localVariableExists(name);
if (exp)
exp->localVariables[name] = var;
else
localVariables[name] = var;
}
void Expression::setLocalVariable(std::string name, float* val)
{
auto exp = localVariableExists(name);
if (exp)
exp->localPointers[name] = val;
else
localPointers[name] = val;
}
Variable Expression::getLocalVariable(std::string name)
{
if (localVariables.find(name) != localVariables.end())
return localVariables[name];
if (localPointers.find(name) != localPointers.end())
return Variable(*localPointers[name]);
if (parent)
return parent->getLocalVariable(name);
throw new Exception(Exception::ErrorType::UNKNOWN_VARIABLE);
}
Expression* Expression::localVariableExists(std::string name)
{
if (localVariables.find(name) != localVariables.end())
return this;
if (localPointers.find(name) != localPointers.end())
return this;
if (parent)
return parent->localVariableExists(name);
return nullptr;
}
Expression* Expression::acquire(std::vector<std::shared_ptr<Expression>>* tokens)
{
if (!tokens->empty())
tokens->erase(tokens->begin());
for (int c = 0; c < noArguments; c++)
{
if (tokens->empty())
throw new Exception(Exception::ErrorType::INSUFFICIENT_ARGUMENTS);
arguments.push_back(tokens->front());
tokens->front()->parent = this;
arguments.back()->acquire(tokens);
}
return this;
}
| true |
898255bbbc2f0e4734bdb0a49309ce8c94fe8df7
|
C++
|
scholtes/university
|
/scholtgt-cpp-basics-master/Triangle.h
|
UTF-8
| 784 | 3.53125 | 4 |
[] |
no_license
|
#ifndef TRIANGLE_H
#define TRIANGLE_H
/*
* Triangle.h
* Name: Garrett Scholtes
*
* May 27, 2014
*
* This class implements the Polygon interface to
* handle working with triangles.
*/
#include <iostream>
#include <cmath>
using namespace std;
class Triangle : public Polygon {
public:
// Constructor that takes side lengths
Triangle(double a, double b, double c) {
side1 = a;
side2 = b;
side3 = c;
};
// Destructor
virtual ~Triangle() {}
// Implementation of area
double area() {
// Heron's formula
double s = (side1 + side2 + side3) / 2.0;
return sqrt(s*(s-side1)*(s-side2)*(s-side3));
}
// Implementation of perimeter
double perimeter() {
return side1 + side2 + side3;
}
private:
// Side lengths
double side1;
double side2;
double side3;
};
#endif
| true |
e83237a0028e47ce4bf766dbfee357fd1ef742b8
|
C++
|
Seinjin4/sdl_rogue_like
|
/sdl_rogue_like/ADT/Vector2/Vector2.h
|
UTF-8
| 806 | 3.5 | 4 |
[] |
no_license
|
#pragma once
#include <iostream>
class Vector2
{
private:
double x,y;
public:
Vector2();
Vector2(double x, double y);
double get_x() const;
double get_y() const;
void set_x(double x);
void set_y(double y);
double magnitude() const;// return sqrt(x^2 + y^2)
void normalize(); //Make magnitude 0 while keeping the angle
void vector_floor(); //Round vector's values down
void vector_ceil(); //Round vector's values up
void vector_round(); //Rounds to closest integer
void vector_ceil_abs(); //Rounds vector's values up from abs() perspective, negative - down, positive - up
Vector2 operator + (const Vector2& v);
Vector2 operator - (const Vector2& v);
Vector2 operator * (const double& x);
friend std::ostream& operator << (std::ostream& os, const Vector2& v);
};
| true |
3ef4060762dd3f37263d8af5ead9029ccdf49106
|
C++
|
romandion/Lab
|
/rbtree/Main.cpp
|
WINDOWS-1252
| 1,314 | 2.53125 | 3 |
[] |
no_license
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <map>
#include "rbtree.h"
#include "test.h"
int main(int argc , char * argv[])
{
rb_root_t root = {NULL} ;
test_node_t * nodes = build_test_nodes(kMaxSize) ;
int elapse = ::test_insert(&root , nodes , kMaxSize) ;
::printf("insert elapse = %d \n" , elapse) ;
test_validate(&root) ;
//
DWORD start_tick = ::GetTickCount() ;
for(int idx = 0 ; idx < kMaxSize ; ++idx)
{
int result = 0 ;
if((result = test_find(&root , idx)) != 0)
::printf("find'result = %d \n" , result) ;
}
DWORD end_tick = ::GetTickCount() ;
elapse = (int)(end_tick - start_tick) ;
::printf("find elapse = %d \n" , elapse) ;
//ɾ
start_tick = ::GetTickCount() ;
for(int idx = 0 ; idx < kMaxSize ; ++idx)
{
int result = test_erase(&root , idx) ;
if(result != 0)
::printf("erase'result = %d \n" , result) ;
if(test_find(&root , idx) != -1)
::printf("erase failed\n") ;
}
end_tick = ::GetTickCount() ;
elapse = (int)(end_tick - start_tick) ;
::printf("erase elapse = %d \n" , elapse) ;
test_validate(&root) ;
return 0 ;
}
| true |
729c2b93128aaa89b2959d1573d6e403c4cbdcba
|
C++
|
AdamWelch1/CryptoPals
|
/rc4.h
|
UTF-8
| 848 | 3.015625 | 3 |
[] |
no_license
|
#ifndef RC4_H
#define RC4_H
#include <cstdint>
class RC4 {
public:
// Key-schedule
RC4(uint8_t *key, uint32_t length)
{
doKeySchedule(key, length);
}
void doKeySchedule(uint8_t *key, uint32_t length)
{
for(uint32_t i = 0; i < 256; i++)
iState[i] = i;
uint16_t j;
for(uint32_t i = 0; i < 256; i++)
{
j = (j + iState[i] + key[i % length]) % 256;
uint8_t tmp = iState[i];
iState[i] = iState[j];
iState[j] = tmp;
}
}
void getBytes(uint8_t *outBuffer, uint32_t count)
{
uint16_t i = 0, j = 0;
for(uint32_t c = 0; c < count; c++)
{
i = (i + 1) % 256;
j = (j + iState[i]) % 256;
uint8_t tmp = iState[i];
iState[i] = iState[j];
iState[j] = tmp;
outBuffer[c] = iState[(iState[i] + iState[j]) % 256];
}
}
private:
uint8_t iState[256];
};
#endif
| true |
276247aee73d44eccf4ef30a3b9e7be299e3005e
|
C++
|
ebogucka/venenum
|
/src/Venenum/Creature.cpp
|
UTF-8
| 7,309 | 2.9375 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"MIT",
"BSD-3-Clause",
"Zlib",
"BSL-1.0"
] |
permissive
|
#include "Creature.h"
#include "Player.h"
Creature::Creature(GameContext& context) : context(context), animation(false)
{
}
Creature::Creature(Creature::CreatureType type, GameContext& context, int id) : type(type), context(context), id(id), animation(false)
{
setProperties();
}
Creature::Creature(Creature::CreatureType type, int x, int y, GameContext& context, int id) : type(type), context(context), id(id), animation(false)
{
setProperties();
setPosition(x, y);
}
void Creature::saveState(boost::property_tree::ptree& tree)
{
boost::property_tree::ptree child;
child.put("id", id);
child.put("type", type);
child.put("position.x", position.x);
child.put("position.y", position.y);
child.put("HP", HP);
tree.add_child("game.monsters.monster", child);
}
void Creature::loadState(boost::property_tree::ptree& tree, GameContext& context)
{
int id = tree.get<int>("id");
enum Creature::CreatureType loadedType = static_cast<Creature::CreatureType>(tree.get<int>("type"));
Creature* loadedMonster = new Creature(loadedType, context, id);
loadedMonster->setPosition(tree.get<int>("position.x"), tree.get<int>("position.y"));
loadedMonster->HP = tree.get<int>("HP");
context.monsters.insert(std::make_pair(id, loadedMonster));
}
void Creature::loadData(GameContext& context)
{
using namespace boost::property_tree;
ptree file;
read_xml("../data/game.dat", file);
int i = 0;
BOOST_FOREACH(ptree::value_type &value, file.get_child("monsters"))
{
Creature::data.push_back(new Creature::CreatureData());
Creature::data[i]->name = value.second.get<std::string>("name");
Creature::data[i]->HP = value.second.get<int>("HP");
Creature::data[i]->ATK = value.second.get<int>("ATK");
Creature::data[i]->DEF = value.second.get<int>("DEF");
Creature::data[i]->speed = value.second.get<int>("speed");
Creature::data[i]->XPGained = value.second.get<int>("XPGained");
Creature::data[i]->texture = new sf::Texture();
Creature::data[i]->texture->loadFromFile("../images/monsters/" + value.second.get<std::string>("image"));
i++;
}
}
Creature::MoveResult Creature::act()
{
if(canSeePlayer())
{
return chasePlayer();
}
else
{
return moveRandomly();
}
}
Creature::MoveResult Creature::chasePlayer()
{
sf::Vector2u playerPosition = context.player->getPosition();
sf::Vector2i direction = sf::Vector2i(playerPosition - position);
int number;
if(direction.x == 0)
{
number = 1;
}
else if(direction.y == 0)
{
number = 0;
}
else
{
number = rand() % 2;
}
Creature::MoveResult result = Creature::NONE;
switch(number)
{
case 0:
if(direction.x > 0)
{
result = moveRight();
}
else if(direction.x < 0)
{
result = moveLeft();
}
break;
case 1:
if(direction.y > 0)
{
result = moveDown();
}
else if(direction.y < 0)
{
result = moveUp();
}
break;
}
if(result == Creature::OK || result == Creature::PLAYER_KILLED)
{
return result;
}
return moveRandomly();
}
Creature::MoveResult Creature::moveRandomly()
{
bool finished = false;
Creature::MoveResult result = Creature::NONE;
int attempts = 0;
while(!finished && attempts < 10)
{
int number = rand() % 4;
switch(number)
{
case 0:
result = moveUp();
break;
case 1:
result = moveRight();
break;
case 2:
result = moveDown();
break;
case 3:
result = moveLeft();
break;
}
if(result == Creature::OK || result == Creature::PLAYER_KILLED)
{
return result;
}
attempts++;
}
return Creature::FAILED;
}
bool Creature::attack(Creature* defender)
{
sprite.move(0, -10);
animation = true;
int damage = Combat::calculateDamage(getATK(), defender->getDEF());
std::ostringstream msg;
if(damage > 0)
{
defender->decreaseHP(damage);
msg << name << " deals " << damage << " damage to " << defender->getName() << ".";
}
else
{
msg << name << " misses!";
}
context.hud->writeMessage(msg);
if(defender->isDead())
{
bool result = defender->processDeath(); // 0 - monster died, 1 - player died
if(result == false)
{
delete defender;
}
return result;
}
return false;
}
void Creature::draw()
{
context.window->draw(sprite);
}
Creature::MoveResult Creature::moveLeft()
{
return move(position.x - 1, position.y);
}
Creature::MoveResult Creature::moveRight()
{
return move(position.x + 1, position.y);
}
Creature::MoveResult Creature::moveUp()
{
return move(position.x, position.y - 1);
}
Creature::MoveResult Creature::moveDown()
{
return move(position.x, position.y + 1);
}
Creature::MoveResult Creature::move(int x, int y)
{
if(context.map->isTilePassable(x, y))
{
context.map->resetMonster(position.x, position.y);
setPosition(x, y);
return Creature::OK;
}
else if(context.map->hasPlayer(x, y))
{
if(attack((Creature *)context.player))
{
return Creature::PLAYER_KILLED;
}
else
{
return Creature::OK;
}
}
return Creature::FAILED;
}
bool Creature::processDeath()
{
std::ostringstream msg;
msg << name << " dies!";
context.hud->writeMessage(msg);
context.map->resetMonster(position.x, position.y);
context.monsters.erase(id);
context.player->addXP(Creature::data[type]->XPGained);
return false;
}
sf::Vector2u Creature::getPosition()
{
return position;
}
void Creature::setPosition(int x, int y)
{
context.map->setMonster(x, y, id);
position.x = x;
position.y = y;
sprite.setPosition(x * Tile::SIZE, y * Tile::SIZE);
}
void Creature::setProperties()
{
name = Creature::data[type]->name;
HP = Creature::data[type]->HP;
sprite.setTexture(*Creature::data[type]->texture);
playerVisible = false;
}
std::string Creature::getName()
{
return name;
}
int Creature::getID(void)
{
return id;
}
void Creature::decreaseHP(int damage)
{
HP -= damage;
if(HP < 0)
{
HP = 0;
}
}
int Creature::getATK()
{
return Creature::data[type]->ATK;
}
int Creature::getDEF()
{
return Creature::data[type]->DEF;
}
int Creature::getHP()
{
return HP;
}
int Creature::getSpeed()
{
return Creature::data[type]->speed;
}
bool Creature::isDead()
{
return HP == 0;
}
bool Creature::canSeePlayer()
{
return playerVisible;
}
void Creature::setPlayerVisibility(bool flag)
{
playerVisible = flag;
}
void Creature::moveSprite(float x, float y)
{
sprite.move(x, y);
}
bool Creature::getAnimationFlag()
{
return animation;
}
void Creature::setAnimationFlag(bool flag)
{
animation = flag;
}
std::vector<Creature::CreatureData*> Creature::data;
| true |
c6c16db2d98287d5e2d5a2f41e57d110fd1ba9b1
|
C++
|
hzarkov/LetyashtaGad
|
/LetyashtaGad/Drone.cpp
|
UTF-8
| 3,011 | 2.875 | 3 |
[] |
no_license
|
#include "Drone.h"
Drone::Drone() : motors({{9,3,FRONT_LEFT_MOTOR_BINARY},{10,1,FRONT_RIGHT_MOTOR_BINARY},{13,3,BACK_LEFT_MOTOR_BINARY},{14,1,BACK_RIGHT_MOTOR_BINARY}}){
}
int Drone::get_opposite_motor(int m_number){
return (m_number+2 > 3) ? (m_number-2):(m_number+2);
}
void Drone::change_position(char binary,int time){
char check[4] = {
binary & FRONT_LEFT_MOTOR_BINARY,
binary & FRONT_RIGHT_MOTOR_BINARY,
binary & BACK_LEFT_MOTOR_BINARY,
binary & BACK_RIGHT_MOTOR_BINARY
};
// for(int next = 0; next < 4; next++){
// if(this->motors[next].is_max() && check[next]){
// check[next] = 0;
// check[this->get_opposite_motor(next)+3] = 1;
// }
// }
if(check[0]){
FRONT_LEFT_MOTOR.up_motor_power();
}
if(check[1]){
FRONT_RIGHT_MOTOR.up_motor_power();
}
if(check[2]){
BACK_LEFT_MOTOR.up_motor_power();
}
if(check[3]){
BACK_RIGHT_MOTOR.up_motor_power();
}
//
// if(check[4]){
// FRONT_LEFT_MOTOR.low_motor_power();
// }
// if(check[5]){
// FRONT_RIGHT_MOTOR.low_motor_power();
// }
// if(check[6]){
// BACK_LEFT_MOTOR.low_motor_power();
// }
// if(check[7]){
// BACK_RIGHT_MOTOR.low_motor_power();
// }
delay(time);
if(check[0]){
FRONT_LEFT_MOTOR.low_motor_power();
}
if(check[1]){
FRONT_RIGHT_MOTOR.low_motor_power();
}
if(check[2]){
BACK_LEFT_MOTOR.low_motor_power();
}
if(check[3]){
BACK_RIGHT_MOTOR.low_motor_power();
}
//
// if(check[4]){
// FRONT_LEFT_MOTOR.up_motor_power();
// }
// if(check[5]){
// FRONT_RIGHT_MOTOR.up_motor_power();
// }
// if(check[6]){
// BACK_LEFT_MOTOR.up_motor_power();
// }
// if(check[7]){
// BACK_RIGHT_MOTOR.up_motor_power();
// }
}
void Drone::move(drone_move move){
switch(move){
case UP:
for(int next = 0; next < 4; next++){
this->motors[next].up_motor_power();
}
break;
case DOWN:
for(int next = 0; next < 4; next++){
this->motors[next].low_motor_power();
}
break;
case LEFT:
this->change_position(GO_LEFT_BINARY,2000);
break;
case RIGHT:
this->change_position(GO_RIGHT_BINARY,2000);
break;
case FORWARD:
this->change_position(GO_FORWARD_BINARY,2000);
break;
case BACKWARD:
this->change_position(GO_BACKWARD_BINARY,2000);
break;
case MOTOR_STOP:
for(int next = 0; next < 4; next++){
this->motors[next].motor_start_power();
}
break;
}
}
void Drone::start(){
//delay(1000);
//while(input = Serial.read(), input != 'R');
// for(i = 0; i < 4; i++){
// pinMode(motor[i].get_id(), OUTPUT);
// motor[i].init_motor();
// }
//while(input = Serial.read(), input != 'S');
//delay(1000);
for(int next = 0; next < 4; next++){
//pinMode(motors[next].get_id(), OUTPUT);
this->motors[next].motor_start_power();
}
}
void Drone::one_motor_test(){
BACK_RIGHT_MOTOR.up_motor_power();
//delay(2000);
// BACK_RIGHT_MOTOR.low_motor_power();
}
| true |
0eba47244f6de389798e1e05904386a68d2476b8
|
C++
|
prathyushk/Interspace
|
/interspace-server/Enemy.cpp
|
UTF-8
| 2,074 | 2.578125 | 3 |
[] |
no_license
|
#include "Enemy.h"
#include <btBulletDynamicsCommon.h>
#include "PhysicsManager.h"
#include <BulletDynamics/Character/btKinematicCharacterController.h>
#include <BulletCollision/CollisionDispatch/btGhostObject.h>
#include <boost/thread/mutex.hpp>
#include <SimpleMutex.h>
#include "Client.h"
Enemy::Enemy(int inputDamage, int inputFov, int inputMaxhealth, int inputIndex, btConvexShape* shape, btTransform& transform, PhysicsManager* phys)
: maxHealth(inputMaxhealth), health(inputMaxhealth), damage(inputDamage), fov(inputFov), index(inputIndex), spawn(transform.getOrigin())
{
control = phys->addCharacterControl(transform, shape, 0.05f);
target = NULL;
}
btVector3 Enemy::getPosition()
{
return control->getGhostObject()->getWorldTransform().getOrigin();
}
btVector3 Enemy::getDirection()
{
return direction;
}
btVector3 Enemy::getWalkDirection()
{
return walkDirection;
}
btKinematicCharacterController* Enemy::getControl()
{
return control;
}
int Enemy::getDamage()
{
return damage;
}
int Enemy::getHealth()
{
return health;
}
void Enemy::takeDamage(int damage)
{
health -= damage;
if(health <= 0)
{
control->getGhostObject()->getWorldTransform().setOrigin(spawn);
health = maxHealth;
}
}
void Enemy::setTarget(Client* client)
{
target = client;
}
Client* Enemy::getTarget()
{
return target;
}
int Enemy::getFov()
{
return fov;
}
void Enemy::setWalkDirection(const btVector3& dir)
{
walkDirection = dir;
}
void Enemy::update()
{
try{
if(target == NULL)
{
control->setWalkDirection(walkDirection);
direction = walkDirection;
}
else
{
btVector3 temp = target->getPos() - getPosition();
direction = btVector3(temp.x(), 0, temp.z());
if(getPosition().distance(target->getPos()) <= 40)
control->setWalkDirection(btVector3(0,0,0));
else
{
walkDirection = btVector3(direction.x() / 250,0,direction.z()/250);
control->setWalkDirection(walkDirection);
}
}
}
catch(int e){}
}
| true |
f03dea2bcdcac4a4c347b4ad24515f4f9f3e79d0
|
C++
|
S-Hucks/cs2400
|
/cube.cc
|
UTF-8
| 1,026 | 3.84375 | 4 |
[] |
no_license
|
/*
* File: cube.cc
* Author: Nasseef Abukamail
* Date: February 18, 2019
* Description: A program to demonstrate a value-returning functions
*/
#include <iostream>
#include <iomanip>
#include <cstdlib>
using namespace std;
//function prototypes (Function Declaration)
int cube (int value);
void printInstructions();
int main()
{
int numberCubed, number = 2;
printInstructions();
printInstructions();
//function call with number as argument
numberCubed = cube(number);
cout << "The cube of "
<< number << " is " << numberCubed << endl;
cout << cube(3) << endl;
int x = cube(3) * 2;
cout << x << endl;
cube(10); //waste of time (Don't do it)
return 0;
}
//Function definition
// value is a formal parameter
int cube(int value) //Function heading
{ //body of the function
int result; //local variable
result = value * value * value;
return result; //result returned to main
}
void printInstructions() {
cout << "This program calculates the cube of a number" <<endl;
}
| true |
303a75d7e6ae039efc0e5c931d9b80aa3ec164d0
|
C++
|
kavin23923/Leetcode
|
/contest/196/2.cpp
|
UTF-8
| 272 | 2.671875 | 3 |
[] |
no_license
|
class Solution {
public:
int getLastMoment(int n, vector<int>& left, vector<int>& right) {
int res = 0;
for (int ant : left) {
res = max(res, ant - 0);
}
for (int ant : right) {
res = max(res, n - ant);
}
return res;
}
};
| true |
4510c28e7f5306d18bbf04af9c7ac7b0c68d300a
|
C++
|
purduerov/ROV-Maelstrom
|
/Software/TeensyPowerBoard/mainCode/thrusterPWMWrapper.cpp
|
UTF-8
| 758 | 2.90625 | 3 |
[
"MIT"
] |
permissive
|
#include "thrusterPWMWrapper.h"
thrusterPWMWrapper::thrusterPWMWrapper(int address, int pUsePWM)
{
if (!pUsePWM) {
//esc = new Arduino_I2C_ESC(address);
myaddress = address;
}
else
{
myservo.attach(address);
}
}
void thrusterPWMWrapper::set(int value)
{
if (!usePWM)
{
driver.setPWM(myaddress, 0, i2c_to_PWM(value));
}
else
{
myservo.write(i2c_to_PWM(value));
}
}
//the value should be between 63 (full reverse for now) and 123 (full forward for now)
//93 means stopped. these values will be tuned in the future as more testing is done with
//physical hardware
int thrusterPWMWrapper::i2c_to_PWM(int i2c)
{
if (i2c == 0) return 93; //force the mapped value to be 0
return map(i2c, -32768, 32767, 63, 123);
}
| true |
e1f262d1e2d202310521b96d6a11ae894df27f57
|
C++
|
atharvanan1/concurrent
|
/project/treiber_stack.h
|
UTF-8
| 363 | 2.71875 | 3 |
[] |
no_license
|
// sgl_stack.h
#ifndef TREIBER_STACK_H // include guard
#define TREIBER_STACK_H
#include <atomic>
#include <list>
using namespace std;
class t_stack{
public:
class node{
public:
node(int v):val(v){} //constructor
int val;
node *next;
};
list <node*> hazard_list;
atomic <node*> top;
void push(int val);
int pop();
};
#endif /* TREIBER_STACK_H */
| true |
18a3c6d26bb37bf3b8fcad98aa121d2d87bed994
|
C++
|
jhnaldo/problem-solving
|
/acmicpc/cpp/1002.cc
|
UTF-8
| 717 | 2.96875 | 3 |
[] |
no_license
|
#include <iostream>
using namespace std;
int main()
{
int num, k;
int x1, y1, r1;
int x2, y2, r2;
int sq_dist, sq_add, sq_sub;
cin >> num;
while(num>0){
cin >> x1 >> y1 >> r1;
cin >> x2 >> y2 >> r2;
sq_add = (r1+r2) * (r1+r2);
sq_sub = (r1-r2) * (r1-r2);
sq_dist = (x1-x2)*(x1-x2)+(y1-y2)*(y1-y2);
if ( sq_add < sq_dist || sq_sub > sq_dist ){
cout << 0 << endl;
}else if ( sq_dist == 0 && r1 == r2 ){
cout << -1 << endl;
}else if ( sq_add == sq_dist || sq_sub == sq_dist ){
cout << 1 << endl;
}else{
cout << 2 << endl;
}
num--;
}
return 0;
}
| true |
30ac728e6191ad20d7a4a83d3841315ad0af42b5
|
C++
|
mattialab/elastica
|
/source/RodExternalForces.h
|
UTF-8
| 23,669 | 2.515625 | 3 |
[
"MIT"
] |
permissive
|
#ifndef RODEXTERNALFORCES_H_
#define RODEXTERNALFORCES_H_
#include <limits>
#include "Interaction.h"
#include "MathFunctions.h"
#include "Rod.h"
#include "RodBoundaryConditions.h"
#include "SplineProfileZeroEnds.h"
using namespace std;
// Abstract ExternalForce class representing some external force acting upon a
// single Rod
class ExternalForces {
protected:
typedef std::vector<Vector3> VV3;
typedef std::vector<Matrix3> VM3;
typedef std::vector<REAL> VREAL;
typedef std::vector<bool> VBOOL;
typedef std::vector<int> VINT;
typedef std::vector<Rod *> Vrodptr;
typedef std::vector<ExternalForces *> Vefptr;
typedef std::vector<RodBC *> Vbcptr;
public:
virtual ~ExternalForces() {}
virtual void applyForces(Rod &R, const REAL time) = 0;
};
class MultipleForces : public ExternalForces {
public:
Vefptr forces;
MultipleForces() : ExternalForces() {}
MultipleForces(Vefptr forces) : ExternalForces(), forces(forces) {}
void add(ExternalForces *singleForce) { forces.push_back(singleForce); }
MultipleForces *get() {
/*
Vefptr container;
container.push_back(this);
return container;
*/
MultipleForces *container;
container = this;
return container;
}
void applyForces(Rod &R, const REAL time) {
for (unsigned int i = 0; i < forces.size(); i++)
forces[i]->applyForces(R, time);
}
};
class NoForces : public ExternalForces {
public:
void applyForces(Rod &R, const REAL time) {}
};
// Periodic load is applied at the second hand
class PeriodicLoad : public ExternalForces {
public:
const Vector3 F;
const REAL omega;
PeriodicLoad(const Vector3 _F, const REAL _omega)
: ExternalForces(), F(_F), omega(_omega) {}
void applyForces(Rod &R, const REAL time) {
R.externalForces.back() += F * sin(omega * time);
}
};
// Periodic couple is applied at the second hand
class PeriodicCouple : public ExternalForces {
public:
typedef enum { D1, D2, D3 } Direction;
const Direction dir;
Vector3 maskDirection;
const REAL M;
const REAL omega;
PeriodicCouple(const REAL _M, const REAL _omega, const Direction _dir)
: ExternalForces(), M(_M), omega(_omega), dir(_dir) {
// Active torque expressed directly in the material frame of reference,
// hence the naming D1, D2, D3!
switch (dir) {
case Direction::D1:
maskDirection = Vector3(1.0, 0.0, 0.0);
break;
case Direction::D2:
maskDirection = Vector3(0.0, 1.0, 0.0);
break;
case Direction::D3:
maskDirection = Vector3(0.0, 0.0, 1.0);
break;
default:
assert(false);
break;
}
}
void applyForces(Rod &R, const REAL time) {
R.externalTorques.back() += M * maskDirection * sin(omega * time);
}
};
// Elbow Validating Muscle
class MuscleContraction : public ExternalForces {
public:
const REAL Amp;
const REAL w;
MuscleContraction(const REAL Amp, const REAL w)
: ExternalForces(), Amp(Amp), w(w) {}
void applyForces(Rod &R, const REAL time) {
const int size = R.n;
// cout<<(R.edge[0].unitize()*Amp*sin(w*time))<<endl;
const REAL o_Length = vSum(R.l0);
const REAL Length = vSum(R.l);
const REAL ratio = Length / o_Length * 100.0;
REAL Reduction = 1.0;
REAL Tissue = 0.0;
REAL factor = 0.0;
const REAL Firing = (time <= 0.15) ? (time / 0.15) : 1.0;
/*
The polynomial below is equivalent to the polynomial
given in the SI of our paper. For legacy reasons, we have
broken it down into two piecewise functions as shown below for different
ratio (eta).
*/
if (ratio < 100.0 /*This represents eta < 1*/) {
Reduction = (-0.036 * ratio * ratio + 7.2 * ratio - 260) / 100.0 +
0.5 * ((100.0 - ratio) / 100.0) / 6.0 - 0.027;
/*
The factor below represents the extra force scale factor in our muscle
simulation below. This force applied on the muscle starts from
the second from last nodes from either ends and linearly scales up
with the muscle node position, reaching a maximum at the muscle center.
This factor represents the maximum additional force on the muscle. See
graph below.
Additional Force
| /\---------------------Factor*Force on muscle
| / \
| / \
| / \
|_/________\_ Position
1 N-1
This force will contract the muscle elements more towards the center.
This is biologically realistic since th contraction of the muscle fiber is
not uniform. We note here the output force of the muscle does not
significantly change with the inclusion of this additional force, as its
value is 0 at the ends and because the muscle fibers are soft.
*/
factor = 0.3;
} else /*This represents eta > 1*/ {
Reduction =
(50 + 50 * sin((2 * M_PI / 120.0) * (ratio - 100 + 30))) / 100.0 -
0.5 * ((ratio - 100) / 100.0) / 6.0;
Tissue = (4 * exp(0.045 * (ratio - 100)) - 4) / 100;
}
R.externalForces[0] +=
R.edge[0].unitize() * Firing * Amp * (Reduction + Tissue);
R.externalForces[size] +=
-R.edge[size - 1].unitize() * Firing * Amp * (Reduction + Tissue);
for (unsigned int i = 1; i < (size / 2); i++) {
R.externalForces[i] += R.edge[i].unitize() * Firing *
(Amp * (Reduction + Tissue)) *
(1 + factor * i / 8);
R.externalForces[i] += -1 * R.edge[i - 1].unitize() * Firing *
(Amp * (Reduction + Tissue)) *
(1 + factor * (i - 1) / 8);
R.externalForces[size - i] += -1 * R.edge[size - i - 1].unitize() *
Firing * (Amp * (Reduction + Tissue)) *
(1 + factor * i / 8);
R.externalForces[size - i] += R.edge[size - i].unitize() * Firing *
(Amp * (Reduction + Tissue)) *
(1 + factor * (i - 1) / 8);
}
R.externalForces[size / 2] += R.edge[size / 2].unitize() * Firing *
(Amp * (Reduction + Tissue)) * (1 + factor);
R.externalForces[size / 2] += -1 * R.edge[size / 2 - 1].unitize() * Firing *
(Amp * (Reduction + Tissue)) * (1 + factor);
}
};
// A periodic local contraction
class LocalTorque : public ExternalForces {
public:
const Vector3 A;
const REAL w;
const int index;
LocalTorque(const Vector3 A, const REAL w, const int index)
: ExternalForces(), A(A), w(w), index(index) {}
void applyForces(Rod &R, const REAL time) {
const Vector3 torque = A * abs(sin(w * time));
R.externalTorques[index] += R.Q[index] * torque;
}
};
// A periodic local contraction
class LocalForce : public ExternalForces {
public:
const REAL Amp;
const REAL w;
LocalForce(const REAL Amp, const REAL w) : ExternalForces(), Amp(Amp), w(w) {}
void applyForces(Rod &R, const REAL time) {
const int size = R.n;
R.externalForces[0] = (R.edge[0].unitize()) * Amp * abs(sin(w * time));
R.externalForces[size] =
-1 * (R.edge[size - 1].unitize()) * Amp * abs(sin(w * time));
for (unsigned int i = 1; i < (size); i++) {
R.externalForces[i] += (R.edge[i].unitize()) * Amp * abs(sin(w * time));
R.externalForces[i] +=
-1 * (R.edge[i - 1].unitize()) * Amp * abs(sin(w * time));
}
}
};
// A periodic point force
class Pointforce : public ExternalForces {
public:
const Vector3 A;
const REAL w;
const int index;
Pointforce(const Vector3 A, const REAL w, const int index)
: ExternalForces(), A(A), w(w), index(index) {}
void applyForces(Rod &R, const REAL time) {
const Vector3 force = A * abs(sin(w * time));
R.externalForces[index] += force;
}
};
// A periodic point force
class Periodiclinearforce : public ExternalForces {
public:
const int index;
const REAL Amp;
Periodiclinearforce(const int index, const REAL Amp)
: ExternalForces(), Amp(Amp), index(index) {}
void applyForces(Rod &R, const REAL time) {
REAL realamp = 0.0;
if (time < 0.2) {
realamp = Amp * time / 0.2;
} else if (time < 0.6) {
realamp = Amp - Amp * (time - 0.2) / 0.2;
} else if (time < 1.0) {
realamp = -Amp + Amp * (time - 0.6) / 0.2;
} else {
realamp = 0.0;
}
R.externalForces[index] += realamp * Vector3(0.0, 0.0, 1.0);
}
};
// Exerts a force proportional to vertex mass on each vertex in a prescribed
// direction
class GravityForce : public ExternalForces {
public:
const Vector3 F;
GravityForce(const Vector3 F) : ExternalForces(), F(F) {}
void applyForces(Rod &R, const REAL time) {
R.externalForces += R.m * F;
// cout<<R.externalForces<<endl;
}
};
class ConstantMuscleTorques : public ExternalForces {
public:
const REAL A, rumpUpTime;
const Vector3 director;
ConstantMuscleTorques(const REAL _A, const Vector3 _director,
const REAL _rumpUpTime)
: ExternalForces(), A(_A), director(_director), rumpUpTime(_rumpUpTime) {}
void applyForces(Rod &R, const REAL time) {
const VREAL s = vCumSum(R.l0);
assert(s.size() == (unsigned int)R.n);
assert(s.size() == (unsigned int)R.externalTorques.size());
// cout<<R.Q.back()<<endl;
for (unsigned int i = 0; i < (unsigned int)R.n; i++) {
const REAL factorTime = (time <= rumpUpTime) ? (time / rumpUpTime) : 1.0;
const REAL torque = factorTime * A;
// R.externalTorques[i - 1] -= torque*director;
R.externalTorques[i] += torque * director;
}
}
};
// Muscles actually exert torques, not forces, we just name it this way
// following convention T = A sin(wx - vt), traveling wave with Vector3 A,
// magnitude |A| A muscle acts at a vertex, imposing equal and opposite torques
// on each adjacent edge
class MuscleForce : public ExternalForces {
public:
const Vector3 A;
const REAL w, v;
MuscleForce(const Vector3 A, const REAL w, const REAL v)
: ExternalForces(), A(A), w(w), v(v) {}
void applyForces(Rod &R, const REAL time) {
const VREAL s = vCumSum(R.l0);
for (unsigned int i = 1; i < (unsigned int)R.n; i++) {
const Vector3 torque = A * sin(w * time - v * s[i]);
R.externalTorques[i - 1] -= torque;
R.externalTorques[i] += torque;
}
}
};
// Spline muscles actually exert torques, not forces, we just name it this way
// following convention T = A * sin(wx - vt), traveling wave with Vector3 A,
// magnitude |A|. A is a spline profile, so A(s). A muscle acts at a vertex,
// imposing equal and opposite torques on each adjacent edge
class SplineMuscleTorques_O : public ExternalForces {
public:
SplineProfileZeroEnds spline;
const REAL w, v, rumpUpTime;
const Vector3 direction;
SplineMuscleTorques_O(vector<double> A, const REAL w, const REAL v,
const Vector3 _direction, const REAL _rumpUpTime)
: ExternalForces(),
spline(A),
w(w),
v(v),
direction(_direction),
rumpUpTime(_rumpUpTime) {}
void applyForces(Rod &R, const REAL time) {
const VREAL s = vCumSum(R.l0);
for (unsigned int i = 1; i < (unsigned int)R.n; i++) {
const REAL factor = (time <= rumpUpTime) ? (time / rumpUpTime) : 1.0;
const REAL torque =
factor * spline.getProfile(s[i]) * sin(w * time - v * s[i]);
// R.externalTorques[i] += R.Q[i] * direction * torque * R.l0[i];
R.externalTorques[i - 1] -= R.Q[i - 1] * direction * torque;
R.externalTorques[i] += R.Q[i] * direction * torque;
}
}
};
// Spline muscles actually exert torques, not forces, we just name it this way
// following convention T = A * sin(wx - vt), traveling wave with Vector3 A,
// magnitude |A|. A is a spline profile, so A(s). A muscle acts at a vertex,
// imposing equal and opposite torques on each adjacent edge
// A DISCRETE VERSION
class SplineMuscleTorques : public ExternalForces {
public:
// SplineProfileZeroEnds spline;
const REAL w, v, rumpUpTime;
const vector<double> amp;
const Vector3 direction;
SplineMuscleTorques(vector<double> A, const REAL w, const REAL v,
const Vector3 _direction, const REAL _rumpUpTime)
: ExternalForces(),
amp(A),
w(w),
v(v),
direction(_direction),
rumpUpTime(_rumpUpTime) {}
void applyForces(Rod &R, const REAL time) {
/*(
const VREAL s = vCumSum(R.l0);
for(unsigned int i = 6; i < ((unsigned int)R.n-7); i=i+12)
{
const REAL factor =
(time<=rumpUpTime)?(time/rumpUpTime):1.0; const REAL torque = 0.3*factor
* spline.getProfile(s[i]) * sin( w*time - v*s[i] );
//R.externalTorques[i] += R.Q[i] * direction * torque *
R.l0[i]; R.externalTorques[i - 1] -= R.Q[i-1] * direction * torque;
R.externalTorques[i+28] += R.Q[i+28] * direction *
torque;
}
*/
const VREAL s = vCumSum(R.l0);
for (unsigned int i = 27; i < 72; i = i + 22) {
const REAL timeD = i * 1.0 / v;
const REAL Realtime = time - timeD;
REAL ramp = (Realtime <= 1.0) ? (Realtime / 1.0) : 1.0;
ramp = (Realtime <= 0.0) ? 0.0 : ramp;
REAL torque = 0.0;
unsigned int index = i / 22;
torque = ramp * amp[index - 1] * sin(w * Realtime);
R.externalTorques[i - 22] -= R.Q[i - 22] * direction * torque;
R.externalTorques[i + 22] += R.Q[i + 22] * direction * torque;
}
}
};
class SplineMuscleTorques_opti : public ExternalForces {
public:
const REAL w, v;
const vector<double> amp;
const Vector3 direction;
const vector<int> index;
const int N;
REAL OldLength[16];
REAL OLength[16];
SplineMuscleTorques_opti(vector<double> A, const REAL w, const REAL v,
const Vector3 _direction, const vector<int> _index,
const int _N)
: ExternalForces(),
amp(A),
w(w),
v(v),
direction(_direction),
index(_index),
N(_N) {}
void applyForces(Rod &R, const REAL time) {
if (time == 0.5e-5) {
for (unsigned int i = 0; i < N; i++) {
OldLength[2 * i] = 0.01 * (index[2 * i + 1] - index[2 * i] + 1);
OldLength[2 * i + 1] = 0.01 * (index[2 * i + 1] - index[2 * i] + 1);
OLength[2 * i] = OldLength[2 * i];
OLength[2 * i + 1] = OldLength[2 * i + 1];
cout << "111" << endl;
}
}
for (unsigned int i = 0; i < N; i++) {
const REAL timeD = index[2 * i] * 1.0 / v;
const REAL Realtime = time - timeD;
REAL ramp = (Realtime <= 1.0) ? (Realtime / 1.0) : 1.0;
ramp = (Realtime <= 0.0) ? 0.0 : ramp;
REAL torque = 0.0;
torque = ramp * amp[i] * sin(w * Realtime);
const int start = index[2 * i];
const int end = index[2 * i + 1];
R.externalTorques[start] -= R.Q[start] * (direction * torque);
R.externalTorques[end] += R.Q[end] * (direction * torque);
}
}
};
// Instead of a sine wave, this muscular contraction is highly localized, namely
// a gaussian with width w. It travels with speed v down the snake. The torque
// is determined by the variable direction that is expressed in the laboratory
// frame of reference.
class LocalizedMuscleForce : public ExternalForces {
public:
const REAL A, sigma, v, position, rumpUpTime;
const Vector3 direction;
LocalizedMuscleForce(const REAL _A, const REAL _sigma, const REAL _v,
const REAL _position, const Vector3 _direction,
const REAL _rumpUpTime)
: ExternalForces(),
A(_A),
sigma(_sigma),
v(_v),
position(_position),
direction(_direction),
rumpUpTime(_rumpUpTime) {}
void applyForces(Rod &R, const REAL time) {
const VREAL s = vCumSum(R.l0);
for (unsigned int i = 1; i < (unsigned int)R.n; i++) {
const REAL factorTime = (time <= rumpUpTime) ? (time / rumpUpTime) : 1.0;
const REAL torque =
factorTime * A *
exp(-pow(s[i] - position - v * time, 2) / (2.0 * sigma * sigma));
R.externalTorques[i - 1] -= torque * (R.Q[i - 1] * direction);
R.externalTorques[i] += torque * (R.Q[i] * direction);
}
}
};
// Instead of a sine wave, this muscular contraction is highly localized, namely
// a gaussian with width w. It travels with speed v down the snake. The torque
// here is directly associated to the directors of the material frame
class LocalizedMuscleForceLagrangian_ForcedToBeInPlane : public ExternalForces {
public:
const REAL A, sigma, v, position, rumpUpTime;
const Vector3 director, normalToDesiredPlane;
LocalizedMuscleForceLagrangian_ForcedToBeInPlane(
const REAL _A, const REAL _sigma, const REAL _v, const REAL _position,
const Vector3 _director, const Vector3 _normalToDesiredPlane,
const REAL _rumpUpTime)
: ExternalForces(),
A(_A),
sigma(_sigma),
v(_v),
position(_position),
director(_director),
normalToDesiredPlane(_normalToDesiredPlane),
rumpUpTime(_rumpUpTime) {}
void applyForces(Rod &R, const REAL time) {
const VREAL s = vCumSum(R.l0);
// const REAL totalLength = s.back();
// const REAL widthSigmoid = 20.0;
// const REAL xSigmoid = 2.0/3.0;
for (unsigned int i = 1; i < (unsigned int)R.n; i++) {
// const REAL factorSigmoid = 1.0
// - 1.0/(1.0+exp(-widthSigmoid*(s[i]/totalLength-xSigmoid))); //
// normalized between 0 and 1
const REAL factorTime = (time <= rumpUpTime) ? (time / rumpUpTime) : 1.0;
const REAL torque =
factorTime * A *
exp(-pow(s[i] - position - v * time, 2) / (2.0 * sigma * sigma));
R.externalTorques[i - 1] -= torque * director;
R.externalTorques[i] += torque * director;
}
}
};
// Represents constant forces at the endpoints. Note that a fixed endpoint
// will be represented by the bc function, so its tension force should
// be zero -- only free ends make sense with tension forces
class HelicalBucklingForcesAndTorques : public ExternalForces {
public:
Vector3 startForce, endForce;
Vector3 startTorque, endTorque;
HelicalBucklingForcesAndTorques(Vector3 _startForce, Vector3 _endForce,
Vector3 _startTorque, Vector3 _endTorque)
: ExternalForces(),
startForce(_startForce),
endForce(_endForce),
startTorque(_startTorque),
endTorque(_endTorque) {}
void applyForces(Rod &R, const REAL time) {
R.externalForces.front() = startForce;
R.externalForces.back() = endForce;
R.externalTorques.front() = startTorque;
R.externalTorques.back() = endTorque;
}
};
// Periodic loads
class PeriodicLoadLongitudinalWaves : public ExternalForces {
public:
const REAL frequency;
const Vector3 load;
PeriodicLoadLongitudinalWaves(const REAL _frequency, const Vector3 _load)
: ExternalForces(), frequency(_frequency), load(_load) {}
void applyForces(Rod &R, const REAL time) {
R.externalForces.back() = load * sin(frequency * time);
}
};
// Represents constant forces at the endpoints. Note that a fixed endpoint
// will be represented by the bc function, so its tension force should
// be zero -- only free ends make sense with tension forces
class EndpointForces : public ExternalForces {
public:
Vector3 startForce, endForce;
EndpointForces(Vector3 startForce, Vector3 endForce)
: ExternalForces(), startForce(startForce), endForce(endForce) {}
void applyForces(Rod &R, const REAL time) {
R.externalForces[0] += startForce;
R.externalForces[R.n] += endForce;
}
};
// Represents constant forces at the endpoints. Note that a fixed endpoint
// will be represented by the bc function, so its tension force should
// be zero -- only free ends make sense with tension forces
class GradualEndpointForces : public ExternalForces {
public:
const REAL rampupTime;
Vector3 startForce, endForce;
GradualEndpointForces(const Vector3 _startForce, const Vector3 _endForce,
const REAL _rampupTime)
: ExternalForces(),
startForce(_startForce),
endForce(_endForce),
rampupTime(_rampupTime) {}
void applyForces(Rod &R, const REAL time) {
assert(rampupTime >= 0.0);
const REAL fraction =
(rampupTime == 0.0) ? 1.0 : min(1.0, time / rampupTime);
R.externalForces[0] += fraction * startForce;
R.externalForces[R.n] += fraction * endForce;
}
};
class GradualEndpointTorques : public ExternalForces {
public:
const REAL rampupTime;
Vector3 startTorque, endTorque;
GradualEndpointTorques(const Vector3 _startTorque, const Vector3 _endTorque,
const REAL _rampupTime)
: ExternalForces(),
startTorque(_startTorque),
endTorque(_endTorque),
rampupTime(_rampupTime) {}
void applyForces(Rod &R, const REAL time) {
assert(rampupTime >= 0.0);
const REAL fraction =
(rampupTime == 0.0) ? 1.0 : min(1.0, time / rampupTime);
R.externalTorques.front() += fraction * R.Q.front() * startTorque;
R.externalTorques.back() += fraction * R.Q.back() * endTorque;
}
};
// Apply pointwise force on one end for a given amount of time and then release
class OneEndTemporaryForce : public ExternalForces {
public:
const REAL timeForceIsApplied;
const Vector3 force;
OneEndTemporaryForce(const Vector3 _force, const REAL _timeForceIsApplied)
: ExternalForces(),
force(_force),
timeForceIsApplied(_timeForceIsApplied) {}
void applyForces(Rod &R, const REAL time) {
if (time < timeForceIsApplied) R.externalForces.back() += force;
}
};
// Represents constant forces at the endpoints. Note that a fixed endpoint
// will be represented by the bc function, so its tension force should
// be zero -- only free ends make sense with tension forces
class EndpointTorques : public ExternalForces {
public:
Vector3 startTorque, endTorque;
EndpointTorques(Vector3 _startTorque, Vector3 _endTorque)
: ExternalForces(), startTorque(_startTorque), endTorque(_endTorque) {}
void applyForces(Rod &R, const REAL time) {
R.externalTorques.front() += (R.Q.front() * startTorque);
R.externalTorques.back() += (R.Q.back() * endTorque);
}
};
class UniformTorques : public ExternalForces {
public:
const Vector3 torque;
UniformTorques(const Vector3 _torque) : ExternalForces(), torque(_torque) {}
void applyForces(Rod &R, const REAL time) {
R.externalTorques += R.Q * torque;
}
};
class UniformForces : public ExternalForces {
public:
const Vector3 force;
UniformForces(const Vector3 _force) : ExternalForces(), force(_force) {}
void applyForces(Rod &R, const REAL time) {
R.externalForces += force;
// This is bacause, the first and last masses are half the others!
R.externalForces.front() -= force / 2.0;
R.externalForces.back() -= force / 2.0;
}
};
// A random force with strength A and width sigma
class RandomForces : public ExternalForces {
public:
REAL A;
RandomForces(REAL A) : ExternalForces(), A(A) {}
void applyForces(Rod &R, const REAL time) {
// A is a force density per unit length
// const int nSegments = R.n;
// const REAL L = vSum(R.l);
// const REAL scaledA = A*L/nSegments;
const REAL scaledA = A;
R.externalForces += scaledA * vRandVector3(R.n + 1);
}
};
#endif
| true |
26a7246a4e124afa7a26f0ec31bca3131539cacc
|
C++
|
ccoale/frisk
|
/inc/TestCollection.h
|
UTF-8
| 1,452 | 3.09375 | 3 |
[
"Apache-2.0"
] |
permissive
|
#ifndef _TEST_COLLECTION_H
#define _TEST_COLLECTION_H
#include "Test.h"
#include <functional>
#include "Reporter.h"
namespace Frisk
{
class Reporter;
class TestCollection
{
typedef struct _TestFuncPair {
Test test;
std::function<void(Frisk::Test &)> func;
} TestFuncPair;
protected:
/**
* The list of tests that this collection should execute.
*/
std::list<TestCollection::TestFuncPair> tests;
/**
* The number of failures in the last run of tests.
*/
int lastFailCount;
public:
/**
* Initializes a new instance of TestCollection.
*/
TestCollection();
/**
* Destroys this instance of TestCollection.
*/
virtual ~TestCollection();
/**
* Adds a test to the test collection.
* @param func The function that defines the tests.
* @param name The name of the test, if it is not initialized or named in the function.
*/
virtual void addTest(std::function<void(Frisk::Test &)> func, const std::string &name = "");
/**
* Runs the given tests and returns a list of the test objects.
* @param failfast If true, then the tests will be run only until the first failure.
* @returns A list of Test objects.
*/
virtual std::list<Frisk::Test> runTests(bool failfast = true, Reporter *reporter = nullptr);
/**
* Returns the number of failures in the last run of tests.
*/
virtual int getLastFailCount() const;
};
}
#endif /* _TEST_COLLETION_H */
| true |
9e84b8e5f799ccbc7cae78119e96d66c5ec8da7c
|
C++
|
TomSmartBishop/avl
|
/inc/vec/v.inl
|
UTF-8
| 6,559 | 3.125 | 3 |
[
"MIT"
] |
permissive
|
#ifndef AVL_V_INL
#define AVL_V_INL
#pragma once
/// avl: A Vector Library
/// \author Thomas Pollak
namespace avl
{
/// \defgroup Helper functions
/// \{
//Component type helper
avl_ainl_res constexpr auto cmp(const v& vec) noexcept -> rem_const_ref_t<decltype(vec[0])>
{
return vec[0];
}
/// \}
/// \defgroup Getters and setters for all vectors
/// \{
/// Access the vector components by a range checked index from 0 to dim-1
avl_ainl_res constexpr auto get(const v& vec, const s::size_t idx) noexcept(ndebug||exuse) -> decltype(cmp(vec))
{
assert(idx < dim< rem_const_ref_t< decltype( vec ) > >::value);
return vec[idx];
}
/// Access the vector components by a static range checked index from 0 to dim-1
template<s::size_t _Idx> avl_ainl_res constexpr auto get(const v& vec) noexcept -> decltype(cmp(vec))
{
static_assert(_Idx < dim< rem_const_ref_t< decltype( vec ) > >::value, "Index is out of range");
return vec[_Idx];
}
/// Set a single component by index from 0 to dim-1
avl_ainl constexpr auto set(v& vec, const s::size_t idx, const sc scalar) noexcept(ndebug||exuse) -> void
{
static_assert(eq< decltype( vec[idx] ), decltype( scalar ) >::value, "Supply a scalar of the vectors element type.");
assert(idx < dim< rem_const_ref_t< decltype( vec ) > >::value);
vec[idx] = scalar;
}
/// Set a single component by static index from 0 to dim-1
template<s::size_t _Idx> avl_ainl constexpr auto set(v& vec, const sc scalar) noexcept -> void
{
static_assert(eq< decltype( vec[_Idx] ), decltype( scalar ) >::value, "Supply a scalar of the vectors element type.");
static_assert(_Idx < dim< rem_const_ref_t< decltype( vec ) > >::value, "Index is out of range");
vec[_Idx] = scalar;
}
/// \}
/// \defgroup Vector length operations
/// \{
/// Returns a new vector with the requested length
avl_ainl_res constexpr auto setlen_mk(const v& vec, const sc len_to_set) noexcept(ndebug||exuse)
{
const auto vec_len = len(vec);
assert(vec_len!=cnst<decltype(vec_len)>::zero);
return mul_mk(vec, len_to_set / vec_len);
}
/// Set the length of the vector
avl_ainl constexpr auto setlen_set(v& vec, const sc len_to_set) noexcept(ndebug||exuse) -> void
{
const auto vec_len = len(vec);
assert(vec_len!=cnst<decltype(vec_len)>::zero);
mul_set(vec, len_to_set / vec_len);
}
/// Set the length of the vector and return the same vector (chained)
avl_ainl_res constexpr auto setlen(v& vec, const sc len_to_set) noexcept(ndebug||exuse) -> decltype(vec)
{
const auto vec_len = len(vec);
assert(vec_len!=cnst<decltype(vec_len)>::zero);
mul_set(vec, len_to_set / vec_len);
return vec;
}
/// Calculate the length of the vector, prefere len_sqr when comparing distances
avl_ainl_res constexpr auto len(const v& vec) noexcept -> decltype(cmp(vec))
{
//len_sqr will never return any negativ values so we can gurantee noexcept
const auto vec_square_len = len_sqr(vec);
return static_cast<decltype(cmp(vec))>( s::sqrt( vec_square_len ) );
}
/// Returns a normalized vector
avl_ainl_res constexpr auto norm_mk(const v& vec ) noexcept(ndebug||exuse)
{
const auto vec_len = len(vec);
return div_mk(vec, vec_len); //div might assert in debug
}
/// Returns a normalized vector, use alternative vector if the current vector length is 0
avl_ainl_res constexpr auto norm_mk(const v& vec , const v& vec_if_zero_len) noexcept
{
const auto vec_len = len(vec);
if(vec_len==cnst<decltype(vec_len)>::zero)
return vec_if_zero_len;
return div_mk(vec, vec_len); //div might assert in debug
}
/// Normalize the current vector
avl_ainl constexpr auto norm_set(v& vec ) noexcept -> void
{
const auto vec_len = len(vec);
div_set(vec, vec_len); //div might assert in debug
}
/// Normalize the current vector, use alternative vector if the current vector length is 0
avl_ainl constexpr auto norm_set(v& vec , const v& vec_if_zero_len) noexcept -> void
{
const auto vec_len = len(vec);
if(vec_len==cnst<decltype(vec_len)>::zero)
{
vec = vec_if_zero_len;
return;
}
div_set(vec, vec_len); //div might assert in debug
}
/// Normalize the current vector and return the same vector (chained)
avl_ainl_res constexpr auto norm(v& vec ) noexcept -> decltype(vec)
{
const auto vec_len = len(vec);
div_set(vec, vec_len); //div might assert in debug
return vec;
}
/// Normalize the current vector and return the same vector (chained), use alternative vector if the current vector length is 0
avl_ainl_res constexpr auto norm(v& vec , const v& vec_if_zero_len) noexcept -> decltype(vec)
{
const auto vec_len = len(vec);
if(vec_len==cnst<decltype(vec_len)>::zero)
{
vec = vec_if_zero_len;
return vec;
}
div_set(vec, vec_len); //div might assert in debug
return vec;
}
/// \}
/// \defgroup Spacial operations
/// \{
/// Calculate the angle between two vectors in radian
avl_ainl_res constexpr auto angle_rd(const v& vec, const decltype(vec) other) noexcept -> decltype(cmp(vec))
{
const auto vec_len = len(vec);
const auto other_len = len(other);
const auto dot_prod = dot(vec, other);
return s::acos( dot_prod / ( vec_len * other_len ) );
}
/// Calculate the angle between two vectors in degree
avl_ainl_res constexpr auto angle_dg(const v& vec, const decltype(vec) other) noexcept -> decltype(cmp(vec))
{
const auto vec_len = len(vec);
const auto other_len = len(other);
const auto dot_prod = dot(vec, other);
return s::acos( dot_prod / ( vec_len * other_len ) ) * cnst<decltype(cmp(vec))>::to_deg;
}
/// Get the direction relative to another point excluding colinear and opposite-but-colinear (faster than get_dir_col)
avl_ainl_res constexpr auto get_dir(const v& vec, const v& other) noexcept -> dir
{
const auto dotProduct = dot(vec, other);
if( utl::eqls(dotProduct, decltype(dotProduct){0}, cnst<decltype(cmp(vec))>::big_epsln) ) {
return dir::perpend;
} else if( dotProduct > decltype(dotProduct){0}) {
return dir::same;
} else {
return dir::opp;
}
}
/// Get the direction relative to another point excluding colinear and opposite-but-colinear (faster than get_dir_col)
avl_ainl_res constexpr auto get_dir(const v& vec, const v& other, const sc epsilon) noexcept -> dir
{
const auto dotProduct = dot(vec, other);
if( utl::eqls(dotProduct, decltype(dotProduct){0}, epsilon) ) {
return dir::perpend;
} else if( dotProduct > decltype(dotProduct){0}) {
return dir::same;
} else {
return dir::opp;
}
}
/// \}
}
#endif // AVL_V_INL
| true |
0902f220ed33142d4e6bed77c34cec2a887e2e41
|
C++
|
smfaisal/leetcode_problems
|
/reverse_bits.cc
|
UTF-8
| 481 | 3.34375 | 3 |
[] |
no_license
|
#include <iostream>
using namespace std;
class Solution {
public:
uint32_t reverseBits(uint32_t n) {
uint32_t res = 0;
uint32_t mask = 1;
for (int i = 0; i < sizeof(uint32_t)*8; i++) {
if (n & mask<<i) {
res |= 1 << (sizeof(uint32_t)*8-1-i);
}
}
return res;
}
};
int main() {
Solution s;
uint32_t n = 43261596;
uint32_t res;
res = s.reverseBits(n);
cout << "Reverse Bits of " << n << " is: " << res << endl;
return 0;
}
| true |
21ade384ea3d3379fc64cf6e3aa48da805227e3a
|
C++
|
Barvius/oop_kursovoy
|
/Person.h
|
UTF-8
| 414 | 2.640625 | 3 |
[] |
no_license
|
#pragma once
#include <GL/glut.h>
#include<cmath>
#include "Coord.h"
class Person{
private:
Coord Position;
int Size = 30;
GLuint Texture;
bool lookLeft = false;
bool lookRight = true;
public:
int GetSize();
void LookLeft();
void LookRight();
void MovePositionX(int);
void SetPositionX(int);
void SetPositionY(int);
Coord GetPosition();
void Draw();
Person();
Person(Coord,GLuint);
~Person();
};
| true |
fcc82e468ec29fea9c27707cbfe1c2c8f8ba51bd
|
C++
|
tareyza/Learning-CPP
|
/Chapter 1/Problem 1/main.cpp
|
UTF-8
| 249 | 3.21875 | 3 |
[] |
no_license
|
#include "stdafx.h"
#include <iostream>
int readNumber() {
int x;
std::cin >> x;
return x;
}
void writeAnswer(int x)
{
std::cout << "Sum: " << x;
}
int main()
{
int x = readNumber();
int y = readNumber();
writeAnswer(x + y);
return 0;
}
| true |
c2907b1802ba8dfe1ed2abe82fabf8f295016b65
|
C++
|
vlad-zhogolev/CG-Seminar12
|
/CourseWork3/src/Objects/Object.cpp
|
UTF-8
| 419 | 2.6875 | 3 |
[] |
no_license
|
#include <Objects/Object.h>
glm::mat4 Object::getModelMatrix()
{
glm::mat4 model{};
// translate
model = glm::translate(model, _position);
// rotate model using quaternion
glm::quat quaternion(glm::vec3(glm::radians(_rotation.x), glm::radians(_rotation.y), glm::radians(_rotation.z)));
model = model * toMat4(quaternion);
// scale
model = glm::scale(model, _scale);
return model;
}
| true |
4a7083709482b3e99a067cf305415c1e20859e57
|
C++
|
0x01111/ChSeg
|
/loadData.h
|
GB18030
| 4,576 | 2.84375 | 3 |
[] |
no_license
|
#include <iostream>
#include <stdlib.h>
#include <string>
#include <math.h>
#include <fstream>
#include <sstream>
#include <stack>
#include <string>
using namespace std;
#define ATTR_NUM 1500
struct Data
{
//ù
int id;
string attr_string[ATTR_NUM];//ַ
double weight;
Data *next;
int len;
};
class dataToMatrix
{
public:
Data *dataSet;
int col;
int row;
public:
int loadData(dataToMatrix *dtm,char *file)
{
int i=0,j=0,pos=0,k;
char ch='/';
ifstream infile;
string tmpstrline;
Data *p;
dtm->dataSet=new Data;
dtm->dataSet->next=NULL;
p=dtm->dataSet;
Data *datatmp;
dtm->col=0;
cout<<file<<endl;
infile.open(file,ios::in);
while(!infile.eof())
{
getline(infile,tmpstrline,'\n');//ȡļһеݣΪstring
stringstream input(tmpstrline);
if(tmpstrline!="\0")////ڶȡļͬò
{
datatmp=new Data;
datatmp->id=i;
datatmp->next=NULL;
j=0;
while(input>>datatmp->attr_string[j])
{
pos=datatmp->attr_string[j].find(ch,0);
datatmp->attr_string[j]=datatmp->attr_string[j].substr(0,pos);
j++;
}
datatmp->attr_string[j]="#";
datatmp->len=j;
p->next=datatmp;
p=p->next;
dtm->col++;
}
i++;
}
infile.close();
return 0;
}
int loadData(dataToMatrix *dtm,char *file,int type)
{
int i=0,j=0;
ifstream infile;
string tmpstrline;
Data *p;
dtm->dataSet=new Data;
dtm->dataSet->next=NULL;
p=dtm->dataSet;
Data *datatmp;
dtm->col=1;
cout<<file<<endl;
infile.open(file,ios::in);
datatmp=new Data;
datatmp->next=NULL;
while(!infile.eof())
{
getline(infile,tmpstrline,'\n');//ȡļһеݣΪstring
stringstream input(tmpstrline);
if(tmpstrline!="\0")////ڶȡļͬò
{
while(input>>datatmp->attr_string[j])
{
j++;
}
}
}
p->next=datatmp;
datatmp->len=j;
dtm->row=j;
infile.close();
return 0;
}
int loadData(dataToMatrix *dtm,char *file,char type)
{
int i=0,j=0,pos=0,k;
char ch=' ';
ifstream infile;
string tmpstrline;
Data *p;
dtm->dataSet=new Data;
dtm->dataSet->next=NULL;
p=dtm->dataSet;
Data *datatmp;
dtm->col=0;
dtm->row=ATTR_NUM;
cout<<file<<endl;
infile.open(file,ios::in);
while(!infile.eof()&&i<20)
{
getline(infile,tmpstrline,'\n');//ȡļһеݣΪstring
stringstream input(tmpstrline);
if(tmpstrline!="\0")////ڶȡļͬò
{
datatmp=new Data;
datatmp->id=i;
datatmp->next=NULL;
k=0,j=0;
int len=tmpstrline.length();
while(j*2<len)
{
if(tmpstrline.substr(j*2,1)!=" ")
{
datatmp->attr_string[k]=tmpstrline.substr(j*2,2);
//cout<<datatmp->attr_string[k]<<"&";
k++;
}
j++;
}
//datatmp->attr_string[k]="#";
datatmp->len=k;
p->next=datatmp;
p=p->next;
dtm->col++;
}
i++;
}
//cout<<"k="<<k<<endl;
infile.close();
return 0;
}
int print(dataToMatrix dtm)
{
//ݼǷȷ
int i,j;
Data *p=dtm.dataSet->next;
for(i=0; i<dtm.col&&p!=NULL; i++)
{
for(j=0; p->attr_string[j]!="#"&&j<dtm.row; j++)
{
cout<<p->attr_string[j]<<" ";
}
p=p->next;
cout<<endl;
}
return i;
}
};
| true |
2ba908654ffbe303a0dc2bbb300367dfbcb6d054
|
C++
|
Sassafrass6/MyneCraft
|
/Source/Core/Perlin.cpp
|
UTF-8
| 1,717 | 3.21875 | 3 |
[] |
no_license
|
#include "Perlin.h"
/* PsuedoCode taken from https://en.wikipedia.org/wiki/Perlin_noise */
Perlin::Perlin(float dnsty) : density(dnsty) {
size = xMax * yMax;
density = (density > 0.0f ? density : 0.1f);
generateGradientTrivial();
}
void Perlin::generateGradientTrivial() {
for (int i = 0; i < xMax; i++) {
for (int j = 0; j < yMax; j++) {
gradient[i][j][0] = float(Rand::rand()) / (Rand::RANDMAX/2) - 1.0f;
gradient[i][j][1] = float(Rand::rand()) / (Rand::RANDMAX/2) - 1.0f;
}
}
}
// Function to linearly interpolate between a0 and a1
// Weight w should be in the range [0.0, 1.0]
float Perlin::lerp(float a0, float a1, float w) {
return (1.0 - w)*a0 + w*a1;
}
// Computes the dot product of the distance and gradient vectors.
float Perlin::dotGridGradient(int ix, int iy, float x, float y) {
// Compute the distance vector
float dx = x - (float)ix;
float dy = y - (float)iy;
ix = abs(ix % xMax);
iy = abs(iy % yMax);
// Compute the dot-product
return (dx*gradient[iy][ix][0] + dy*gradient[iy][ix][1]);
}
// Compute Perlin noise at coordinates x, y
float Perlin::getPerlin(float x, float y) {
// Determine grid cell coordinates
int x0 = (x >= 0.0 ? (int)x : (int)x - 1);
int x1 = x0 + 1;
int y0 = (y >= 0.0 ? (int)y : (int)y - 1);
int y1 = y0 + 1;
// Determine interpolation weights
float sx = x - (float)x0;
float sy = y - (float)y0;
// Interpolate between grid point gradients
float n0, n1, ix0, ix1, value;
n0 = dotGridGradient(x0, y0, x, y);
n1 = dotGridGradient(x1, y0, x, y);
ix0 = lerp(n0, n1, sx);
n0 = dotGridGradient(x0, y1, x, y);
n1 = dotGridGradient(x1, y1, x, y);
ix1 = lerp(n0, n1, sx);
value = lerp(ix0, ix1, sy);
float ret = value;
return ret;
}
| true |
452f0e22619917f3eadffccb1047600b40f3f825
|
C++
|
YazanZebak/Algorithms-and-DataStructures
|
/Misc/Elementary Math.cpp
|
UTF-8
| 1,820 | 3.046875 | 3 |
[] |
no_license
|
const double PI = acos(-1);
const double e = exp(1.0) ;
const double phi = (1.0 + sqrt(5.0))/2.0 ;
const double inf = std::numeric_limits<double>::infinity();
const double nan = std::numeric_limits<double>::quiet_NaN();
//! get length of digits before cycle of a/b
void solve(int a , int b) {
int result = a/b , remainder = a%b , index = 0 ;
map < int , int > remainderIndex ;
vector < int > digits ;
while(!remainderIndex.count(remainder)) {
remainderIndex[ remainder ] = index++ ;
result = remainder * 10 / b ;
digits.push_back( result );
remainder = (remainder * 10) % b ;
}
int cycleStartIndex = remainderIndex[ remainder ];
int cyclSize = index - cycleStartIndex ;
}
// round : nearest integer to x
// ceil : round up
// floor : round down
// trunc : round toward zero ( remove fraction )
// Warning!! : round(4.5) = 5
// round(x , m) * m == greatest multiple of m smaller than x
int integer_round(int x , int y){
(x > 0 ? (x + y/2)/y : (x - y/2)/y) ;
}
int integer_ceil(int x , int y){
return (x + y - 1)/y ;
}
void logArithmetic() {
// logb( sqrtP(x) ) = logb(x) / p;
// b = 1 / (x ^ logb(x)) ;
// x * ( b ^ y ) = b ^ ( logb( x ) + y );
}
//! power comparison a^b ? c^d
int comp(int a , int b , int c , int d){
double c1 = b * log(a) , c2 = d * log(c) ;
if(c1 - c2 < 0) return -1 ;
else if(c1 - c2 > 0) return 1 ;
else 0
}
double logBase(double base , double x) {
return (log(x) / log(base));
}
// ( a * b ) % m
typedef long long unsigned int llu;
typedef long long int ll ;
typedef long double ld;
llu mul_mod(llu a, llu b, llu m){
llu y = (llu)((ld)a*(ld)b/m+(ld)1/2);
y = y * m;
llu x = a * b;
llu r = x - y;
if ( (ll)r < 0 ){
r = r + m; y = y - 1;
}
return r;
}
| true |
c2ed9480e15d888333007ceb2c0dc1c660c66b75
|
C++
|
clzdl/BusinessUtil
|
/src/AmqpClient.cpp
|
UTF-8
| 3,022 | 2.78125 | 3 |
[] |
no_license
|
/*
* AmqpClient.cpp
*
* Created on: 2018年3月12日
* Author: chengl
*/
#include <AmqpClient.h>
#include <sstream>
namespace BusinessUtil{
AmqpClient::AmqpClient(std::string user , std::string pwd, std::string host , short port , std::string vhost)
:m_stop(false),
m_connection(nullptr),
m_tcpHandler(nullptr),
m_eventThread(nullptr)
{
m_address = new AMQP::Address(BuildAddress(user,pwd,host,port,vhost));
}
AmqpClient::~AmqpClient()
{
CloseConnection();
delete m_address;
m_eventThread->join();
delete m_eventThread;
}
void AmqpClient::EventLoop(ITcpHandler *tcpHandler)
{
m_tcpHandler = tcpHandler;
m_connection = new AMQP::TcpConnection(tcpHandler , *m_address);
m_eventThread = new std::thread(std::bind(&AmqpClient::Run ,this));
}
void AmqpClient::ReEventLoop()
{
CloseConnection();
m_eventThread->join();
delete m_eventThread;
m_connection = new AMQP::TcpConnection(m_tcpHandler , *m_address);
m_eventThread = new std::thread(std::bind(&AmqpClient::Run ,this));
}
void AmqpClient::Stop()
{
m_stop = true;
CloseConnection();
}
bool AmqpClient::IsStop()
{
return m_stop;
}
void AmqpClient::CloseConnection()
{
if(m_connection)
{
m_connection->close();
delete m_connection;
m_connection = nullptr;
}
}
void AmqpClient::Run()
{
int err = 0;
int maxFd = 0;
fd_set readSet;
fd_set wirteSet;
while(!m_stop)
{
struct timeval tv;
tv.tv_sec = 5;
tv.tv_usec = 0;
FD_ZERO(&readSet);
FD_ZERO(&wirteSet);
for(auto it : m_fdMap)
{
if(it.second & AMQP::readable)
FD_SET(it.first , &readSet);
if(it.second & AMQP::writable )
FD_SET(it.first , &wirteSet);
if(it.first > maxFd)
maxFd = it.first;
}
err = select(maxFd + 1, &readSet, &wirteSet, NULL, &tv);
if( err == EINTR)
{
continue;
}
else if (err < 0)
{
fprintf(stderr , "select error.\n");
continue;
}
else if (err == 0)
{
fprintf(stderr , "select timeout.\n");
continue;
}
int flags = 0;
for(auto it : m_fdMap)
{
flags = 0;
if(FD_ISSET(it.first,&readSet))
{
flags |= AMQP::readable;
}
if(FD_ISSET(it.first,&wirteSet))
{
flags |= AMQP::writable;
}
m_connection->process(it.first , flags);
}
}
}
std::string AmqpClient::BuildAddress(std::string user , std::string pwd, std::string host , short port , std::string vhost)
{
std::stringstream ss;
ss<<"amqp://"<<user<<":"<<pwd<<"@"<<host<<":"<<port<<"/"<<vhost;
return ss.str();
}
std::shared_ptr<AMQP::TcpChannel> AmqpClient::CreateChannel()
{
return std::make_shared<AMQP::TcpChannel>(m_connection);
}
}
| true |
227d193555884fc22a3eb8c38bda02c4b9df78ab
|
C++
|
Nikvand/others
|
/Source.cpp
|
UTF-8
| 8,032 | 2.921875 | 3 |
[] |
no_license
|
/*Commenting here*/
#include <ipp.h>
#include <string>
#include <vector>
#include <iostream>
#include <opencv/cv.h>
#include <opencv/highgui.h>
#include <deque>
class member
{
public:
member(unsigned int joined_month)
:_joined_month(joined_month)
{
}
unsigned int joined_month(){return _joined_month;}
private:
unsigned int _joined_month;
};
class society
{
public:
society()
{
_population = 70000000;
_termination_time = 6;
_profit_time = 2; //6 child: it happened in second month
}
society(unsigned long long int population, unsigned int termination_time, unsigned int profit_time)
:_population(population),
_termination_time(termination_time),
_profit_time(profit_time)
{
}
int draw(unsigned long long int profite_member, unsigned long long int current_member, unsigned int current_month)
{
cv::Mat out(540, 960, CV_8UC3);
unsigned long long int non_profite_member = current_member - profite_member;
//Member
{
cv::line(out,cv::Point(40,275) , cv::Point(700,275), cv::Scalar(255,255,255));
cv::putText(out, "Month", cv::Point(705,275), cv::FONT_HERSHEY_COMPLEX_SMALL, 0.4, cvScalar(255,255,250), 1, CV_AA);
cv::line(out,cv::Point(40,275) , cv::Point(40,10), cv::Scalar(255,255,255));
cv::putText(out, "Population", cv::Point(50,10), cv::FONT_HERSHEY_COMPLEX_SMALL, 0.4, cvScalar(255,255,250), 1, CV_AA);
unsigned int pixels_member = current_member * 255 / _population;
if(member_per_mount.size() == 0) member_per_mount.push_back(std::pair<unsigned long long int, int>(pixels_member+1, current_month));
else if(member_per_mount.back().second == current_month) member_per_mount.back().first =(pixels_member+1);
else member_per_mount.push_back(std::pair<unsigned long long int, int>(pixels_member+1, current_month));
int lenght = 30;
for(size_t i = 0 ; i < member_per_mount.size();i++)
for(size_t j = 270; j > 270-member_per_mount[i].first ; j--)
for(size_t k = 50 ; k < 50+lenght ; k++)
{
int color = 255 - member_per_mount[i].first;
if(color > 255) color =255;
if(color < 50 ) color = 50;
out.data[out.step[0]*j + (out.step[1]* (k+(i*lenght))) + 0] = color;
}
}
//Profit
{
cv::line(out,cv::Point(40,501) , cv::Point(350,501), cv::Scalar(255,255,255));
cv::putText(out, "With profit", cv::Point(75,520), cv::FONT_HERSHEY_COMPLEX_SMALL, 0.4, cvScalar(255,255,250), 1, CV_AA);
cv::putText(out, "Without profit", cv::Point(225,520), cv::FONT_HERSHEY_COMPLEX_SMALL, 0.4, cvScalar(255,255,250), 1, CV_AA);
cv::line(out,cv::Point(40,501) , cv::Point(40,300), cv::Scalar(255,255,255));
cv::putText(out, "Number", cv::Point(50,300), cv::FONT_HERSHEY_COMPLEX_SMALL, 0.4, cvScalar(255,255,250), 1, CV_AA);
unsigned int pixels_profite = (profite_member * 200 / _population)+1;
unsigned int pixels_non_profite = (non_profite_member * 200 / _population)+1;
int lenght = 100;
for(size_t i = 500; i > 500-pixels_profite ; i--)
for(size_t j = 50 ; j < 50+lenght ; j++)
out.data[out.step[0]*i + out.step[1]* j + 1] = 255;
for(size_t i = 500; i > 500-pixels_non_profite ; i--)
for(size_t j = 200 ; j < 200+lenght ; j++)
out.data[out.step[0]*i + out.step[1]* j + 2] = 255;
}
{
std::string Result;
std::ostringstream convert;
convert << current_month; // insert the textual representation of 'Number' in the characters in the stream
Result = "Current month: " + convert.str();
cv::putText(out, Result, cv::Point(500,440),
cv::FONT_HERSHEY_COMPLEX_SMALL, 0.8, cvScalar(200,200,250), 1, CV_AA);
}
{
std::string Result;
std::ostringstream convert;
convert << current_member; // insert the textual representation of 'Number' in the characters in the stream
Result = "Current members: " + convert.str();
cv::putText(out, Result, cv::Point(500,460),
cv::FONT_HERSHEY_COMPLEX_SMALL, 0.8, cvScalar(200,200,250), 1, CV_AA);
} {
std::string Result;
std::ostringstream convert;
convert << profite_member; // insert the textual representation of 'Number' in the characters in the stream
Result = "Member with profit: " + convert.str();
cv::putText(out, Result, cv::Point(500,480),
cv::FONT_HERSHEY_COMPLEX_SMALL, 0.8, cvScalar(200,200,250), 1, CV_AA);
}
{
std::string Result;
std::ostringstream convert;
convert << non_profite_member; // insert the textual representation of 'Number' in the characters in the stream
Result = "Member without profit: " + convert.str();
cv::putText(out, Result, cv::Point(500,500),
cv::FONT_HERSHEY_COMPLEX_SMALL, 0.8, cvScalar(200,200,250), 1, CV_AA);
}
cv::imshow("Result", out);
cv::waitKey(3);
return 1;
}
unsigned long long int population(){return _population;}
unsigned int termination_time(){return _termination_time;}
unsigned int profit_time(){return _profit_time;}
private:
unsigned long long int _population;
unsigned int _termination_time;
unsigned int _profit_time;
std::vector<std::pair<unsigned long long int,int>> member_per_mount;
};
int main()
{
int in_para = -1;
while(in_para != 89 && in_para != 121 && in_para!= 78 && in_para != 110)
{
std::cout << std::endl<<"Use default parameters? (y/n)"<<std::endl;
std::cout << "Default parameters are:"<<std::endl<<" Population: 70,000,000" <<std::endl<<
" Give up period: 6 months"<<std::endl<<
" Receive profit after having 6 members"<<std::endl;
in_para = getchar();
}
society country;
if(in_para == 78 || in_para == 110) //No
{
unsigned long long int pop;
unsigned int termperiod;
int prof_mem;
std::cout << std::endl;
std::cout << "Enter population(e.g. 70000000): ";
std::cin>> pop;
std::cout << std::endl;
std::cout << "Enter give up period(e.g. 6): ";
std::cin>> termperiod;
std::cout << std::endl;
std::cout << "Enter number of member to gain profit(e.g. 6): ";
std::cin>> prof_mem;
unsigned int prof_period = 0;
while(prof_mem > 0)
{
prof_period++;
prof_mem -= pow(2, prof_period);
}
country = society(pop, termperiod, prof_period);
}
unsigned long long int profite_member = 0;
unsigned long long int current_member = 1;
unsigned int current_month = 1;
std::deque<member> members;
members.push_back(member(current_month-1));
while(1)
{
for(size_t i = 0 ; i < members.size() ; i++)
{
if (( current_month - members.front().joined_month()) == (country.termination_time()+1) )
members.pop_front();
else
break;
}
unsigned int membersize = members.size();
for(size_t i = 0 ; i < membersize; i++)
{
members.push_back(member(current_month));
current_member++;
if(current_member >= (country.population())) break;
members.push_back(member(current_month));
current_member++;
if(current_member >= (country.population())) break;
if(i%10000 == 0) country.draw(profite_member,current_member,current_month);
}
for(size_t i = 0 ; i < members.size(); i++)
{
if(current_member >= (country.population()-1)) break;
if (( current_month - members[i].joined_month()) == country.profit_time())
profite_member++;
else if((current_month - members[i].joined_month()) < country.profit_time())
break;
if(i%10000 == 0) country.draw(profite_member,current_member,current_month);
}
country.draw(profite_member,current_member,current_month);
if(current_member >= (country.population())) break;
current_month++;
}
country.draw(profite_member,current_member,current_month);
std::cout << "Press any key..."<<std::endl;
cv::waitKey();
getchar();
return 1;
}
| true |
bc509c4bb6ab867685fc022bca24224292c019d6
|
C++
|
RealLeonardoHuang/ISE209
|
/Chapter 2/2-32/2-32(do-while版).cpp
|
ISO-8859-1
| 346 | 3.375 | 3 |
[] |
no_license
|
//2-32do-while棩
#include <iostream>
using namespace std;
int main()
{
int m = 56;
int n = 0;
do
{
cout << "Guess a number!(1~100)" << endl;
cin >> n;
if (n > m)
{
cout << "Too big!" << endl;
}
else if (n < m)
{
cout < "Too small!" << endl;
}
else
cout << "Bingo!" << endl;
} while (n != m);
return 0;
}
| true |
19e1a78da06ab1b0a7e36af9684467e6698dc78e
|
C++
|
miscalculation53/typical90_source
|
/060_1.cpp
|
UTF-8
| 953 | 2.9375 | 3 |
[] |
no_license
|
#include <bits/stdc++.h>
using namespace std;
int INF = 1 << 30;
int main()
{
int N;
cin >> N;
vector<int> A(N);
for (int i = 0; i < N; i++)
{
cin >> A.at(i);
A.at(i) = N + 1 - A.at(i); // 単調減少 → 単調増加 を作る問題にする
}
vector<int> dp(N + 2, INF);
dp.at(0) = -INF;
for (auto a : A)
{
// 通常の LIS で選べる 「a を使う」 「何もしない」 に加え 「-a を使う」 も選べる, これで単調増加を作る問題になった
auto itmi = lower_bound(dp.begin(), dp.end(), -a);
auto itpl = lower_bound(dp.begin(), dp.end(), a);
int imi = itmi - dp.begin(), ipl = itpl - dp.begin();
if (dp.at(ipl - 1) != -a) dp.at(ipl) = a; // ただし -2, 2 みたいになるとやばいのでそれだけ除外
dp.at(imi) = -a;
}
for (int i = 1; i < N + 2; i++)
{
if (dp.at(i) == INF)
{
cout << i - 1 << endl;
return 0;
}
}
}
| true |
6bdcd98060b7c464bafc92e18e3d2ff9ac3ee0fc
|
C++
|
d3roch4/storage
|
/storage/functions.cpp
|
UTF-8
| 1,069 | 2.75 | 3 |
[] |
no_license
|
#include "functions.h"
#include <string>
namespace storage {
std::string typeName(const std::type_info &ti, std::string& name, Entity* entity){
if(ti == typeid(std::string))
return "text";
else if(ti == typeid(char) || ti==typeid(unsigned char))
return "char";
else if(ti == typeid(short) || ti==typeid(unsigned short))
return "smallint";
else if(ti == typeid(int) || ti==typeid(unsigned int))
return "int";
else if(ti == typeid(long) || ti==typeid(unsigned long))
return "bigint";
else if(ti == typeid(long long) || ti==typeid(unsigned long long))
return "bigint";
else if(ti == typeid(bool))
return "bit(1)";
else if(ti == typeid(float))
return "float";
else if(ti == typeid(double))
return "float";
else if(ti == typeid(std::chrono::time_point<std::chrono::system_clock>))
return "TIMESTAMP";
else{
return "";
}
throw_with_trace(std::runtime_error("getTypeDB: type not implemented for: "+entity->name+"::"+name));
}
}
| true |
ca9a0e78d59682f9c31e2640687bb59c8407ab9b
|
C++
|
zhangsdly/Effective_c_plus_plus
|
/hiding_names.cpp
|
UTF-8
| 1,299 | 3.5625 | 4 |
[] |
no_license
|
#include <iostream>
/*========== Avoid hiding inherited names ================================
Shakespeare had a thing about names. "What's in a name?" he asked,
"A rose by any other name would smell as sweet."
The Bard also wrote,
"he that filches from me my good name ... makes me poor indeed."
========================================================================*/
class Base
{
public:
Base() {}
virtual ~Base()
{
std::cout << "Base destructor"<<std::endl;
}
virtual void mf1() = 0;
virtual void mf2()
{
std::cout << "Base::mf2" << std::endl;
}
void mf3()
{
std::cout<< "Base::mf3"<<std::endl;
}
};
class Derived: public Base
{
public:
Derived(){}
~Derived()
{
std::cout<<"Derived destructor"<<std::endl;
}
virtual void mf1()
{
std::cout<< "Derived::mf1" << std::endl;
}
void mf3()
{
std::cout<< "Derived::mf3" << std::endl;
}
void mf4()
{
std::cout<<"Derived::mf4"<< std::endl;
Base::mf3();
}
};
int main()
{
Derived *t = new Derived;
t->mf1(); //Derived
t->mf2(); //Base
t->mf3(); //Derived, hiding
t->mf4(); //Derived::mf4, Base:mf3
delete t; //Derived , Base destructor
return 0;
}
| true |
4f9a53e8ceed45cacb06cc3c6b69ceb182930384
|
C++
|
arcogelderblom/AdventOfCode2019
|
/05-december/main.cpp
|
UTF-8
| 868 | 3.265625 | 3 |
[] |
no_license
|
#include "FileLoader.hpp"
#include "IntcodeComputer.hpp"
#include <iostream>
int main() {
FileLoader fileLoader;
std::vector<std::string> codes = fileLoader.getCommaSeparatedVectorFromFile("05-december/input.txt");
std::vector<int> program;
for (std::string code : codes) {
program.push_back(std::stoi(code));
}
IntcodeComputer intcodeComputer(program);
std::cout << "Insert 1 when prompted for puzzle 1." << std::endl;
intcodeComputer.getResultFromAddress(0);
std::cout << "Read the result to puzzle one from the command line." << std::endl;
IntcodeComputer intcodeComputer2(program);
std::cout << "Insert 5 when prompted for puzzle 2." << std::endl;
intcodeComputer2.getResultFromAddress(0);
std::cout << "Read the result to puzzle two from the command line." << std::endl;
return 0;
}
| true |
a54a3cc5f10e3e92eb6bd7cec6dfb5cf4d27da19
|
C++
|
bbom16/study_algorithm
|
/algorithm_2020_cplus/b14499.cpp
|
UHC
| 2,109 | 3.46875 | 3 |
[] |
no_license
|
//2020.02.03
//boj 14499
//ֻ
//ùķ̼
//ֻ ٴ ٲ ġ ã° ذ ٽ
// ٲ 迭 ̿ ؼ ذ
#include <iostream>
#include <cstdio>
using namespace std;
int N, M, x, y, K;
int map[21][21];
int current_location[6]; //ֻ ġ
int next_location[6] = { 6,3,4,2,5,1 }; //ֻ ű ġ ( ٴ 6 command ٲ ġ)
int dx[] = { 0,0,0,-1,1 };
int dy[] = { 0,1,-1,0,0 };
int dice[7] = { 0, }; //ֻ 鿡
bool chk_range(int x, int y) {
if (x < 0 || x >= N || y < 0 || y >= M)
return false;
return true;
}
void play_dice(int x, int y, int c) {
/* command ݴ (1-2, 3-4) */
int tmp;
if (c == 1)
tmp = 2;
else if (c == 2)
tmp = 1;
else if (c == 3)
tmp = 4;
else if (c == 4)
tmp = 3;
/* ֻ ٲ ֻ 迭 */
next_location[0] = current_location[c];
next_location[c] = 7 - current_location[0];
next_location[tmp] = current_location[0];
next_location[5] = 7 - current_location[c];
//ٴ
int bottom = next_location[0];
/* 0̸ ֻ ظ , ƴϸ ֻ ٴڿ 0 */
if (map[x][y] == 0) {
map[x][y] = dice[bottom];
}
else {
dice[bottom] = map[x][y];
map[x][y] = 0;
}
printf("%d\n", dice[7 - bottom]);
}
int main(int argc, char *argv[]) {
scanf("%d %d %d %d %d", &N, &M, &x, &y, &K);
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
scanf("%d", &map[i][j]);
}
}
int command;
while (K--) {
/* next current copy */
for (int i = 0; i < 6; i++) {
current_location[i] = next_location[i];
}
scanf("%d", &command);
/* ɿ ´ ġ ̵ */
x += dx[command];
y += dy[command];
if (!chk_range(x, y)) {
x -= dx[command];
y -= dy[command];
continue;
}
play_dice(x, y, command);
}
return 0;
}
| true |
2b3edc00a039a95ade09fd6a736d7f05237cdadd
|
C++
|
LuciaRavazzi/TesiTriennale_Fisica
|
/Kohn-Sham/V_Diretto.h
|
UTF-8
| 883 | 2.546875 | 3 |
[] |
no_license
|
#ifndef V_Diretto_h
#define V_Diretto_h
#include "nr.h"
#include "function.h"
#include "density.h"
using namespace std;
//Tiene conto del potenziale di Hartree.
class V_Diretto: public Function {
public:
//Costruttore di potenziale nullo.
V_Diretto(const Vec_DP &x);
//Aggiorno dopo aver ricevuto la densità.
V_Diretto(const Density &);
//Altro costrutture.
V_Diretto(const Vec_DP &x, const Vec_DP &y, double yp1=0, double ypn=0);
//Valuta la funzione potenziale nei punti della mesh.
void Evaluate(const Density &);
//Uguaglia due funzioni.
void operator= (const V_Diretto &f);
};
V_Diretto operator*(const double, V_Diretto &);
V_Diretto operator+(V_Diretto , V_Diretto );
V_Diretto operator-(V_Diretto , V_Diretto );
//restituisce la differenza fra 2 potenziali
double Get_err(V_Diretto &s, V_Diretto &d);
#endif
| true |
5169151f8151cf05e055fb97d1217b95d37fa5bd
|
C++
|
ilanolkies/metnum-tp2
|
/src/knn.cpp
|
UTF-8
| 2,136 | 3.078125 | 3 |
[] |
no_license
|
#include <algorithm>
//#include <chrono>
#include <iostream>
#include "knn.h"
#include <limits>
#include <queue>
using namespace std;
KNNClassifier::KNNClassifier(unsigned int n_neighbors)
{
k = n_neighbors;
}
void KNNClassifier::fit(SparseMatrix X, Matrix y)
{
matrizX = X;
matrizY = y;
}
Vector KNNClassifier::predict(SparseMatrix X)
{
auto result = Vector(X.rows());
for (int i = 0; i < X.rows(); i++)
result(i) = predecirFila(X, i);
return result;
}
uint KNNClassifier::predecirFila(SparseMatrix &X, int fila){
// min heap para almacenar las distancias, asociadas con la reseña
priority_queue<cercano> queue;
double distancia;
// calculamos la distancia a cada fila de la matriz
for (uint i = 0; i < matrizX.rows(); i++) {
distancia = 0;
// SparseMatrix::InnerIterator itera las columnas existentes
SparseMatrix::InnerIterator it_train(matrizX, i);
SparseMatrix::InnerIterator it_test(X, fila);
// vamos a ir sumando prograsivamente por los indices existentes
while (it_test && it_train) {
// si el indice de train es menor que el de test
while (it_train.index() < it_test.index()) {
distancia += pow(it_train.value(), 2);
++it_train;
}
// si el indice de test es menor que el de train
while (it_test.index() < it_train.index()) {
distancia += pow(it_test.value(), 2);
++it_test;
}
// si los indices son iguales
if (it_test && it_train && it_train.index() == it_test.index()) {
distancia += pow(it_test.value() - it_train.value(), 2);
++it_test;
++it_train;
}
}
//Agregado a priority queue
cercano a;
a.distancia = sqrt(distancia);
a.resenia = matrizY(0, i);
queue.push(a);
}
unsigned int positivas = 0;
// obtenemos los k mas cercanos
for (unsigned int i = 0; i < k; i++)
if (queue.empty())
cerr << "Error cola vacia: K es mayor a cantidad de filas " << endl;
else {
cercano a = queue.top();
if (a.resenia)
positivas++;
queue.pop();
}
return positivas * 2 >= k ? 1 : 0;
}
| true |
a124abe01a641864ff1013ee7b3a144fc9938518
|
C++
|
flysaiah/583-possible-benchmarks
|
/loop_removal.cpp
|
UTF-8
| 36,490 | 2.703125 | 3 |
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
/*
Copyright 2007-2008 Adobe Systems Incorporated
Copyright 2018 Chris Cox
Distributed under the MIT License (see accompanying file LICENSE_1_0_0.txt
or a copy at http://stlab.adobe.com/licenses.html )
Goal: Test compiler optimizations related to removing unnecessary loops.
Assumptions:
1) The compiler will normalize loops.
Additional optimizations should not depend on syntax of loop.
See also: loop_normalize.cpp
2) The compiler will remove empty loops.
aka: dead loop removal
3) The compiler will remove loops whose contents do not contribute to output / results.
aka: dead loop removal after removing dead code from loop body
4) The compiler will remove constant length loops when the result can be calculated directly.
5) The compiler will remove variable length loops when the result can be calculated directly.
NOTE - loops that cannot be entered are covered in dead_code_elimination.cpp
NOTE - I found nested pointless loops worse than this in a physics simulation package.
Names have been removed to protect the innocent grad students maintaining said package.
*/
#include "benchmark_stdint.hpp"
#include <stddef.h>
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <math.h>
#include "benchmark_results.h"
#include "benchmark_timer.h"
/******************************************************************************/
// this constant may need to be adjusted to give reasonable minimum times
// For best results, times should be about 1.0 seconds for the minimum test run
// In this file, correct results take zero time, so adjust for the bad results.
int iterations = 40000;
#define SIZE 100000
// initial value for filling our arrays, may be changed from the command line
double init_value = 3.0;
// global count for loop multiplication
// value must be less than 8th root of (2^31)-1 or about 14
int count = 6;
int count_array[ 8 ];
/******************************************************************************/
#include "benchmark_shared_tests.h"
/******************************************************************************/
template <typename T>
inline void check_sum(T result, int length) {
T temp = (length*length)*(length*length)*(length*length)*(length*length);
if (!tolerance_equal<T>(result,temp)) printf("test %i failed\n", current_test);
}
/******************************************************************************/
template <typename T>
inline void check_sum(T result, int* lengths) {
T temp = (lengths[0]*lengths[1])*(lengths[2]*lengths[3])*(lengths[4]*lengths[5])*(lengths[6]*lengths[7]);
if (!tolerance_equal<T>(result,temp)) printf("test %i failed\n", current_test);
}
/******************************************************************************/
template <typename T>
inline void check_sum2(T result) {
T temp = (T)255 * (T)SIZE;
if (!tolerance_equal<T>(result,temp)) printf("test %i failed\n", current_test);
}
/******************************************************************************/
/******************************************************************************/
template <typename T >
void test_loop_opt(int length, const char *label) {
int i;
start_timer();
for(i = 0; i < iterations; ++i) {
T result = 0;
result = (length*length)*(length*length)*(length*length)*(length*length);
check_sum<T>(result, length);
}
record_result( timer(), label );
}
/******************************************************************************/
template <typename T >
void test_for_loop_single(int length, const char *label) {
int i;
start_timer();
for(i = 0; i < iterations; ++i) {
T result = 0;
int x, y, z, w, j, k, i, m;
for (x = 0; x < length; ++x)
for (y = 0; y < length; ++y)
for (z = 0; z < length; ++z)
for (w = 0; w < length; ++w)
for (j = 0; j < length; ++j)
for (k = 0; k < length; ++k)
for (i = 0; i < length; ++i)
for (m = 0; m < length; ++m)
++result;
check_sum<T>(result, length);
}
record_result( timer(), label );
}
/******************************************************************************/
template <typename T >
void test_for_loop_single2(int length, const char *label) {
int i;
start_timer();
for(i = 0; i < iterations; ++i) {
T result = 0;
int x, y, z, w, j, k, i, m;
for (x = length; x > 0; --x)
for (y = length; y > 0; --y)
for (z = length; z > 0; --z)
for (w = length; w > 0; --w)
for (j = length; j > 0; --j)
for (k = length; k > 0; --k)
for (i = length; i > 0; --i)
for (m = length; m > 0; --m)
++result;
check_sum<T>(result, length);
}
record_result( timer(), label );
}
/******************************************************************************/
template <typename T >
void test_for_loop_single3(int length, const char *label) {
int i;
start_timer();
for(i = 0; i < iterations; ++i) {
T result = 0;
int x, y, z, w, j, k, i, m;
for (x = 0; x < length; ++x)
for (y = length; y > 0; --y)
for (z = 0; z < length; ++z)
for (w = length; w > 0; --w)
for (j = 0; j < length; ++j)
for (k = length; k > 0; --k)
for (i = 0; i < length; ++i)
for (m = length; m > 0; --m)
++result;
check_sum<T>(result, length);
}
record_result( timer(), label );
}
/******************************************************************************/
template <typename T >
void test_while_loop_single(int length, const char *label) {
int i;
start_timer();
for(i = 0; i < iterations; ++i) {
T result = 0;
int x, y, z, w, j, k, i, m;
x = 0;
while (x < length) {
y = 0;
while (y < length) {
z = 0;
while (z < length) {
w = 0;
while (w < length) {
j = 0;
while (j < length) {
k = 0;
while (k < length) {
i = 0;
while (i < length) {
m = 0;
while (m < length) {
++result;
++m;
}
++i;
}
++k;
}
++j;
}
++w;
}
++z;
}
++y;
}
++x;
}
check_sum<T>(result, length);
}
record_result( timer(), label );
}
/******************************************************************************/
template <typename T >
void test_do_loop_single(int length, const char *label) {
int i;
start_timer();
for(i = 0; i < iterations; ++i) {
T result = 0;
int x, y, z, w, j, k, i, m;
x = 0;
if (length > 0)
do {
y = 0;
do {
z = 0;
do {
w = 0;
do {
j = 0;
do {
k = 0;
do {
i = 0;
do {
m = 0;
do {
++result;
++m;
} while (m < length);
++i;
} while (i < length);
++k;
} while (k < length);
++j;
} while (j < length);
++w;
} while (w < length);
++z;
} while (z < length);
++y;
} while (y < length);
++x;
} while (x < length);
check_sum<T>(result, length);
}
record_result( timer(), label );
}
/******************************************************************************/
template <typename T >
void test_goto_loop_single(int length, const char *label) {
int i;
start_timer();
for(i = 0; i < iterations; ++i) {
T result = 0;
int x, y, z, w, j, k, i, m;
x = 0;
if (length > 0)
{
loop_start_x:
y = 0;
{
loop_start_y:
z = 0;
{
loop_start_z:
w = 0;
{
loop_start_w:
j = 0;
{
loop_start_j:
k = 0;
{
loop_start_k:
i = 0;
{
loop_start_i:
m = 0;
{
loop_start_m:
++result;
++m;
if (m < length)
goto loop_start_m;
}
++i;
if (i < length)
goto loop_start_i;
}
++k;
if (k < length)
goto loop_start_k;
}
++j;
if (j < length)
goto loop_start_j;
}
++w;
if (w < length)
goto loop_start_w;
}
++z;
if (z < length)
goto loop_start_z;
}
++y;
if (y < length)
goto loop_start_y;
}
++x;
if (x < length)
goto loop_start_x;
}
check_sum<T>(result, length);
}
record_result( timer(), label );
}
/******************************************************************************/
// scalar replacement of arrays would help here
template <typename T >
void test_for_loop_multiple(int* lengths, const char *label) {
int i;
start_timer();
for(i = 0; i < iterations; ++i) {
T result = 0;
int x, y, z, w, j, k, i, m;
for (x = 0; x < lengths[0]; ++x)
for (y = 0; y < lengths[1]; ++y)
for (z = 0; z < lengths[2]; ++z)
for (w = 0; w < lengths[3]; ++w)
for (j = 0; j < lengths[4]; ++j)
for (k = 0; k < lengths[5]; ++k)
for (i = 0; i < lengths[6]; ++i)
for (m = 0; m < lengths[7]; ++m)
++result;
check_sum<T>(result, lengths);
}
record_result( timer(), label );
}
/******************************************************************************/
// scalar replacement of arrays would help here
template <typename T >
void test_for_loop_multiple2(int* lengths, const char *label) {
int i;
start_timer();
for(i = 0; i < iterations; ++i) {
T result = 0;
int x, y, z, w, j, k, i, m;
for (x = lengths[0]; x > 0; --x)
for (y = lengths[1]; y > 0; --y)
for (z = lengths[2]; z > 0; --z)
for (w = lengths[3]; w > 0; --w)
for (j = lengths[4]; j > 0; --j)
for (k = lengths[5]; k > 0; --k)
for (i = lengths[6]; i > 0; --i)
for (m = lengths[7]; m > 0; --m)
++result;
check_sum<T>(result, lengths);
}
record_result( timer(), label );
}
/******************************************************************************/
// scalar replacement of arrays would help here
template <typename T >
void test_for_loop_multiple3(int* lengths, const char *label) {
int i;
start_timer();
for(i = 0; i < iterations; ++i) {
T result = 0;
int x, y, z, w, j, k, i, m;
for (x = 0; x < lengths[0]; ++x)
for (y = lengths[1]; y > 0; --y)
for (z = 0; z < lengths[2]; ++z)
for (w = lengths[3]; w > 0; --w)
for (j = 0; j < lengths[4]; ++j)
for (k = lengths[5]; k > 0; --k)
for (i = 0; i < lengths[6]; ++i)
for (m = lengths[7]; m > 0; --m)
++result;
check_sum<T>(result, lengths);
}
record_result( timer(), label );
}
/******************************************************************************/
template <typename T >
void test_while_loop_multiple(int* lengths, const char *label) {
int i;
start_timer();
for(i = 0; i < iterations; ++i) {
T result = 0;
int x, y, z, w, j, k, i, m;
x = 0;
while (x < lengths[0]) {
y = 0;
while (y < lengths[1]) {
z = 0;
while (z < lengths[2]) {
w = 0;
while (w < lengths[3]) {
j = 0;
while (j < lengths[4]) {
k = 0;
while (k < lengths[5]) {
i = 0;
while (i < lengths[6]) {
m = 0;
while (m < lengths[7]) {
++result;
++m;
}
++i;
}
++k;
}
++j;
}
++w;
}
++z;
}
++y;
}
++x;
}
check_sum<T>(result, lengths);
}
record_result( timer(), label );
}
/******************************************************************************/
template <typename T >
void test_do_loop_multiple(int* lengths, const char *label) {
int i;
start_timer();
for(i = 0; i < iterations; ++i) {
T result = 0;
int x, y, z, w, j, k, i, m;
x = 0;
if (lengths[0] > 0)
do {
y = 0;
if (lengths[1] > 0)
do {
z = 0;
if (lengths[2] > 0)
do {
w = 0;
if (lengths[3] > 0)
do {
j = 0;
if (lengths[4] > 0)
do {
k = 0;
if (lengths[5] > 0)
do {
i = 0;
if (lengths[6] > 0)
do {
m = 0;
if (lengths[7] > 0)
do {
++result;
++m;
} while (m < lengths[7]);
++i;
} while (i < lengths[6]);
++k;
} while (k < lengths[5]);
++j;
} while (j < lengths[4]);
++w;
} while (w < lengths[3]);
++z;
} while (z < lengths[2]);
++y;
} while (y < lengths[1]);
++x;
} while (x < lengths[0]);
check_sum<T>(result, lengths);
}
record_result( timer(), label );
}
/******************************************************************************/
template <typename T >
void test_goto_loop_multiple(int* lengths, const char *label) {
int i;
start_timer();
for(i = 0; i < iterations; ++i) {
T result = 0;
int x, y, z, w, j, k, i, m;
x = 0;
if (lengths[0] > 0)
{
loop_start_x:
y = 0;
if (lengths[1] > 0)
{
loop_start_y:
z = 0;
if (lengths[2] > 0)
{
loop_start_z:
w = 0;
if (lengths[3] > 0)
{
loop_start_w:
j = 0;
if (lengths[4] > 0)
{
loop_start_j:
k = 0;
if (lengths[5] > 0)
{
loop_start_k:
i = 0;
if (lengths[6] > 0)
{
loop_start_i:
m = 0;
if (lengths[7] > 0)
{
loop_start_m:
++result;
++m;
if (m < lengths[7])
goto loop_start_m;
}
++i;
if (i < lengths[6])
goto loop_start_i;
}
++k;
if (k < lengths[5])
goto loop_start_k;
}
++j;
if (j < lengths[4])
goto loop_start_j;
}
++w;
if (w < lengths[3])
goto loop_start_w;
}
++z;
if (z < lengths[2])
goto loop_start_z;
}
++y;
if (y < lengths[1])
goto loop_start_y;
}
++x;
if (x < lengths[0])
goto loop_start_x;
}
check_sum<T>(result, lengths);
}
record_result( timer(), label );
}
/******************************************************************************/
/******************************************************************************/
template <typename T >
void test_loop_const_opt(const char *label) {
int i;
start_timer();
for(i = 0; i < iterations; ++i) {
T result = 0;
result = (T)SIZE * (T)255;
check_sum2<T>(result);
}
record_result( timer(), label );
}
/******************************************************************************/
template <typename T >
void test_for_loop_const(const char *label) {
int i;
start_timer();
for(i = 0; i < iterations; ++i) {
T result = 0;
int x, i;
for (x = 0; x < SIZE; ++x) {
T temp = 0;
for (i = 0; i < 8; ++i) {
temp += T(1L << i);
}
result += temp;
}
check_sum2<T>(result);
}
record_result( timer(), label );
}
/******************************************************************************/
template <typename T >
void test_for_loop_const2(const char *label) {
int i;
start_timer();
for(i = 0; i < iterations; ++i) {
T result = 0;
int x, i;
for (x = SIZE; x > 0; --x) {
T temp = 0;
for (i = 0; i < 8; ++i) {
temp += T(1L << i);
}
result += temp;
}
check_sum2<T>(result);
}
record_result( timer(), label );
}
/******************************************************************************/
template <typename T >
void test_for_loop_const3(const char *label) {
int i;
start_timer();
for(i = 0; i < iterations; ++i) {
T result = 0;
int x, i;
for (x = 0; x < SIZE; ++x) {
T temp = 0;
for (i = 0; i < 8; ++i) {
temp += T(0x80L >> i);
}
result += temp;
}
check_sum2<T>(result);
}
record_result( timer(), label );
}
/******************************************************************************/
template <typename T >
void test_for_loop_const4(const char *label) {
int i;
start_timer();
for(i = 0; i < iterations; ++i) {
T result = 0;
int x, i;
for (x = SIZE; x > 0; --x) {
T temp = 0;
for (i = 7; i >= 0; --i) {
temp += T(1L << i);
}
result += temp;
}
check_sum2<T>(result);
}
record_result( timer(), label );
}
/******************************************************************************/
template <typename T >
void test_while_loop_const(const char *label) {
int i;
start_timer();
for(i = 0; i < iterations; ++i) {
T result = 0;
int x, i;
for (x = 0; x < SIZE; ++x) {
T temp = 0;
i = 0;
while ( i < 8 ) {
temp += T(1L << i);
++i;
}
result += temp;
}
check_sum2<T>(result);
}
record_result( timer(), label );
}
/******************************************************************************/
template <typename T >
void test_do_loop_const(const char *label) {
int i;
start_timer();
for(i = 0; i < iterations; ++i) {
T result = 0;
int x, i;
for (x = 0; x < SIZE; ++x) {
T temp = 0;
i = 0;
do {
temp += T(1L << i);
++i;
} while ( i < 8 );
result += temp;
}
check_sum2<T>(result);
}
record_result( timer(), label );
}
/******************************************************************************/
template <typename T >
void test_goto_loop_const(const char *label) {
int i;
start_timer();
for(i = 0; i < iterations; ++i) {
T result = 0;
int x, i;
for (x = 0; x < SIZE; ++x) {
T temp = 0;
i = 0;
{
loop_start:
temp += T(1L << i);
++i;
if (i < 8)
goto loop_start;
}
result += temp;
}
check_sum2<T>(result);
}
record_result( timer(), label );
}
/******************************************************************************/
/******************************************************************************/
template <typename T >
void test_loop_empty_opt(const char *label) {
int i;
start_timer();
for(i = 0; i < iterations; ++i) {
T result = 0;
result = (T)SIZE * (T)255;
check_sum2<T>(result);
}
record_result( timer(), label );
}
/******************************************************************************/
template <typename T >
void test_for_loop_empty(const char *label) {
int i;
start_timer();
for(i = 0; i < iterations; ++i) {
T result = 0;
int x;
for (x = 0; x < SIZE; ++x) {
}
for (x = 0; x < SIZE; ++x) {
}
for (x = 0; x < SIZE; ++x) {
}
for (x = 0; x < SIZE; ++x) {
}
for (x = 0; x < SIZE; ++x) {
}
for (x = 0; x < SIZE; ++x) {
}
for (x = 0; x < SIZE; ++x) {
}
for (x = 0; x < SIZE; ++x) {
}
result = (T)SIZE * (T)255;
check_sum2<T>(result);
}
record_result( timer(), label );
}
/******************************************************************************/
// reverse loop direction
template <typename T >
void test_for_loop_empty2(const char *label) {
int i;
start_timer();
for(i = 0; i < iterations; ++i) {
T result = 0;
int x;
for (x = SIZE; x > 0; --x) {
}
for (x = SIZE; x > 0; --x) {
}
for (x = SIZE; x > 0; --x) {
}
for (x = SIZE; x > 0; --x) {
}
for (x = SIZE; x > 0; --x) {
}
for (x = SIZE; x > 0; --x) {
}
for (x = SIZE; x > 0; --x) {
}
for (x = SIZE; x > 0; --x) {
}
result = (T)SIZE * (T)255;
check_sum2<T>(result);
}
record_result( timer(), label );
}
/******************************************************************************/
template <typename T >
void test_while_loop_empty(const char *label) {
int i;
start_timer();
for(i = 0; i < iterations; ++i) {
T result = 0;
int x;
x = 0;
while (x < SIZE) {
++x;
}
x = 0;
while (x < SIZE) {
++x;
}
x = 0;
while (x < SIZE) {
++x;
}
x = 0;
while (x < SIZE) {
++x;
}
x = 0;
while (x < SIZE) {
++x;
}
x = 0;
while (x < SIZE) {
++x;
}
x = 0;
while (x < SIZE) {
++x;
}
x = 0;
while (x < SIZE) {
++x;
}
result = (T)SIZE * (T)255;
check_sum2<T>(result);
}
record_result( timer(), label );
}
/******************************************************************************/
template <typename T >
void test_do_loop_empty(const char *label) {
int i;
start_timer();
for(i = 0; i < iterations; ++i) {
T result = 0;
int x;
x = 0;
if (SIZE > 0)
do {
++x;
} while (x < SIZE);
x = 0;
if (SIZE > 0)
do {
++x;
} while (x < SIZE);
x = 0;
if (SIZE > 0)
do {
++x;
} while (x < SIZE);
x = 0;
if (SIZE > 0)
do {
++x;
} while (x < SIZE);
x = 0;
if (SIZE > 0)
do {
++x;
} while (x < SIZE);
x = 0;
if (SIZE > 0)
do {
++x;
} while (x < SIZE);
x = 0;
if (SIZE > 0)
do {
++x;
} while (x < SIZE);
x = 0;
if (SIZE > 0)
do {
++x;
} while (x < SIZE);
result = (T)SIZE * (T)255;
check_sum2<T>(result);
}
record_result( timer(), label );
}
/******************************************************************************/
template <typename T >
void test_goto_loop_empty(const char *label) {
int i;
start_timer();
for(i = 0; i < iterations; ++i) {
T result = 0;
int x;
x = 0;
if (SIZE > 0)
{
loop_start1:
++x;
if (x < SIZE)
goto loop_start1;
}
x = 0;
if (SIZE > 0)
{
loop_start2:
++x;
if (x < SIZE)
goto loop_start2;
}
x = 0;
if (SIZE > 0)
{
loop_start3:
++x;
if (x < SIZE)
goto loop_start3;
}
x = 0;
if (SIZE > 0)
{
loop_start4:
++x;
if (x < SIZE)
goto loop_start4;
}
x = 0;
{
loop_start5:
++x;
if (x < SIZE)
goto loop_start5;
}
x = 0;
if (SIZE > 0)
{
loop_start6:
++x;
if (x < SIZE)
goto loop_start6;
}
x = 0;
if (SIZE > 0)
{
loop_start7:
++x;
if (x < SIZE)
goto loop_start7;
}
x = 0;
if (SIZE > 0)
{
loop_start8:
++x;
if (x < SIZE)
goto loop_start8;
}
result = (T)SIZE * (T)255;
check_sum2<T>(result);
}
record_result( timer(), label );
}
/******************************************************************************/
/******************************************************************************/
template <typename T >
void test_for_loop_dead(const char *label) {
int i;
start_timer();
for(i = 0; i < iterations; ++i) {
T result = 0;
T temp = 0;
int x;
for (x = 0; x < SIZE; ++x) {
++temp;
}
for (x = 0; x < SIZE; ++x) {
temp += 3;
}
for (x = 0; x < SIZE; ++x) {
temp ^= 0xAA;
}
for (x = 0; x < SIZE; ++x) {
++temp;
}
for (x = 0; x < SIZE; ++x) {
temp -= 2;
}
for (x = 0; x < SIZE; ++x) {
temp &= 0x55;
}
for (x = 0; x < SIZE; ++x) {
++temp;
}
for (x = 0; x < SIZE; ++x) {
temp -= 7;
}
result = (T)SIZE * (T)255;
check_sum2<T>(result);
}
record_result( timer(), label );
}
/******************************************************************************/
template <typename T >
void test_for_loop_dead2(const char *label) {
int i;
start_timer();
for(i = 0; i < iterations; ++i) {
T result = 0;
T temp = 0;
int x;
for (x = SIZE; x > 0; --x) {
++temp;
}
for (x = SIZE; x > 0; --x) {
temp += 3;
}
for (x = SIZE; x > 0; --x) {
temp ^= 0xAA;
}
for (x = SIZE; x > 0; --x) {
++temp;
}
for (x = SIZE; x > 0; --x) {
temp -= 2;
}
for (x = SIZE; x > 0; --x) {
temp &= 0x55;
}
for (x = SIZE; x > 0; --x) {
++temp;
}
for (x = SIZE; x > 0; --x) {
temp -= 7;
}
result = (T)SIZE * (T)255;
check_sum2<T>(result);
}
record_result( timer(), label );
}
/******************************************************************************/
template <typename T >
void test_for_loop_dead3(const char *label) {
int i;
T result = 0;
start_timer();
for(i = 0; i < iterations; ++i) {
int x;
for (x = 0; x < SIZE; ++x) {
result = x * 9;
}
for (x = 0; x < SIZE; ++x) {
result = x * 11;
}
for (x = 0; x < SIZE; ++x) {
result = x + 5;
}
for (x = 0; x < SIZE; ++x) {
result += x ^ 0x55;
}
for (x = 0; x < SIZE; ++x) {
result ^= x | 0x55;
}
for (x = 0; x < SIZE; ++x) {
result |= x & 0x55;
}
for (x = 0; x < SIZE; ++x) {
result += (x * 11) ^ 0x55;
}
for (x = 0; x < SIZE; ++x) {
result += ((x * 13) / 7) ^ 0xAA;
}
result = (T)SIZE * (T)255;
check_sum2<T>(result);
}
record_result( timer(), label );
}
/******************************************************************************/
template <typename T >
void test_while_loop_dead(const char *label) {
int i;
start_timer();
for(i = 0; i < iterations; ++i) {
T result = 0;
T temp = 0;
int x;
x = 0;
while (x < SIZE) {
++temp;
++x;
}
x = 0;
while (x < SIZE) {
temp += 3;
++x;
}
x = 0;
while (x < SIZE) {
++temp;
++x;
}
x = 0;
while (x < SIZE) {
++temp;
++x;
}
x = 0;
while (x < SIZE) {
temp -= 2;
++x;
}
x = 0;
while (x < SIZE) {
++temp;
++x;
}
x = 0;
while (x < SIZE) {
++temp;
++x;
}
x = 0;
while (x < SIZE) {
temp -= 7;
++x;
}
result = (T)SIZE * (T)255;
check_sum2<T>(result);
}
record_result( timer(), label );
}
/******************************************************************************/
template <typename T >
void test_do_loop_dead(const char *label) {
int i;
start_timer();
for(i = 0; i < iterations; ++i) {
T result = 0;
T temp = 0;
int x;
x = 0;
if (SIZE > 0)
do {
++temp;
++x;
} while (x < SIZE);
x = 0;
if (SIZE > 0)
do {
temp += 3;
++x;
} while (x < SIZE);
x = 0;
if (SIZE > 0)
do {
++temp;
++x;
} while (x < SIZE);
x = 0;
if (SIZE > 0)
do {
++temp;
++x;
} while (x < SIZE);
x = 0;
if (SIZE > 0)
do {
temp -= 2;
++x;
} while (x < SIZE);
x = 0;
if (SIZE > 0)
do {
++temp;
++x;
} while (x < SIZE);
x = 0;
if (SIZE > 0)
do {
++temp;
++x;
} while (x < SIZE);
x = 0;
if (SIZE > 0)
do {
temp -= 7;
++x;
} while (x < SIZE);
result = (T)SIZE * (T)255;
check_sum2<T>(result);
}
record_result( timer(), label );
}
/******************************************************************************/
template <typename T >
void test_goto_loop_dead(const char *label) {
int i;
start_timer();
for(i = 0; i < iterations; ++i) {
T result = 0;
T temp = 0;
int x;
x = 0;
if (SIZE > 0)
{
loop_start1:
++temp;
++x;
if (x < SIZE)
goto loop_start1;
}
x = 0;
if (SIZE > 0)
{
loop_start2:
temp += 3;
++x;
if (x < SIZE)
goto loop_start2;
}
x = 0;
if (SIZE > 0)
{
loop_start3:
++temp;
++x;
if (x < SIZE)
goto loop_start3;
}
x = 0;
if (SIZE > 0)
{
loop_start4:
++temp;
++x;
if (x < SIZE)
goto loop_start4;
}
x = 0;
if (SIZE > 0)
{
loop_start5:
temp -= 2;
++x;
if (x < SIZE)
goto loop_start5;
}
x = 0;
if (SIZE > 0)
{
loop_start6:
++temp;
++x;
if (x < SIZE)
goto loop_start6;
}
x = 0;
if (SIZE > 0)
{
loop_start7:
++temp;
++x;
if (x < SIZE)
goto loop_start7;
}
x = 0;
if (SIZE > 0)
{
loop_start8:
temp -= 7;
++x;
if (x < SIZE)
goto loop_start8;
}
result = (T)SIZE * (T)255;
check_sum2<T>(result);
}
record_result( timer(), label );
}
/******************************************************************************/
/******************************************************************************/
int main(int argc, char** argv) {
// output command for documentation:
int i;
for (i = 0; i < argc; ++i)
printf("%s ", argv[i] );
printf("\n");
if (argc > 1) iterations = atoi(argv[1]);
if (argc > 2) init_value = (double) atof(argv[2]);
if (argc > 3) count = (int) atoi(argv[3]);
// int32_t
test_loop_empty_opt<int32_t>( "int32_t loop removal empty optimal");
test_for_loop_empty<int32_t>( "int32_t for loop removal empty");
test_for_loop_empty2<int32_t>( "int32_t for loop removal empty reverse");
test_while_loop_empty<int32_t>( "int32_t while loop removal empty");
test_do_loop_empty<int32_t>( "int32_t do loop removal empty");
test_goto_loop_empty<int32_t>( "int32_t goto loop removal empty");
summarize("int32_t empty loop removal", SIZE, iterations, kDontShowGMeans, kDontShowPenalty );
test_loop_empty_opt<int32_t>( "int32_t loop removal dead optimal");
test_for_loop_dead<int32_t>( "int32_t for loop removal dead");
test_for_loop_dead2<int32_t>( "int32_t for loop removal dead reverse");
test_for_loop_dead3<int32_t>( "int32_t for loop removal dead assign");
test_while_loop_dead<int32_t>( "int32_t while loop removal dead");
test_do_loop_dead<int32_t>( "int32_t do loop removal dead");
test_goto_loop_dead<int32_t>( "int32_t goto loop removal dead");
summarize("int32_t dead loop removal", SIZE, iterations, kDontShowGMeans, kDontShowPenalty );
test_loop_const_opt<int32_t>( "int32_t loop removal const optimal");
test_for_loop_const<int32_t>( "int32_t for loop removal const");
test_for_loop_const2<int32_t>( "int32_t for loop removal const reverse");
test_for_loop_const3<int32_t>( "int32_t for loop removal const reverse bit");
test_for_loop_const4<int32_t>( "int32_t for loop removal const reverse2");
test_while_loop_const<int32_t>( "int32_t while loop removal const");
test_do_loop_const<int32_t>( "int32_t do loop removal const");
test_goto_loop_const<int32_t>( "int32_t goto loop removal const");
summarize("int32_t const loop removal", SIZE, iterations, kDontShowGMeans, kDontShowPenalty );
test_loop_opt<int32_t>( count, "int32_t loop removal variable optimal");
test_for_loop_single<int32_t>( count, "int32_t for loop removal variable single");
test_for_loop_single2<int32_t>( count, "int32_t for loop removal variable single reverse");
test_for_loop_single3<int32_t>( count, "int32_t for loop removal variable single mixed");
test_while_loop_single<int32_t>( count, "int32_t while loop removal variable single");
test_do_loop_single<int32_t>( count, "int32_t do loop removal variable single");
test_goto_loop_single<int32_t>( count, "int32_t goto loop removal variable single");
::fill( count_array, count_array+8, count );
test_for_loop_multiple<int32_t>( count_array, "int32_t for loop removal variable multiple");
test_for_loop_multiple2<int32_t>( count_array, "int32_t for loop removal variable multiple reverse");
test_for_loop_multiple3<int32_t>( count_array, "int32_t for loop removal variable multiple mixed");
test_while_loop_multiple<int32_t>( count_array, "int32_t while loop removal variable multiple");
test_do_loop_multiple<int32_t>( count_array, "int32_t do loop removal variable multiple");
test_goto_loop_multiple<int32_t>( count_array, "int32_t goto loop removal variable multiple");
summarize("int32_t variable loop removal", (count*count)*(count*count)*(count*count)*(count*count), iterations, kDontShowGMeans, kDontShowPenalty );
return 0;
}
// the end
/******************************************************************************/
/******************************************************************************/
| true |
90666951b884bf1a1229b41b67728978c69bfbed
|
C++
|
dgalide/piscinecpp
|
/D05/ex04/main.cpp
|
UTF-8
| 758 | 2.53125 | 3 |
[] |
no_license
|
#include "Bureaucrat.hpp"
#include "Form.hpp"
#include "PresidentialPardonForm.hpp"
#include "RobotomyRequestForm.hpp"
#include "ShrubberyCreationForm.hpp"
#include "Intern.hpp"
#include "OfficeBlock.hpp"
class Form;
class Bureaucrat;
int main(void)
{
Intern *idiotOne = new Intern();
Bureaucrat *hermes = new Bureaucrat("Hermes Conrad", 150);
Bureaucrat *bob = new Bureaucrat("Bobby Bobson", 150);
OfficeBlock ob;
ob.setIntern(idiotOne);
ob.setSigningBureaucrat(bob);
ob.setExecutingBureaucrat(hermes);
try {
ob.doBureaucracy("president", "Pigley");
} catch (std::exception & e) {
std::cout << e.what() << std::endl;
}
return 0;
}
| true |
1ea5fadbd84104cc76f73fab3318456dea03caf5
|
C++
|
srfilipek/savr
|
/tests/sys_clock/main.cpp
|
UTF-8
| 2,247 | 2.546875 | 3 |
[
"MIT"
] |
permissive
|
/*************************************************************//**
* @file main.c
*
* @author Stefan Filipek
******************************************************************/
#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>
#include <stdio.h>
#include <inttypes.h>
#include <stdlib.h>
#include <string.h>
#include <savr/cpp_pgmspace.h>
#include <savr/sci.h>
#include <savr/terminal.h>
#include <savr/clock.h>
#include <savr/gpio.h>
#include <savr/utils.h>
#define enable_interrupts() sei()
using namespace savr;
/**
* Terminal command callbacks
*/
static uint8_t
tick(char* args)
{
printf_P(PSTR("%lu\n"), clock::ticks());
return 0;
}
/**
* Terminal command callbacks
*/
static uint8_t
tick_byte(char* args)
{
printf_P(PSTR("%u\n"), clock::ticks_byte());
return 0;
}
/**
* Terminal command callbacks
*/
[[noreturn]] static uint8_t
tock(char* args)
{
while(true) {
printf_P(PSTR("%lu\n"), clock::ticks());
}
}
/**
* Terminal command callbacks
*/
[[noreturn]] static uint8_t
tock_byte(char* args)
{
while(true) {
printf_P(PSTR("%u\n"), clock::ticks_byte());
}
}
// Command list
static cmd::CommandList cmd_list = {
{"tick", tick, "Prints the number of ticks elapsed"},
{"tock", tock, "Continually prints the number of ticks elapsed"},
{"tick-byte", tick_byte, "Prints the lowest byte of the number of ticks elapsed"},
{"tock-byte", tock_byte, "Continually prints the lowest byte of number of ticks elapsed"},
};
// Terminal display
#define welcome_message PSTR("Clock tick test\n")
#define prompt_string PSTR("] ")
/**
* Main
*/
int main(void) {
sci::init(250000uL); // bps
enable_interrupts();
term::init(welcome_message, prompt_string,
cmd_list, utils::array_size(cmd_list));
// LED output for the pulse
gpio::out<gpio::D7>();
gpio::low<gpio::D7>();
clock::init();
uint32_t last_tick = 0;
while(true) {
uint32_t now = clock::ticks();
if((now - last_tick) > clock::TICKS_PER_SEC) {
last_tick = now;
gpio::toggle<gpio::D7>();
}
term::work();
}
/* NOTREACHED */
return 0;
}
EMPTY_INTERRUPT(__vector_default)
| true |
901e73d0976fefaf1aadbc5cbee14a2a3042dc38
|
C++
|
ojy0216/BOJ
|
/5430.cpp
|
UTF-8
| 1,448 | 2.84375 | 3 |
[] |
no_license
|
#include <iostream>
#include <string>
#include <deque>
#include <vector>
#include <algorithm>
using namespace std;
int main(){
cin.tie(NULL);
cout.tie(NULL);
ios::sync_with_stdio(false);
int t;
cin >> t;
for(int i = 0; i < t; i++){
string s;
cin >> s;
int n;
cin >> n;
deque<int> dq;
string num;
cin >> num;
string tmp;
for(auto c : num){
if(isdigit(c))
tmp.push_back(c);
else if(!tmp.empty()){
dq.push_back(stoi(tmp));
tmp.clear();
}
}
bool valid = true;
bool forward = true;
for(auto op : s){
if(op == 'R')
forward = forward ? false : true;
else if(op == 'D'){
if(dq.empty()){
cout << "error\n";
valid = false;
break;
}
else if(forward)
dq.pop_front();
else if(!forward)
dq.pop_back();
}
}
if(!forward)
reverse(dq.begin(), dq.end());
if(!valid)
continue;
cout << "[";
while(!dq.empty()){
cout << dq.front();
dq.pop_front();
if(!dq.empty())
cout << ",";
}
cout << "]\n";
}
}
| true |
90aec2b05034980a1fa6d70dd40be3694a25b529
|
C++
|
navitasinghal/College-Lab
|
/Network Programming Lab/Lab2/q3.cpp
|
UTF-8
| 2,253 | 3.34375 | 3 |
[] |
no_license
|
#include <iostream>
#include <string>
#include <list>
using namespace std;
struct Fragments
{
string data;
int serialNo; //set this -1 for the original data and 1,2,3... for the fragmented data
int frame[3];
};
Fragments *newFragment(string data, int serialNo, int frame_0, int frame_1, int frame_2)
{
Fragments *tmp = new Fragments();
tmp->data = data;
tmp->serialNo = serialNo;
tmp->frame[0] = frame_0;
tmp->frame[1] = frame_1;
tmp->frame[2] = frame_2;
return tmp;
}
list<Fragments* > fragmentationModel(Fragments *original, int mtu)
{
list<Fragments* > buffer;
int i;
int sn = 1;
for (i = 0; i < original->data.size()-mtu; i = i + mtu) // include all fragment but not the last one as that
{ // one should have frame_2 = 0
Fragments *tmp = newFragment(original->data.substr(i,mtu), sn, 0, 1, 1);
buffer.push_back(tmp);
sn++;
}
Fragments *tmp = newFragment(original->data.substr(i), sn, 0, 1, 0);
buffer.push_back(tmp);
return buffer;
}
void display(list<Fragments* > buffer)
{
list<Fragments* >::iterator it;
for(it = buffer.begin(); it != buffer.end(); it++)
{
cout << "S. No:\t" << (*it)->serialNo << endl;
cout << "Data:\t" << (*it)->data << endl;
cout << "Flag:\t";
for(int i = 0; i < 3; i++)
{
cout << (*it)->frame[i] << " ";
}
cout << endl;
}
}
string reassemblyModel(list<Fragments *> buffer)
{
cout << "--- Information about all the fragments of the original data ---\n" << endl;
display(buffer);
cout << endl;
cout << "Reassembling all the fragments based on the serial number of all the fragments..." << endl;
sleep(2);
string reassembledData = "";
while(!buffer.empty())
{
Fragments *tmp;
tmp = buffer.front();
reassembledData.append(tmp->data);
buffer.pop_front();
}
return reassembledData;
}
int main()
{
string data;
int mtu;
cout << "Enter the data :\t";
cin >> data;
cout << "Enter the MTU :\t";
cin >> mtu;
Fragments *original = newFragment(data, -1, 0, 0, 0);
if(data.size() <= mtu)
cout << "No fragmentation model to be applied.\n";
else
{
list<Fragments* > buffer = fragmentationModel(original, mtu);
string reassembledData = reassemblyModel(buffer);
cout << "Reassembled data : " << reassembledData << endl;
}
return 0;
}
| true |
d5a9532513990892ea3749c70b40fc68a111ad9d
|
C++
|
SE-OOP/Assignment_02
|
/201816040119/Ex07_14.cpp
|
UTF-8
| 720 | 3.46875 | 3 |
[] |
no_license
|
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int i,m;//i用于循环,m作为读取变量
int a=0;
vector<int> integer(1);//分配一个内存为一的vector数组
cin>>m;
integer[0]=m;//读取输入的第一个数存入
for(i=0;i<19;i++)
{
cin>>m;
for(size_t j=0;j<integer.size();j++)//循环判定是否已经有相同值存在
{
if(m==integer[j])
a=1;
}
if(a==0)//如果不存在把读取的数存入
{
integer.push_back(m);//插入尾部扩大储存空间
}
a=0;
}
for(size_t i=0;i<integer.size();i++)
cout <<integer[i]<<" " ;
return 0;
}
| true |
9fefba9742e806b759ae9dff2efa59db6f03154e
|
C++
|
kaaczmar/EZI-source
|
/MiOIB/projekty/ATSP/Parser.cpp
|
UTF-8
| 2,153 | 2.640625 | 3 |
[] |
no_license
|
/*
* Parser.cpp
*
* Created on: 2011-09-26
* Author: jawora
*/
#include <Parser.hpp>
#include <iostream>
#include <fstream>
#include <boost/tokenizer.hpp>
#include <boost/foreach.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/regex.hpp>
#include <boost/lexical_cast.hpp>
#include <list>
using namespace std;
using namespace boost;
Parser::Parser(string filename) :
filePath(filename.c_str()) {
}
bool Parser::load(ATSPData &data) {
boost::filesystem::fstream file(filePath);
if (!file.is_open()) {
cerr << "Bad file" << endl;
return false;
}
string line;
vector<string> tokens;
while (file.good()) {
getline(file, line);
replace_all_regex(line, regex("[ \t\n]+"), string(" "));
replace_all_regex(line, regex("[ \t\n]+$"), string(""));
replace_all_regex(line, regex("^[ \t\n]+"), string(""));
split(tokens, line, boost::is_any_of("\t\n "));
if (tokens[0] == "DIMENSION:") {
try {
data.setDimension(lexical_cast<int> (tokens[1]));
} catch (bad_lexical_cast &) {
cerr << "Bad dimensions" << endl;
return false;
}
}
if (tokens[0] == "OPTIMAL:") {
try {
data.setOptimalSolution(lexical_cast<int> (tokens[1]));
} catch (bad_lexical_cast &) {
cerr << "Bad optimal solution" << endl;
return false;
}
}
if (tokens[0] == "EDGE_WEIGHT_SECTION") {
// cout << "Reading wheights" << endl;
break;
}
}
unsigned int x = 0, y = 0;
while (file.good()) {
getline(file, line);
replace_all_regex(line, regex("[ \t\n]+"), string(" "));
replace_all_regex(line, regex("[ \t\n]+$"), string(""));
replace_all_regex(line, regex("^[ \t\n]+"), string(""));
split(tokens, line, boost::is_any_of("\t\n "));
if (tokens[0] == "EOF") {
// cout << "End" << endl;
break;
}
BOOST_FOREACH(string tok, tokens)
{
if (tok.length() == 0)
continue;
try {
data.data[x++][y] = lexical_cast<int>(tok);
if (x >= data.getDimension()){
x = 0;
y++;
}
} catch(bad_lexical_cast &) {
cerr << "Bad value: " << tok << "[" << tok.length() << "]" << endl;
}
}
}
// data.print();
return true;
}
| true |
941b1afd42bd2bbdb8dd32896e149cb153b6dea5
|
C++
|
Alex23013/ejercicios_casa
|
/prob_04_factoial.cpp
|
UTF-8
| 321 | 3.25 | 3 |
[] |
no_license
|
#include<iostream>
using namespace std;
float factorial=1,n,i;
int main()
{
int n;
cout<<"factorial de que numero ? " <<endl;
cin>>n;
int factorial =1;
for ( int i =2;i<n+1;i++)
{
factorial=factorial *i;
//cout << factorial <<endl;
}
cout << "factorial de " << n << " es " << factorial << endl;
}
| true |
6110f8e9e19d8203fbe29e8e63655e843b86f3f8
|
C++
|
guynir42/util
|
/+stat/sum_single.cpp
|
UTF-8
| 2,336 | 2.875 | 3 |
[] |
no_license
|
#include "mex.h"
void mexFunction( int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[] ){
// check inputs!
if (nrhs==0){
mexPrintf("Usage: S = sum_singles(matrix)\n");
mexPrintf("Takes inputs of types double, single and uint16 and returns a sum along the 3rd dimension in single precision.\n");
return;
}
if(mxIsEmpty(prhs[0])){ // no input, then just return with all empty outputs...
const mwSize dims[]={0,0};
plhs[0]=mxCreateNumericArray(0,dims, mxSINGLE_CLASS, mxREAL); // return an empty array
return;
}
mwSize *dims=(mwSize*)mxGetDimensions(prhs[0]); // dims[0] is the height while dims[1] is the width while dim[2] is the number of frames
int ndims=mxGetNumberOfDimensions(prhs[0]);
if(ndims>3) mexErrMsgIdAndTxt("MATLAB:util:stat:sum_singles:inputMoreThan3D", "Input 1 to sum_singles should have at most 3 dimensions...");
if(ndims<3){
plhs[0]=mxDuplicateArray(prhs[0]);
return;
}
mwSize dims_out[2]={dims[0], dims[1]};
int N=dims_out[0]*dims_out[1]; // total size of output array
plhs[0]=mxCreateNumericArray(2, dims_out, mxSINGLE_CLASS, mxREAL); // create the output matrix (in matlab)
float *output=(float*) mxGetData(plhs[0]); // get the C type array
if(mxIsClass(prhs[0], "double")){
double *matrix=(double*) mxGetData(prhs[0]);
for(int j=0;j<dims[2];j++){// go over all frames
for(int i=0;i<N;i++){ // go over pixels in each image
output[i]+=matrix[j*N+i];
} // for i (pixels in image)
} // for j (frames)
}
else if(mxIsClass(prhs[0], "single")){
float *matrix=(float*) mxGetData(prhs[0]);
for(int j=0;j<dims[2];j++){// go over all frames
for(int i=0;i<N;i++){ // go over pixels in each image
output[i]+=matrix[j*N+i];
} // for i (pixels in image)
} // for j (frames)
}
else if(mxIsClass(prhs[0], "uint16")){
short unsigned int *matrix=(short unsigned int*) mxGetData(prhs[0]);
for(int j=0;j<dims[2];j++){// go over all frames
for(int i=0;i<N;i++){ // go over pixels in each image
output[i]+=matrix[j*N+i];
} // for i (pixels in image)
} // for j (frames)
}
else mexErrMsgIdAndTxt("MATLAB:util:stat:sum_singles:inputTypeUnrecognized", "Input 1 to sum_singles is not a double, single or uint16 array...");
}
| true |
609b6192d35f764e12923a2832790ef8e31a80de
|
C++
|
LiisaLoog/pleistocene-wolves
|
/Data/neigh_inc.cpp
|
UTF-8
| 847 | 3.03125 | 3 |
[] |
no_license
|
//-----------------------------------------------------------------------------------
// Graph defining wolf regions
//
// 0: Europe
// 1: Central_North_Eurasia
// 2: Beringia
// 3: Middle_East
// 4: South_East_Asia
// 5: Arctic_North_America
// 6: North_America
//
//-----------------------------------------------------------------------------------
const int nDemes = 7;
const int nNeigh = 16;
int neigh[nNeigh] = {
1, // 0
0, 2, 3, 4, // 1
1, 4, 5, 6, // 2
1, // 3
1, 2, // 4
2, 6, // 5
2, 5 // 6
};
const int nNeighs[nDemes] = {
1, // Deme 0: 1
4, // Deme 1: 5
4, // Deme 2: 9
1, // Deme 3: 10
2, // Deme 4: 12
2, // Deme 5: 14
2 // Deme 6: 16
};
// 0 1 2 3 4 5 6, terminal
const int neighStart[nDemes+1] = { 0, 1, 5, 9, 10, 12, 14, 16 };
| true |
7440b72aae8d18627d56396725ef66fd75f98274
|
C++
|
eaguilerai/libagir
|
/include/agir/ui/console/abstract/menu.h
|
UTF-8
| 530 | 2.5625 | 3 |
[] |
no_license
|
/*!
* \file menu.h
* \brief Contains the definition of the agir::ui::console::abstract::Menu
* interface.
* \author Erasmo Aguilera
* \date April 19, 2015
*/
#ifndef AGIR__UI__CONSOLE__ABSTRACT__MENU_H
#define AGIR__UI__CONSOLE__ABSTRACT__MENU_H
namespace agir {
namespace ui {
namespace console {
namespace abstract {
/// Interface for menu objects that may be shown on the console.
class Menu
{
public:
/// Shows the menu on the console.
virtual void show() const = 0;
};
}
}
}
}
#endif
| true |
c4fa54d874cc40fd918de09a7f5744feb879e772
|
C++
|
calgagi/competitive_programming
|
/misc/hackerrank/hacktheinterview/maximum_streaks.cpp
|
UTF-8
| 1,782 | 3.5625 | 4 |
[] |
no_license
|
#include <bits/stdc++.h>
using namespace std;
string ltrim(const string &);
string rtrim(const string &);
/*
* Complete the 'getMaxStreaks' function below.
*
* The function is expected to return an INTEGER_ARRAY.
* The function accepts STRING_ARRAY toss as parameter.
*/
vector<int> getMaxStreaks(vector<string> toss) {
// Return an array of two integers containing the maximum streak of heads and tails respectively
int n = toss.size();
int streakH = 0, streakT = 0;
vector<int> res = {0, 0};
for (int i = 0; i < n; i++) {
if (toss[i] == "Heads") {
streakH++;
streakT = 0;
} else {
streakT++;
streakH = 0;
}
res[0] = max(res[0], streakH);
res[1] = max(res[1], streakT);
}
return res;
}
int main()
{
ofstream fout(getenv("OUTPUT_PATH"));
string toss_count_temp;
getline(cin, toss_count_temp);
int toss_count = stoi(ltrim(rtrim(toss_count_temp)));
vector<string> toss(toss_count);
for (int i = 0; i < toss_count; i++) {
string toss_item;
getline(cin, toss_item);
toss[i] = toss_item;
}
vector<int> ans = getMaxStreaks(toss);
for (int i = 0; i < ans.size(); i++) {
fout << ans[i];
if (i != ans.size() - 1) {
fout << " ";
}
}
fout << "\n";
fout.close();
return 0;
}
string ltrim(const string &str) {
string s(str);
s.erase(
s.begin(),
find_if(s.begin(), s.end(), not1(ptr_fun<int, int>(isspace)))
);
return s;
}
string rtrim(const string &str) {
string s(str);
s.erase(
find_if(s.rbegin(), s.rend(), not1(ptr_fun<int, int>(isspace))).base(),
s.end()
);
return s;
}
| true |
eaeed0e143cc67f6ccabf60806def30b5548396f
|
C++
|
omelkonian/snap
|
/src/project_main/main_part1.cpp
|
UTF-8
| 6,968 | 2.765625 | 3 |
[] |
no_license
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include "../graph_metrics/metrics.h"
#include "GraphLib.h"
#include "defines.h"
using namespace std;
#define PERSON_PROPERTIES_NUM 3
#define PERSON_REL_PROPERTIES_NUM 2
#define CHECK(text, actual, expected) \
if (actual != expected) { \
printf("%-30s: Failed | actual = %3d, expected = %3d\n", \
text, \
actual, \
expected); \
} else { \
printf("%-30s: Success\n", text); \
}
/* Creates a node person and sets its properties */
Node* setPersonProperties(int id, char* name, char* surname, int age);
/* Creates an edge between two persons and sets its properties */
Edge* setEdgeProperties(int startNodeID, int endNodeID, char* type, int weight);
/* Prints a person's properties */
void printPersonProperties(Node* n);
/* Prints an edge's properties */
void printEdgeProperties(int startID, Edge* n);
int main_part1(void) {
int m = 2;
int c = 3;
/*create empty graph*/
Graph* g = createGraph(m, c);
/*create node and set node properties*/
Node* n1 = setPersonProperties(5, "lonely", "loner", 29);
Node* n2 = setPersonProperties(1, "herald", "kllapi", 22);
Node* n3 = setPersonProperties(2, "marialena", "kiriakidi", 25);
Node* n4 = setPersonProperties(10, "antonia", "saravanou", 18);
Node* n5 = setPersonProperties(6, "manos", "karvounis", 19);
Node* n6 = setPersonProperties(3, "giannis", "chronis", 20);
Node* n7 = setPersonProperties(4, "christoforos", "sfiggos", 16);
Node* n8 = setPersonProperties(7, "stamatis", "xristoforidis", 24);
Node* n9 = setPersonProperties(8, "xristos", "mallios", 29);
Node* n10 = setPersonProperties(14, "johnny", "depp", 35);
Node* n11 = setPersonProperties(12, "fox", "mulder", 29);
Node* n12 = setPersonProperties(16, "dana", "scully", 25);
/*insert nodes in graph*/
insertNode(n1, g);
insertNode(n2, g);
insertNode(n3, g);
insertNode(n4, g);
insertNode(n5, g);
insertNode(n6, g);
insertNode(n7, g);
insertNode(n8, g);
insertNode(n10, g);
insertNode(n9, g);
insertNode(n11, g);
insertNode(n12, g);
/* Create edges and set properties */
Edge* e1 = setEdgeProperties(1, 6, "knows", 30);
Edge* e2 = setEdgeProperties(6, 1, "knows", 30);
Edge* e3 = setEdgeProperties(1, 2, "knows", 20);
Edge* e4 = setEdgeProperties(2, 1, "knows", 20);
Edge* e5 = setEdgeProperties(1, 4, "knows", 30);
Edge* e6 = setEdgeProperties(4, 1, "knows", 30);
Edge* e7 = setEdgeProperties(2, 6, "knows", 10);
Edge* e8 = setEdgeProperties(6, 2, "knows", 10);
Edge* e9 = setEdgeProperties(4, 3, "knows", 30);
Edge* e10 = setEdgeProperties(3, 4, "knows", 30);
Edge* e11 = setEdgeProperties(4, 7, "knows", 30);
Edge* e12 = setEdgeProperties(7, 4, "knows", 30);
Edge* e13 = setEdgeProperties(4, 8, "knows", 10);
Edge* e14 = setEdgeProperties(8, 4, "knows", 10);
Edge* e15 = setEdgeProperties(3, 10, "knows", 30);
Edge* e16 = setEdgeProperties(10, 3, "knows", 30);
Edge* e17 = setEdgeProperties(10, 7, "knows", 30);
Edge* e18 = setEdgeProperties(7, 10, "knows", 30);
Edge* e19 = setEdgeProperties(10, 14, "knows", 50);
Edge* e20 = setEdgeProperties(14, 10, "knows", 50);
Edge* e21 = setEdgeProperties(14, 12, "knows", 30);
Edge* e22 = setEdgeProperties(12, 14, "knows", 30);
Edge* e23 = setEdgeProperties(12, 16, "knows", 30);
Edge* e24 = setEdgeProperties(16, 12, "knows", 30);
Edge* e25 = setEdgeProperties(16, 14, "knows", 30);
Edge* e26 = setEdgeProperties(14, 16, "knows", 30);
// Edge* e27 = setEdgeProperties(3, 8, "knows", 30);
// Edge* e28 = setEdgeProperties(8, 3, "knows", 30);
// Edge* e29 = setEdgeProperties(8, 10, "knows", 10);
// Edge* e30 = setEdgeProperties(10, 8, "knows", 10);
/* Insert edges in graph */
insertEdge(1, e1, g);
insertEdge(6, e2, g);
insertEdge(1, e3, g);
insertEdge(2, e4, g);
insertEdge(1, e5, g);
insertEdge(4, e6, g);
insertEdge(2, e7, g);
insertEdge(6, e8, g);
insertEdge(4, e9, g);
insertEdge(3, e10, g);
insertEdge(4, e11, g);
insertEdge(7, e12, g);
insertEdge(4, e13, g);
insertEdge(8, e14, g);
insertEdge(3, e15, g);
insertEdge(10, e16, g);
insertEdge(10, e17, g);
insertEdge(7, e18, g);
insertEdge(10, e19, g);
insertEdge(14, e20, g);
insertEdge(14, e21, g);
insertEdge(12, e22, g);
insertEdge(12, e23, g);
insertEdge(16, e24, g);
insertEdge(16, e25, g);
insertEdge(14, e26, g);
/* Perform lookups in the graph */
Node* nl1 = lookupNode(12, g);
printPersonProperties(nl1);
Node* nl2 = lookupNode(16, g);
printPersonProperties(nl2);
cout << endl;
cout << endl;
/* Find shortest path 1-1 */
int spt1 = reachNode1(1, 12, g);
CHECK("Shortest path between nodes (1,12)", spt1, 5);
int spt2 = reachNode1(14, 14, g);
CHECK("Shortest path between nodes (14,14)", spt2, 0);
int spt3 = reachNode1(3, 16, g);
CHECK("Shortest path between nodes (3,16)", spt3, 3);
int spt4 = reachNode1(5, 3, g);
CHECK("Shortest path between nodes (5,3)", spt4, INFINITY_REACH_NODE);
/* Find shortest paths 1-N */
ResultSet* res = reachNodeN(1, g);
Pairr results[10] = { { 2, 1 }, { 6, 1 }, { 4, 1 }, { 3, 2 }, { 7, 2 }, { 8, 2 }, { 10, 3 }, { 14, 4 }, { 16, 5 }, { 12, 5 } };
Pair* pair;
int k;
int counter = 0;
while ((pair = res->next()) != NULL) {
++counter;
for (k = 0; k < 10; ++k) {
if (results[k].ID == pair->getNodeId()) {
if (results[k].distance == pair->getDistance()) {
printf("Shortest path between nodes (%d,%d): Success\n", 1, results[k].ID);
} else {
printf("Shortest path between nodes (%d,%d): Failed | actual = %3d, expected = %3d\n", 1, results[k].ID, pair->getDistance(), results[k].distance);
}
break;
}
}
if (k == 10) {
printf("ReachNodeN : Failed | Your returned an extra Pair(%d,%d) ", pair->getNodeId(), pair->getDistance());
}
}
CHECK("Number of pairs in the ResultSet", counter, 10);
// Free ResultSet.
delete res;
delete g;
return EXIT_SUCCESS;
}
Node* setPersonProperties(int id, char* name, char* surname, int age) {
/*create properties*/
Properties* prop = createProperties(PERSON_PROPERTIES_NUM);
setStringProperty(name, 0, prop);
setStringProperty(surname, 1, prop);
setIntegerProperty(age, 2, prop);
/*create node*/
Node* n = createNode(id, prop);
return n;
}
Edge* setEdgeProperties(int startNodeID, int endNodeID, char* type, int weight) {
/*create edge properties*/
Properties* propEdge = createProperties(PERSON_REL_PROPERTIES_NUM);
setStringProperty(type, 0, propEdge);
setIntegerProperty(weight, 1, propEdge);
/*create an edge*/
Edge* e = createEdge(startNodeID, endNodeID, propEdge);
return e;
}
void printPersonProperties(Node* n) {
n->print();
}
void printEdgeProperties(int startID, Edge* e) {
e->print();
}
| true |
af0fd518370b41ee22564334e325333f8c75abfb
|
C++
|
BreakChir/Algo
|
/Strings/L.cpp
|
UTF-8
| 2,652 | 2.75 | 3 |
[] |
no_license
|
#include <iostream>
#include <map>
using namespace std;
int *len;
int *link;
int last, sizeGL;
long *countWays;
bool *was;
map<char, int> *nextTo;
void init(int size) {
len = new int[size];
link = new int[size];
countWays = new long[size];
was = new bool[size];
nextTo = new map<char, int>[size];
for (int i = 0; i < size; ++i) {
len[i] = 0;
link[i] = 0;
countWays[i] = 0;
was[i] = false;
}
last = 0;
link[0] = -1;
sizeGL = 1;
}
long dfs(int v) {
was[v] = true;
if (nextTo[v].empty())
++countWays[v];
for (auto it : nextTo[v]) {
if (was[it.second]) countWays[v] += countWays[it.second];
else countWays[v] += dfs(it.second);
}
return countWays[v];
}
void add(char c) {
len[sizeGL] = len[last] + 1;
int cur = sizeGL++;
int p = last;
while (p >= 0 && nextTo[p][c] == 0) {
nextTo[p][c] = cur;
p = link[p];
}
if (p != -1) {
int q = nextTo[p][c];
if (len[p] + 1 == len[q]) {
link[cur] = q;
} else {
link[sizeGL] = link[q];
nextTo[sizeGL] = nextTo[q];
int node = sizeGL++;
len[node] = len[p] + 1;
link[q] = node;
link[cur] = node;
while (p >= 0 && nextTo[p][c] == q) {
nextTo[p][c] = node;
p = link[p];
}
}
}
last = cur;
}
int main() {
std::ios::sync_with_stdio(false);
freopen("shifts.in", "r", stdin);
freopen("shifts.out", "w", stdout);
init(2000000);
string s;
cin >> s;
size_t length = s.length();
for (size_t i = 0; i < length; ++i) {
add(s[i]);
}
for (size_t i = 0; i < length; ++i) {
add(s[i]);
}
countWays[0] = dfs(0);
int k;
cin >> k;
bool exist = true;
int cur = 0;
string ans;
bool yes;
while (true) {
bool good = false;
yes = false;
for (auto it : nextTo[cur]) {
yes = true;
int to = it.second;
if (countWays[to] < k) {
k -= countWays[to];
} else {
good = true;
cur = to;
ans += it.first;
if (ans.length() == s.length()) {
yes = false;
break;
}
break;
}
}
if (!yes) break;
if (!good) {
exist = false;
break;
}
}
if (exist) cout << ans;
else cout << "IMPOSSIBLE";
return 0;
}
| true |
76a18b502ce297d91c95818f04054752a79fabb0
|
C++
|
mcc12357/acm-
|
/nyoj 284(优先队列).cpp
|
GB18030
| 1,354 | 2.796875 | 3 |
[] |
no_license
|
#include<iostream>
using namespace std;
#include<stdio.h>
#include<string.h>
#include<queue>
int m,n;
int sx,sy;
int res;
int dx[] = {1,0,-1,0};
int dy[] = {0,1,0,-1};
char map[305][305];
int visited[305][305];
struct node
{
int x,y,step;
friend bool operator < (const node &s1,const node &s2)//Ĭ<ȷԪȼϵ
{
return s1.step > s2.step;
}
};
const int inf = 1e7;
void bfs(int sx,int sy)
{
priority_queue<node> q;
node tm;
tm.step = 0;
tm.x = sx;
tm.y = sy;
q.push(tm);
while(!q.empty())
{
tm = q.top();
q.pop();
if(map[tm.x][tm.y]=='T')
{
res = tm.step;
return ;
}
int i;
for(i=0;i<4;i++)
{
int tx = tm.x + dx[i];
int ty = tm.y + dy[i];
if(tx>=0 && tx<m && ty>=0 && ty<n && map[tx][ty]!='S' && map[tx][ty]!='R' && !visited[tx][ty])
{
node tp;
tp.x = tx;
tp.y = ty;
if(map[tx][ty]=='B') tp.step = tm.step + 2;
else tp.step = tm.step + 1;
q.push(tp);
visited[tx][ty] = 1;
}
}
}
}
int main()
{
while(~scanf("%d %d",&m,&n) && (m||n))
{
int i,j;
for(i=0;i<m;i++)
for(j=0;j<n;j++)
{
cin>>map[i][j];
if(map[i][j]=='Y')
{
sx = i;
sy = j;
map[i][j] = 'S';
}
}
memset(visited,0,sizeof(visited));
res = inf;
bfs(sx,sy);
if(res==inf) printf("-1\n");
else printf("%d\n",res);
}
return 0;
}
| true |
ee6c6a77481496b84ae58e573491c521ff718834
|
C++
|
CaseySingleton/42-cpp-piscine
|
/d00/ex02/Account.class.cpp
|
UTF-8
| 3,690 | 2.828125 | 3 |
[] |
no_license
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* Account.class.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: csinglet <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/07/15 20:26:57 by csinglet #+# #+# */
/* Updated: 2019/07/15 20:26:58 by csinglet ### ########.fr */
/* */
/* ************************************************************************** */
#include "Account.class.hpp"
#include <iostream>
#include <iomanip>
#include <ctime>
int Account::_nbAccounts = 0;
int Account::_totalAmount = 0;
int Account::_totalNbDeposits = 0;
int Account::_totalNbWithdrawals = 0;
Account::Account(int initial_deposit) : _nbWithdrawals(0), _nbDeposits(0), _amount(initial_deposit), _accountIndex(_nbAccounts)
{
_nbAccounts++;
_totalAmount += initial_deposit;
_displayTimestamp();
std::cout << "index:" << _accountIndex << ";amount:" << _amount << ";created" << std::endl;
return ;
}
Account::~Account(void)
{
_displayTimestamp();
std::cout << "index:" << _accountIndex << ";amount:" << _amount << ";closed" << std::endl;
return ;
}
int Account::getNbAccounts(void)
{
return (_nbAccounts);
}
int Account::getTotalAmount(void)
{
return (_totalAmount);
}
int Account::getNbDeposits(void)
{
return (_totalNbDeposits);
}
int Account::getNbWithdrawals(void)
{
return (_totalNbWithdrawals);
}
void Account::displayAccountsInfos(void)
{
Account::_displayTimestamp();
std::cout << "accounts:" << getNbAccounts() << ";total:" << getTotalAmount() << ";deposits:" << getNbDeposits() << ";withdrawls:" << getNbWithdrawals() << std::endl;
return ;
}
void Account::makeDeposit(int deposit)
{
_displayTimestamp();
std::cout << "index:" << _accountIndex << ";p_amount:" << _amount << ";deposit:" << deposit;
_totalNbDeposits++;
_nbDeposits++;
_amount += deposit;
_totalAmount += deposit;
std::cout << ";amount:" << _amount << ";nb_deposits:" << _nbDeposits << std::endl;
}
bool Account::makeWithdrawal(int withdrawl)
{
_displayTimestamp();
std::cout << "index:" << _accountIndex << ";p_amount:" << _amount;
if (withdrawl > _amount)
{
std::cout << ";withdrawl:refused" << std::endl;
return (false);
}
_totalNbWithdrawals++;
_nbWithdrawals++;
_amount -= withdrawl;
std::cout << ";withdrawl:" << withdrawl << ";amount:" << _amount << ";nb_withdrawals:" << _nbWithdrawals << std::endl;
return (true);
}
int Account::checkAmount(void) const
{
return (_totalAmount);
}
void Account::displayStatus(void) const
{
Account::_displayTimestamp();
std::cout << "index:" << _accountIndex << ";amount:" << _amount << ";deposits:" << _nbDeposits << ";withdrawls:" << _nbWithdrawals << std::endl;
}
void Account::_displayTimestamp(void)
{
time_t current_epoc_time;
time(¤t_epoc_time);
tm *lt = localtime(¤t_epoc_time);
std::cout << "[" << lt->tm_year + 1900; // tm_year is years since 1900
std::cout << std::setfill('0') << std::setw(2) << lt->tm_mon + 1;
std::cout << std::setfill('0') << std::setw(2) << lt->tm_mday << "_";
std::cout << std::setfill('0') << std::setw(2) << lt->tm_hour;
std::cout << std::setfill('0') << std::setw(2) << lt->tm_min;
std::cout << std::setfill('0') << std::setw(2) << lt->tm_sec << "] ";
}
| true |
846f42556354432f70d10f8ad4d93c97c5681060
|
C++
|
K7H64T15/game
|
/code/globalPhaseControl.cpp
|
UTF-8
| 2,589 | 2.671875 | 3 |
[] |
no_license
|
#include "globalPhaseControl.h"
globalPhaseControl::globalPhaseControl()
{
endFlag = false;
}
globalPhaseControl::~globalPhaseControl()
{
}
int globalPhaseControl::phaseSequence(Map ¤tMap, Player ¤tPlayer)
{
movePhase(currentMap, currentPlayer);
checkPosition(currentMap);
localEventPhase();
checkStatus(currentPlayer);
checkFlags();
checkStatus(currentPlayer);
return endPhase();
}
int globalPhaseControl::movePhase(Map ¤tMap, Player ¤tPlayer)
{
system("cls");
currentMap.draw();
bool moveStatus = false;
while (!moveStatus)
{
int key;
key = _getch();
switch (key)
{
case 72: moveStatus = currentMap.movePlayer(UP);
break;
case 77: moveStatus = currentMap.movePlayer(RIGHT);
break;
case 80: moveStatus = currentMap.movePlayer(DOWN);
break;
case 75: moveStatus = currentMap.movePlayer(LEFT);
break;
case 9: seePlayerList(currentPlayer);
system("cls");
currentMap.draw();
break;
case 27: endFlag = true;
return 0;
}
}
return 0;
}
int globalPhaseControl::checkPosition(Map ¤tMap)
{
//check field type for event gen
return 0;
}
int globalPhaseControl::localEventPhase()
{
return 0;
}
int globalPhaseControl::checkFlags()
{
if (endFlag == true)
{
return 1;
}
//checks for global event flags and starting globalEventPhase
globalEventPhase();
return 0;
}
void globalPhaseControl::checkStatus(Player ¤tPlayer)
{
if (currentPlayer.getHealthPointsCurrent() <= 0)
{
endFlag = true;
}
}
int globalPhaseControl::globalEventPhase()
{
return 0;
}
int globalPhaseControl::endPhase()
{
if (endFlag == true)
{
return 1;
}
return 0;
}
void globalPhaseControl::seePlayerList(Player ¤tPlayer)
{
system("cls");
cout << "Name: " << currentPlayer.getName() << "\n\n";
cout << "HP: " << currentPlayer.getHealthPointsCurrent() << " \\ " << currentPlayer.getHealthPointsMax() << "\n";
cout << "MP: " << currentPlayer.getManaPointsCurrent() << " \\ " << currentPlayer.getManaPointsMax() << "\n";
cout << "VP: " << currentPlayer.getStaminaPointsCurrent() << " \\ " << currentPlayer.getStaminaPointsMax() << "\n\n";
cout << "STR: " << currentPlayer.getStat(STRENGTH) << "\n";
cout << "AGI: " << currentPlayer.getStat(AGILITY) << "\n";
cout << "CON: " << currentPlayer.getStat(CONSTITUTION) << "\n";
cout << "PER: " << currentPlayer.getStat(PERCEPTION) << "\n";
cout << "INT: " << currentPlayer.getStat(INTELLIGENCE) << "\n";
cout << "CHA: " << currentPlayer.getStat(CHARISMA) << "\n\n";
system("pause");
}
void globalPhaseControl::seeGlobalMap(Map ¤tMap)
{
}
| true |
684c72956ff12ee9728291a901431b73b455588e
|
C++
|
Koukan/Grab
|
/common/libnet/src/SelectPolicy.cpp
|
UTF-8
| 3,124 | 2.578125 | 3 |
[] |
no_license
|
#include "SelectPolicy.hpp"
NET_USE_NAMESPACE
#include <iostream>
SelectPolicy::SelectPolicy() : _maxfd(0), _rsize(0), _wsize(0), _esize(0)
{
FD_ZERO(&_read_set);
FD_ZERO(&_write_set);
FD_ZERO(&_except_set);
}
SelectPolicy::~SelectPolicy()
{}
bool SelectPolicy::registerHandler(Socket &socket, EventHandler &handler, int mask)
{
auto handle = socket.getHandle();
auto it = _sockets.find(&socket);
if (it != _sockets.end())
{
int old_mask = it->second;
if (old_mask == mask)
return true;
if (old_mask & Reactor::READ || old_mask & Reactor::ACCEPT)
_rsize--;
if (old_mask & Reactor::WRITE)
_wsize--;
_esize--;
}
if (mask & Reactor::READ || mask & Reactor::ACCEPT)
{
FD_SET(handle, &_read_set);
_rsize++;
}
if (mask & Reactor::WRITE)
{
FD_SET(handle, &_write_set);
_wsize++;
}
FD_SET(handle, &_except_set);
_esize++;
if (handle > _maxfd)
_maxfd = (size_t)handle;
_sockets[&socket] = mask;
socket.setEventHandler(&handler);
return true;
}
bool SelectPolicy::removeHandler(Socket &socket)
{
auto handle = socket.getHandle();
auto it = _sockets.find(&socket);
if (it == _sockets.end())
return false;
int mask = it->second;
if (mask & Reactor::READ || mask & Reactor::ACCEPT)
{
FD_CLR(handle, &_read_set);
_rsize--;
}
if (mask & Reactor::WRITE)
{
FD_CLR(handle, &_write_set);
_wsize--;
}
FD_CLR(handle, &_except_set);
_esize--;
_sockets.erase(it);
socket.setEventHandler(nullptr);
#ifndef _WIN32
if (handle == _maxfd)
{
int max = 0;
for (auto &it : _sockets)
if (it.first->getHandle() > max)
max = it.first->getHandle();
_maxfd = max;
}
#endif
return true;
}
int SelectPolicy::waitForEvent(int timeout)
{
struct timeval time;
int ret;
fd_set *set[3];
Clock clock;
while (_wait)
{
int t = this->handleTimers(timeout);
if (t >= 0)
{
time.tv_sec = t / 1000;
time.tv_usec = (t % 1000) * 1000;
}
fd_set rs = _read_set, ws = _write_set, es = _except_set;
set[0] = (_rsize == 0) ? nullptr : &rs;
set[1] = (_wsize == 0) ? nullptr : &ws;
set[2] = (_esize == 0) ? nullptr : &es;
#if defined (_WIN32)
if (!set[0] && !set[1] && !set[2])
{
Net::Clock::sleep(t);
continue ;
}
else
#endif
ret = ::select(_maxfd + 1, set[0], set[1], set[2], (t < 0) ? nullptr : &time);
if ((ret == -1 && errno == EINTR) || (ret == 0 && timeout != 0))
continue ;
if (ret == -1)
std::cerr << Net::getLastError() << std::endl;
if (ret == -1 || (ret == 0 && timeout == 0))
return ret;
if (timeout > 0)
{
timeout -= clock.getElapsedTime();
clock.update();
if (timeout < 0)
timeout = 0;
}
for (auto it = _sockets.begin(); it != _sockets.end();)
{
auto socket = it->first;
auto handler = socket->getEventHandler();
auto handle = socket->getHandle();
++it;
if (FD_ISSET(handle, &es))
handler->handleClose(*socket);
else
{
if (FD_ISSET(handle, &rs) && handler->handleInput(*socket) <= 0)
handler->handleClose(*socket);
else if (FD_ISSET(handle, &ws) && handler->handleOutput(*socket) <= 0)
handler->handleClose(*socket);
}
}
}
return 0;
}
| true |
fb7c8cb7748d8ede68d87c45ac161e6e729117f2
|
C++
|
philipglazman/Kono-cpp
|
/src/player.cpp
|
UTF-8
| 39,409 | 3.3125 | 3 |
[] |
no_license
|
#include "stdafx.h"
#include "player.h"
#include "board.h"
player::player()
{
};
void player::play(std::vector< std::vector <char> > &boardTable)
{
};
/* *********************************************************************
Function Name: help
Purpose: Provide help strategy to the player dependent on conditions of the board.
In the following order, block strategy, capture strategy, offensive strategy, and retreat strategy are prioritized.
Parameters:
gameBoard, pointer to an instantiated board object.
a_color, color of the player asking for help.
a_opponentColor, color of the opponent.
Return Value: none.
Local Variables:
none.
Algorithm:
1) Call updateState method to update the player's list of available pieces and positions of opponent pieces.
2) Check the color of the player.
3) If opponent piece is close to the home side, then attempt to block it.
4) If blocked or cannot block, then continue.
5) Check if player has any super pieces available, if so, then attempt to capture an opponent piece.
6) If no super pieces are available or cannot capture opponent piece, then check if any pieces can advance forward to enemy side.
7) If no pieces can advance, then retreat.
8) If pieces available to move forward, then play offensively and move forward.
Assistance Received: none
********************************************************************* */
void player::help(board &gameBoard,char a_color,char a_opponentColor)
{
m_color = a_color;
m_opponentColor = a_opponentColor;
localBoard = &gameBoard;
updateState(gameBoard, m_color, a_opponentColor);
availablePiecesIter availablePieces = (*m_availablePieces).begin();
// If home side is top.
if(m_color == 'W')
{
//IF - opponent's piece is close to home, check if that piece is blocked.
if(m_closestOpponent.first <= std::sqrt(m_boardSize))
{
//IF - if the opponent's piece is already blocked, continue to play offensively.
if( boardTable[m_closestOpponent.first-1][m_closestOpponent.second-1] == m_color && boardTable[m_closestOpponent.first-1][m_closestOpponent.second+1] == m_color)
{
if(!playCapture())
{
if(checkForRetreat())
{
playRetreat();
}
else
{
playOffensively();
}
}
}
//ELSE - Check available pieces that can block opponent.
else
{
// Check if west side is blocked, if so, then prepare to block from east.
if(!blockFromEast())
{
if(!blockFromWest())
{
if(!playCapture())
{
if(checkForRetreat())
{
playRetreat();
}
else
{
playOffensively();
}
}
}
}
}
}
else
//ELSE - randomly move piece to opponent's end.
{
if(!playCapture())
{
if(checkForRetreat())
{
playRetreat();
}
else
{
playOffensively();
}
}
}
}
// Computer is black
else
{
if(m_closestOpponent.first+1 >= std::sqrt(m_boardSize))
{
//IF - if the opponent's piece is already blocked, continue to play offensively.
if( localBoard -> isValidOpenLocation(m_closestOpponent.first+2,m_closestOpponent.second) && localBoard -> isValidOpenLocation(m_closestOpponent.first+2,m_closestOpponent.second+2))
{
if(!playCapture())
{
if(checkForRetreat())
{
playRetreat();
}
else
{
playOffensively();
}
}
}
//ELSE - Check available pieces that can block opponent.
else
{
// Check if west side is blocked, if so, then prepare to block from east.
if(!blockFromEast())
{
if(!blockFromWest())
{
if(!playCapture())
{
if(checkForRetreat())
{
playRetreat();
}
else
{
playOffensively();
}
}
}
}
}
}
else
//ELSE - randomly move piece to opponent's end.
{
if(!playCapture())
{
if(checkForRetreat())
{
playRetreat();
}
else
{
playOffensively();
}
}
}
}
delete m_availablePieces;
};
/* *********************************************************************
Function Name: showDefenseDecision
Purpose: Suggest to user to play in defensive strategy (block).
Parameters:
a_initialRow, an integer for the row coordinate of the computer piece.
a_initialColumn, an integer for the column coordinate of the computer piece.
a_direction, a string. Holds the direction that the computer is moving (NE,SE,SW,NW).
a_finalRow, an integer for the row coordinate of the human piece that the computer is trying to block.
a_finalColumn, an integer for the column coordinate of the human piece that the computer is trying to block.
Return Value: none.
Local Variables:
none.
Algorithm:
1) Announce to player the computer's decision to move a piece at a certain direction.
2) Announce to player what piece is is trying to block.
Assistance Received: none
********************************************************************* */
void
player::showDefenseDecision(int a_initialRow, int a_initialColumn,std::string a_direction, int a_finalRow, int a_finalColumn)
{
std::cout << "It is suggested to move the piece at (" << a_initialRow << "," << a_initialColumn << ") " << a_direction << "." << std::endl;
std::cout << "This will block the piece at ("<< a_finalRow <<","<<a_finalColumn <<")." << std::endl;
}
/* *********************************************************************
Function Name: showOffenseDecision
Purpose: Suggest to user to play in offensive strategy.
Parameters:
a_initialRow, an integer for the row coordinate of the computer piece.
a_initialColumn, an integer for the column coordinate of the computer piece.
a_direction, a string. Holds the direction that the computer is moving (NE,SE,SW,NW).
a_finalRow, an integer for the row coordinate that the piece is moving to.
a_finalColumn, an integer for the column coordinate that the piece is moving to.
Return Value: none.
Local Variables:
none.
Algorithm:
1) Announce to player the computer's decision to move a piece at a certain direction.
2) Announce to player where it is moving it.
Assistance Received: none
********************************************************************* */
void
player::showOffenseDecision(int a_initialRow, int a_initialColumn,std::string a_direction, int a_finalRow, int a_finalColumn)
{
std::cout << "It is suggested to move the piece at (" << a_initialRow << "," << a_initialColumn << ") " << a_direction << "." << std::endl;
std::cout << "This will advance the piece to (" << a_finalRow << "," << a_finalColumn << ")" << std::endl;
}
/* *********************************************************************
Function Name: showRetreatDecision
Purpose: Suggest to user to play in retreat strategy.
Parameters:
a_initialRow, an integer for the row coordinate of the computer piece.
a_initialColumn, an integer for the column coordinate of the computer piece.
a_direction, a string. Holds the direction that the computer is moving (NE,SE,SW,NW).
a_finalRow, an integer for the row coordinate that the piece is moving to.
a_finalColumn, an integer for the column coordinate that the piece is moving to.
Return Value: none.
Local Variables:
none.
Algorithm:
1) Announce to player the computer's decision to move a piece at a certain direction.
2) Announce to player where it is moving it.
Assistance Received: none
********************************************************************* */
void
player::showRetreatDecision(int a_initialRow, int a_initialColumn,std::string a_direction, int a_finalRow, int a_finalColumn)
{
std::cout << "It is suggested to move the piece at (" << a_initialRow << "," << a_initialColumn << ") " << a_direction << "." << std::endl;
std::cout << "This will retreat the piece back to (" << a_finalRow << "," << a_finalColumn << ")" << std::endl;
}
/* *********************************************************************
Function Name: showCaptureDecision
Purpose: Suggest to user to play in capture strategy.
Parameters:
a_initialRow, an integer for the row coordinate of the computer piece.
a_initialColumn, an integer for the column coordinate of the computer piece.
a_direction, a string. Holds the direction that the computer is moving (NE,SE,SW,NW).
a_finalRow, an integer for the row coordinate that the piece is moving to.
a_finalColumn, an integer for the column coordinate that the piece is moving to.
Return Value: none.
Local Variables:
none.
Algorithm:
1) Announce to player the computer's decision to move a piece at a certain direction.
2) Announce to player where it is moving it.
Assistance Received: none
********************************************************************* */
void
player::showCaptureDecision(int a_initialRow, int a_initialColumn,std::string a_direction, int a_finalRow, int a_finalColumn)
{
std::cout << "It is suggested to move the piece at (" << a_initialRow << "," << a_initialColumn << ") " << a_direction << "." << std::endl;
std::cout << "This will capture the other piece at (" << a_finalRow << "," << a_finalColumn << ")" << std::endl;
}
/* *********************************************************************
Function Name: blockFromWest
Purpose: Part of the player's strategy, check to see if a particular piece can be blocked from the west.
Check to see if there is a valid piece that can be moved from either southwest, north, south, southeast or northwest.
Parameters:
none.
Return Value: Boolean value confirming that the player was notified a suggestion to move a piece
Local Variables:
none.
Algorithm:
1) Depending on if the player is white or black, different piece positions will be checked.
2) If computer is white do steps 3 - 5
3) Check if a piece is located northwest of an opponent piece, if so, then suggest for player to block by moving there.
4) Check if a piece is located southwest of an opponent piece, if so, then suggest for player to block by moving there.
5) Check if a piece is located north of an opponent piece, if so, then suggest for player to block by moving there.
6) If player is black do steps 7 - 9
7) Check if a piece is located west of an opponent piece, if so, then suggest for player to block by moving there.
8) Check if a piece is located southwest of an opponent piece, if so, then suggest for player to block by moving there.
9) Check if a piece is located south of an opponent piece, if so, then suggest for player to block by moving there.
10) If cannot find a valid piece to block with, then return false. If a piece blocked the opponent piece, then return true.
Assistance Received: none
********************************************************************* */
bool
player::blockFromWest()
{
// Computer color is white.
if(m_color == 'W')
{
// If a there is an available piece located NW, move to block the oppponent piece.
if(localBoard -> isValidPieceToMove(m_color,m_closestOpponent.first-1,m_closestOpponent.second-1) && localBoard -> isValidLocationToMove(m_closestOpponent.first,m_closestOpponent.second))
// boardTable[m_closestOpponent.first-2][m_closestOpponent.second-2] == m_color)
{
showDefenseDecision(m_closestOpponent.first-1,m_closestOpponent.second-1,"southeast",m_closestOpponent.first+1,m_closestOpponent.second+1);
return true;
}
// MAYBE first -1 ???
// If a there is an available piece located SW, move to block the oppponent piece.
else if(localBoard -> isValidPieceToMove(m_color,m_closestOpponent.first,m_closestOpponent.second-1) && localBoard -> isValidLocationToMove(m_closestOpponent.first,m_closestOpponent.second))
//boardTable[m_closestOpponent.first][m_closestOpponent.second-2] == m_color
{
showDefenseDecision(m_closestOpponent.first,m_closestOpponent.second-1,"northeast",m_closestOpponent.first+1,m_closestOpponent.second+1);
return true;
}
// If a there is an available piece located N, move to block the oppponent piece.
else if(localBoard -> isValidPieceToMove(m_color,m_closestOpponent.first-1,m_closestOpponent.second) && localBoard -> isValidLocationToMove(m_closestOpponent.first,m_closestOpponent.second))
//boardTable[m_closestOpponent.first-2][m_closestOpponent.second] == m_color
{
showDefenseDecision(m_closestOpponent.first -1,m_closestOpponent.second,"southwest",m_closestOpponent.first+1,m_closestOpponent.second+1);
return true;
}
// Else report back that it could not be blocked from the west side.
else
{
return false;
}
}
// Computer color is black.
else
{
// Check if there is an available piece from the West.
if(localBoard -> isValidPieceToMove(m_color,m_closestOpponent.first+1,m_closestOpponent.second-1) && localBoard -> isValidLocationToMove(m_closestOpponent.first+2,m_closestOpponent.second))
// boardTable[m_closestOpponent.first-2][m_closestOpponent.second-2] == m_color)
{
showDefenseDecision(m_closestOpponent.first+1,m_closestOpponent.second-1,"southeast",m_closestOpponent.first+1,m_closestOpponent.second+1);
return true;
}
// MAYBE first -1 ???
// Check if there is an available piece from the Southwest.
else if(localBoard -> isValidPieceToMove(m_color,m_closestOpponent.first+3,m_closestOpponent.second-1) && localBoard -> isValidLocationToMove(m_closestOpponent.first+2,m_closestOpponent.second))
//boardTable[m_closestOpponent.first][m_closestOpponent.second-2] == m_color
{
showDefenseDecision(m_closestOpponent.first+3,m_closestOpponent.second-1,"northeast",m_closestOpponent.first+1,m_closestOpponent.second+1);
return true;
}
// Check if there is an available piece from the South.
else if(localBoard -> isValidPieceToMove(m_color,m_closestOpponent.first+3,m_closestOpponent.second+1) && localBoard -> isValidLocationToMove(m_closestOpponent.first+2,m_closestOpponent.second))
//boardTable[m_closestOpponent.first-2][m_closestOpponent.second] == m_color
{
showDefenseDecision(m_closestOpponent.first+3,m_closestOpponent.second+1,"northwest",m_closestOpponent.first+1,m_closestOpponent.second+1);
return true;
}
// Else report back that it could not be blocked from the west side.
else
{
return false;
}
}
}
/* *********************************************************************
Function Name: blockFromEast
Purpose: Part of the player's strategy, check to see if a particular piece can be blocked from the east.
Check to see if there is a valid piece that can be moved from either southwest, north, south, southeast, or northwest.
Parameters:
none.
Return Value: Boolean value confirming that a computer player was notified a suggestion to block.
Local Variables:
none.
Algorithm:
1) Depending on if the player is white or black, different piece positions will be checked.
2) If player is white do steps 3 - 5
3) Check if a piece is located northeast of an opponent piece, if so, then suggest for player to block by moving there.
4) Check if a piece is located southwest of an opponent piece, if so, then suggest for player to block by moving there.
5) Check if a piece is located north of an opponent piece, if so, then suggest for player to block by moving there.
6) If player is black do steps 7 - 9
7) Check if a piece is located east of an opponent piece, if so, then suggest for player to block by moving there.
8) Check if a piece is located southeast of an opponent piece, if so, then suggest for player to block by moving there.
9) Check if a piece is located south of an opponent piece, if so, then suggest for player to block by moving there.
10) If cannot find a valid piece to block with, then return false. If a piece blocked the opponent piece, then return true.
Assistance Received: none
********************************************************************* */
bool
player::blockFromEast()
{
if(m_color == 'W')
{
// If a there is an available piece located NE, move to block the oppponent piece.
if(localBoard -> isValidPieceToMove(m_color,m_closestOpponent.first-1,m_closestOpponent.second+3) && localBoard -> isValidLocationToMove(m_closestOpponent.first,m_closestOpponent.second+2))
{
showDefenseDecision(m_closestOpponent.first-1,m_closestOpponent.second+3,"southwest",m_closestOpponent.first+1,m_closestOpponent.second+1);
return true;
}
// If a there is an available piece located E, move to block the oppponent piece.
if(localBoard -> isValidPieceToMove(m_color,m_closestOpponent.first+1,m_closestOpponent.second+3) && localBoard -> isValidLocationToMove(m_closestOpponent.first,m_closestOpponent.second+2))
{
showDefenseDecision(m_closestOpponent.first +1,m_closestOpponent.second+3,"northeast",m_closestOpponent.first+1,m_closestOpponent.second+1);
return true;
}
// If a there is an available piece located N, move to block the oppponent piece.
if(localBoard -> isValidPieceToMove(m_color,m_closestOpponent.first-1,m_closestOpponent.second+1) && localBoard -> isValidLocationToMove(m_closestOpponent.first,m_closestOpponent.second+2))
{
showDefenseDecision(m_closestOpponent.first -1,m_closestOpponent.second,"southeast",m_closestOpponent.first+1,m_closestOpponent.second+1);
return true;
}
// Else report back that it could not be blocked from the west side.
return false;
}
//computer color is black
else
{
// Check if there is an available piece from the East.
if(localBoard -> isValidPieceToMove(m_color,m_closestOpponent.first+1,m_closestOpponent.second+3) && localBoard -> isValidLocationToMove(m_closestOpponent.first+2,m_closestOpponent.second+2))
{
showDefenseDecision(m_closestOpponent.first+1,m_closestOpponent.second+3,"southwest",m_closestOpponent.first+1,m_closestOpponent.second+1);
return true;
}
// Check if there is an available piece from the Southeast.
if(localBoard -> isValidPieceToMove(m_color,m_closestOpponent.first+3,m_closestOpponent.second+3) && localBoard -> isValidLocationToMove(m_closestOpponent.first+2,m_closestOpponent.second+2))
{
showDefenseDecision(m_closestOpponent.first +3,m_closestOpponent.second+3,"northeast",m_closestOpponent.first+1,m_closestOpponent.second+1);
return true;
}
// Check if there is an available piece from the South.
if(localBoard -> isValidPieceToMove(m_color,m_closestOpponent.first+3,m_closestOpponent.second+1) && localBoard -> isValidLocationToMove(m_closestOpponent.first+2,m_closestOpponent.second+2))
{
showDefenseDecision(m_closestOpponent.first +3,m_closestOpponent.second +1,"southeast",m_closestOpponent.first+1,m_closestOpponent.second+1);
return true;
}
// Else report back that it could not be blocked from the west side.
return false;
}
};
/* *********************************************************************
Function Name: updateState
Purpose: Check if the player has any super pieces that can capture a nearby oppponent piece. If it does, suggest to capture the piece.
Parameters:
gameBoard, pointer to an instantiated board object.
a_color, color of the player asking for help.
a_opponentColor, color of the opponent.
Return Value: none.
Local Variables:
friendlySide, iterator for moving down the board - relative to the color of the piece.
oppositeSide, iteratore for moving down the board - relative to the color of the piece.
Algorithm:
1) Cycle through the board and load friendly pieces into m_availablePieces vector.
2) Iterate through the board and find the opponent coordinates closest to home side.
3) Iterate through the board and find the friendly piece coordinates closest to opponent side.
Assistance Received: none
********************************************************************* */
void
player::updateState(board &a_gameBoard, char a_color,char a_opponentColor)
{
localBoard = &a_gameBoard;
m_color = a_color;
m_opponentColor = a_opponentColor;
boardTable = localBoard -> getBoard();
m_boardSize = localBoard -> getBoardSize();
iter friendlySide;
iter opponentSide;
// vector of availble friendly pieces
m_availablePieces = new std::vector< std::pair<int,int> >;
// Load vector of available computer pieces.
for( int row = 0; row < m_boardSize; row++ )
{
for( int col = 0; col < m_boardSize; col++ )
{
if(boardTable[row][col]==m_color || boardTable[row][col]==tolower(m_color,std::locale()) )
{
m_availablePieces -> push_back( std::make_pair(row,col) );
}
}
}
if( m_color == 'W')
{
// If friendly side is on the top (W), opponnent side is on bottom (B)
friendlySide = boardTable.begin();
opponentSide = boardTable.end()-1;
// Iterate from top to bottom to find closest opponent
for ( ; friendlySide != opponentSide ; ++friendlySide )
{
colIter col = std::find(friendlySide->begin(), friendlySide->end(), m_opponentColor);
if ( col != friendlySide->end() )
{
m_closestOpponent = std::make_pair(distance(boardTable.begin(),friendlySide),distance(friendlySide->begin(),col));
break;
}
}
friendlySide = boardTable.begin();
// Iterate from bottom to top to find furthest friendly piece.
for ( ; opponentSide >= friendlySide ; --opponentSide )
{
colIter col = std::find(opponentSide->begin(), opponentSide->end(), m_color);
if ( col != opponentSide->end() )
{
m_furthestFriendly = std::make_pair(distance(boardTable.begin(),opponentSide), distance(opponentSide->begin(),col));
break;
}
}
}
else
{
// If friendly side is on the bottom (B), opponnent side is on top (W)
friendlySide = boardTable.end()-1;
opponentSide = boardTable.begin();
// Iterate from the bottom to the top to find the closest opponent piece.
for ( ; friendlySide >= opponentSide ; --friendlySide )
{
colIter col = std::find(friendlySide->begin(), friendlySide->end(), m_opponentColor);
if ( col != friendlySide->end() )
{
m_closestOpponent = std::make_pair(distance(boardTable.begin(),friendlySide), distance(friendlySide->begin(),col));
break;
}
}
friendlySide = boardTable.end()-1;
// Iterate from the the top to the bottom to find the furthest friendly piece.
for ( ; opponentSide != friendlySide ; ++opponentSide )
{
colIter col = std::find(opponentSide->begin(), opponentSide->end(), m_color);
if ( col != opponentSide->end() )
{
m_furthestFriendly = std::make_pair(distance(boardTable.begin(),opponentSide), distance(opponentSide->begin(),col));
break;
}
}
}
};
/* *********************************************************************
Function Name: playCapture
Purpose: Check if the player has any super pieces that can capture a nearby oppponent piece. If it does, suggest to capture the piece.
Parameters:
none.
Return Value: Boolean value for it there was a super piece that can capture an opponent.
Local Variables:
eachPiece, a pair of integers holding the coordinates of a player piece.
Algorithm:
1) Cycle through available pieces and see if the piece is a super piece.
2) If there is a super piece, then do steps 3 - 6, else return false.
3) Check if opponent is located in southeast, if so then suggest to play that they capture it. And return true.
4) Check if opponent is located in southwest, if so then suggest to play that they capture it. And return true.
5) Check if opponent is located in northwest, if so then suggest to play that they capture it. And return true.
6) Check if opponent is located in northeast, if so then suggest to play that they capture it. And return true.
7) If no pieces can capture, then return false.
Assistance Received: none
********************************************************************* */
bool
player::playCapture()
{
for( std::pair<int,int> eachPiece : (*m_availablePieces))
{
// Check if piece is a super piece.
if(localBoard -> getPieceAtLocation(eachPiece.first+1,eachPiece.second+1) == tolower(m_color,std::locale()))
{
// Check if opponent is located southeast.
if(localBoard->getPieceAtLocation(eachPiece.first+2,eachPiece.second+2) == m_opponentColor || localBoard->getPieceAtLocation(eachPiece.first+2,eachPiece.second+2) == tolower(m_opponentColor,std::locale()) )
{
// Check if piece can move Southeast.
if(localBoard -> isValidLocationToMove(eachPiece.first+2,eachPiece.second+2,true))
{
showCaptureDecision( eachPiece.first + 1,eachPiece.second + 1,"southeast",eachPiece.first+2,eachPiece.second+2);
return true;
}
}
// Check if opponent is located Southwest.
else if(localBoard->getPieceAtLocation(eachPiece.first+2,eachPiece.second) == m_opponentColor || localBoard->getPieceAtLocation(eachPiece.first+2,eachPiece.second) == tolower(m_opponentColor,std::locale()) )
{
// Check if piece can move Southwest.
if(localBoard -> isValidLocationToMove(eachPiece.first+2,eachPiece.second,true))
{
showCaptureDecision( eachPiece.first + 1,eachPiece.second + 1,"southwest",eachPiece.first+2,eachPiece.second);
return true;
}
}
// Check if opponent is located Northwest.
else if(localBoard->getPieceAtLocation(eachPiece.first,eachPiece.second) == m_opponentColor || localBoard->getPieceAtLocation(eachPiece.first,eachPiece.second) == tolower(m_opponentColor,std::locale()) )
{
// Check if piece can move Northwest.
if(localBoard -> isValidLocationToMove(eachPiece.first,eachPiece.second,true))
{
showCaptureDecision( eachPiece.first + 1,eachPiece.second + 1,"northwest",eachPiece.first,eachPiece.second);
return true;
}
}
// Check if opponent is located Northeast.
else if(localBoard->getPieceAtLocation(eachPiece.first,eachPiece.second+2) == m_opponentColor || localBoard->getPieceAtLocation(eachPiece.first,eachPiece.second+2) == tolower(m_opponentColor,std::locale()) )
{
// Check if piece can move Northeast.
if(localBoard -> isValidLocationToMove(eachPiece.first,eachPiece.second+2,true))
{
showCaptureDecision( eachPiece.first + 1,eachPiece.second + 1,"northeast",eachPiece.first,eachPiece.second+2);
return true;
}
}
}
}
// No available moves that can capture pieces.
return false;
}
/* *********************************************************************
Function Name: checkForRetreat
Purpose: Check if any piece can move forward. If it cannot, then it lets the computer know that it must retreat one piece.
Parameters:
none.
Return Value: Boolean value to notify computer strategy that it must retreat a piece.
Local Variables:
eachPiece, a pair of integers holding the coordinates of a computer piece.
Algorithm:
1) Cycle through available pieces.
2) If white, do steps 3-5
3) Check if piece can move southwest, if so return false.
4) Check if piece can move southeast, if so return false.
5) If cannot move south, then return true. A piece must be sent in retreat.
6) If black, do steps 7-9
7) Check if piece can move northeast, if so return false.
8) Check if piece can move northwest, if so return false.
9) If cannot move north, then return true. A piece must be sent in retreat.
Assistance Received: none
********************************************************************* */
bool
player::checkForRetreat()
{
if(m_color == 'W')
{
for( std::pair<int,int> eachPiece : (*m_availablePieces))
{
// Check if piece can move Southeast.
if(localBoard -> isValidLocationToMove(eachPiece.first+2,eachPiece.second+2))
{
return false;
}
// Check if piece can move Southwest.
else if(localBoard -> isValidLocationToMove(eachPiece.first+2,eachPiece.second))
{
return false;
}
}
// There are no available pieces that can move forward.
return true;
}
if(m_color == 'B')
{
for( std::pair<int,int> eachPiece : (*m_availablePieces))
{
// Check if piece can move Northeast.
if(localBoard -> isValidLocationToMove(eachPiece.first,eachPiece.second+2))
{
return false;
}
// Check if piece can move Northwest.
else if(localBoard -> isValidLocationToMove(eachPiece.first,eachPiece.second))
{
return false;
}
}
// There are no available pieces that can move forward.
return true;
}
};
/* *********************************************************************
Function Name: playRetreat
Purpose: Called when a piece must be sent in retreat. It randomly picks a piece and suggest that the player moves that piece in the direction of home side.
Parameters:
none.
Return Value: none.
Local Variables:
didMove, boolean holding if player made move.
pieceToMove, a pair of integers holding the coordinates of a player piece.
Algorithm:
1) Cycle through available pieces.
2) If white, do steps 3-4
3) Check if piece can move northwest, if so then suggest that the player move it northwest.
4) Check if piece can move northeast, if so then suggest that the player move it northeast.
5) If black, do steps 6-7
6) Check if piece can move southeast, if so then suggest that the player move it southeast.
7) Check if piece can move southwest, if so then suggest that the player move it southwest.
Assistance Received: none
********************************************************************* */
void
player::playRetreat()
{
if(m_color == 'W')
{
// Picking random piece.
bool didMove = true;
while(didMove)
{
std::pair<int,int> pieceToMove = pickRandomPiece();
if(localBoard -> isValidPieceToMove(m_color,pieceToMove.first+1,pieceToMove.second+1))
{
// Retreat Northwest.
if(localBoard -> isValidLocationToMove(pieceToMove.first,pieceToMove.second))
{
showRetreatDecision( pieceToMove.first + 1,pieceToMove.second + 1,"northwest",pieceToMove.first,pieceToMove.second);
didMove = false;
}
// Retreat Northeast
else if(localBoard -> isValidLocationToMove(pieceToMove.first,pieceToMove.second+2))
{
showRetreatDecision(pieceToMove.first + 1,pieceToMove.second + 1,"northeast",pieceToMove.first, pieceToMove.second+2);
didMove = false;
}
}
}
}
else
{
bool didMove = true;
while(didMove)
{
std::pair<int,int> pieceToMove = pickRandomPiece();
if(localBoard -> isValidPieceToMove(m_color,pieceToMove.first+1,pieceToMove.second+1))
{
// Retreat Southeast.
if(localBoard -> isValidLocationToMove(pieceToMove.first+2,pieceToMove.second+2))
{
showRetreatDecision( pieceToMove.first + 1,pieceToMove.second + 1,"southeast",pieceToMove.first + 2,pieceToMove.second + 2);
didMove = false;
}
// Retreat Southwest.
else if(localBoard -> isValidLocationToMove(pieceToMove.first+2,pieceToMove.second))
{
showRetreatDecision(pieceToMove.first + 1,pieceToMove.second + 1,"southwest",pieceToMove.first + 2, pieceToMove.second);
didMove = false;
}
}
}
}
};
/* *********************************************************************
Function Name: playOffensively
Purpose: Called when player strategy must be offensive. Function picks a random piece and suggests player movevs it to opponent's side.
Parameters:
none.
Return Value: none.
Local Variables:
didMove, boolean holding if computer made move.
Algorithm:
1) If white, do steps 2-3
2) Check if piece can move southeast, if so then suggest that the player move it southeast.
3) Check if piece can move southwest, if so then suggest that the player move it southwest.
4) If black, do steps 5-6
5) Check if piece can move northwest, if so then suggest that the player move it northwest.
6) Check if piece can move northeast, if so then suggest that the player move it northeast.
Assistance Received: none
********************************************************************* */
void
player::playOffensively()
{
if(m_color == 'W')
{
// Picking random piece.
bool didMove = true;
while(didMove)
{
std::pair<int,int> pieceToMove = pickRandomPiece();
if(localBoard -> isValidPieceToMove(m_color,pieceToMove.first+1,pieceToMove.second+1))
{
if(localBoard -> isValidLocationToMove(pieceToMove.first+2,pieceToMove.second+2))
{
showOffenseDecision( pieceToMove.first + 1,pieceToMove.second + 1,"southeast",pieceToMove.first + 2,pieceToMove.second + 2);
didMove = false;
}
else if(localBoard -> isValidLocationToMove(pieceToMove.first+2,pieceToMove.second))
{
showOffenseDecision(pieceToMove.first + 1,pieceToMove.second + 1,"southwest",pieceToMove.first + 2, pieceToMove.second);
didMove = false;
}
}
}
}
// computer is black
else
{
// Picking random piece.
bool didMove = true;
while(didMove)
{
std::pair<int,int> pieceToMove = pickRandomPiece();
if(localBoard -> isValidPieceToMove(m_color,pieceToMove.first+1,pieceToMove.second+1))
{
if(localBoard -> isValidLocationToMove(pieceToMove.first,pieceToMove.second+2))
{
showOffenseDecision(pieceToMove.first + 1,pieceToMove.second + 1,"northeast",pieceToMove.first,pieceToMove.second + 2);
didMove = false;
}
else if(localBoard -> isValidLocationToMove(pieceToMove.first,pieceToMove.second))
{
showOffenseDecision(pieceToMove.first + 1,pieceToMove.second + 1,"northwest",pieceToMove.first,pieceToMove.second);
didMove = false;
}
}
}
}
};
/* *********************************************************************
Function Name: pickRandomPiece
Purpose: Returns a random piece from available pieces. Used for offensive strategy.
Parameters:
none.
Return Value: Pair of ints representing row/column coordinates.
Local Variables:
none.
Algorithm:
1) Use rand to return a random index of available pieces.
Assistance Received: none
********************************************************************* */
std::pair<int,int>
player::pickRandomPiece()
{
return (*m_availablePieces)[rand() % (m_availablePieces->size())];
}
| true |
dd473185724977d614fad2c13baabf4c7602768f
|
C++
|
steelriors/Informatika_Vajda
|
/gyakorlas1/main.cpp
|
ISO-8859-2
| 1,003 | 2.953125 | 3 |
[] |
no_license
|
#include <iostream>
using namespace std;
/*
int main()
{
//FELADAT: RJUNK PROGRAMOT, AMI MEGNZI,
//HOGY A HROMSZG VALBAN KIRAJZOLHAT E!
int a,b,c;
cout << "Kerem az 'a' oldalt: " << endl;
cin >> a;
cout << "Kerem a 'b' oldalt: " << endl;
cin >> b;
cout << "Kerem a 'c' oldalt: " << endl;
cin >> c;
if ((a+b)>c && (a+c)>b && (b+c)>a)
{
cout << "Kirajzolhato a haromszog" << endl;
}else
cout << "Ez nem haromszog" << endl;
}
*/
/* FELADAT:
RJ EGY PROGRAMOT, AMI BEKRI A FELHASZNLTL
EGY TGLALAP KT OLDALT, MAJD KISZMOLJA A
KERLETT S TERLETT, VALAMINT KI IS RJA AZ
EREDMNYT!*/
int main()
{
int a,b,K,T;
cout << "Kerem az 'a' oldalt: " << endl;
cin >> a;
cout << "Kerem a 'b' oldalt: " << endl;
cin >> b;
K = (a+b)*2;
T = a*b;
//KIIRATS
cout << "Kerulet: " << K << endl;
cout << "Terulet: " << T << endl;
}
| true |
50b0f3388a9bdebf0848f409bdb2e13f6fe3273d
|
C++
|
rcosnita/git-semantic-versioning
|
/include/semver.h
|
UTF-8
| 1,513 | 2.859375 | 3 |
[] |
no_license
|
#ifndef GITSEMVER_INCLUDE_SEMVER_H_
#define GITSEMVER_INCLUDE_SEMVER_H_
#include <exception>
#include <providers/provider.h>
namespace gitsemver {
/**
* Semver provides the logic for interacting with an underlining repository.
*/
class Semver {
public:
template<typename T>
Semver(T&& gitProvider, int shaLength = providers::SHA_NUM_OF_CHARS)
: gitProvider_(std::forward<T>(gitProvider)),
shaLength_(shaLength) {
}
/**
* Retrieves the next potential version of the code base based on the past created tags.
* In case no previous tag was created, we will suggest 0.1.0-<branch-name>-<commit sha>.
* Branch name will be omitted for develop and master.
* In case the tool is executed against a tag, the tag name will be returned.
*/
std::string nextVersion(const std::string& tagsFilter) const;
virtual ~Semver() noexcept = default;
private:
/**
* Increments the patch version by 1 and returns the new version.
*/
std::string incrementVersion(const std::string& version) const;
/**
* Appends the branch name and the git commit shorten sha as suffix to the identified semantic version.
*/
std::string toSemanticVersionWithPrefix(const std::string& version) const;
private:
providers::GitProvider* gitProvider_;
int shaLength_;
};
}
#endif // GITSEMVER_INCLUDE_SEMVER_H_
| true |
43fc5e7bdea7c17e81f86a5dba464bb4781eb728
|
C++
|
BUCTdarkness/JiyiShen-s-Coding
|
/DataStruct/二叉树/自顶向下的赫夫曼编码.cpp
|
UTF-8
| 1,937 | 2.765625 | 3 |
[] |
no_license
|
#include<iostream>
#include<cstring>
#define MAX_LEN 500
using namespace std;
struct HaffmanTree
{
int weight;
int parent;
int lchild;
int rchild;
};
HaffmanTree t[MAX_LEN];
int n,m;
void initialize()
{
for(int i=1;i<=n;i++)
{
cin>>t[i].weight;
t[i].parent=-1;
t[i].lchild=-1;
t[i].rchild=-1;
}
m=n+n-1;
for(int i=n+1;i<=m;i++)
{
t[i].parent=-1;
t[i].lchild=-1;
t[i].rchild=-1;
}
}
void createTree()
{
for(int i=n+1;i<=m;i++)
{
int min1=1<<30;
int min2=1<<30;
int pos1,pos2;
for(int j=1;j<i;j++)
{
if(t[j].parent==-1)
{
if(t[j].weight<min1)
{
pos2=pos1;
min2=min1;
pos1=j;
min1=t[j].weight;
}
else if(t[j].weight<min2)
{
pos2=j;
min2=t[j].weight;
}
}
}
if(pos1>pos2)
{
int temp=pos1;
pos1=pos2;
pos2=temp;
}
t[i].lchild=pos1;
t[i].rchild=pos2;
t[i].weight=t[pos1].weight+t[pos2].weight;
t[pos1].parent=t[pos2].parent=i;
}
}
void makecode1()
{
char cd[n];
int c=m;
int cdlen=0;
char hc[n+1][n+1];
for(int i=1;i<=m;i++)
t[i].weight=0;
while(c!=-1)
{
if(t[c].weight==0)
{
t[c].weight=1;
if(t[c].lchild!=-1)
{
c=t[c].lchild;
cd[cdlen++]='0';
}
else if(t[c].rchild==-1)
{
cd[cdlen]='\0';
strcpy(hc[c],cd);
}
}
else if(t[c].weight==1)
{
t[c].weight=2;
if(t[c].rchild!=-1)
{
c=t[c].rchild;
cd[cdlen++]='1';
}
}
else
{
t[c].weight=0;
c=t[c].parent;
--cdlen;
}
}
for(int i=1;i<=n;i++)
cout<<hc[i]<<endl;
}
void makecode2()
{
char cd[n];
cd[n-1]='\0';
for(int i=1;i<=n;i++)
{
int start=n-1;
for(int c=i,f=t[i].parent;f!=-1;c=f,f=t[f].parent)
{
if(t[f].lchild==c)
{
cd[--start]='0';
}
else
cd[--start]='1';
}
for(int k=start;k<n-1;k++)
cout<<cd[k];
cout<<endl;
}
}
int main()
{
while(cin>>n)
{
memset(t,0,sizeof(t));
initialize();
createTree();
makecode1();
}
return 0;
}
| true |
b962010787c44ce75fe5b1aacd11c9155d6602f7
|
C++
|
elemenofi/twist
|
/src/paginator.cpp
|
UTF-8
| 3,703 | 2.609375 | 3 |
[] |
no_license
|
#include <Arduino.h>
#include "sequencer.h"
#include "paginator.h"
#include "step.h"
#include "controller.h"
#include "led.h"
Paginator::Paginator (Sequencer* sequencer) {
_sequencer = sequencer;
_currentEditPage = 0;
_createdPages = 0;
_currentPlaybackPage = 0;
};
int Paginator::getPage () {
return _currentEditPage;
};
void Paginator::getNextPlaybackPage (int direction) {
if (_createdPages == 0) return;
if (_currentPlaybackPage < _createdPages && direction == 1) {
_currentPlaybackPage++;
} else if (_currentPlaybackPage > 0 && direction == -1) {
_currentPlaybackPage--;
} else if (_currentPlaybackPage == 0 && direction == -1) {
_currentPlaybackPage = _createdPages;
} else if (_currentPlaybackPage == _createdPages) {
_currentPlaybackPage = 0;
}
// Serial.println("Current playback page");
// Serial.println(_currentPlaybackPage);
for (size_t i = 0; i < 4; i++) {
_sequencer->_stepsPlayback[i] = _pages[_currentPlaybackPage][i];
}
};
void Paginator::nextPage () {
if (_currentEditPage < 3) {
changePage(1);
_currentEditPage++;
_sequencer->_controller->_leds[_currentEditPage]->blink(3);
}
debugPages();
};
void Paginator::previousPage () {
if (_currentEditPage > 0) {
changePage(-1);
_currentEditPage--;
_sequencer->_controller->_leds[_currentEditPage]->blink(3);
};
debugPages();
};
void Paginator::changePage (int direction) {
if (direction == 1 && _createdPages < 3 && _currentEditPage == _createdPages) {
// this is a nasty flag i should get rid of
_createdPages++;
// //Serial.println("Incrementing created pages to:");
// //Serial.println(_createdPages);
}
for (size_t i = 0; i < 4; i++) {
// put current page steps in memory
_pages[_currentEditPage][i] = _sequencer->_stepsEdit[i];
// if there is not a defined step for the page then create steps
// if there are steps put them into the stepsEdit of the sequencer
if (_pages[_currentEditPage + direction][i] == 0) {
Serial.println("no steps yet");
Step * step = new Step(_sequencer);
if (_sequencer->_controller->getCopyMode()) {
copyStep(step, _sequencer->_stepsEdit[i]);
}
_sequencer->_stepsEdit[i] = step;
_pages[_currentEditPage + direction][i] = step;
} else {
Serial.println("loading from memory");
Step * step = new Step(_sequencer);
if (_sequencer->_controller->getCopyMode()) {
Serial.println("copying and setting in memory");
copyStep(step, _sequencer->_stepsEdit[i]);
} else {
Serial.println("copying only from memory");
copyStep(step, _pages[_currentEditPage + direction][i]);
}
Serial.println("Setting steps for editing");
_pages[_currentEditPage + direction][i] = step;
_sequencer->_stepsEdit[i] = step;
}
setLeds(i);
}
};
// maybe this function should be in the
void Paginator::copyStep (Step* step1, Step* step2) {
step1->pitchScale = step2->pitchScale;
step1->pitchGrade = step2->pitchGrade;
step1->velocity = step2->velocity;
step1->length = step2->length;
step1->_state = step2->_state;
step1->chance = step2->chance;
step1->swing = step2->swing;
};
void Paginator::setLeds (size_t i) {
// toggle the leds for the loaded steps
Step * newStep = _sequencer->_stepsEdit[i];
Led * newStepLed = _sequencer->_controller->_leds[i];
if (newStep->_state == 0) {
newStepLed->off();
} else {
newStepLed->on();
}
};
void Paginator::debugPages () {
for (size_t i = 0; i < 4; i++) {
for (size_t y = 0; y < 4; y++) {
Step * step = _pages[i][y];
Serial.println(step->_state);
}
}
};
| true |
d3457126046792453ba88998a63ff6e4505f2a9b
|
C++
|
liushengxi13689209566/Programming-language-learning
|
/C-pp/chapter10/10.3.2test.cpp
|
UTF-8
| 1,307 | 3.28125 | 3 |
[] |
no_license
|
/*************************************************************************
> File Name: 10.11.cpp
> Author:
> Mail:
> Created Time: 2018年01月28日 星期日 14时14分20秒
************************************************************************/
#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
using namespace std;
bool isshorter(const string &a ,const string &b){
return a.size() < b.size();
}
void fun(vector<string> &strVec ,vector<string>::size_type sz){
sort(strVec.begin(),strVec.end());
auto end_unique = unique(strVec.begin(),strVec.end());
strVec.erase(end_unique,strVec.end());
stable_sort(strVec.begin(),strVec.end(),isshorter); //先按长度排序,在按字典序排序
//找到第一个大于等于给定单词长度的迭代器 ,计算数目 ,并输出
auto wc = find_if(strVec.begin(),strVec.end() ,[sz](const string &a){
return a.size() > sz ;});
auto count = strVec.end() - wc ;
cout << " 数目为 :" << count << endl ;
for_each(wc,strVec.end() ,[](const string &s){
cout << s << " " ;
});
cout << endl ;
}
//目标:求大于等于一个给定单词长度的数目,并输出
int main(void){
vector<string> strVec{"the","quick","red","fox","jumps","over",
"the","slow","red","turtle"};
fun(strVec ,3);
return 0 ;
}
| true |
45e109534e51bee5d31434a9846efa9cdfb76fc1
|
C++
|
egosick196/heimaPractice_employeeManage
|
/Boss.cpp
|
UTF-8
| 391 | 2.71875 | 3 |
[] |
no_license
|
#include "Boss.h"
using namespace std;
Boss::Boss(int id, string name, int dId)
{
m_ID = id;
m_name = name;
m_deptID = dId;
}
void Boss::showInfo()
{
cout << "职工编号: " << m_ID << endl
<< "职工姓名: " << m_name << endl
<< "岗位: " << getDeptID() << endl
<< "职责:统管公司事务。\n" << endl;
}
string Boss::getDeptID()
{
return string("总裁");
}
| true |
6e896a77c3a8031331f34e7f9acb03c5adebd9ce
|
C++
|
davefutyan/common_sw
|
/utilities/tests/unit_test/src/TestUtc.cxx
|
UTF-8
| 7,094 | 2.921875 | 3 |
[] |
no_license
|
/** ****************************************************************************
* @file
*
* @ingroup utilities
* @brief unit_test of the UTC class
*
* @author Reiner Rohlfs UGE
*
* @version 5.1 2016-03-19 RRO the maximum year is now 2037
* @version 4.3 2015-10-27 RRO #9302 testing new operators
* @version 3.0 2015-01-24 RRO first version
*
*/
#define BOOST_TEST_MAIN
#include "boost/test/unit_test.hpp"
#include "boost/test/floating_point_comparison.hpp"
#include <stdexcept>
#include <string>
#include "ProgramParams.hxx"
#include "Utc.hxx"
#include "Mjd.hxx"
#include "DeltaTime.hxx"
using namespace boost::unit_test;
struct UtcFixture {
UtcFixture() {
m_params = CheopsInit(framework::master_test_suite().argc,
framework::master_test_suite().argv);
}
~UtcFixture() {
}
ParamsPtr m_params;
};
BOOST_FIXTURE_TEST_SUITE( testUtc, UtcFixture )
////////////////////////////////////////////////////////////////////////////////
BOOST_AUTO_TEST_CASE( NoSecFraction )
{
// this should work
UTC utc(2015, 01, 24, 13, 4, 3);
BOOST_CHECK_EQUAL(utc.getUtc(), std::string("2015-01-24T13:04:03.000000"));
}
////////////////////////////////////////////////////////////////////////////////
BOOST_AUTO_TEST_CASE( WithSecFraction )
{
UTC utc(2015, 01, 24, 13, 4, 3, 0.03);
BOOST_CHECK_EQUAL(utc.getUtc(), std::string("2015-01-24T13:04:03.030000"));
}
////////////////////////////////////////////////////////////////////////////////
BOOST_AUTO_TEST_CASE( Wrong_Input_String )
{
bool test;
// wrong year
test = false;
try {
UTC utc("15-3-12T23:04:23");
}
catch (std::runtime_error & error) {
BOOST_CHECK_EQUAL(error.what(),
std::string("The format of the UTC as string is not as expected."
"Expected: yyyy-mm-ddThh:mm:ss.ffffff, but found: 15-3-12T23:04:23") );
test = true;
}
BOOST_CHECK_EQUAL(true, test);
// wrong separator
test = false;
try {
UTC utc("2015-03+12T23:04:23");
}
catch (std::runtime_error & error) {
BOOST_CHECK_EQUAL(error.what(),
std::string("The format of the UTC as string is not as expected."
"Expected: yyyy-mm-ddThh:mm:ss.ffffff, but found: 2015-03+12T23:04:23") );
test = true;
}
BOOST_CHECK_EQUAL(true, test);
// wrong year
test = false;
try {
UTC utc2(215, 01, 24, 13, 4, 3);
}
catch (std::runtime_error & error) {
BOOST_CHECK_EQUAL(error.what(),
std::string("The year of a utc has to be in the range from 1970 to 2037."
" UTC - constructor found 215") );
test = true;
}
BOOST_CHECK_EQUAL(true, test);
// wrong month
test = false;
try {
UTC utc2(2015, 00, 24, 13, 4, 3);
}
catch (std::runtime_error & error) {
BOOST_CHECK_EQUAL(error.what(),
std::string("The month of a utc has to be in the range from 1 to 12."
" UTC - constructor found 0") );
test = true;
}
BOOST_CHECK_EQUAL(true, test);
// wrong day
test = false;
try {
UTC utc2(2015, 02, 30, 13, 4, 3);
}
catch (std::runtime_error & error) {
BOOST_CHECK_EQUAL(error.what(),
std::string("The day of a utc for month February has to be in the range from 1 to 29."
" UTC - constructor found 30") );
test = true;
}
BOOST_CHECK_EQUAL(true, test);
// wrong hour
test = false;
try {
UTC utc2(2015, 01, 24, 24, 4, 3);
}
catch (std::runtime_error & error) {
BOOST_CHECK_EQUAL(error.what(),
std::string("The hour of a utc has to be in the range from 0 to 23."
" UTC - constructor found 24") );
test = true;
}
BOOST_CHECK_EQUAL(true, test);
// wrong minute
test = false;
try {
UTC utc2(2015, 01, 24, 13, 70, 3);
}
catch (std::runtime_error & error) {
BOOST_CHECK_EQUAL(error.what(),
std::string("The minute of a utc has to be in the range from 0 to 59."
" UTC - constructor found 70") );
test = true;
}
BOOST_CHECK_EQUAL(true, test);
// wrong second
test = false;
try {
UTC utc2(2015, 01, 24, 13, 7, 63);
}
catch (std::runtime_error & error) {
BOOST_CHECK_EQUAL(error.what(),
std::string("The second of a utc has to be in the range from 0 to 60."
" UTC - constructor found 63") );
test = true;
}
BOOST_CHECK_EQUAL(true, test);
// wrong fraction of a second
test = false;
try {
UTC utc2(2015, 01, 24, 13, 4, 3, 1.4);
}
catch (std::runtime_error & error) {
BOOST_CHECK_EQUAL(error.what(),
std::string("The fraction of a second of a utc has to be less than 1.0."
" UTC - constructor found 1.400000") );
test = true;
}
BOOST_CHECK_EQUAL(true, test);
}
////////////////////////////////////////////////////////////////////////////////
BOOST_AUTO_TEST_CASE( Operators )
{
UTC utc1("2015-04-06T13:02:17");
UTC utc2("2015-04-06T13:02:17.040000");
BOOST_CHECK_EQUAL(utc1 < utc2, true);
BOOST_CHECK_EQUAL(utc2.getUtc(true), std::string("2015-04-06T13:02:17"));
BOOST_CHECK_EQUAL(utc1.getUtc(), std::string("2015-04-06T13:02:17.000000"));
BOOST_CHECK_EQUAL(utc2.getFileNamePattern(), std::string("TU2015-04-06T13-02-17"));
}
////////////////////////////////////////////////////////////////////////////////
BOOST_AUTO_TEST_CASE( Single_Item )
{
UTC utc("2015-04-06T13:02:17.040");
BOOST_CHECK_EQUAL(utc.getYear(), 2015);
BOOST_CHECK_EQUAL(utc.getMonth(), 4);
BOOST_CHECK_EQUAL(utc.getDay(), 6);
BOOST_CHECK_EQUAL(utc.getHour(), 13);
BOOST_CHECK_EQUAL(utc.getMinute(), 2);
BOOST_CHECK_EQUAL(utc.getSecond(), 17);
BOOST_CHECK_EQUAL(utc.getSecFraction(), 0.04);
}
////////////////////////////////////////////////////////////////////////////////
BOOST_AUTO_TEST_CASE( deltaTime )
{
UTC utc("2015-04-06T13:02:17.040");
DeltaTime delta(61.5); // 1 minute 1 sec 0.5 sec
BOOST_CHECK_EQUAL((utc + delta).getUtc(), std::string("2015-04-06T13:03:18.540000"));
BOOST_CHECK_EQUAL((utc - delta).getUtc(), std::string("2015-04-06T13:01:15.540000"));
utc += delta;
BOOST_CHECK_EQUAL(utc.getUtc(), std::string("2015-04-06T13:03:18.540000"));
utc -= delta;
BOOST_CHECK_EQUAL(utc.getUtc(), std::string("2015-04-06T13:02:17.040000"));
}
////////////////////////////////////////////////////////////////////////////////
//BOOST_AUTO_TEST_CASE( Utc2Mjd )
//{
// UTC utc1("2010-01-01T00:00:00.000");
// BOOST_CHECK_CLOSE((double)(utc1.getMjd()), 55197.0003725, 0.0000001);
//
// UTC utc2("2010-01-01T12:00:00.000");
// BOOST_CHECK_CLOSE((double)(utc2.getMjd()), 55197.5003725, 0.0000001);
//
// UTC utc3("2010-01-01T00:01:00.000");
// BOOST_CHECK_CLOSE((double)(utc3.getMjd()), 55197.001067, 0.0000001);
//
//}
BOOST_AUTO_TEST_SUITE_END()
| true |
ccb79993357a8973f17efc3c369cfcee338e623b
|
C++
|
linjw1008/common_algorithms
|
/sorting_algorithm/insert_sort.cpp
|
UTF-8
| 839 | 3.78125 | 4 |
[] |
no_license
|
//插入排序
#include <iostream>
using namespace std;
class InsertSort
{
public:
void sort_V1(int *array, int n)
{
for (int i = 1; i < n; i++)
{
int insertValue = array[i];
int j;
for (j = i - 1; j >= 0 && insertValue < array[j]; j--)
{
array[j + 1] = array[j];
}
array[j + 1] = insertValue;
}
}
};
int main()
{
InsertSort insertsort;
int array[] = {5, 7, 9, 4, 1, 3, 5, 11, 66, 44, 52, 98, 19, 67, 24, 0};
//int array[] = {0,1,2,3,4,5,6,7,8,9};
insertsort.sort_V1(array, sizeof(array)/sizeof(int));
for (int i = 0; i < sizeof(array)/sizeof(int); i++)
{
cout << array[i] << " " << endl;
}
return 0;
}
| true |
7e9b101c4fb846c532434bf939866293c1e762b7
|
C++
|
CognitiveModeling/snn-robotic-trunk
|
/src/SNN/Gradients/CurrentInputGradient.h
|
UTF-8
| 2,609 | 2.71875 | 3 |
[
"MIT"
] |
permissive
|
#ifndef __CURRENT_INPUT_GRADIENT_H__
#define __CURRENT_INPUT_GRADIENT_H__
#include "BasicGradient.h"
#include "BasicNetwork.h"
#include "BasicNetworkOptions.h"
#include "utils.h"
/**
* Gradient for firing rates
*/
namespace SNN {
namespace Gradients {
class CurrentInputGradient: public Interfaces::BasicGradient {
private:
/* the time period for the gradient */
int startTime, endTime;
/* neuron interval associated with the input */
unsigned firstNeuron, lastNeuron;
/* the input errors over time */
FloatType *inputErrorsOverTime;
/* the total number of input neurons */
unsigned numInputNeurons;
/* salling factor */
FloatType scallingFactor;
/* should calculate the gradient for non synapse dependent gradients */
virtual FloatType calcGradient() {
FloatType inputGradient = 0;
for (int t = startTime; t <= endTime; t++) {
for (unsigned n = firstNeuron; n <= lastNeuron; n++) {
inputGradient += inputErrorsOverTime[t * numInputNeurons + n];
}
}
return scallingFactor * inputGradient / ((endTime - startTime + 1) * (lastNeuron - firstNeuron + 1));
}
public:
/* constructor */
CurrentInputGradient(
int startTime,
int endTime,
unsigned firstNeuron,
unsigned lastNeuron,
unsigned numInputNeurons,
FloatType *inputErrorsOverTime
):
startTime(startTime),
endTime(endTime),
firstNeuron(firstNeuron),
lastNeuron(lastNeuron),
inputErrorsOverTime(inputErrorsOverTime),
numInputNeurons(numInputNeurons),
scallingFactor(1){ }
/* sets the start and end time of this */
void setTimeWindow(int startTime, int endTime) {
this->startTime = startTime;
this->endTime = endTime;
}
/* sets the scallingFactor */
void setScallingFactor(FloatType scallingFactor) {
this->scallingFactor = scallingFactor;
}
};
}
}
#endif
| true |
38cdffdb3ad52d971f82ad01112c72f36bd10a97
|
C++
|
wzsayiie/ob-mobile
|
/library/ctool/ctool/cpp/cqvalue.cpp
|
UTF-8
| 8,267 | 3.078125 | 3 |
[] |
no_license
|
#include "cqvalue.hh"
using namespace cq;
typedef std::string str_t ;
typedef std::vector<value> vector_t ;
typedef std::map<std::string, value> str_map_t;
typedef std::map<int64_t, value> int_map_t;
inline str_t &str (void *p) { return *(str_t *)p; }
inline vector_t &vector (void *p) { return *(vector_t *)p; }
inline str_map_t &str_map(void *p) { return *(str_map_t *)p; }
inline int_map_t &int_map(void *p) { return *(int_map_t *)p; }
static void convert(_value_dat *dat, value_type type) {
if (dat->type == type) {
return;
}
//delete old data:
switch (dat->type) {
break; case type_str : delete &str (dat->a_ptr);
break; case type_vector : delete &vector (dat->a_ptr);
break; case type_str_map: delete &str_map(dat->a_ptr);
break; case type_int_map: delete &int_map(dat->a_ptr);
default:;
}
//assign new data:
dat->type = type;
switch (type) {
break; case type_null : dat->a_int64 = 0;
break; case type_bool : dat->a_bool = false;
break; case type_int64 : dat->a_int64 = 0;
break; case type_double : dat->a_double = 0.0;
break; case type_str : dat->a_ptr = new str_t;
break; case type_vector : dat->a_ptr = new vector_t;
break; case type_str_map: dat->a_ptr = new str_map_t;
break; case type_int_map: dat->a_ptr = new int_map_t;
default:;
}
}
//construct:
value::value() { *this = nullptr; }
value::value(std::nullptr_t) { *this = nullptr; }
value::value(bool v) { *this = v; }
value::value(int8_t v) { *this = v; }
value::value(int16_t v) { *this = v; }
value::value(int32_t v) { *this = v; }
value::value(int64_t v) { *this = v; }
value::value(float v) { *this = v; }
value::value(double v) { *this = v; }
value::value(const char *v) { *this = v; }
value::value(const str_t &v) { *this = v; }
value::value(const vector_t &v) { *this = v; }
value::value(const str_map_t &v) { *this = v; }
value::value(const int_map_t &v) { *this = v; }
value::value(const value &v) { *this = v; }
//getter:
value_type value::type() const {
return dat.type;
}
bool value::get_bool() const {
switch (dat.type) {
break; case type_null : return false;
break; case type_bool : return dat.a_bool;
break; case type_int64 : return dat.a_int64 != 0;
break; case type_double : return cq_dbl_equal(dat.a_double, 0.0);
break; case type_str : return !str (dat.a_ptr).empty();
break; case type_vector : return !vector (dat.a_ptr).empty();
break; case type_str_map: return !str_map(dat.a_ptr).empty();
break; case type_int_map: return !int_map(dat.a_ptr).empty();
default /* unexpected */: return false;
}
}
int8_t value::get_int8 () const { return (int8_t )get_int64(); }
int16_t value::get_int16() const { return (int16_t)get_int64(); }
int32_t value::get_int32() const { return (int32_t)get_int64(); }
int64_t value::get_int64() const {
switch (dat.type) {
break; case type_null : return 0;
break; case type_bool : return dat.a_bool ? 1 : 0;
break; case type_int64 : return dat.a_int64;
break; case type_double : return (int64_t)dat.a_double;
break; case type_str : return atoll(str(dat.a_ptr).c_str());
break; case type_vector : return 0;
break; case type_str_map: return 0;
break; case type_int_map: return 0;
default /* unexpected */: return 0;
}
}
float value::get_float() const {
return (float)get_double();
}
double value::get_double() const {
switch (dat.type) {
break; case type_null : return 0.0;
break; case type_bool : return dat.a_bool ? 1.0 : 0.0;
break; case type_int64 : return (double)dat.a_int64;
break; case type_double : return dat.a_double;
break; case type_str : return atof(str(dat.a_ptr).c_str());
break; case type_vector : return 0.0;
break; case type_str_map: return 0.0;
break; case type_int_map: return 0.0;
default /* unexpected */: return 0.0;
}
}
str_t value::get_str() const {
switch (dat.type) {
break; case type_null : return "null";
break; case type_bool : return dat.a_bool ? "true" : "false";
break; case type_int64 : return std::to_string(dat.a_int64);
break; case type_double : return std::to_string(dat.a_double);
break; case type_str : return str(dat.a_ptr);
break; case type_vector : return "[...]";
break; case type_str_map: return "{...}";
break; case type_int_map: return "{...}";
default /* unexpected */: return "null";
}
}
vector_t value::get_vector() const {
if (dat.type == type_vector) {
return vector(dat.a_ptr);
} else {
return vector_t();
}
}
str_map_t value::get_str_map() const {
if (dat.type == type_int_map) {
//int_map_t can be cast to str_map_t.
const int_map_t &from = int_map(dat.a_ptr);
str_map_t to;
for (const auto &cp : from) {
to[std::to_string(cp.first)] = cp.second;
}
return to;
} else if (dat.type == type_str_map) {
return str_map(dat.a_ptr);
} else {
return str_map_t();
}
}
int_map_t value::get_int_map() const {
if (dat.type == type_int_map) {
return int_map(dat.a_ptr);
} else {
return int_map_t();
}
}
//setter:
const value &value::operator=(std::nullptr_t) {
convert(&dat, type_null);
return *this;
}
const value &value::operator=(bool v) {
convert(&dat, type_bool);
dat.a_bool = v;
return *this;
}
const value &value::operator=(int8_t v) { return *this = (int64_t)v; }
const value &value::operator=(int16_t v) { return *this = (int64_t)v; }
const value &value::operator=(int32_t v) { return *this = (int64_t)v; }
const value &value::operator=(int64_t v) {
convert(&dat, type_int64);
dat.a_int64 = v;
return *this;
}
const value &value::operator=(float v) {
*this = (double)v;
return *this;
}
const value &value::operator=(double v) {
convert(&dat, type_double);
dat.a_double = v;
return *this;
}
const value &value::operator=(const char *v) {
if (v != nullptr) {
convert(&dat, type_str);
str(dat.a_ptr) = v;
} else {
convert(&dat, type_null);
}
return *this;
}
const value &value::operator=(const str_t &v) {
convert(&dat, type_str);
str(dat.a_ptr) = v;
return *this;
}
const value &value::operator=(const vector_t &v) {
convert(&dat, type_vector);
vector(dat.a_ptr) = v;
return *this;
}
const value &value::operator=(const str_map_t &v) {
convert(&dat, type_str_map);
str_map(dat.a_ptr) = v;
return *this;
}
const value &value::operator=(const int_map_t &v) {
convert(&dat, type_int_map);
int_map(dat.a_ptr) = v;
return *this;
}
const value &value::operator=(const value &v) {
convert(&dat, v.dat.type);
switch (dat.type) {
break; case type_null : dat.a_int64 = v.dat.a_int64;
break; case type_bool : dat.a_bool = v.dat.a_bool;
break; case type_int64 : dat.a_int64 = v.dat.a_int64;
break; case type_double : dat.a_double = v.dat.a_double;
break; case type_str : str (dat.a_ptr) = str (v.dat.a_ptr);
break; case type_vector : vector (dat.a_ptr) = vector (v.dat.a_ptr);
break; case type_str_map: str_map(dat.a_ptr) = str_map(v.dat.a_ptr);
break; case type_int_map: int_map(dat.a_ptr) = int_map(v.dat.a_ptr);
default /* unexpected */: dat.a_int64 = v.dat.a_int64;
}
return *this;
}
vector_t &value::as_vector() {
convert(&dat, type_vector);
return vector(dat.a_ptr);
}
str_map_t &value::as_str_map() {
convert(&dat, type_str_map);
return str_map(dat.a_ptr);
}
int_map_t &value::as_int_map() {
convert(&dat, type_int_map);
return int_map(dat.a_ptr);
}
value &value::operator[](const std::string &k) {
convert(&dat, type_str_map);
return str_map(dat.a_ptr)[k];
}
//destruct:
value::~value() {
convert(&dat, type_null);
}
| true |
6cb975c4676ec744c51e369b1ed543c360540a3d
|
C++
|
ImageProcessing-ElectronicPublications/pngpaf
|
/src/twoDtree.h
|
UTF-8
| 5,603 | 3.359375 | 3 |
[
"Unlicense"
] |
permissive
|
#ifndef _TWODTREE_H_
#define _TWODTREE_H_
#include <limits.h>
#include <utility>
#include "util/PNG.h"
#include "util/RGBAPixel.h"
#include "stats.h"
using namespace std;
using namespace util;
/*
* This is a structure used in decomposing an image
* into rectangles of similarly colored pixels.
* This is a slight modification of a Kd tree of dimension 2.
*/
class twoDtree
{
private:
/*
* Node class is encapsulated.
* Users should not know anything about its implementation.
*/
class Node
{
public:
//Node constructor
Node(pair<int,int> ul, pair<int,int> lr, RGBAPixel a);
pair<int,int> upLeft;
pair<int,int> lowRight;
RGBAPixel avg;
//ptr to left subtree
Node * left;
//ptr to right subtree
Node * right;
};
public:
/*
* Since this structure will allocate dynamic memory, we define
* the following next three functions.
*/
/*
* twoDtree destructor.
* Destroys all of the memory associated with the
* current twoDtree. This function should ensure that
* memory does not leak on destruction of a twoDtree.
*/
~twoDtree();
/*
* Copy constructor for a twoDtree.
* @param other The twoDtree we are copying.
*/
twoDtree(const twoDtree & other);
/*
* Overloaded assignment operator for twoDtrees.
* @param rhs The right hand side of the assignment statement.
*/
twoDtree & operator=(const twoDtree & rhs);
/*
* Constructor that builds a twoDtree out of the given PNG.
* Every leaf in the tree corresponds to a pixel in the PNG.
* Every non-leaf node corresponds to a rectangle of pixels
* in the original PNG, represented by an (x,y) pair for the
* upper left corner of the rectangle and an (x,y) pair for
* lower right corner of the rectangle. In addition, the Node
* stores a pixel representing the average color over the
* rectangle.
*
* Every node's left and right children correspond to a partition
* of the node's rectangle into two smaller rectangles. The node's
* rectangle is split by the horizontal or vertical line that
* results in the two smaller rectangles whose sum of squared
* differences from their mean is as small as possible.
*
* The left child of the node will contain the upper left corner
* of the node's rectangle, and the right child will contain the
* lower right corner.
*
* This function will build the stats object used to score the
* splitting lines.
*/
twoDtree(PNG & imIn);
/*
* Render returns a PNG image consisting of the pixels
* stored in the tree.
* Draws every leaf node's rectangle onto a PNG canvas using the
* average color stored in the node.
* @Return PNG images of pixels stored in tree
*/
PNG render();
/*
* Trims subtrees as high as possible in the tree.
* A subtree is pruned (cleared) if at least the percentage of its leaves are
* within tolerance of the average color stored in the root of the subtree.
* Pruning criteria should be evaluated on the original tree, not
* on a pruned subtree. (we only expect that trees would be pruned once.)
* @Param pct percentage of leaves
* @Param tol tolerance for pruning
*/
void prune(double pct, int tol);
private:
//ptr to the root of the twoDtree
Node* root;
//height of PNG represented by the tree
int height;
//width of PNG represented by the tree
int width;
/*
* Destroys all dynamically allocated memory associated with the
* current twoDtree class.
*/
void clear();
/*
* Copies the parameter other twoDtree into the current twoDtree.
* Does not free any memory. Used by copy constructor and op=.
* @param other The twoDtree to be copied.
*/
void copy(const twoDtree & other);
/*
* Private helper function for the constructor. Builds
* the tree according to the specification of the constructor.
* @param s Contains the data used to split the rectangles
* @param ul upper left point of current node's rectangle.
* @param lr lower right point of current node's rectangle.
* @Return pointer to pixel node
*/
Node * buildTree(stats & s,pair<int,int> ul, pair<int,int> lr);
/*
* Recursive helper function for clear()
* @Param rootD is a node of the tree
*/
void deleteTree(Node* &rootD);
/*
* Recursive helper function for copy()
* @Param other is a node of the tree
* @Return pointer to copied node
*/
Node * copyTree(Node* other);
/*
* Recursive helper function for render()
* @Param roote is a node in the tree
* @Param img is the PNG image
*/
void changeLeafColour(Node* root, PNG &img);
/*
* Recursive helper function for prune()
* @Param node if the node to be pruned
* @Param pct is the percentage of leaf nodes
* @Param tol is the tolerance for pruning
*/
void toPrune(Node* &node, double pct, int tol);
/*
* Recursive helper function for toPrune()
* @Param subRoot is the node to prune
* @Param child is the node of subRoote
* @Param withinTol is the number of nodes within tolerance at subRoot
* @Param totalNodes is thetotal nodes at subRoot
* @Param tol is the tolerance for pruning
*/
void calculateDistance(Node* &subRoot, Node* &child, double &withinTol, double &totalNodes, int tol);
};
#endif
| true |
39e156f6674d7af869f0e132c563945b0f9be845
|
C++
|
defuyun/ACM
|
/excercise/word_sort.cpp
|
UTF-8
| 1,637 | 3.6875 | 4 |
[] |
no_license
|
// Q. you are given a list of words followed by ****** call it a dict
// then another list of random words, print out the words in dict that can be identified
// by reforming the new input words in alphabetical order, print :( if the new word cannot be found in the dict
/*
e.g. input: abcj kitty olleh hello ***** bcja elolh yiktt james
output: abcj
hello olleh // print hello before olleh since hello comes before in alphabetical order
kitty
'frown';
*/
// so what we do is, first sort the entered dict so that it prints in alpha order
// to make comparing simple for the random words, sort the individual words in the dict
// now each time a random word is entered, we sort this random word and compare to the sorted words in the
// dict, since sorted words must be in the same order, we can just use strcmp
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int cmp_char(void * a,void * b){
return *(char *)a - *(char *)b;
}
int cmp_string(void * a, void * b){
return strcmp((char *)a, (char *)b);
}
int main(){
char dict[1000][25], sorted[1000][25],word[25];
int len = 0;
while(scanf("%s",dict[len])){
if(dict[len][0] == '*') break;
len++;
}
qsort(dict,len,sizeof(dict[0]),cmp_string);
for(int i = 0;i < len; i++){
strcpy(sorted[i],dict[i]);
qsort(sorted,strlen(sorted[i]),sizeof(char),cmp_char);
}
while(scanf("%s",word)){
int found = 0;
qsort(word,strlen(word),sizeof(char),cmp_char);
for(int i = 0; i < len; i++){
if(!strcmp(word,sorted[i])){
found = 1;
std::cout << dict[i] << " ";
}
}
if(!found){
std::cout << ":(";
}
std::cout << "\n";
}
}
| true |
1a2ae54be3843ae83d4814378c9721be1ae03a97
|
C++
|
Issic47/muduo-x
|
/muduo/base/ThreadLocalSingleton.h
|
UTF-8
| 1,610 | 2.96875 | 3 |
[] |
no_license
|
// Use of this source code is governed by a BSD-style license
// that can be found in the License file.
//
// Author: Shuo Chen (chenshuo at chenshuo dot com), Bijin Chen
#ifndef MUDUO_BASE_THREADLOCALSINGLETON_H
#define MUDUO_BASE_THREADLOCALSINGLETON_H
#include <muduo/base/Types.h>
#include <boost/noncopyable.hpp>
#include <assert.h>
namespace muduo
{
template<typename T>
class ThreadLocalSingleton : boost::noncopyable
{
public:
static T& instance()
{
if (!t_value_)
{
t_value_ = new T();
deleter_.set(t_value_);
}
return *t_value_;
}
static T* pointer()
{
return t_value_;
}
// WARNING: need to call destroy before the thread exit
static void destroy()
{
destructor(t_value_);
}
private:
ThreadLocalSingleton();
~ThreadLocalSingleton();
static void destructor(void* obj)
{
assert(obj == t_value_);
typedef char T_must_be_complete_type[sizeof(T) == 0 ? -1 : 1];
T_must_be_complete_type dummy; (void) dummy;
delete t_value_;
t_value_ = 0;
}
class Deleter
{
public:
Deleter()
{
uv_key_create(&pkey_);
}
~Deleter()
{
destructor(uv_key_get(&pkey_));
uv_key_delete(&pkey_);
}
void set(T* newObj)
{
assert(uv_key_get(&pkey_) == NULL);
uv_key_set(&pkey_, newObj);
}
uv_key_t pkey_;
};
static thread_local T* t_value_;
static Deleter deleter_;
};
template<typename T>
thread_local T* ThreadLocalSingleton<T>::t_value_ = 0;
template<typename T>
typename ThreadLocalSingleton<T>::Deleter ThreadLocalSingleton<T>::deleter_;
}
#endif
| true |
c855a246d69fc31982fdbb246a710f08ca5d68b5
|
C++
|
mikolajmale/Cpp_sample_with_tests
|
/src/Device.cpp
|
UTF-8
| 2,384 | 3.046875 | 3 |
[] |
no_license
|
#include "Device.h"
Device::Device(const int samples)
{
createSampleDataBase(samples);
std::array<std::string, 3> message;
std::string line;
std::ifstream data_file("data.txt");
if (data_file.is_open())
{
while (std::getline(data_file , line))
{
size_t pos = 0;
std::string token;
int i = 0;
while ((pos = line.find(',')) != std::string::npos) {
token = line.substr(0, pos);
message[i++] = token;
line.erase(0, pos + 1);
if (i == 2) message[2] = line;
}
data.push_back(message);
}
data_file.close();
}
}
Device::~Device()
{
}
void Device::createSampleDataBase(int samples)
{
srand((unsigned)time(NULL));
int device = 0, state = 0;
long long hex1 = 0, hex2 = 0, hex3 = 0;
std::ofstream data_file("data.txt");
for (int i = 0; i < samples; ++i)
{
device = rand() % 5;
state = rand() % 3;
hex1 = rand() % 0xFFFF;
hex2 = rand() % 0xFFFF;
hex3 = rand() % 0xFF;
long long unsigned hex = (hex1 << 24) | (hex2 << 8) | (hex3);
std::stringstream str;
data_file << printDevice(device) << "," << printState(state) << "," << std::hex << hex << std::endl;
str << std::hex << hex;
std::bitset<40> binary(hex);
}
data_file.close();
}
std::string Device::printState(int state)
{
std::string state_string;
switch (state)
{
case OK:
state_string = "OK";
break;
case WARNING:
state_string = "WARNING";
break;
case FAILURE:
state_string = "FAILURE";
break;
default:
break;
}
return state_string;
}
std::string Device::printDevice(int devices)
{
std::string sensor;
switch (devices)
{
case LIGHT_SENSOR:
sensor = "LIGHT_SENSOR";
break;
case PARKING_SENSOR:
sensor = "PARKING_SENSOR";
break;
case TEMPERATURE_SENSOR:
sensor = "TEMPERATURE_SENSOR";
break;
case POSITION_SENSOR:
sensor = "POSITION_SENSOR";
break;
case HAL_SENSOR:
sensor = "HAL_SENSOR";
break;
default:
break;
}
return sensor;
}
void Device::printFailedDevices(void)
{
std::array<std::string , 3> message;
long long hex = 0;
for(unsigned int i = 0 ; i < data.size() ; ++i)
{
message = data[i];
if(message[1] == "FAILURE")
{
hex = (long long)strtol(message[2].c_str(), 0, 16);
std::cout << message[0] << " , " << std::bitset<40>(hex) << '\n';
}
}
}
| true |
d768c47eb3049fac3719f2ee0ea1917500991e69
|
C++
|
toAlice/CO004_MUST_Project
|
/policy.h
|
UTF-8
| 810 | 2.640625 | 3 |
[] |
no_license
|
#pragma once
#include <string>
#include <utility>
#include "schedulerutils.h"
class Policy {
private:
static const std::string LABEL;
static const std::string FCFS;
static const std::string RR;
static const std::string PRIORITY;
static const std::string SJF;
using State = u8;
static constexpr State GOOD{0u};
static constexpr State WRONG{1u};
static constexpr State NOT_IMPLEMENTED{WRONG << 1u};
private:
State state{GOOD}; // good;
std::string policy;
public:
Policy();
explicit Policy(std::string policy);
bool good() const;
bool is_wrong() const;
bool is_not_implemented() const;
bool is_FCFS() const;
bool is_RR() const;
bool is_PRIORITY() const;
bool is_SJF() const;
std::string to_string() const;
};
| true |
f4d643b1c5dad9889425cc7942047300a0515a09
|
C++
|
b-it-bots/mas_perception
|
/mcr_linear_regression/common/src/laser_scan_linear_regression.cpp
|
UTF-8
| 2,633 | 2.890625 | 3 |
[] |
no_license
|
#include <vector>
#include <math.h>
#include <iostream>
#include "mcr_linear_regression/laser_scan_linear_regression.h"
namespace LaserScanLinearRegression
{
std::vector<ScanItem> ScanItemFilter::filterByDistance(std::vector<ScanItem> items, double minDistance, double maxDistance)
{
std::vector<ScanItem> filteredData;
for (unsigned int i = 0; i < items.size(); i++)
{
if (items[i].distance >= minDistance && items[i].distance <= maxDistance)
{
filteredData.push_back(items[i]);
}
}
return filteredData;
}
std::vector<ScanItem> ScanItemFilter::filterByAngle(std::vector<ScanItem> items, double minAngle, double maxAngle)
{
std::vector<ScanItem> filteredData;
for (unsigned int i = 0; i < items.size(); i++)
{
if (items[i].angle >= minAngle && items[i].angle <= maxAngle)
{
filteredData.push_back(items[i]);
}
}
return filteredData;
}
std::vector<ScanItem> ScanItemFilter::filterMidAngle(std::vector<ScanItem> items, double angleFromCenter)
{
std::vector<ScanItem> filteredData;
for (unsigned int i = 0; i < items.size(); i++)
{
if (fabs(items[i].angle) >= angleFromCenter)
{
filteredData.push_back(items[i]);
}
}
return filteredData;
}
bool RegressionAnalysis::calculateCoefficient(std::vector<ScanItem> items, double& center, double& a, double &b)
{
double Sxx = 0.0;
double Sxy = 0.0;
double Syy = 0.0;
double xm = 0.0;
double ym = 0.0;
center = 0;
a = 0;
b = 0;
if (items.size() == 0)
{
return false;
}
//std::cout << "Items: " << items.size() << std::endl;
for (unsigned int i = 0; i < items.size(); i++)
{
ScanItem it = items[i];
xm += it.x();
ym += it.y();
//std::cout << "Item : " << it.x() << ", " << it.y() << " - " << it.angle << " - " << it.distance << std::endl;
}
xm /= items.size();
ym /= items.size();
for (unsigned int i = 0; i < items.size(); i++)
{
ScanItem it = items[i];
Sxx += (it.x() - xm) * (it.x() - xm);
Sxy += (it.x() - xm) * (it.y() - ym);
Syy += (it.y() - ym) * (it.y() - ym);
}
//std::cout << "Sxx: " << Sxx << std::endl;
//std::cout << "Sxy: " << Sxy << std::endl;
//std::cout << "Syy: " << Syy << std::endl;
//b = Sxx / Sxy;
b = Sxy / Syy;
a = xm - b * ym;
center = ym;
//std::cout << "a: " << a << std::endl;
//std::cout << "b: " << b << std::endl;
//std::cout << "center: " << ym << std::endl;
return true;
}
}
| true |
11edda205d66fd6c919ef754efa52e311c83a53e
|
C++
|
thejosess/Informatica-UGR
|
/2ºAÑO/1ºCuatrimestre/ED/Practicas/practica3/duda sobre cola.cpp
|
UTF-8
| 4,926 | 3.765625 | 4 |
[] |
no_license
|
#include<stack>
#include<iostream>
using namespace std ;
template<typename T>
struct celda_cola{
T valor ;
T maximo ;
} ;
template<typename T>
class Cola_max{
private:
stack<celda_cola<T> > pila_cola, auxiliar ;
public:
/*Una cola dispone de front*, back*, push*, pop*, size* y empty**/
/*Se traducirán a frente, dorso, poner, quitar, num_elementos y vacio*/
/*Además añadiremos el método maximo* */
bool vacio() const{
return pila_cola.empty() ;
}
size_t num_elementos() const{
return pila_cola.size() ;
}
T & dorso (){
return pila_cola.top() ;
}
const T & dorso() const{
return pila_cola.top() ;
}
T & frente (){
celda_cola<T> item_frente ;
while(!pila_cola.empty()){
auxiliar.push(pila_cola.top()) ;
pila_cola.pop() ;
}
item_frente = auxiliar.top();
while(!auxiliar.empty()){
pila_cola.push(auxiliar.top()) ;
auxiliar.pop() ;
}
return item_frente.valor ;
}
const T & frente() const{
celda_cola<T> item_frente ;
while(!pila_cola.empty()){
auxiliar.push(pila_cola.top()) ;
pila_cola.pop() ;
}
item_frente = auxiliar.top();
while(!auxiliar.empty()){
pila_cola.push(auxiliar.top()) ;
auxiliar.pop() ;
}
return item_frente.valor ;
}
T maximo() const{
return pila_cola.top().maximo ;
}
void poner (T introducido){
celda_cola<T> a_introducir ;
a_introducir.valor = introducido ;
a_introducir.maximo = introducido ;
auxiliar.push(a_introducir) ; /*Violacion de segmento aqui*/
if(introducido > pila_cola.top().maximo){
while(!pila_cola.empty()){
pila_cola.top().maximo = introducido ;
auxiliar.push(pila_cola.top());
pila_cola.pop() ;
}
}
while(!auxiliar.empty()){
pila_cola.push(auxiliar.top()) ;
auxiliar.pop() ;
}
}
void quitar (){
T max_anterior = pila_cola.top().maximo ;
pila_cola.pop() ;
if(pila_cola.top().valor < max_anterior){
while(!pila_cola.empty()){
max_anterior = pila_cola.top().valor ;
pila_cola.top().maximo = max_anterior ;
auxiliar.push(pila_cola.top());
pila_cola.pop() ;
}
while(!auxiliar.empty()){
pila_cola.push(auxiliar.top()) ;
auxiliar.pop() ;
}
}
}
};
int main(){
Cola_max <int> p;
p.poner(2);
cout << "Se introduce el valor 2. El maximo es " << p.maximo() << endl;
p.poner(5);
cout << "Se introduce el valor 5. El maximo es " << p.maximo() << endl;
p.poner(4);
cout << "Se introduce el valor 4. El maximo es " << p.maximo() << endl;
p.poner(9);
cout << "Se introduce el valor 9. El maximo es " << p.maximo() << endl;
p.poner(7);
cout << "Se introduce el valor 7. El maximo es " << p.maximo() << endl;
p.poner(8);
cout << "Se introduce el valor 8. El maximo es " << p.maximo() << endl;
cout << "La cola tiene " << p.num_elementos() << " elementos. ";
cout << "El maximo es " << p.maximo() << endl;
while(!p.vacio()){
cout << "El frente contiene " << p.frente() << ". ";
cout << "El maximo es " << p.maximo() << ". ";
p.quitar();
cout << "Se quita este valor" << endl;
}
Cola_max <float> q;
q.poner(2.4);
cout << "Se introduce el valor 2.4. El maximo es " << q.maximo() << endl;
q.poner(5.5);
cout << "Se introduce el valor 5.5. El maximo es " << q.maximo() << endl;
q.poner(4.1);
cout << "Se introduce el valor 4.1. El maximo es " << q.maximo() << endl;
q.poner(9.6);
cout << "Se introduce el valor 9.6. El maximo es " << q.maximo() << endl;
q.poner(7.9);
cout << "Se introduce el valor 7.9. El maximo es " << q.maximo() << endl;
q.poner(8.3);
cout << "Se introduce el valor 8.3. El maximo es " << q.maximo() << endl;
cout << "La cola tiene " << q.num_elementos() << " elementos. ";
cout << "El maximo es " << q.maximo() << endl;
while(!q.vacio()){
cout << "El frente contiene " << q.frente() << ". ";
cout << "El maximo es " << q.maximo() << ". ";
q.quitar();
cout << "Se quita este valor" << endl;
}
return 0;
}
| true |
dc05109e6d24cb705db295a980fbaae9972f9191
|
C++
|
nagraw01/ads1
|
/pr4/Project4/Project4/Project4/FindPack/FindPack.cpp
|
UTF-8
| 1,297 | 3.078125 | 3 |
[] |
no_license
|
#include "FindPack.h"
using namespace std;
void FindPack::readPackages(string s)
{
std::string PATH = s;
DIR *dir = opendir(PATH);
struct dirent *entry = readdir(dir);// reading the directory
while (entry != NULL)// for each content of directory
{
if (entry->d_type == DT_DIR) {// checking if it is a folder
std::string pathIN;
string dir_name(entry->d_name);// dir_name is the variable for each content of directory
pathIN = PATH + dir_name;
DIR *dirIN = opendir(pathIN);
int hncpp = 1;
struct dirent *entryIN = readdir(dirIN);
while (entryIN != NULL && hncpp != 3) {//for each content of package
string file_name(entryIN->d_name);
if (file_name.compare(dir_name + ".h") == 0) {//check if it has a header file
++hncpp;
}
if (file_name.compare(dir_name + ".cpp") == 0) {//check if it has a cpp file
++hncpp;
}
entryIN = readdir(dirIN);
}
closedir(dirIN);
if (hncpp == 3) {// as stated in the problem...only considered a package if both
//header and cpp files are there
pack.push_back(entry->d_name);
}
}
entry = readdir(dir);
}
//displayg the packages
display_pack();
closedir(dir);
}
void FindPack::display_pack() {
for (string k : pack) {
cout << k << endl;
}
}
| true |
4bc46156e21a0810d400b6788bd4864160f89aa2
|
C++
|
madeso/infofile
|
/src/infofile/infofile.test.cc
|
UTF-8
| 28,571 | 2.859375 | 3 |
[
"Zlib",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
#include <cstring>
#include "catch.hpp"
#include "catchy/stringeq.h"
#include "infofile/infofile.h"
using namespace infofile;
TEST_CASE("testparsing", "[infofile]")
{
std::vector<std::string> errors;
std::shared_ptr<infofile::Node> val = infofile::Parse("inline", "{key=value;}", &errors);
REQUIRE(catchy::StringEq(errors, {}));
REQUIRE(val != nullptr);
REQUIRE(1 == val->children.size());
CHECK("key" == val->children[0]->name);
CHECK("value" == val->children[0]->value);
}
TEST_CASE("testparsing_opass", "[infofile]")
{
std::vector<std::string> errors;
std::shared_ptr<infofile::Node> val = infofile::Parse("inline", "{key value;}", &errors);
REQUIRE(catchy::StringEq(errors, {}));
REQUIRE(val != nullptr);
REQUIRE(1 == val->children.size());
CHECK("key" == val->children[0]->name);
CHECK("value" == val->children[0]->value);
}
TEST_CASE("testparsing_osep", "[infofile]")
{
std::vector<std::string> errors;
std::shared_ptr<infofile::Node> val = infofile::Parse("inline", "{key value}", &errors);
REQUIRE(catchy::StringEq(errors, {}));
REQUIRE(val != nullptr);
REQUIRE(1 == val->children.size());
CHECK("key" == val->children[0]->name);
CHECK("value" == val->children[0]->value);
}
TEST_CASE("testparsing_twokeys", "[infofile]")
{
std::vector<std::string> errors;
std::shared_ptr<infofile::Node> val = infofile::Parse("inline", "{key value k v}", &errors);
REQUIRE(catchy::StringEq(errors, {}));
REQUIRE(val != nullptr);
REQUIRE(2 == val->children.size());
CHECK("key" == val->children[0]->name);
CHECK("value" == val->children[0]->value);
CHECK("k" == val->children[1]->name);
CHECK("v" == val->children[1]->value);
}
TEST_CASE("testparsing_array", "[infofile]")
{
std::vector<std::string> errors;
std::shared_ptr<infofile::Node> val = infofile::Parse("inline", "[value v]", &errors);
REQUIRE(catchy::StringEq(errors, {}));
REQUIRE(val != nullptr);
REQUIRE(2 == val->children.size());
CHECK("" == val->children[0]->name);
CHECK("value" == val->children[0]->value);
CHECK("" == val->children[1]->name);
CHECK("v" == val->children[1]->value);
}
TEST_CASE("testparsing_array_sep_comma", "[infofile]")
{
std::vector<std::string> errors;
std::shared_ptr<infofile::Node> val = infofile::Parse("inline", "[value, v]", &errors);
REQUIRE(catchy::StringEq(errors, {}));
REQUIRE(val != nullptr);
REQUIRE(2 == val->children.size());
CHECK("" == val->children[0]->name);
CHECK("value" == val->children[0]->value);
CHECK("" == val->children[1]->name);
CHECK("v" == val->children[1]->value);
}
TEST_CASE("testparsing_array_sep_semicolon", "[infofile]")
{
std::vector<std::string> errors;
std::shared_ptr<infofile::Node> val = infofile::Parse("inline", "[value; v;]", &errors);
REQUIRE(catchy::StringEq(errors, {}));
REQUIRE(val != nullptr);
REQUIRE(2 == val->children.size());
CHECK("" == val->children[0]->name);
CHECK("value" == val->children[0]->value);
CHECK("" == val->children[1]->name);
CHECK("v" == val->children[1]->value);
}
TEST_CASE("testparsing_subkey", "[infofile]")
{
std::vector<std::string> errors;
std::shared_ptr<infofile::Node> val = infofile::Parse("inline", "[{key value}]", &errors);
REQUIRE(catchy::StringEq(errors, {}));
REQUIRE(val != nullptr);
REQUIRE(1 == val->children.size());
REQUIRE(val != nullptr);
std::shared_ptr<Node> n = val->children[0];
CHECK("" == n->name);
CHECK("" == n->value);
REQUIRE(1 == n->children.size());
CHECK("key" == n->children[0]->name);
CHECK("value" == n->children[0]->value);
}
TEST_CASE("testparsing_subkey_multiple", "[infofile]")
{
std::vector<std::string> errors;
std::shared_ptr<infofile::Node> val = infofile::Parse("inline", "[{a aa} {b bb}]", &errors);
REQUIRE(catchy::StringEq(errors, {}));
REQUIRE(val != nullptr);
REQUIRE(2 == val->children.size());
CHECK("" == val->name);
CHECK("" == val->value);
// array 0 -> struct 0
REQUIRE(1 == val->children[0]->children.size());
CHECK("a" == val->children[0]->children[0]->name);
CHECK("aa" == val->children[0]->children[0]->value);
// array 1 -> struct 0
REQUIRE(1 == val->children[1]->children.size());
CHECK("b" == val->children[1]->children[0]->name);
CHECK("bb" == val->children[1]->children[0]->value);
}
TEST_CASE("testparsing_subkey_multiple_comma", "[infofile]")
{
std::vector<std::string> errors;
std::shared_ptr<infofile::Node> val = infofile::Parse("inline", "[{a aa}, {b bb}]", &errors);
REQUIRE(catchy::StringEq(errors, {}));
REQUIRE(val != nullptr);
REQUIRE(2 == val->children.size());
CHECK("" == val->name);
CHECK("" == val->value);
// array 0 -> struct 0
REQUIRE(1 == val->children[0]->children.size());
CHECK("a" == val->children[0]->children[0]->name);
CHECK("aa" == val->children[0]->children[0]->value);
// array 1 -> struct 0
REQUIRE(1 == val->children[1]->children.size());
CHECK("b" == val->children[1]->children[0]->name);
CHECK("bb" == val->children[1]->children[0]->value);
}
TEST_CASE("testparsing_subkey_multiple_semicolon", "[infofile]")
{
std::vector<std::string> errors;
std::shared_ptr<infofile::Node> val = infofile::Parse("inline", "[{a aa}; {b bb};]", &errors);
REQUIRE(catchy::StringEq(errors, {}));
REQUIRE(val != nullptr);
REQUIRE(2 == val->children.size());
CHECK("" == val->name);
CHECK("" == val->value);
// array 0 -> struct 0
REQUIRE(1 == val->children[0]->children.size());
CHECK("a" == val->children[0]->children[0]->name);
CHECK("aa" == val->children[0]->children[0]->value);
// array 1 -> struct 0
REQUIRE(1 == val->children[1]->children.size());
CHECK("b" == val->children[1]->children[0]->name);
CHECK("bb" == val->children[1]->children[0]->value);
}
TEST_CASE("test_basic_string", "[infofile]")
{
std::vector<std::string> errors;
std::shared_ptr<infofile::Node> val = infofile::Parse("inline", "{\"'key'\"=\"value\";}", &errors);
REQUIRE(catchy::StringEq(errors, {}));
REQUIRE(val != nullptr);
REQUIRE(1 == val->children.size());
CHECK("'key'" == val->children[0]->name);
CHECK("value" == val->children[0]->value);
}
TEST_CASE("test_advanced_string", "[infofile]")
{
std::vector<std::string> errors;
std::shared_ptr<infofile::Node> val = infofile::Parse("inline", "{\"key\\n\\t\"=\"value\\\"\";}", &errors);
REQUIRE(catchy::StringEq(errors, {}));
REQUIRE(val != nullptr);
REQUIRE(1 == val->children.size());
CHECK("key\n\t" == val->children[0]->name);
CHECK("value\"" == val->children[0]->value);
}
TEST_CASE("test_basic_string_single", "[infofile]")
{
std::vector<std::string> errors;
std::shared_ptr<infofile::Node> val = infofile::Parse("inline", "{'\"key\"'='value is nice';}", &errors);
REQUIRE(catchy::StringEq(errors, {}));
REQUIRE(val != nullptr);
REQUIRE(1 == val->children.size());
CHECK("\"key\"" == val->children[0]->name);
CHECK("value is nice" == val->children[0]->value);
}
TEST_CASE("test_verbatim_string", "[infofile]")
{
std::vector<std::string> errors;
std::shared_ptr<infofile::Node> val = infofile::Parse("inline", "{path @\"c:\\Docs\\Source\\a.txt\";}", &errors);
REQUIRE(catchy::StringEq(errors, {}));
REQUIRE(val != nullptr);
REQUIRE(1 == val->children.size());
CHECK("path" == val->children[0]->name);
CHECK("c:\\Docs\\Source\\a.txt" == val->children[0]->value);
}
TEST_CASE("test_verbatim_string_tricky", "[infofile]")
{
std::vector<std::string> errors;
std::shared_ptr<infofile::Node> val = infofile::Parse("inline", "{path @\"c:\\Docs\\Source\\\";}", &errors);
REQUIRE(catchy::StringEq(errors, {}));
REQUIRE(val != nullptr);
REQUIRE(1 == val->children.size());
CHECK("path" == val->children[0]->name);
CHECK("c:\\Docs\\Source\\" == val->children[0]->value);
}
TEST_CASE("test_verbatim_double_quotes", "[infofile]")
{
std::vector<std::string> errors;
std::string src = "{line @\"\"\"Ahoy!\"\" cried the captain.\";}";
std::shared_ptr<infofile::Node> val = infofile::Parse("inline", src, &errors);
REQUIRE(catchy::StringEq(errors, {}));
REQUIRE(val != nullptr);
REQUIRE(1 == val->children.size());
CHECK("line" == val->children[0]->name);
CHECK("\"Ahoy!\" cried the captain." == val->children[0]->value);
}
TEST_CASE("test_verbatim_char", "[infofile]")
{
std::vector<std::string> errors;
std::shared_ptr<infofile::Node> val = infofile::Parse("inline", "{path @'c:\\Docs\\Source\\a.txt';}", &errors);
REQUIRE(catchy::StringEq(errors, {}));
REQUIRE(val != nullptr);
REQUIRE(1 == val->children.size());
CHECK("path" == val->children[0]->name);
CHECK("c:\\Docs\\Source\\a.txt" == val->children[0]->value);
}
TEST_CASE("test_verbatim_char_tricky", "[infofile]")
{
std::vector<std::string> errors;
std::shared_ptr<infofile::Node> val = infofile::Parse("inline", "{path @'c:\\Docs\\Source\\\';}", &errors);
REQUIRE(catchy::StringEq(errors, {}));
REQUIRE(val != nullptr);
REQUIRE(1 == val->children.size());
CHECK("path" == val->children[0]->name);
CHECK("c:\\Docs\\Source\\" == val->children[0]->value);
}
TEST_CASE("test_verbatim_char_double_quotes", "[infofile]")
{
std::vector<std::string> errors;
std::string src = "{line @'''Ahoy!'' cried the captain.';}";
std::shared_ptr<infofile::Node> val = infofile::Parse("inline", src, &errors);
REQUIRE(catchy::StringEq(errors, {}));
REQUIRE(val != nullptr);
REQUIRE(1 == val->children.size());
CHECK("line" == val->children[0]->name);
CHECK("'Ahoy!' cried the captain." == val->children[0]->value);
}
TEST_CASE("test_multiline_string_basic", "[infofile]")
{
std::vector<std::string> errors;
std::string src = "{line \"\"\"this is a long string\"\"\"}";
std::shared_ptr<infofile::Node> val = infofile::Parse("inline", src, &errors);
REQUIRE(catchy::StringEq(errors, {}));
REQUIRE(val != nullptr);
REQUIRE(1 == val->children.size());
CHECK("line" == val->children[0]->name);
CHECK("this is a long string" == val->children[0]->value);
}
TEST_CASE("test_multiline_string_newlines", "[infofile]")
{
std::vector<std::string> errors;
std::string src = "{line \"\"\"this\nis\na\nlong\nstring\tright?\"\"\"}";
std::shared_ptr<infofile::Node> val = infofile::Parse("inline", src, &errors);
REQUIRE(catchy::StringEq(errors, {}));
REQUIRE(val != nullptr);
REQUIRE(1 == val->children.size());
CHECK("line" == val->children[0]->name);
CHECK("this\nis\na\nlong\nstring\tright?" == val->children[0]->value);
}
TEST_CASE("test_newline_in_string_error", "[infofile]")
{
std::vector<std::string> errors;
std::string src = "{line \"hello\nworld\"}";
std::shared_ptr<infofile::Node> val = infofile::Parse("inline", src, &errors);
const unsigned int ZERO = 0;
REQUIRE(errors.size() > ZERO);
// todo(Gustav): error is always nullptr?
// REQUIRE(val == nullptr);
}
TEST_CASE("test_newline_in_char_error", "[infofile]")
{
std::vector<std::string> errors;
std::string src = "{line 'hello\nworld'}";
std::shared_ptr<infofile::Node> val = infofile::Parse("inline", src, &errors);
const unsigned int ZERO = 0;
REQUIRE(errors.size() > ZERO);
// todo(Gustav): error is always nullptr?
// REQUIRE(val == nullptr);
}
TEST_CASE("test_newline_in_verbatim_string_error", "[infofile]")
{
std::vector<std::string> errors;
std::string src = "{line @\"hello\nworld\"}";
std::shared_ptr<infofile::Node> val = infofile::Parse("inline", src, &errors);
const unsigned int ZERO = 0;
REQUIRE(errors.size() > ZERO);
// todo(Gustav): error is always nullptr?
// REQUIRE(val == nullptr);
}
TEST_CASE("test_newline_in_verbatim_char_error", "[infofile]")
{
std::vector<std::string> errors;
std::string src = "{line @'hello\nworld'}";
std::shared_ptr<infofile::Node> val = infofile::Parse("inline", src, &errors);
const unsigned int ZERO = 0;
REQUIRE(errors.size() > ZERO);
// todo(Gustav): error is always nullptr?
// REQUIRE(val == nullptr);
}
TEST_CASE("test_here_doc", "[infofile]")
{
std::vector<std::string> errors;
// when heredoc ends they ignore everything to the newline, therefore
// we need the extra newline or the source will not parse and complain
// about a EOF error
std::string src = "{line <<EOF dog\nHello world EOF\ncat\nEOF dog=cat\n}";
std::shared_ptr<infofile::Node> val = infofile::Parse("inline", src, &errors);
REQUIRE(catchy::StringEq(errors, {}));
REQUIRE(val != nullptr);
REQUIRE(1 == val->children.size());
CHECK("line" == val->children[0]->name);
CHECK("Hello world EOF\ncat" == val->children[0]->value);
}
TEST_CASE("test_heredoc_error_eof", "[infofile]")
{
std::vector<std::string> errors;
std::string src = "{line <<EOF dog\nHello world EOF\ncat\nEOF dog=cat}";
std::shared_ptr<infofile::Node> val = infofile::Parse("inline", src, &errors);
const unsigned int ZERO = 0;
REQUIRE(errors.size() > ZERO);
// todo(Gustav): error is always nullptr?
// REQUIRE(val == nullptr);
}
TEST_CASE("test_heredoc_error_noname", "[infofile]")
{
std::vector<std::string> errors;
std::string src = "{line <<EOF\ndog\nHello world EOF\ncat\nEOF dog=cat}";
std::shared_ptr<infofile::Node> val = infofile::Parse("inline", src, &errors);
const unsigned int ZERO = 0;
REQUIRE(errors.size() > ZERO);
// todo(Gustav): error is always nullptr?
// REQUIRE(val == nullptr);
}
TEST_CASE("test_singleline_comment", "[infofile]")
{
std::vector<std::string> errors;
std::string src = "{// this is a comment\nline dog}";
std::shared_ptr<infofile::Node> val = infofile::Parse("inline", src, &errors);
REQUIRE(catchy::StringEq(errors, {}));
REQUIRE(val != nullptr);
REQUIRE(1 == val->children.size());
CHECK("line" == val->children[0]->name);
CHECK("dog" == val->children[0]->value);
}
TEST_CASE("test_multiline_comment_simple", "[infofile]")
{
std::vector<std::string> errors;
std::string src = "{line /*hello\nworld*/ dog}";
std::shared_ptr<infofile::Node> val = infofile::Parse("inline", src, &errors);
REQUIRE(catchy::StringEq(errors, {}));
REQUIRE(val != nullptr);
REQUIRE(1 == val->children.size());
CHECK("line" == val->children[0]->name);
CHECK("dog" == val->children[0]->value);
}
TEST_CASE("test_multiline_comment_complex", "[infofile]")
{
std::vector<std::string> errors;
std::string src = "{line /***\nhello/* cat dog */\nworld ***/ dog}";
std::shared_ptr<infofile::Node> val = infofile::Parse("inline", src, &errors);
REQUIRE(catchy::StringEq(errors, {}));
REQUIRE(val != nullptr);
REQUIRE(1 == val->children.size());
CHECK("line" == val->children[0]->name);
CHECK("dog" == val->children[0]->value);
}
TEST_CASE("test_combine", "[infofile]")
{
std::vector<std::string> errors;
std::string src = "{li + ne do \\ g}";
std::shared_ptr<infofile::Node> val = infofile::Parse("inline", src, &errors);
REQUIRE(catchy::StringEq(errors, {}));
REQUIRE(val != nullptr);
REQUIRE(1 == val->children.size());
CHECK("line" == val->children[0]->name);
CHECK("dog" == val->children[0]->value);
}
TEST_CASE("test_root_struct", "[infofile]")
{
std::vector<std::string> errors;
std::string src = "line dog";
std::shared_ptr<infofile::Node> val = infofile::Parse("inline", src, &errors);
REQUIRE(catchy::StringEq(errors, {}));
REQUIRE(val != nullptr);
REQUIRE(1 == val->children.size());
CHECK("line" == val->children[0]->name);
CHECK("dog" == val->children[0]->value);
}
TEST_CASE("test_unicode_characters", "[infofile]")
{
std::vector<std::string> errors;
std::string src = "'ナ' 'ㄅ'";
std::shared_ptr<infofile::Node> val = infofile::Parse("inline", src, &errors);
REQUIRE(catchy::StringEq(errors, {}));
REQUIRE(val != nullptr);
REQUIRE(1 == val->children.size());
CHECK("ナ" == val->children[0]->name);
CHECK("ㄅ" == val->children[0]->value);
}
TEST_CASE("test_number_basic", "[infofile]")
{
std::vector<std::string> errors;
std::string src = "[ 12 ]";
std::shared_ptr<infofile::Node> val = infofile::Parse("inline", src, &errors);
REQUIRE(catchy::StringEq(errors, {}));
REQUIRE(val != nullptr);
REQUIRE(1 == val->children.size());
CHECK("12" == val->children[0]->value);
}
TEST_CASE("test_number_double", "[infofile]")
{
std::vector<std::string> errors;
std::string src = "[ 25.6 ]";
std::shared_ptr<infofile::Node> val = infofile::Parse("inline", src, &errors);
REQUIRE(catchy::StringEq(errors, {}));
REQUIRE(val != nullptr);
REQUIRE(1 == val->children.size());
CHECK("25.6" == val->children[0]->value);
}
/*
Will have to investigate if we want to specify numbers this way, as it
// seems that parsing might be harder if we do
TEST_CASE("test_double_start_with_dot", "[infofile]")
{
std::vector<std::string> errors;
std::string src = "[ .42 ]";
std::shared_ptr<infofile::Node> val = infofile::Parse("inline", src, &errors);
REQUIRE(catchy::StringEq(errors, {}));
REQUIRE(val != nullptr);
REQUIRE(1 == val->children.size());
CHECK(".42" == val->children[0]->value);
}
*/
TEST_CASE("test_float", "[infofile]")
{
std::vector<std::string> errors;
std::string src = "[ 35f ]";
std::shared_ptr<infofile::Node> val = infofile::Parse("inline", src, &errors);
REQUIRE(catchy::StringEq(errors, {}));
REQUIRE(val != nullptr);
REQUIRE(1 == val->children.size());
CHECK("35f" == val->children[0]->value);
}
TEST_CASE("test_float_with_decimalpoint", "[infofile]")
{
std::vector<std::string> errors;
std::string src = "[ 12.3f ]";
std::shared_ptr<infofile::Node> val = infofile::Parse("inline", src, &errors);
REQUIRE(catchy::StringEq(errors, {}));
REQUIRE(val != nullptr);
REQUIRE(1 == val->children.size());
CHECK("12.3f" == val->children[0]->value);
}
//////////////////////////////////////////////////////////////////////////
TEST_CASE("test_negative_number_basic", "[infofile]")
{
std::vector<std::string> errors;
std::string src = "[ -12 ]";
std::shared_ptr<infofile::Node> val = infofile::Parse("inline", src, &errors);
REQUIRE(catchy::StringEq(errors, {}));
REQUIRE(val != nullptr);
REQUIRE(1 == val->children.size());
CHECK("-12" == val->children[0]->value);
}
TEST_CASE("test_negative_number_double", "[infofile]")
{
std::vector<std::string> errors;
std::string src = "[ -25.6 ]";
std::shared_ptr<infofile::Node> val = infofile::Parse("inline", src, &errors);
REQUIRE(catchy::StringEq(errors, {}));
REQUIRE(val != nullptr);
REQUIRE(1 == val->children.size());
CHECK("-25.6" == val->children[0]->value);
}
TEST_CASE("test_negative_float", "[infofile]")
{
std::vector<std::string> errors;
std::string src = "[ -35f ]";
std::shared_ptr<infofile::Node> val = infofile::Parse("inline", src, &errors);
REQUIRE(catchy::StringEq(errors, {}));
REQUIRE(val != nullptr);
REQUIRE(1 == val->children.size());
CHECK("-35f" == val->children[0]->value);
}
TEST_CASE("test_negative_float_with_decimalpoint", "[infofile]")
{
std::vector<std::string> errors;
std::string src = "[ -12.3f ]";
std::shared_ptr<infofile::Node> val = infofile::Parse("inline", src, &errors);
REQUIRE(catchy::StringEq(errors, {}));
REQUIRE(val != nullptr);
REQUIRE(1 == val->children.size());
CHECK("-12.3f" == val->children[0]->value);
}
TEST_CASE("test_advanced_ident", "[infofile]")
{
std::vector<std::string> errors;
std::string src = "jesus.opponent the.dude@gmail.com";
std::shared_ptr<infofile::Node> val = infofile::Parse("inline", src, &errors);
REQUIRE(catchy::StringEq(errors, {}));
REQUIRE(val != nullptr);
REQUIRE(1 == val->children.size());
CHECK("jesus.opponent" == val->children[0]->name);
CHECK("the.dude@gmail.com" == val->children[0]->value);
}
TEST_CASE("test_css_color", "[infofile]")
{
std::vector<std::string> errors;
std::string src = "#000 #12ffAA";
std::shared_ptr<infofile::Node> val = infofile::Parse("inline", src, &errors);
REQUIRE(catchy::StringEq(errors, {}));
REQUIRE(val != nullptr);
REQUIRE(1 == val->children.size());
CHECK("#000" == val->children[0]->name);
CHECK("#12ffAA" == val->children[0]->value);
}
TEST_CASE("test_underscore", "[infofile]")
{
std::vector<std::string> errors;
std::string src = "[hello_world]";
std::shared_ptr<infofile::Node> val = infofile::Parse("inline", src, &errors);
REQUIRE(catchy::StringEq(errors, {}));
REQUIRE(val != nullptr);
REQUIRE(1 == val->children.size());
CHECK("hello_world" == val->children[0]->value);
}
TEST_CASE("test_zero_escape", "[infofile]")
{
std::vector<std::string> errors;
std::string src = "[\"hello\\0world\"]";
std::shared_ptr<infofile::Node> val = infofile::Parse("inline", src, &errors);
REQUIRE(catchy::StringEq(errors, {}));
REQUIRE(val != nullptr);
REQUIRE(1 == val->children.size());
CHECK(11 == val->children[0]->value.size());
// REQUIRE(0 == std::memcmp("hello\0world", val->children[0]->value.data(), 11));
CHECK(catchy::StringEq(std::string("hello\0world", 11), val->children[0]->value));
}
TEST_CASE("test_empty_struct", "[infofile]")
{
std::vector<std::string> errors;
std::string src = "dog {}";
std::shared_ptr<infofile::Node> val = infofile::Parse("inline", src, &errors);
REQUIRE(catchy::StringEq(errors, {}));
REQUIRE(val != nullptr);
REQUIRE(1 == val->children.size());
CHECK("dog" == val->children[0]->name);
CHECK("" == val->children[0]->value);
CHECK(0 == val->children[0]->children.size());
}
TEST_CASE("test_empty_array", "[infofile]")
{
std::vector<std::string> errors;
std::string src = "dog []";
std::shared_ptr<infofile::Node> val = infofile::Parse("inline", src, &errors);
REQUIRE(catchy::StringEq(errors, {}));
REQUIRE(val != nullptr);
REQUIRE(1 == val->children.size());
CHECK("dog" == val->children[0]->name);
CHECK("" == val->children[0]->value);
CHECK(0 == val->children[0]->children.size());
}
TEST_CASE("test_advanced_struct", "[infofile]")
{
std::vector<std::string> errors;
std::string src = "key value {a b}";
std::shared_ptr<infofile::Node> val = infofile::Parse("inline", src, &errors);
REQUIRE(catchy::StringEq(errors, {}));
REQUIRE(val != nullptr);
REQUIRE(1 == val->children.size());
CHECK("key" == val->children[0]->name);
CHECK("value" == val->children[0]->value);
CHECK(1 == val->children[0]->children.size());
CHECK("a" == val->children[0]->children[0]->name);
CHECK("b" == val->children[0]->children[0]->value);
}
TEST_CASE("test_advanced_struct_with_assign", "[infofile]")
{
std::vector<std::string> errors;
std::string src = "key : value := {a b}";
std::shared_ptr<infofile::Node> val = infofile::Parse("inline", src, &errors);
REQUIRE(catchy::StringEq(errors, {}));
REQUIRE(val != nullptr);
REQUIRE(1 == val->children.size());
CHECK("key" == val->children[0]->name);
CHECK("value" == val->children[0]->value);
CHECK(1 == val->children[0]->children.size());
CHECK("a" == val->children[0]->children[0]->name);
CHECK("b" == val->children[0]->children[0]->value);
}
TEST_CASE("test_advanced_struct_with_assign_no_value", "[infofile]")
{
std::vector<std::string> errors;
std::string src = "key := {a b}";
std::shared_ptr<infofile::Node> val = infofile::Parse("inline", src, &errors);
REQUIRE(catchy::StringEq(errors, {}));
REQUIRE(val != nullptr);
REQUIRE(1 == val->children.size());
CHECK("key" == val->children[0]->name);
CHECK("" == val->children[0]->value);
CHECK(1 == val->children[0]->children.size());
CHECK("a" == val->children[0]->children[0]->name);
CHECK("b" == val->children[0]->children[0]->value);
}
/*
Possible bad typos could exist bc of this, probably shouldn't be allowed
TEST_CASE("test_advanced_struct_with_assign_and_empty_value", "[infofile]")
{
std::vector<std::string> errors;
std::string src = "key : := {a b}";
std::shared_ptr<infofile::Node> val = infofile::Parse("inline", src, &errors);
REQUIRE(catchy::StringEq(errors, {}));
REQUIRE(val != nullptr);
REQUIRE(1 == val->children.size());
CHECK("key" == val->name);
CHECK("" == val->value);
CHECK(1 == val->children.size());
REQUIRE(val->children != nullptr);
CHECK("a" == val->children->name);
CHECK("b" == val->children->value);
}
*/
TEST_CASE("test_advanced_array", "[infofile]")
{
std::vector<std::string> errors;
std::string src = "key value [a]";
std::shared_ptr<infofile::Node> val = infofile::Parse("inline", src, &errors);
REQUIRE(catchy::StringEq(errors, {}));
REQUIRE(val != nullptr);
REQUIRE(1 == val->children[0]->children.size());
CHECK("key" == val->children[0]->name);
CHECK("value" == val->children[0]->value);
CHECK(1 == val->children[0]->children.size());
CHECK("" == val->children[0]->children[0]->name);
CHECK("a" == val->children[0]->children[0]->value);
}
TEST_CASE("test_advanced_array_with_assign", "[infofile]")
{
std::vector<std::string> errors;
std::string src = "key : value := [a]";
std::shared_ptr<infofile::Node> val = infofile::Parse("inline", src, &errors);
REQUIRE(catchy::StringEq(errors, {}));
REQUIRE(val != nullptr);
REQUIRE(1 == val->children.size());
CHECK("key" == val->children[0]->name);
CHECK("value" == val->children[0]->value);
CHECK(1 == val->children[0]->children.size());
CHECK("" == val->children[0]->children[0]->name);
CHECK("a" == val->children[0]->children[0]->value);
}
TEST_CASE("test_advanced_array_with_assign_no_value", "[infofile]")
{
std::vector<std::string> errors;
std::string src = "key := [a]";
std::shared_ptr<infofile::Node> val = infofile::Parse("inline", src, &errors);
REQUIRE(catchy::StringEq(errors, {}));
REQUIRE(val != nullptr);
REQUIRE(1 == val->children.size());
CHECK("key" == val->children[0]->name);
CHECK("" == val->children[0]->value);
CHECK(1 == val->children[0]->children.size());
CHECK("" == val->children[0]->children[0]->name);
CHECK("a" == val->children[0]->children[0]->value);
}
TEST_CASE("test_octal", "[infofile]")
{
std::vector<std::string> errors;
std::string src = "[ 0042 ]";
std::shared_ptr<infofile::Node> val = infofile::Parse("inline", src, &errors);
REQUIRE(catchy::StringEq(errors, {}));
REQUIRE(val != nullptr);
REQUIRE(1 == val->children.size());
CHECK("0042" == val->children[0]->value);
}
TEST_CASE("test_hexadecimal", "[infofile]")
{
std::vector<std::string> errors;
std::string src = "[ 0xaeF2 ]";
std::shared_ptr<infofile::Node> val = infofile::Parse("inline", src, &errors);
REQUIRE(catchy::StringEq(errors, {}));
REQUIRE(val != nullptr);
REQUIRE(1 == val->children.size());
CHECK("0xaeF2" == val->children[0]->value);
}
TEST_CASE("test_binary", "[infofile]")
{
std::vector<std::string> errors;
std::string src = "[ 0b00010000 ]";
std::shared_ptr<infofile::Node> val = infofile::Parse("inline", src, &errors);
REQUIRE(catchy::StringEq(errors, {}));
REQUIRE(val != nullptr);
REQUIRE(1 == val->children.size());
CHECK("0b00010000" == val->children[0]->value);
}
/*
// todo: implement unicode escape characters
// taken from here https://github.com/dropbox/json11/blob/master/test.cpp
TEST_CASE("test_unicode_escape", "[infofile]")
{
const std::string src =
R"([ "blah\ud83d\udca9blah\ud83dblah\udca9blah\u0000blah\u1234" ])";
const char utf8[] = "blah" "\xf0\x9f\x92\xa9" "blah" "\xed\xa0\xbd" "blah"
"\xed\xb2\xa9" "blah" "\0" "blah" "\xe1\x88\xb4";
std::vector<std::string> errors;
std::shared_ptr<infofile::Node> uni = infofile::Parse("inline", src, &errors);
REQUIRE(catchy::StringEq(errors, {}));
REQUIRE(uni != nullptr);
REQUIRE(1 == uni->children.size());
}
*/
| true |
d09192af1899e3dbd49e08ede09e8a55223504a6
|
C++
|
erikwilson/CactusCon7
|
/badge/badge/WiFi.ino
|
UTF-8
| 400 | 2.578125 | 3 |
[] |
no_license
|
bool turnWiFiOnAndConnect() {
WiFi.mode(WIFI_STA);
WiFi.begin(WLAN_SSID, WLAN_PASSWD);
Serial.print(F("Bringing up wifi please wait"));
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
IPAddress ip = WiFi.localIP();
Serial.println(F("DONE"));
Serial.print(F("My IP address:"));
Serial.println(ip);
}
bool turnWiFiOff() {
WiFi.mode(WIFI_OFF);
}
| true |
de726da21202748fc75064b2c8cec8895d7f5503
|
C++
|
DChang87/Competitive-Programming-Solutions
|
/Cow Photography Bronze.cpp
|
UTF-8
| 3,981 | 3.625 | 4 |
[] |
no_license
|
/*Utilizing sorting function in C++
The cows are in a particularly mischievous mood today! All Farmer John wants to do is take a photograph of
the cows standing in a line, but they keep moving right before he has a chance to snap the picture.
Specifically, FJ's N (1 <= N <= 20,000) cows are tagged with ID numbers 1...N. FJ wants to take a picture of
the cows standing in a line in a very specific ordering, represented by the contents of an array A[1...N],
where A[j] gives the ID number of the jth cow in the ordering. He arranges the cows in this order, but
just before he can press the button on his camera to snap the picture, up to one cow moves to a new position in the
lineup. More precisely, either no cows move, or one cow vacates her current position in the lineup and then
re-inserts herself at a new position in the lineup. Frustrated but not deterred, FJ again arranges his cows according
to the ordering in A, but again, right before he can snap a picture, up to one cow (different from the first)
moves to a new position in the lineup.
The process above repeats for a total of five photographs before FJ gives up. Given the contents of each
photograph, see if you can reconstruct the original intended ordering A. Each photograph shows an ordering of the
cows in which up to one cow has moved to a new location, starting from the initial ordering in A. Moreover, if a
cow opts to move herself to a new location in one of the photographs, then she does not actively move in any
of the other photographs (although she can end up at a different position due to other cows moving, of course).
//Solution Notes: There are several ways to approach this problem. Perhaps the simplest (which also solves the harder
silver/gold variant of this problem where multiple cows can move in each photo) is just to sort, as shown in the code below.
Sorting requires that we can compare two cows A and B to tell which should go first. Fortunately, if we look at any two cows
A and B, they will be in the correct relative order in at least 3 of the 5 photographs, since movements of other cows
will not change the relative ordering of A and B -- only movement of A or B can change their relative order, and A
and B can themselves move in at most 2 of photos. We can therefore compare any pair (A,B) by taking a "majority vote"
based on their relative order in all 5 photographs (i.e., A < B if A precedes B in at least 3 of the 5 photos).
The code below uses a "map" to record the position in each ordering of each cow based on its ID number; this
approach is nice because it does not need to assume the ID numbers are small consecutive integers; however,
since we know our ID numbers are 1...N, a simple array would have worked also for this task.
//Since we know that at most one cow moves per photo in this problem, other solutions exist, some of them even more
efficient than the O(n log n) sorting approach above. For example, the "correct" first cow must appear in one of the
first two positions in at least 4 of the 5 photos. If there is only one cow satisfying this property, we place it first
in the final output and continue. Otherwise, if there are two cows satisfying this property, we compare them as above and
place the correct cow first, continuing in this fashion as we output all the cows in the correct order in only O(n) total time.
*/
#include <iostream>
#include <algorithm>
#include <map>
#include <cstdio>
using namespace std;
#define MAXN 20000
int A[MAXN];
map<int, int> pos[5];
bool cmp(int a, int b) {
int f = 0;
for(int i = 0; i < 5; i++) {
f += pos[i][a] < pos[i][b];
}
return f > 2;
}
int main() {
freopen("photo.in", "r", stdin);
freopen("photo.out", "w", stdout);
int N; cin >> N;
for(int i = 0; i < 5; i++) {
for(int j = 0; j < N; j++) {
int x; cin >> x;
pos[i][x] = j;
A[j] = x;
}
}
sort(A, A + N, cmp);
for(int i = 0; i < N; i++) {
cout << A[i] << '\n';
}
}
| true |
9dc18bb840edf24aad82376a7c37b53c13c0cffd
|
C++
|
karmazynow-a/dijkstraMPI
|
/Dijkstra/DijkstraCommon/DijkstraAlgorithmBackend.cpp
|
UTF-8
| 2,379 | 2.703125 | 3 |
[
"MIT"
] |
permissive
|
#include "DijkstraAlgorithmBackend.h"
#include <utility>
DijkstraAlgorithmBackend::DijkstraAlgorithmBackend(const std::pair<int, int>& verticesToHandleRange, int totalNumberOfVertices, int sourceVertexIndex) :
verticesToHandleRange(verticesToHandleRange),
distances(verticesToHandleRange.second - verticesToHandleRange.first + 1, std::numeric_limits<double>::infinity()),
predecessors(verticesToHandleRange.second - verticesToHandleRange.first + 1, -1),
totalNumberOfVertices(totalNumberOfVertices)
{
if (sourceVertexIndex >= verticesToHandleRange.first && sourceVertexIndex <= verticesToHandleRange.second) {
distances.at(sourceVertexIndex - verticesToHandleRange.first) = 0;
}
}
VertexData DijkstraAlgorithmBackend::findVertexWithMinimalDistanceToCluster() {
int closestVertex = -1;
double shortestDistance = std::numeric_limits<double>::infinity();
for (int i = 0; i < distances.size(); ++i) {
if (processedVerticesCluster.find(i + verticesToHandleRange.first) == processedVerticesCluster.end()) {
if (distances.at(i) < shortestDistance) {
closestVertex = verticesToHandleRange.first + i;
shortestDistance = distances.at(i);
}
}
}
return (closestVertex != -1
? createVertexDataInstance(distances.at(closestVertex - verticesToHandleRange.first), closestVertex)
: createVertexDataInstance());
}
void DijkstraAlgorithmBackend::performInnerForLoop(const VertexData& vertexClosestToCluster, const std::vector<double>& processedPartOfAdjacencyMatrix) {
int numberOfVerticesToHandle = verticesToHandleRange.second - verticesToHandleRange.first + 1;
for (int i = 0; i < numberOfVerticesToHandle; ++i) {
// if vertex has already been processed, we skip it
if (processedVerticesCluster.find(verticesToHandleRange.first + i) != processedVerticesCluster.end()) {
continue;
}
double valueInMatrix = (processedPartOfAdjacencyMatrix.at(i * totalNumberOfVertices + vertexClosestToCluster.vertexNumber) < 0.001
? std::numeric_limits<double>::infinity()
: processedPartOfAdjacencyMatrix.at(i * totalNumberOfVertices + vertexClosestToCluster.vertexNumber));
double altDistance = valueInMatrix + vertexClosestToCluster.distance;
if (altDistance < distances.at(i)) {
distances.at(i) = altDistance;
predecessors.at(i) = vertexClosestToCluster.vertexNumber;
}
}
}
| true |