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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
2300ece83238e0fe51a66dba443618b803e660e4 | C++ | BrandtArcaneAviator/ProjectEuler | /Problem61_CyclicFigurateNumbers/AlternativeMethods.cpp | UTF-8 | 4,607 | 3.0625 | 3 | [] | no_license | ///* For loops for polygonal values: */
//for (lint_t trin{ 45 }; trin <= 140; ++trin)
//{
// tempTri = calculatePolygonalValue(trin, PolygonalType::triangular);
// for (lint_t squaren{ 32 }; squaren <= 99; ++squaren)
// {
// tempSquare = calculatePolygonalValue(squaren, PolygonalType::square);
// if (checkCyclicPair4digit(tempTri, tempSquare))
// {
// /* If true, move to next polygonal number: */
// for (lint_t pentn{ 26 }; pentn <= 81; ++pentn)
// {
// tempPent = calculatePolygonalValue(pentn, PolygonalType::pentagonal);
// if (checkCyclicPair4digit(tempSquare, tempPent))
// {
// for (lint_t hexn{ 23 }; hexn <= 70; ++hexn)
// {
// tempHex = calculatePolygonalValue(hexn, PolygonalType::hexagonal);
// if (checkCyclicPair4digit(tempPent, tempHex))
// {
// for (lint_t heptn{21}; heptn <= 63; ++heptn)
// {
// tempHept = calculatePolygonalValue(heptn, PolygonalType::heptagonal);
// if (checkCyclicPair4digit(tempHex, tempHept))
// {
// for (lint_t octn{19}; octn <= 58; ++octn)
// {
// tempOct = calculatePolygonalValue(octn, PolygonalType::octagonal);
// /* For last element in cycle, also check against first element: */
// if (checkCyclicPair4digit(tempHept, tempOct) && checkCyclicPair4digit(tempOct, tempTri))
// {
// /* If true, we've found the set so record it: */
// cyclicSet.at(0) = tempTri;
// cyclicSet.at(1) = tempSquare;
// cyclicSet.at(2) = tempPent;
// cyclicSet.at(3) = tempHex;
// cyclicSet.at(4) = tempHept;
// cyclicSet.at(5) = tempOct;
// setisFound = true;
// }
// if (setisFound)
// {
// break;
// }
// }
// }
//
// if (setisFound)
// {
// break;
// }
// }
// }
//
// if (setisFound)
// {
// break;
// }
// }
// }
//
// if (setisFound)
// {
// break;
// }
// }
// }
//
// if (setisFound)
// {
// break;
// }
// }
// if (setisFound)
// {
// break;
// }
//}
///* Alternate method including various permutations: */
//for (lint_t trin{ 45 }; trin <= 140; ++trin)
//{
// tempTri = calculatePolygonalValue(trin, PolygonalType::triangular);
// for (lint_t squaren{ 32 }; squaren <= 99; ++squaren)
// {
// tempSquare = calculatePolygonalValue(squaren, PolygonalType::square);
// for (lint_t pentn{ 26 }; pentn <= 81; ++pentn)
// {
// tempPent = calculatePolygonalValue(pentn, PolygonalType::pentagonal);
// for (lint_t hexn{ 23 }; hexn <= 70; ++hexn)
// {
// tempHex = calculatePolygonalValue(hexn, PolygonalType::hexagonal);
// for (lint_t heptn{ 21 }; heptn <= 63; ++heptn)
// {
// tempHept = calculatePolygonalValue(heptn, PolygonalType::heptagonal);
// for (lint_t octn{ 19 }; octn <= 58; ++octn)
// {
// tempOct = calculatePolygonalValue(octn, PolygonalType::octagonal);
// /* Now we set up a permutation: */
// cyclicSet.at(0) = tempTri;
// cyclicSet.at(1) = tempSquare;
// cyclicSet.at(2) = tempPent;
// cyclicSet.at(3) = tempHex;
// cyclicSet.at(4) = tempHept;
// cyclicSet.at(5) = tempOct;
// /* Now check this and all other possible permuations: */
// do
// {
// if (checkCyclicPair4digit(cyclicSet.at(0), cyclicSet.at(1)))
// {
// if (checkCyclicPair4digit(cyclicSet.at(1), cyclicSet.at(2)))
// {
// if (checkCyclicPair4digit(cyclicSet.at(2), cyclicSet.at(3)))
// {
// if (checkCyclicPair4digit(cyclicSet.at(3), cyclicSet.at(4)))
// {
// if (checkCyclicPair4digit(cyclicSet.at(4), cyclicSet.at(5)))
// {
// if (checkCyclicPair4digit(cyclicSet.at(5), cyclicSet.at(0)))
// {
// setisFound = true;
// break;
// }
// }
// }
// }
// }
// }
// } while (std::next_permutation(cyclicSet.begin(), cyclicSet.end()));
// if (setisFound)
// {
// break;
// }
// }
// if (setisFound)
// {
// break;
// }
// }
// if (setisFound)
// {
// break;
// }
// }
// if (setisFound)
// {
// break;
// }
// }
// if (setisFound)
// {
// break;
// }
// }
// if (setisFound)
// {
// break;
// }
//} | true |
5a27618e30f5498a919fd7f522580d4fd6dca5d0 | C++ | hassanjallow/isis3 | /src/base/objs/ObliqueCylindrical/unitTest.cpp | UTF-8 | 5,155 | 2.6875 | 3 | [
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-public-domain"
] | permissive | #include <iostream>
#include <iomanip>
#include <cmath>
#include "iException.h"
#include "ObliqueCylindrical.h"
#include "ProjectionFactory.h"
#include "Preference.h"
using namespace std;
int main (int argc, char *argv[]) {
Isis::Preference::Preferences(true);
cout << "UNIT TEST FOR ObliqueCylindrical" << endl << endl;
Isis::Pvl lab;
lab.AddGroup(Isis::PvlGroup("Mapping"));
Isis::PvlGroup &mapGrp = lab.FindGroup("Mapping");
mapGrp += Isis::PvlKeyword("EquatorialRadius",2575000.0);
mapGrp += Isis::PvlKeyword("PolarRadius",2575000.0);
mapGrp += Isis::PvlKeyword("PoleLatitude", 22.858149);
mapGrp += Isis::PvlKeyword("PoleLongitude", 297.158602);
mapGrp += Isis::PvlKeyword("LatitudeType","Planetocentric");
mapGrp += Isis::PvlKeyword("LongitudeDirection","PositiveWest");
mapGrp += Isis::PvlKeyword("LongitudeDomain",360);
mapGrp += Isis::PvlKeyword("ProjectionName","ObliqueCylindrical");
mapGrp += Isis::PvlKeyword("MinimumLatitude",-90);
mapGrp += Isis::PvlKeyword("MaximumLatitude",0.92523);
mapGrp += Isis::PvlKeyword("MinimumLongitude",-0.8235);
mapGrp += Isis::PvlKeyword("MaximumLongitude",180.5);
cout << "Test missing pole rotation keyword ..." << endl;
try {
Isis::ObliqueCylindrical p(lab);
}
catch (Isis::iException &e) {
e.Report(false);
}
cout << endl;
// Add the missing keyword "PoleRotation"
mapGrp += Isis::PvlKeyword("PoleRotation", 45.7832);
// testing operator ==
cout << "Testing operator == ..." << endl;
try {
Isis::ObliqueCylindrical p1(lab);
Isis::ObliqueCylindrical p2(lab);
bool flag = (p1 == p2);
if (flag) {
cout << "(p1==p2) = True" << endl;
}
else {
cout << "*** Error ****"<< endl;
}
}
catch (Isis::iException &e) {
e.Report(false);
}
cout << endl;
try {
Isis::Projection &p = *Isis::ProjectionFactory::Create(lab);
cout << "Test X,Y,Z Axis Vector Calculations ... " << endl;
cout << "Map Group Data (X[0]): " << (double)mapGrp["XAxisVector"][0] << endl;
cout << "Map Group Data (X[1]): " << (double)mapGrp["XAxisVector"][1] << endl;
cout << "Map Group Data (X[2]): " << (double)mapGrp["XAxisVector"][2] << endl;
cout << "Map Group Data (Y[0]): " << (double)mapGrp["YAxisVector"][0] << endl;
cout << "Map Group Data (Y[1]): " << (double)mapGrp["YAxisVector"][1] << endl;
cout << "Map Group Data (Y[2]): " << (double)mapGrp["YAxisVector"][2] << endl;
cout << "Map Group Data (Z[0]): " << (double)mapGrp["ZAxisVector"][0] << endl;
cout << "Map Group Data (Z[1]): " << (double)mapGrp["ZAxisVector"][1] << endl;
cout << "Map Group Data (Z[2]): " << (double)mapGrp["ZAxisVector"][2] << endl;
cout << endl;
const double X = -2646.237039, Y = -537.814519;
cout << setprecision(13);
cout << "Test SetCoordinate method ... " << endl;
cout << "Setting coordinate to (" << X << "," << Y << ")" << endl;
p.SetCoordinate(X,Y);
cout << "Latitude: " << p.Latitude() << endl;
cout << "Longitude: " << p.Longitude() << endl;
cout << "XCoord: " << p.XCoord() << endl;
cout << "YCoord: " << p.YCoord() << endl;
cout << endl;
cout << "Test SetGround method ... " << endl;
cout << std::setprecision(10);
cout << "Setting ground to (" << p.Latitude() << "," << p.Longitude() << ")" << endl;
p.SetGround(p.Latitude(),p.Longitude());
cout << "Latitude: " << p.Latitude() << endl;
cout << "Longitude: " << p.Longitude() << endl;
cout << "XCoord: " << p.XCoord() << endl;
cout << "YCoord: " << p.YCoord() << endl;
cout << endl;
cout << "Test XYRange method ... " << endl;
cout << std::setprecision(8);
double minX = 0.0,maxX = 1.0,minY = 2.0,maxY = 3.0;
p.XYRange(minX,maxX,minY,maxY);
cout << "\n\nMinimum X: " << minX << endl;
cout << "Maximum X: " << maxX << endl;
cout << "Minimum Y: " << minY << endl;
cout << "Maximum Y: " << maxY << endl;
cout << endl;
Isis::Projection *s = &p;
cout << "Test Name and comparision method ... " << endl;
cout << "Name: " << s->Name() << endl;
cout << "operator== " << (*s == *s) << endl;
cout << endl;
mapGrp["PoleRotation"] = 43.8423;
Isis::ObliqueCylindrical different(lab);
cout << "Test Name and comparision method with differing data... " << endl;
cout << "Name: " << s->Name() << endl;
cout << "operator== " << (different == *s) << endl;
cout << endl;
cout << "Testing Mapping() methods ... " << endl;
Isis::Pvl tmp1;
Isis::Pvl tmp2;
Isis::Pvl tmp3;
tmp1.AddGroup(p.Mapping());
tmp2.AddGroup(p.MappingLatitudes());
tmp3.AddGroup(p.MappingLongitudes());
cout << "Mapping() = " << endl;
cout << tmp1 << endl;
cout << "MappingLatitudes() = " << endl;
cout << tmp2 << endl;
cout << "MappingLongitudes() = " << endl;
cout << tmp3 << endl;
cout << endl;
}
catch (Isis::iException &e) {
e.Report(false);
}
}
| true |
540f05a90ab8b37e80f1484b6338f255fd75577f | C++ | FrolovNikolay/MathRedactor-PAKETA- | /MathRedactorPaketa/MathRedactorPaketa/WinPlotter/FormulaParser.cpp | UTF-8 | 13,142 | 3.0625 | 3 | [] | no_license | // Автор: Федюнин Валерий
#include "FormulaParser.h"
#include <assert.h>
#include <vector>
#include <set>
#include <algorithm>
namespace {
// возвращает размер пространства, в котором задается формула
int GetSpaceDimension( const std::vector<std::string>& equations )
{
if( equations.size() == 2 || ( equations.size() == 1 && equations[0][0] == 'y' ) ) {
return 2;
}
return 3;
}
// возвращает индекс парной скобки
int GetMatchingBracket( const std::string& text, int i )
{
assert( text[i] == '(' );
assert( i != text.length() - 1 );
int bracketBalance = 1;
i++;
do {
if( text[i] == '(' ) {
bracketBalance++;
} else if( text[i] == ')' ) {
bracketBalance--;
if( bracketBalance == 0 ) {
return i;
}
}
i++;
} while( i < text.length() );
assert( i != text.length() );
}
// является ли данный символ переменной t
bool IsParameterT( const std::string& text, int i )
{
return( text[i] == 't' && ( i == 0 || text[i - 1] != 'r' )
&& ( i + 1 >= static_cast<int>( text.size() ) || text[i + 1] != 'g' ) );
}
// является ли данный символ переменной l
bool IsParameterL( const std::string& text, int i )
{
return( text[i] == 'l' && ( i == 0 || text[i - 1] != 'u' ) );
}
// получить размерность графика (т.е. кол-во его параметров: 2 - поверхность. 1 - кривая)
int GetPlotDimension( const std::vector<std::string>& equations )
{
if( equations.size() != 1 ) {
bool lFound = false, tFound = false;
for( int i = 0; i < static_cast<int>( equations.size() ); ++i ) {
for( int j = 0; j < static_cast< int >( equations[i].length() ); ++j ) {
if( IsParameterT( equations[i], j ) ) {
tFound = true;
} else if( IsParameterL( equations[i], j ) ) {
lFound = true;
}
}
}
return std::max( 1, static_cast< int >( lFound ) +static_cast< int >( tFound ) );
} else {
if( equations[0][0] == 'y' ) {
return 1;
} else {
return 2;
}
}
}
// проверить префиксы уравнений
void CheckEquationsCorrectness( const std::vector<std::string>& equations )
{
std::string variables = "xyz";
for( int i = 0; i < static_cast<int>( equations.size() ); ++i ) {
assert( variables.find( equations[i][0] ) != std::string::npos );
assert( equations[i][1] == '=' );
}
}
// получить переменные, исопльзуемые в уравнении
std::vector<char> GetEquationsVariables( const std::vector<std::string>& equations )
{
std::vector<char> res;
if( equations.size() == 1 ) {
res.push_back( 'x' );
if( equations[0][0] == 'z' ) {
res.push_back( 'y' );
}
} else {
bool tFound = false, lFound = false;
for( int i = 0; i < static_cast<int>( equations.size() ); ++i ) {
for( int j = 0; j < static_cast< int >( equations[i].length() ); ++j ) {
if( IsParameterT( equations[i], j ) ) {
tFound = true;
} else if( IsParameterL( equations[i], j ) ) {
lFound = true;
}
}
}
if( lFound ) {
res.push_back( 'l' );
}
if( tFound || res.empty() ) {
res.push_back( 't' );
}
}
return res;
}
// являются ли 2 символа парными скобкаи
bool PairBrackets( const std::string& equation, int left, int right )
{
if( equation[left] != '(' || equation[right] != ')' ) {
return false;
}
return( GetMatchingBracket( equation, left ) == right );
}
// основная функция, парсит один оператор в данной подстроке (им может быть и вызов функции и число)
// объявление вынесено для возможностей рекурсивного вызова
IOperator* ParseOperator( const std::string& equation, int left, int right );
// парсит бинарный оператор, возвращает 0 при неудаче
IOperator* ParseBinaryOperator( const std::string& equation, int left, int right )
{
assert( left < right );
char operators[3][2] = {{'-', '+'}, {'/', '*'}, {'^', '^'}};
for( int i = 0; i < 3; ++i ) {
int balance = 0;
for( int j = right - 1; j >= left; --j ) {
if( equation[j] == '(' ) {
++balance;
} else if( equation[j] == ')' ) {
--balance;
} else if( ( equation[j] == operators[i][0] || equation[j] == operators[i][1] )
&& balance == 0 && j > left && j < right - 1 )
{
IOperator* leftOperand = ParseOperator( equation, left, j );
IOperator* rightOperand = ParseOperator( equation, j + 1, right );
BINOP type;
switch( equation[j] ) {
case '-':
type = MINUS;
break;
case '+':
type = PLUS;
break;
case '/':
type = DIV;
break;
case '*':
type = TIMES;
break;
case '^':
type = POWER;
break;
}
return new CBinaryOperator( leftOperand, rightOperand, type );
}
}
}
return 0;
}
// парсит вызов функции, возвращает 0 при неудаче
IOperator* ParseFunction( const std::string& equation, int left, int right )
{
assert( left < right );
std::string functionNames[] = {"sin", "cos", "tg", "ctg", "sqrt", "-"};
FUNC types[] = {SIN, COS, TG, CTG, SQRT, UNARY_MINUS};
for( int i = 0; i < 6; ++i ) {
if( left + static_cast<int>( functionNames[i].size() ) < right
&& equation.substr( left, functionNames[i].size() ) == functionNames[i] )
{
return new CFunction( ParseOperator( equation, left + functionNames[i].size(), right ), types[i] );
}
}
return 0;
}
// парсит обращение к переменной, возвращает 0 при неудаче
IOperator* ParseVariable( const std::string& equation, int left, int right )
{
if( left + 1 == right && equation[left] >= 'a' && equation[left] <= 'z' ) {
return new CVariable( equation[left] );
}
return 0;
}
// парсит константу (число), возвращает 0 при неудаче
IOperator* ParseConstant( const std::string& equation, int left, int right )
{
try {
double value = std::stod( equation.substr( left, right - left ) );
return new CConstant( value );
} catch( const std::invalid_argument& ) {
return 0;
}
}
// парсит множественную операцию
IOperator* ParseSetOperation( const std::string& equation, int left, int right )
{
// минимальная длина выражения вида sum(i=0;2;x)
if( right - left < 12 ) {
return 0;
}
SETOPTYPE type;
if( equation.substr( left, 3 ) == "mul" ) {
type = MUL;
} else if( equation.substr( left, 3 ) == "sum" ) {
type = SUM;
} else {
return 0;
}
if( equation[left + 3] != '(' || equation[right - 1] != ')' || equation[left + 5] != '=' ) {
return 0;
}
char variable = equation[left + 4];
if( variable < 'a' || variable > 'z' ) {
return 0;
}
std::vector<int> semicolons;
for( int i = left; i < right && semicolons.size() < 2; ++i ) {
if( equation[i] == ';' ) {
semicolons.push_back( i );
}
}
if( semicolons.size() < 2 ) {
return 0;
}
IOperator* begin = ParseOperator( equation, left + 6, semicolons[0] );
if( begin == 0 ) {
return 0;
}
IOperator* condition = ParseOperator( equation, semicolons[0] + 1, semicolons[1] );
if( condition == 0 ) {
delete( begin );
return 0;
}
IOperator* expression = ParseOperator( equation, semicolons[1] + 1, right - 1 );
if( expression == 0 ) {
delete( begin );
delete( condition );
return 0;
}
return new CSetOperator( variable, expression, begin, condition, type );
}
IOperator* ParseOperator( const std::string& equation, int left, int right )
{
IOperator* res = 0;
while( PairBrackets( equation, left, right - 1 ) ) {
left++;
right--;
}
res = ParseBinaryOperator( equation, left, right );
if( res != 0 ) {
return res;
}
res = ParseFunction( equation, left, right );
if( res != 0 ) {
return res;
}
res = ParseSetOperation( equation, left, right );
if( res != 0 ) {
return res;
}
res = ParseVariable( equation, left, right );
if( res != 0 ) {
return res;
}
res = ParseConstant( equation, left, right );
if( res != 0 ) {
return res;
}
assert( false );
}
// Приводит одну множественную операцию к корректному виду
// Из sum( pre , post ) func в sum( pre , post, func )
std::string PreParseSetOperator( const std::string& _equation, int index );
// найти конец токена (выхов функции, выражения в скобках, обращения к переменной, константы )
int GetTokenEnd( std::string& text, int index ) {
int end;
if( text[index] == '(' ) {
// третий аргумент нечто в скобках
end = GetMatchingBracket( text, index );
} else if( text[index] >= 'a' && text[index] <= 'z'
&& ( index + 1 == text.length() || text[index + 1] < 'a' || text[index + 1] > 'z') )
{
// третий аргумент - переменная
end = index;
} else if( text[index] >= 'a' && text[index] <= 'z' ) {
// третий аргумент - вызов функции
end = index;
while( end + 1 < text.length() &&
text[end + 1] >= 'a' && text[end + 1] <= 'z' )
{
end++;
}
std::string functionName = text.substr( index, end - index + 1 );
if( functionName == "mul" || functionName == "sum" ) {
text = PreParseSetOperator( text, index );
}
end = GetMatchingBracket( text, end + 1 );
} else if( text[index] >= '0' && text[index] <= '9' ) {
// третий аргумент - константа
end = index;
while( end + 1 < text.length() &&
text[end + 1] >= '0' && text[end + 1] <= '9' )
{
end++;
}
}
return end;
}
std::string PreParseSetOperator( const std::string& _equation, int index ) {
std::string equation( _equation );
// игнорируем название
int leftBracket = index + 3;
int rightBracket = GetMatchingBracket( equation, leftBracket );
int argsNum = 1;
for( int i = leftBracket; i <= rightBracket; ++i ) {
if( equation[i] == ';' ) {
++argsNum;
}
}
// уже в требуемом виде
if( argsNum == 3 ) {
return _equation;
}
assert( rightBracket < equation.length() - 1 );
assert( argsNum > 1 && argsNum < 4 );
index = rightBracket + 1;
// конец и начало аргумента. который надо сделать третьим у функции (правый конец включается)
int argumentBegin = index;
int argumentEnd = GetTokenEnd( equation, index );
// если была задана степень
if( argumentEnd + 1 < equation.length() && equation[argumentEnd + 1] == '^' ) {
argumentEnd = GetTokenEnd( equation, argumentEnd + 2 );
}
return equation.substr( 0, rightBracket ).append( ";" )
.append( equation.substr( argumentBegin, argumentEnd - argumentBegin + 1 ) )
.append( ")" ).append( equation.substr( argumentEnd + 1 ) );
}
// Приводит операторы mul, sum к виду, с которым умеет работать Plotter
std::string PreParseEquation( const std::string& _equation ) {
std::string equation( _equation );
int i = std::min( equation.find( "mul" ), equation.find( "sum" ) );
while( i != std::string::npos ) {
equation = PreParseSetOperator( equation, i );
i = std::min( equation.find( "mul", i + 1 ), equation.find( "sum", i + 1 ) );
}
return equation;
}
// Парсит одно уравнение
CEquation ParseEquation( const std::string& _equation )
{
std::string equation = PreParseEquation( _equation );
IOperator* root = ParseOperator( equation, 2, equation.size() );
char resultVariable = equation[0];
return CEquation( resultVariable, root );
}
};
// Парсит всю формулу (которая может содержать несоклько уравнений)
CFormula ParseFormula( const std::string& text ) {
std::vector<std::string> equations( 1 );
std::string spaces = " \t\n\r";
for( int i = 0; i < static_cast<int>( text.size() ); ++i ) {
if( spaces.find( text[i] ) != std::string::npos ) {
continue;
}
if( text[i] == ',' && !equations.back().empty() ) {
equations.push_back( std::string() );
continue;
}
equations.back().push_back( text[i] );
}
CheckEquationsCorrectness( equations );
int spaceDimension = GetSpaceDimension( equations );
assert( spaceDimension >= 2 );
int plotDimension = GetPlotDimension( equations );
std::vector<char> variables = GetEquationsVariables( equations );
CFormula formula( spaceDimension, plotDimension, variables );
for( int i = 0; i < static_cast<int>( equations.size() ); ++i ) {
formula.AddEquation( ParseEquation( equations[i] ) );
}
return formula;
} | true |
bcadf9ada69d1d142f1a6d1faf7e9ea1b96fe665 | C++ | Pradnyan-ACM-Student-Chapter-DYPCOE/Contest-Solutions | /October Dawn 2020/Manasi's Algorithm/manasi_algo.cpp | UTF-8 | 542 | 2.890625 | 3 | [] | no_license | #include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int t;
cin>>t;
while(t--)
{
string s1, s2;
cin>>s1>>s2;
reverse(s1.begin(), s1.end());
reverse(s2.begin(), s2.end());
string s3 = to_string(stoi(s1)+stoi(s2));
reverse(s3.begin(), s3.end());
cout<<stoi(s3)<<endl;
}
return 0;
}
| true |
a8245a74326df31705434bca814e409fdd6f5f53 | C++ | danorel/World-of-Cpp | /Swap/main.cpp | UTF-8 | 3,012 | 3.8125 | 4 | [] | no_license | #include <iostream>
#include <random>
using namespace std;
const int Counter = 8;
// functions
template <typename T>
void QuickSort(T, int, int);
template <typename T>
bool LookFor(T, int, int, int);
/*
template<typename T1, typename T2>
void Swap(T1 *t1, T2 *t2){
auto temp = *t1;
*t1 = *t2;
*t2 = temp;
};
template<typename T>
void Bubble(T *);
template<typename T>
void fillArray(T *);
template<typename T>
void showArray(T *);
*/
// end
int main() {
srand(time(NULL));
/*
double num1;
int num2;
cout << "Enter two different numbers of different types! ";
cin >> num1 >> num2;
cout << "Before transformation: num1: " << num1 << ", num2: " << num2 << endl;
// Swap(&num1, &num2);
cout << "After transformation: num1: " << num1 << ", num2: " << num2 << endl;
*/
int arr[Counter];
for(int i = 0; i < Counter; i++){
arr[i] = rand() % 10;
}
QuickSort(arr, 0, Counter-1);
for(int i = 0; i < Counter; i++){
cout<< arr[i] << endl;
}
int number = 1;
cout << "Answer: " << LookFor(arr, 0, Counter - 1, number);
/*
char arr[Counter];
fillArray(arr);
showArray(arr);
Bubble(arr);
cout << endl;
showArray(arr);
*/
return 0;
}
/*
template<typename T>
void Bubble(T *array){
for(int row = 0; row < Counter; row++){
for(int column = 0; column < Counter; column++){
if(array[column] > array[column+1]){
swap(array[column], array[column+1]);
}
}
}
}
template<typename T>
void fillArray(T *array){
for(int row = 0; row < Counter; row++){
array[row] = 65 + rand() % 91;
}
}
template<typename T>
void showArray(T *array){
for(int row = 0; row < Counter; row++){
cout << array[row] << " ";
}
}
*/
template <typename T>
void QuickSort(T array, int l, int r){
int i, j;
i = l;
j = r;
int middle = array[(i+j)/2];
do{
while(middle > array[i]){
i++;
}
while(middle < array[j]){
j--;
}
if( i <= j){
swap(array[i], array[j]);
i++;
j--;
}
} while(i < j);
if(i < r){
QuickSort(array, i, r);
}
if(j > l){
QuickSort(array, l, j);
}
}
template <typename T>
bool LookFor(T array, int l, int r, int element){
int j = r;
int i = l;
int index = (l+r)/2;
int middle = array[index];
if(l = index){
if(array[l+1] == element){
return true;
} else if(array[l] == element){
return true;
} else {
return false;
}
}
if(element != middle){
if(element > middle){
LookFor(array, index , r, element);
} else if(element < middle){
LookFor(array, l, index, element);
} else {
return false;
}
} else if(element == middle){
return true;
} else {
return false;
}
} | true |
eddba505e6180d2780bae6fd994e652cbd2b42ca | C++ | kdavison/ranbam | /source/engine/math/random/volume/ellipsoid.h | UTF-8 | 1,310 | 2.96875 | 3 | [] | no_license | #pragma once
#include "sphere.h"
#include <random>
#include <boost/math/constants/constants.hpp>
#include <tuple>
namespace ranbam::math::volume
{
class ellipsoid
{
public:
typedef std::tuple<float,float,float> result_type;
public:
ellipsoid(
const double min_a, const double min_b, const double min_c,
const double max_a, const double max_b, const double max_c
)
: _r2(
std::pow(min_a, 2) + std::pow(min_b, 2) + std::pow(min_c, 2),
std::pow(max_a, 2) + std::pow(max_b, 2) + std::pow(max_c, 2)
)
, _max_a(max_a)
, _max_b(max_b)
, _max_c(max_c)
, _radians(0.0, ::boost::math::constants::two_pi<double>())
{
}
template<typename GENERATOR>
result_type operator()(GENERATOR& g) {
const auto theta = _radians(g);
const auto phi = _radians(g);
const double maxr2 = std::pow(_max_a, 2) + std::pow(_max_b, 2) + std::pow(_max_c, 2);
const double scale = std::sqrt(_r2(g) / maxr2);
return std::make_tuple(
_max_a * scale * std::cos(theta)*std::sin(phi),
_max_b * scale * std::sin(theta)*std::sin(phi),
_max_c * scale * std::cos(phi)
);
}
private:
std::uniform_real_distribution<> _r2;
const double _max_a;
const double _max_b;
const double _max_c;
std::uniform_real_distribution<> _radians;
};
}
| true |
5831c708a756bd384ec19b6d8809e985a08ad0fb | C++ | suharto1980/C | /daimon my.cpp | UTF-8 | 412 | 2.84375 | 3 | [] | no_license | #include<stdio.h>
int main(){
int i,j,k;
for ( i=1;i<=5;i++)
{
for (k=1;k<=5-i;k++)
{
printf(" ");
}
for(j=1;j<=i;j++)
{
printf("* ");
}
printf("\n");
}
for(i=1;i<=5;i++)
{
for (k=1;k<i;k++)
{
printf(" ");
}
for ( j=5;j>=i;j--)
{
printf ("* ");
}
printf("\n");
}
return 0;
}
| true |
492510d3f9d9409666fac6f162defd44674dac15 | C++ | haitaox/quora | /v7.cpp | UTF-8 | 5,561 | 2.84375 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct event {
int id;
int time;
int score;
int height;
event() {}
event(int i, int t, int s, int h): id(i), time(t), score(s), height(h) {}
};
class idList {
public:
vector<int> v;
bool operator <(const idList& other) const {
if (v.size() < other.v.size()) return true;
else if (v.size() > other.v.size()) return false;
else {
for (int i = 0; i < v.size(); i++) {
if (v[i] < other.v[i]) return true;
else if (v[i] > other.v[i]) return false;
}
return true;
}
}
};
bool Unequal(const int listHead, const int listEnd, const int H, const event* list, int &maxScore, vector<int> &maxList, int** B, int** Score) {
for (int m = 0; m <= listEnd-listHead+1; m++) {
for (int n = 0; n <= H; n++) {
Score[m][n] = 0;
B[m][n] = 0;
}
}
for (int i = listHead; i <= listEnd; i++) {
for (int j = 1; j <= H; j++) {
if (list[i].height > j) { //not chosen
Score[i-listHead+1][j] = Score[i-listHead][j];
B[i-listHead+1][j] = B[i-listHead][j];
} else {
if (Score[i-listHead][j-list[i].height] + list[i].score > Score[i-listHead][j]) {//chosen
if (Score[i-listHead][j-list[i].height] != 0 || j-list[i].height == 0) {
Score[i-listHead+1][j] = Score[i-listHead][j-list[i].height] + list[i].score;
B[i-listHead+1][j] = list[i].id;
}
} else if (Score[i-listHead][j-list[i].height] + list[i].score < Score[i-listHead][j]) {//not chosen
Score[i-listHead+1][j] = Score[i-listHead][j];
B[i-listHead+1][j] = B[i-listHead][j];
} else {
return false; // equal scores
}
}
}
}
int maxHeight;
for (int m = 1; m <= H; m++) {
if (Score[listEnd-listHead+1][m] > maxScore) {
maxScore = Score[listEnd-listHead+1][m];
maxHeight = m;
}
}
int q = listEnd-listHead+1;
int p = maxHeight;
while (q >= 1 && p >= 0 && B[q][p] != 0) {
q = B[q][p];
maxList.insert(maxList.begin(), q);
p -= list[q-1].height;
q -= listHead;
q--;
}
return true;
}
void Equal (const int listHead, const int listEnd, const int H, const event* list, int &maxScore, vector<int> &maxList, int** Score) {
for (int m = 0; m <= listEnd-listHead+1; m++) {
for (int n = 0; n <= H; n++)
Score[m][n] = 0;
}
vector<int> BT[listEnd-listHead+2][H+1];
idList aList, bList;
for (int i = listHead; i <= listEnd; i++) {
for (int j = 1; j <= H; j++) {
if (list[i].height > j) { //not chosen
Score[i-listHead+1][j] = Score[i-listHead][j];
BT[i-listHead+1][j] = BT[i-listHead][j];
} else {
if (Score[i-listHead][j-list[i].height] + list[i].score > Score[i-listHead][j]) {//chosen
Score[i-listHead+1][j] = Score[i-listHead][j-list[i].height] + list[i].score;
BT[i-listHead+1][j] = BT[i-listHead][j-list[i].height];
BT[i-listHead+1][j].push_back(list[i].id);
} else if (Score[i-listHead][j-list[i].height] + list[i].score < Score[i-listHead][j]) {//not chosen
Score[i-listHead+1][j] = Score[i-listHead][j];
BT[i-listHead+1][j] = BT[i-listHead][j];
} else { // equal scores
aList.v = BT[i-listHead][j-list[i].height];
aList.v.push_back(list[i].id);
bList.v = BT[i-listHead][j];
if (aList < bList) {//chosen
Score[i-listHead+1][j] = Score[i-listHead][j-list[i].height] + list[i].score;
BT[i-listHead+1][j] = BT[i-listHead][j-list[i].height];
BT[i-listHead+1][j].push_back(list[i].id);
} else { //not chosen
Score[i-listHead+1][j] = Score[i-listHead][j];
BT[i-listHead+1][j] = BT[i-listHead][j];
}
}
}
}
}
maxScore = Score[listEnd-listHead+1][H];
maxList = BT[listEnd-listHead+1][H];
}
void reload() {
int N, W, H, ti, sc, he, maxScore, maxHeight, listHead, listEnd;
char type;
// N: number of events; W: time window; H: browser height
cin >> N >> W >> H;
event* list = new event[N];
int** Score = new int*[W+1];
int** B = new int*[W+1];
for (int m = 0; m <= W; m++) {
B[m] = new int[H+1];
Score[m] = new int[H+1];
}
int ID = 1;
vector<int> maxList;
listHead = 0; // earliest event index that's not expired
listEnd = -1; // latest event index
bool list_updated = false; // event(s) added/expired in the event list
bool MAX_updated = false; // event(s) added/expired in maxList
vector<int>::const_iterator listIter;
for (int a = 0; a < N; a++) {
cin >> type >> ti;
if (type == 'S') {
cin >> sc >> he;
list[ID-1] = event(ID++, ti, sc, he);
list_updated = true;
listEnd++;
}
else if (type == 'R') {
if (listHead > listEnd) continue;
if (!maxList.empty()) {
for (int m = 0; m < maxList.size(); m++)
if (ti - list[maxList[m]-1].time > W) {
MAX_updated = true;
break;
}
}
for (int m = listHead; m <= listEnd; m++) {
if (ti - list[m].time > W) {
listHead++;
list_updated = true;
}
else break;
}
if (listHead > listEnd) continue;
if (list_updated || MAX_updated) {
maxScore = 0;
maxList.clear();
if (!Unequal(listHead, listEnd, H, list, maxScore, maxList, B, Score)) {
maxScore = 0;
maxList.clear();
Equal(listHead, listEnd, H, list, maxScore, maxList, Score);
}
}
cout << maxScore << " " << maxList.size();
for (listIter = maxList.begin(); listIter != maxList.end(); ++listIter) {
cout << " " << *listIter;
}
cout << endl;
list_updated = false;
MAX_updated = false;
}
}
for (int n = 0; n <= W; n++) {
delete [] Score[n];
delete [] B[n];
}
delete [] Score;
delete [] B;
delete [] list;
}
int main() {
reload();
}
| true |
09ac30bce852a90fb4182a3f6fad6d9762a8389d | C++ | green-object/Course_work-Lab_3- | /activity.h | UTF-8 | 576 | 2.90625 | 3 | [] | no_license | #ifndef ACTIVITY_H
#define ACTIVITY_H
#include <QString>
//Базовый класс, достижение
class Activity
{
//Наименование
QString name;
//направление
QString trend;
public:
Activity();
//расчет итоговых баллов
virtual int calculateFinishBalls() const = 0;
virtual QString className() const = 0;
QString getName() const;
void setName(const QString &value);
QString getTrend() const;
void setTrend(const QString &value);
};
#endif // ACTIVITY_H
| true |
8fa7c03879f38fdbbbdafb3cc0e07a34a79a71c2 | C++ | GaleaStefan/puzzle-solver | /State.h | UTF-8 | 492 | 2.859375 | 3 | [] | no_license | #pragma once
#include <vector>
#include <string>
struct State
{
int gridSize;
int mDistance;
std::vector<int> tiles;
State();
State(int gridSize, std::vector<int> tiles);
State(const State& previous, int emptyMoveDirection);
bool isGoalState() const;
void calculateManhattanDistance();
int calculateInversions() const;
int getEmptyTileIndex() const;
std::string toString() const;
bool operator==(const State& state2) const;
//bool operator<(const State& other) const;
}; | true |
9ee061c8b71962d1f6e9fda010ed279ae0b7d4e0 | C++ | frozenca/PPP-CPP | /src/18/18-1.cpp | UTF-8 | 375 | 3.171875 | 3 | [] | no_license | #include <cstddef>
#include <iostream>
char* strdup(const char* str) {
size_t len = 0;
const char* s = str;
while (*s) {
len++;
s++;
}
char* dst = new char[len + 1];
char* d = dst;
while ((*dst++ = *str++)) ;
return d;
}
int main() {
const char* str = "abcde";
std::cout << strdup(str) << '\n';
} | true |
8a13cc89eec8282db1850abb018a2bac532f321b | C++ | bencikpeter/HTWG_shark_cage | /Shark Cage/Shark Cage/Shark Cage.cpp | UTF-8 | 1,308 | 2.703125 | 3 | [] | no_license | // Shark Cage.cpp : Entry point for the program.
#include "stdafx.h"
#include <windows.h>
#include <iostream>
#include "ProcessHandler.h"
// Start as LocalSystem
int main(int argc, char* argv[]) {
// Create CageService
ProcessHandler pc;
LPTSTR desktopName = L"desktopName";
LPTSTR appName = _tcsdup(TEXT("CageManager.exe"));
DWORD processId = GetCurrentProcessId();
DWORD sessionId;
if (ProcessIdToSessionId(processId, &sessionId)) {
// CageService starts CageManager
//pc.startCageManager(appName, desktopName, sessionId);
} else {
std::cout << "Unable to get sessionID\n";
return -1;
}
return 0;
}
void startProcessInNewDesktop() {
// Save the current desktop
HDESK currentDesktop = GetThreadDesktop(GetCurrentThreadId());
// Create new desktop and switch to it
LPTSTR desktopName = L"New Desktop";
HDESK newDesktop = CreateDesktop(desktopName, NULL, NULL, 0, GENERIC_ALL, NULL);
SwitchDesktop(newDesktop);
Sleep(500); // Wait to set up desktop
// Create new process on the new desktop
ProcessHandler pc;
pc.createProcess(desktopName);
Sleep(5000);
// Return the old desktop and close the new one
SwitchDesktop(currentDesktop);
CloseDesktop(newDesktop);
} | true |
fb53a98d4dbab6230ce9837a6d0067ae8f83eef3 | C++ | brookejbarton/animation-toolkit | /libsrc/atkui/framework.h | UTF-8 | 1,475 | 2.515625 | 3 | [
"MIT"
] | permissive | #ifndef ATKUI_Framework_H_
#define ATKUI_Framework_H_
#include "atk/toolkit.h"
#include "agl/window.h"
#include "agl/aglm.h"
#include <vector>
namespace atkui {
enum Display { Orthographic, Perspective };
class Framework : public agl::Window {
public:
Framework(Display type, int width = 500, int height = 500);
virtual ~Framework();
protected:
virtual void scene() {} // override to update and draw custom components
virtual void draw() override;
virtual void setColor(const glm::vec3& c);
virtual void push();
virtual void pop();
virtual void rotate(float angle, const glm::vec3& axis);
virtual void translate(const glm::vec3& pos);
virtual void scale(const glm::vec3& size);
virtual void transform(const atk::trs& trs);
virtual void transform(const glm::mat4& trs);
virtual void drawTeapot(const glm::vec3& pos, float size);
virtual void drawCube(const glm::vec3& pos, const glm::vec3& size);
virtual void drawSphere(const glm::vec3& pos, float radius);
virtual void drawLine(const glm::vec3& a, const glm::vec3& b);
virtual void drawCone(const glm::vec3& pos, float size);
virtual void drawTorus(const glm::vec3& pos, float size);
virtual void drawCylinder(const glm::vec3& pos, float size);
virtual void drawFloor(float size, float big = 200, float small = 50);
virtual void drawText(const std::string& msg, float x, float y); // x in [0, width]; y in [0, height]
bool _type;
private:
glm::vec3 _color;
};
}
#endif
| true |
5f2593116c4df05fbff6b8ee4408682988848562 | C++ | zuselegacy/leetcode | /tree/662-max-width-tree.cpp | UTF-8 | 972 | 3.203125 | 3 | [] | no_license | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
void preorder(TreeNode* root, int level, unsigned long index) {
if(root == NULL)
return;
if(levelMap.find(level) == levelMap.end()) {
levelMap[level] = index;
} else {
maxWidth = max(maxWidth, int(index - levelMap[level] + 1));
}
preorder(root->left,level + 1, index *2);
preorder(root->right,level + 1, index *2 + 1);
}
int widthOfBinaryTree(TreeNode* root) {
preorder(root, 0, 1);
return maxWidth;
}
map<int,int> levelMap;
int maxWidth = 1;
};
| true |
eeb5b2a5d136bfa3fa73913d04cc5f330468866f | C++ | xunilrj/sandbox | /courses/kth-distributed-algorithms-1/crtd/counter.005.cxx | UTF-8 | 3,028 | 3.6875 | 4 | [
"Apache-2.0"
] | permissive | #include <cassert>
#include <array>
#include <string>
#include <iostream>
#include <algorithm>
#include <numeric>
template<size_t N>
class Counter{
public:
Counter(size_t index):Index(index),
Increments(),
Decrements()
{
assert(index < N);
}
Counter& operator++(){
++Increments[Index];
return *this;
}
Counter& operator--(){
++Decrements[Index];
return *this;
}
Counter operator & (const Counter<N>& other) const
{
auto result = Counter<N>(this->Index);
for(int i = 0;i < N; ++i){
result.Increments[i] = std::max(
this->Increments[i],
other.Increments[i]);
}
for(int i = 0;i < N; ++i){
result.Decrements[i] = std::max(
this->Decrements[i],
other.Decrements[i]);
}
return result;
}
int getCurrentValue() const
{
auto value = std::accumulate(
std::begin(Increments), std::end(Increments),
0, [](auto& acc, auto& current){
return acc + current;
});
return std::accumulate(
std::begin(Decrements), std::end(Decrements),
value, [](auto& acc, auto& current){
return acc - current;
});
}
private:
size_t Index;
std::array<int, N> Increments;
std::array<int, N> Decrements;
template<size_t N2>
friend std::ostream& operator <<(
std::ostream& out,
const Counter<N2>& counter);
};
template<class T, size_t N>
std::ostream& operator <<(
std::ostream& out,
const std::array<T, N> arr)
{
out << "[";
auto size = arr.size();
for(int i = 0; i < size; ++i){
out << arr[i];
if(i < (size-1)){
out << ",";
}
}
return out << "]";
}
template<size_t N>
std::ostream& operator << (
std::ostream& out,
const Counter<N>& counter)
{
std::cout << "Increments: " << counter.Increments << std::endl;
std::cout << "Decrements: " << counter.Decrements << std::endl;
}
int main(int argc, char ** argv)
{
std::cout << "Running..." << std::endl;
auto likesServer1 = Counter<2>{0};
++likesServer1;
std::cout << "Server 1" << std::endl;
std::cout << likesServer1 << std::endl;
auto likesServer2 = Counter<2>{1};
++likesServer2;
++likesServer2;
--likesServer2;
std::cout << "Server 2" << std::endl;
std::cout << likesServer2 << std::endl;
likesServer1 = likesServer1 & likesServer2;
std::cout << "Merged Server 1" << std::endl;
std::cout << likesServer1 << std::endl;
std::cout << "Final Value" << std::endl;
std::cout << likesServer1.getCurrentValue() << std::endl;
return 0;
} | true |
76a926c08856d7eb8bd5c70c812f648380b170df | C++ | Sitispeaks/turicreate | /src/toolkits/pattern_mining/fp_node.cpp | UTF-8 | 2,486 | 2.765625 | 3 | [
"BSD-3-Clause"
] | permissive | /* Copyright © 2017 Apple Inc. All rights reserved.
*
* Use of this source code is governed by a BSD-3-clause license that can
* be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause
*/
#include <toolkits/pattern_mining/fp_node.hpp>
namespace turi {
namespace pattern_mining {
// FP-Node Implementation
fp_node::fp_node(const size_t& id, const size_t& node_depth){
item_id = id;
item_count = 0;
depth = node_depth;
is_closed_node = false;
}
fp_node* fp_node::add_child(const size_t& child_id){
// Create a new node
auto new_node = std::make_shared<fp_node>(child_id, depth + 1);
// Set this node as parent to new node
new_node->parent_node = this;
// Add new node to children
children_nodes.push_back(new_node);
fp_node* new_pointer = new_node.get();
return new_pointer;
}
fp_node* fp_node::get_child(const size_t& child_id) const{
for(const auto& child_node: children_nodes){
if(child_node->item_id == child_id){
fp_node* child_pointer = child_node.get();
return child_pointer;
}
}
// No Node exists
return nullptr;
}
std::vector<size_t> fp_node::get_path_to_root() {
std::vector<size_t> ids;
fp_node* current_node = this;
while(current_node->item_id != ROOT_ID){
ids.push_back(current_node->item_id);
current_node = current_node->parent_node;
}
return ids;
}
bool fp_node::is_closed() const {
bool is_closed;
// Once closed, a node will remain closed
if(is_closed_node){
is_closed = true;
return is_closed;
}
// Check if the node became closed
if(children_nodes.empty()){
is_closed = true;
return is_closed;
} else {
for(const auto& child_node: children_nodes){
if(child_node->item_count == item_count){
is_closed = false;
return is_closed;
}
}
is_closed = true;
return is_closed;
}
}
void fp_node::erase(){
// If node has a parent
if(parent_node){
// Find parent's pointer to this node
for(auto it = parent_node->children_nodes.begin(); \
it != parent_node->children_nodes.end(); it++){
auto candidate_node = *it;
if(candidate_node->item_id == item_id){
candidate_node.reset();
parent_node->children_nodes.erase(it);
break;
}
}
}
}
} // namespace pattern_mining
} // namespace turi
| true |
38543bd08b13c8198b4d8708e2ebe1af0f3d6721 | C++ | CaspianA1/S2CPP | /Std_Lib/Lists/lists.cpp | UTF-8 | 1,852 | 2.796875 | 3 | [] | no_license | #include <string>
#include <variant>
#include <regex>
#include <ostream>
#include <iostream>
#define print(var) std::cout << var << std::endl
#define print2(var, var2) std::cout << var << var2 << std::endl
#define SEXPRESSO_OPT_OUT_PIKESTYLE
#ifdef SEXPRESSO_OPT_OUT_PIKESTYLE
#ifndef SEXPRESSO_HEADER
#define SEXPRESSO_HEADER
#include <vector>
#include <string>
#include <cstdint>
#include "sexpresso/sexpresso/sexpresso.cpp"
#endif
#endif
#define asString(var, type) format(std::to_string(std::get<type>(var)))
#define ComparableType std::variant<const char*, int, double, bool, ListValue>
std::string format(std::string unformatted) {
sexpresso::Sexp parsedExpr = sexpresso::parse(unformatted);
return parsedExpr.toString();
}
// integer, double, boolean, list, string, variable
typedef enum {I, D, B, L, S, V} Type;
typedef std::variant<int, double, bool, std::string> Value;
struct ListValue {Type t; Value v;};
typedef struct ListValue ListValue;
std::string INT_REGEX = "^[-+]?\\d+$",
DOUBLE_REGEX = "^[-+]?\\d+\\.\\d?$",
BOOLEAN_REGEX = "^(true|false)$";
bool matchRegex(std::string pattern, std::string inputString) {
std::regex expression(pattern);
return std::regex_match(inputString, expression);
}
ListValue getValueType(std::string operationOutp) {
if (matchRegex(INT_REGEX, operationOutp))
return {I, std::stoi(operationOutp)};
else if (matchRegex(DOUBLE_REGEX, operationOutp))
return {D, std::stod(operationOutp)};
else if (matchRegex(BOOLEAN_REGEX, operationOutp))
return {B, (operationOutp == "true")};
else if (operationOutp[0] == '(' && operationOutp.back() == ')')
return {L, operationOutp};
else if (operationOutp[0] == operationOutp.back() && operationOutp.back() == '\"')
return {S, operationOutp};
else
return {V, operationOutp};
} | true |
4f464bb68e7406b27ed4369af35a04533dc89286 | C++ | alu0100406122/SSI-RSA | /rsa.cpp | UTF-8 | 12,740 | 3.625 | 4 | [] | no_license | // Seguridad en Sistemas Informáticos.
// María Nayra Rodríguez Pérez.
#include <vector>
#include <stdlib.h>
#include <iostream>
#include <string.h>
#include <stdio.h>
#include <istream>
#include <cmath>
using namespace std;
// Exponenciación Rápida.
double exponenciacion(int base, int exponente, int mod){
double x = 1;
double y = fmod(base, mod);
while ((exponente > 0) && (y > 1)){
if (fmod(exponente,2) != 0){
x = fmod((x*y), mod);
exponente = (exponente - 1);
}
else{
y = fmod((y*y), mod);
exponente = (exponente / 2);
}
}
return x;
}
// Introducir valores
void pedir_valores(int &p, int &q, int &d){
cout << "Introduzca el valor de un número primo P: ";
cin >> p;
cout << "Introduzca el valor de Q: ";
cin >> q;
cout << "Introduzca el valor de D: ";
cin >> d;
}
// Lehman Peralta
// Comprobar que p no es divisible por ningún primo pequeño (2,3,5,7,11).
bool divisible(int p){
if (((p % 2) != 0) && ((p % 3) != 0) && ((p % 5) != 0) && ((p % 7) != 0) && ((p % 11) != 0)){
return false;
}
else{
return true;
}
}
// Lehman Peralta
// Comprobar que los números aleatorios no se repiten
bool existe_aleatorio(vector<int> v_, int num_, int i_){
bool igual = false;
for (int j=0; j<i_; j++){
if(v_[j] == num_){
igual = true;
break;
}
else{
igual = false;
}
}
return igual;
}
// Lehman Peralta
// Elegir números aleatorios entre 1 y p-1
void aleatorio(vector<int> &v, int tam_, int p){
int num;
int existe = 0;
for (int i=0; i<tam_; i++){
srand(clock());
num = 1 + rand() % (p-1); //variable = limite_inferior + rand() % (limite_superior +1 - limite_inferior) ;
//Comprobación que los números aleatorios no se repitan.
while (existe_aleatorio(v, num, i) == true){
num = 1 + rand() % (p-1); //variable = limite_inferior + rand() % (limite_superior +1 - limite_inferior) ;
}
v[i]=num;
}
cout << "Vector aleatorio obtenido: ";
for (int i=0; i<tam_; i++){
cout << v[i] << " ";
}
cout << endl;
}
/* Función Lehman y Peralta.
1) Comprobar que p no es divisible por ningún primo pequeño (2,3,5,7,11).
2) Elegir 100 enteros aleatorios (a1,a2,...,a100) entre (1 y p-1).
3) Para cada i calcular ai^((p-1)/2) (mod p) */
void lehman_peralta(int p){
int tam;
vector<int> v1;
bool divi = false;
divi = divisible(p);
int exponente = ((p - 1)/2);
double resultado;
bool primo = true;
if (p<100){
tam = (p * 0.2);
}
else{
tam = 100;
}
v1.resize(tam);
//cout << "\t" << "LEHMAN PERALTA" << endl;
// Comprobamos que el número introducido sea un número primo pequeño.
if ( (p!=2) && (p!=3) && (p!=5) && (p!=7) && (p!=11) ){
// 1) Comprobamos que dicho número sea divisible por un primo pequeño.
if (divi == true){
cout << endl;
cout << "El número P es divisible por algún número primo pequeño (2,3,5,7,11)." << endl;
primo = false;
cout << endl;
}
else {
aleatorio(v1,tam, p); // 2)
// 3) Para cada posicion i del vector aleatorio --> ai^(p-1)/2 (mod p):
for (int i=0; i<v1.size(); i++){
resultado = exponenciacion(v1[i], exponente, p);
//cout << "Resultado: " << resultado << endl;
//Comprobamos que el resultado sea 1 o (p-1) para que sea primo.
if ( (resultado == 1) || (resultado == (p - 1)) ){
primo = true;
}
else{
primo = false;
}
}
}
}
cout << endl;
if (primo == true){
cout << p << " es primo. " << endl;
}
else{
cout << p << " NO es primo. " << endl;
}
cout << endl;
}
/* Euclides Extendido
Para el cálculo de mcd(a,b) y b-1 (mod a) (con a>b) :
1) Inicializar: dividendo x0 := a, divisor x1 := b, z-1=0, z0=1
2) Mientras el resto no dé 0: dividir xi-1 por xi y asignar a xi+1 el resto asignar a zi := -div(xi-1,xi)• zi-1+ zi-2
3) El mcd(a,b) es xi
4) Si mcd(a,b)=1, entonces el inverso es zi-1
*/
int euclides(int a, int b, int n){ // b --> phi, a--> d
// Inicializar variables
int resto = 1;
int inverso = 0;
int mcd= 0;
vector<int> z;
z.resize(z.size()+1);
vector<int> x;
x.resize(2);
cout << "b" << b << endl;
x[0] = a; // Dividendo
x[1] = b; // Divisor
z[-1] = 0;
z[0] = 1;
// Mientras que el resto no dé 0
int i = 1;
while(resto != 0){
// Buscamos orden correcto dividendo y divisor.
int aux;
if (x[i-1] < x[i]){
aux = x[i-1];
x[i-1] = x[i];
x[i] = aux;
}
x.resize(x.size()+1);
resto = x[i-1] % x[i];
cout << "Modulo entre: "<< x[i-1] << " y "<< x[i] << " es igual a " << resto << endl;
x[i+1] = resto;
cout << "Resto: " << resto << endl;
z.resize(z.size()+1);
z[i] = -(x[i-1] / x[i]) * z[i-1] + z[i-2];
i++;
}
// Si obtenemos un 1, entonces en z está el inverso.
for (int i=0; i<x.size(); i++){
if ( (x[i] == 0) && (x[i-1] == 1) ){
mcd = x[i-1];
inverso = z[i-2];
}
else{
mcd = x[i-1];
inverso = 0;
}
}
cout << endl;
cout << "m.c.d (a,b): " << mcd << endl;
// Mostramos el vector x.
cout << "Vector X: ";
for (int i=0; i<x.size(); i++){
cout << x[i] << " ";
}
cout << endl;
// Mostramos el vector z.
cout << "Vector Z: ";
for (int i=0; i<z.size(); i++){
cout << z[i] << " ";
}
cout << endl;
// Comprobación si el inverso obtenido es negativo.
if (inverso > 0){
cout << "Inverso: " << inverso << endl;
}
else {
if (inverso < 0){
cout << "n: " << n << endl;
cout << "Inverso: " << inverso << " + Phi(n) " << b << endl;
inverso = (inverso + b);
cout << "Inverso (e): " << inverso << endl;
}
}
cout << endl;
return inverso;
}
// Función para separar espacios y comas al texto de entrada.
vector<char> separar(string texto_){
int i=0;
int j=0;
vector<char> vec_aux;
while (texto_[i] != '\0'){
if(texto_[i] != ' '){
vec_aux.resize(vec_aux.size()+1);
vec_aux[j] = texto_[i];
j++;
}
i++;
}
return vec_aux;
}
// Determinar el valor de j, para separar los bloques.
int generar_j(int n_){
vector<int> v;
int mod = 23456789;
v.resize(v.size()+1);
for (int i=0; i<v.size(); i++){
v.resize(v.size()+1);
v[i] = (exponenciacion(26, i, mod));
if (v[i] > n_){
return i;
}
}
}
// Posición de la letra en el alfabeto.
int pos_letra(char letra){
char abecedario[26];
strcpy(abecedario, "ABCDEFGHIJKLMNOPQRSTUVWXYZ");
int numero;
for (int i=0; i<26; i++){
if(abecedario[i] == letra){
numero = i;
break;
}
}
return numero;
}
// Función para pasar de letras a decimales. tam_bloque --> j
int texto_decimal(vector<char> texto, int tam_bloque){
int valor = 0;
double expon = 0;
int base = 26;
int mod = 23456789;
for (int i=0; i<tam_bloque; i++){
expon = exponenciacion(base, ((tam_bloque-1) - i), mod);
valor += pos_letra(texto[i]) * expon;
}
return valor;
}
//Función que va dividiendo el texto en bloques de tamaño j. Devuelve vector con los enteros.
vector<int> dividir_bloques(vector<char> texto, int tam_bloque){
vector<int> enteros;
int i=0;
int k=0;
int x=0;
//cout << "texto.size(): " << texto.size() << endl;
while (i < texto.size()){
vector<char> aux;
aux.resize(tam_bloque);
while(k<tam_bloque){
aux[k] = texto[i];
k++;
i++;
}
cout << "Vector auxiliar (bloque): ";
for (int i=0; i<aux.size(); i++){
cout << aux[i];
}
cout << endl;
k=0;
enteros.resize(enteros.size()+1);
enteros[x] = texto_decimal(aux, tam_bloque);
x++;
}
return enteros;
}
// Cifrado
vector<int> cifrado(vector<int> enteros_, int e_, int n_){
vector<int> cifrado;
cifrado.resize(enteros_.size());
for (int i=0; i<enteros_.size(); i++){
cifrado[i] = exponenciacion(enteros_[i], e_, n_);
}
return cifrado;
}
// Descifrado
vector<int> descifrado(vector<int> cifrado_, int d_, int n_){
vector<int> descifrado;
descifrado.resize(cifrado_.size());
for (int i=0; i<cifrado_.size(); i++){
descifrado[i] = exponenciacion(cifrado_[i], d_, n_);
}
return descifrado;
}
int main(){
int p;
int q;
int d;
int n; // p*q
int phi;
vector<char> texto_f;
cout << "-------------------------------------------------------------------" << endl;
cout << "\t \t \t \t" << "RSA" << endl;
cout << "-------------------------------------------------------------------" << endl;
cout << endl;
cout << "-------------------------------------------------------------------" << endl;
cout << "1: Introducir información necesaria (p, q, d y texto a cifrar)." << endl;
cout << "-------------------------------------------------------------------" << endl;
cout << endl;
// Paso 1 --> Pedimos los valores p, q, d y texto a cifrar.
pedir_valores(p,q,d);
// Calculo de n y phi
n = (p * q);
phi = (p - 1)*(q - 1);
//Pedimos el texto original
string texto = "AMIGO MIO";
cout << "Texto introducido: " << texto << endl;
texto_f = separar(texto);
for (int i=0; i<texto_f.size(); i++){
cout << texto_f[i];
}
/*texto = new char[256];
cout << "Introduzca el texto original: " << endl;
cin.ignore();
cin.getline(texto,256);
texto_f = separar(texto);
cout << "Texto introducido: " << texto << endl;*/
cout << endl;
cout << "-------------------------------------------------------------------" << endl;
cout << "2: Comprobación que p y q son números primos. LEHMAN PERALTA" << endl;
cout << "-------------------------------------------------------------------" << endl;
cout << endl;
lehman_peralta(p);
lehman_peralta(q);
cout << endl;
cout << "-------------------------------------------------------------------" << endl;
cout << "3: Aplicación del algoritmo de EUCLIDES. Parámetro e." << endl;
cout << "-------------------------------------------------------------------" << endl;
int e = euclides(d, phi, n);
cout << "-------------------------------------------------------------------" << endl;
cout << "4: Convertir texto original en enteros." << endl;
cout << "-------------------------------------------------------------------" << endl;
int j = generar_j(n);
cout << "Generar j: " << j << endl;
vector<int> enteros;
enteros = dividir_bloques(texto_f, (j-1));
cout << endl;
cout << "Enteros: ";
for (int i=0; i<enteros.size(); i++){
cout << enteros[i] << " ";
}
cout << endl;
cout << "-------------------------------------------------------------------" << endl;
cout << "5: Cifrado." << endl;
cout << "-------------------------------------------------------------------" << endl;
vector<int> cif;
//cout << "n: " << n << endl;
//cout << "e: " << e << endl;
cif = cifrado(enteros,e,n);
cout << "C: " ;
for (int i=0; i<cif.size(); i++){
cout << cif[i] << " ";
}
cout << endl;
cout << "-------------------------------------------------------------------" << endl;
cout << "6:: Descifrado." << endl;
cout << "-------------------------------------------------------------------" << endl;
vector<int> descif;
//cout << "DESCIFRADO" << endl;
descif = descifrado(cif,d,n);
cout << "M: " ;
for (int i=0; i<descif.size(); i++){
cout << descif[i] << " ";
}
cout << endl;
cout << "-------------------------------------------------------------------" << endl;
return 0;
} | true |
99dc36fc57d13d8f43655fb471559ec873eded53 | C++ | ckdwns9121/Programing-assignment | /DiscreteMathematics2018/exam.cpp | UHC | 2,556 | 3.203125 | 3 | [] | no_license | #include <iostream>
#include <cstdio>
#include <string>
#include <string.h>
#include <fstream>
using namespace std;
#pragma warning(disable:4996)
char Good_word[27]; //
char P_word[1001]; //
char Q_word[1001]; //Q
int func(int P_size, int Q_size, int G_size) {
int index = 0; // ? ġ Ž ε
int star_count = 0; //ִ ڿ
int check = 0;
int i = 0;
int last_check;
for (i = 0; i < P_size; i++) {
if (P_word[i] == '?') {
int count = 0; // 迭 īƮ
for (int j = 0; j < G_size; j++, count++) {
if (Q_word[index] == Good_word[j]) {
index++;
break;
}
}
if (count == G_size) check = 1; // NO
}
else if (P_word[i] == '*') {
int star_size = Q_size - P_size;
if (star_size >= 0) { // !empty string
//int j = 0;
for (int j = index; j <= (index + star_size); j++) {
for (int k = 0; k < G_size; k++) {
if (Q_word[j] == Good_word[k]) {
star_count++;
}
}
}
if (star_count - 1 == star_size) check = 1; //* ڿ ϶
else {
index += star_size + 1;
}
}
}
else if (P_word[i] == Q_word[index]) index++; //ڸִ ε ű
else if (P_word[i] != Q_word[index]) check = 1; //ٸ ̹Ƿ check = 1;
// fasle Ǻ ʿ ٷbreak
if (check == 1) break;
}
if ((i == P_size) && (Q_word[index] == NULL)) last_check = 1;
else if (check == 1)last_check = 0;
return last_check;
}
int main() {
ifstream input_fp("exam.inp");
ofstream output_fp("exam.out");
int last_check;
int count = 1;
int testCase, num;
input_fp >> testCase;
while (testCase--) {
string goodWord, P, Q;
output_fp << "Test Case: #" << count << endl;
input_fp >> goodWord;
for (int i = 0; i < goodWord.size(); i++)Good_word[i] = goodWord[i];
input_fp >> P;
for (int i = 0; i < P.size(); i++) P_word[i] = P[i];
input_fp >> num;
for (int i = 0; i < num; i++) {
input_fp >> Q;
for (int j = 0; j < Q.size(); j++) {
Q_word[j] = Q[j];
}
last_check = func(P.size(), Q.size(), goodWord.size());
if (last_check == 1) output_fp << "Yes" << endl;
else output_fp << "No" << endl;
memset(Q_word, 0, sizeof(Q_word));
}
count++;
memset(Good_word, 0, sizeof(Good_word));
memset(P_word, 0, sizeof(P_word));
}
input_fp.close();
output_fp.close();
return 0;
}
| true |
28fc00c62632d6517d5c6564a1923017427ce991 | C++ | gui2one/wasm_cave_generator | /cpp/cave_generator.cpp | UTF-8 | 5,919 | 2.71875 | 3 | [] | no_license | #include "cave_generator.h"
#include "emscripten/bind.h"
#include <cstdlib>
#include <iostream>
#include <chrono>
// using namespace emscripten;
EMSCRIPTEN_KEEPALIVE
CaveGenerator::CaveGenerator()
{
m_seed = 0;
m_grid.setResX(32);
m_grid.setResY(32);
printf("--- C++ Cave Generator ---\n");
for (size_t j = 0; j < m_grid.m_resy; j++)
{
for (size_t i = 0; i < m_grid.m_resx; i++)
{
cells.push_back(0);
}
}
// printf("CaveGenerator !!!! Fuck Yeah !!!!\n");
}
EMSCRIPTEN_KEEPALIVE
void CaveGenerator::fillRandom()
{
auto secs = std::chrono::system_clock::now().time_since_epoch();
// std::srand(secs.count());
std::srand(m_seed);
std::vector<int> values;
for (size_t y = 0; y < m_grid.m_resy; y++)
{
for (size_t x = 0; x < m_grid.m_resx; x++)
{
int index = y * 4 + x;
int rand_value = double(std::rand()) / (RAND_MAX)*256;
values.push_back(rand_value > threshold ? 255 : 0);
}
/* code */
}
m_grid.m_cells = values;
}
// EMSCRIPTEN_KEEPALIVE
void CaveGenerator::smooth(int iterations)
{
for (int i = 0; i < iterations; i++)
{
std::vector<int> cells_copy(m_grid.m_cells);
for (int y = 0; y < m_grid.m_resy; y++)
{
for (int x = 0; x < m_grid.m_resx; x++)
{
int index = getCellIndex(x, y);
int num = getNumNeighbours(index);
if (num > 4)
{
cells_copy[index] = 255;
}
else if (num < 4)
{
cells_copy[index] = 0;
}
if (x == 0 || x == m_grid.m_resx - 1 || y == 0 || y == m_grid.m_resy - 1)
{
cells_copy[index] = 0;
}
}
}
m_grid.m_cells = cells_copy;
}
}
std::vector<int> CaveGenerator::make_blob(Grid &grid, int mask_value, std::vector<int> &_filled_cells)
{
std::vector<int> blob;
blob.reserve(grid.m_cells.size());
for (int y = 0; y < grid.m_resy; y++)
{
for (int x = 0; x < grid.m_resx; x++)
{
int index = y * grid.m_resx + x;
int val = 0;
if (grid.m_cells[index] == mask_value)
{
val = 255;
}
blob.emplace_back(val);
if (grid.m_cells[index] == mask_value)
{
_filled_cells[index] = 255;
}
}
}
return blob;
}
void CaveGenerator::inspect()
{
// blobs are here to collect the different filled areas
std::vector<std::vector<int>> blobs;
Grid grid_copy(m_grid);
std::vector<int> filled_cells(grid_copy.m_cells);
std::fill(filled_cells.begin(), filled_cells.end(), 0);
int fill_value = 128;
for (int y = 0; y < m_grid.m_resy; y++)
{
for (int x = 0; x < m_grid.m_resx; x++)
{
int index = y * m_grid.m_resx + x;
if (filled_cells[index] != 255)
{
FloodFill2::floodFill4Stack(grid_copy.m_cells, m_grid.m_resx, m_grid.m_resy, x, y, fill_value, m_grid.m_cells[index]);
auto blob = make_blob(grid_copy, fill_value, filled_cells);
blobs.push_back(blob);
}
}
}
std::cout << "Blob count : " << blobs.size() << std::endl;
// m_grid.m_cells = cells;
}
// EMSCRIPTEN_KEEPALIVE
int CaveGenerator::getCellByCoords(int x, int y, std::vector<int> &cur_cells)
{
int index = y * m_grid.m_resx + x;
return cur_cells[index];
}
// EMSCRIPTEN_KEEPALIVE
int CaveGenerator::getCellIndex(int x, int y)
{
int index = y * m_grid.m_resx + x;
return index;
}
// EMSCRIPTEN_KEEPALIVE
int CaveGenerator::getNumNeighbours(int index)
{
int x = index % m_grid.m_resx;
int y = index / m_grid.m_resx;
int num = 0;
if (x > 0 && x < m_grid.m_resx && y > 0 && y < m_grid.m_resy)
{
int cur_cell = getCellByCoords(x, y - 1, m_grid.m_cells);
if (cur_cell > 128)
num++;
cur_cell = getCellByCoords(x + 1, y - 1, m_grid.m_cells);
if (cur_cell > 128)
num++;
cur_cell = getCellByCoords(x + 1, y, m_grid.m_cells);
if (cur_cell > 128)
num++;
cur_cell = getCellByCoords(x + 1, y + 1, m_grid.m_cells);
if (cur_cell > 128)
num++;
cur_cell = getCellByCoords(x, y + 1, m_grid.m_cells);
if (cur_cell > 128)
num++;
cur_cell = getCellByCoords(x - 1, y + 1, m_grid.m_cells);
if (cur_cell > 128)
num++;
cur_cell = getCellByCoords(x - 1, y, m_grid.m_cells);
if (cur_cell > 128)
num++;
cur_cell = getCellByCoords(x - 1, y - 1, m_grid.m_cells);
if (cur_cell > 128)
num++;
}
return num;
}
EMSCRIPTEN_KEEPALIVE
std::vector<int> CaveGenerator::generate()
{
fillRandom();
smooth(m_smooth_iterations);
// inspect();
return m_grid.m_cells;
}
EMSCRIPTEN_BINDINGS(CaveGenerator_example)
{
// emscripten::class_<CaveGenerator>::function<emscripten::internal::DeduceArgumentsTag, signed char *(CaveGenerator::*)()>;
emscripten::class_<CaveGenerator>("CaveGenerator")
.constructor()
.function("generate", &CaveGenerator::generate)
.function("setThreshold", &CaveGenerator::setThreshold)
.function("getWidth", &CaveGenerator::getWidth)
.function("setWidth", &CaveGenerator::setWidth)
.function("getHeight", &CaveGenerator::getHeight)
.function("setHeight", &CaveGenerator::setHeight)
.function("setRandomSeed", &CaveGenerator::setRandomSeed)
.function("setSmoothIterations", &CaveGenerator::setSmoothIterations);
emscripten::register_vector<int>("vector<int>");
}
| true |
5c318b7d2b553e09aa411571bf42b4807ff21037 | C++ | fliphyyY/semestralkaAUS-2 | /SEM222/Hlavna.cpp | UTF-8 | 31,775 | 2.625 | 3 | [] | no_license | #include "Hlavna.h"
//komparatory,musia byt aj pre int aj pre double
// sluzia na rozhodovaniu quick sortu ci bude roztriedenie vzostupne alebo zostupne
// cize podla coho ma triedit udaje
int vzostupnyKomparator(TableItem<string,int> &a,TableItem<string,int> &b) {
if (a.getData() > b.getData()) { return -1; } // tu vymienam ked lave mansie ako prave
if (a.getData() < b.getData()) { return 1; }// nerobi nic
if (a.getData() == b.getData()) { return 0; } // nic neurobi
};
int zostupnyKomparator(TableItem<string, int> &a, TableItem<string, int> &b) {
if (a.getData() > b.getData()) { return 1; } // nevymien ide od najvacsieho po najmansie
if (a.getData() < b.getData()) { return -1; } // vymienam
if (a.getData() == b.getData()) { return 0; }
};
int vzostupnyKomparatorDouble(TableItem<string, double> &a, TableItem<string, double> &b) {
if (a.getData() > b.getData()) { return -1; }
if (a.getData() < b.getData()) { return 1; }
if (a.getData() == b.getData()) { return 0; }
};
int zostupnyKomparatorDouble(TableItem<string, double> &a, TableItem<string, double> &b) {
if (a.getData() > b.getData()) { return 1; }
if (a.getData() < b.getData()) { return -1; }
if (a.getData() == b.getData()) { return 0; }
};
Hlavna::Hlavna()
{
// tabulky pre ukldanie dat o obci okresu a kraja
// musia byt sortnute koli tomu aby bolo vyhladavanie mensie ako O(n)
// metoda bisekcie tusim
zoznamObci = new Table_ArrayList_Sorted<string, Obec*>(functionCompare<string>);
zoznamOkresov = new Table_ArrayList_Sorted<string, Okres*>(functionCompare<string>);// tabulka okresov
zoznamKrajov = new Table_ArrayList_Sorted<string, Kraj*>(functionCompare<string>);
}
Hlavna::~Hlavna()
{
for (TableItem<string,Obec*> *to : * zoznamObci) {
delete to->getData();
}
delete zoznamObci;
for (TableItem<string,Okres*> *t : *zoznamOkresov) {
delete t->getData();
}
/**/
for (TableItem<string, Kraj*> *t : *zoznamKrajov) {
delete t->getData();
}
delete zoznamOkresov;
delete zoznamKrajov;
}
void Hlavna::nacitaj()
{
// pomocny array list pre obce,nemozem este dat do tabulky lebo tam mi ich utriedi a nebudem
//vediet priradit data
ArrayList<Obec*> *zo = new ArrayList<Obec*>();
//nacitaj obce
ifstream subor("obceN.txt"); // iba nazvy vsetkych obci
while (!subor.eof()) {
string aa;
subor >> aa;
Obec *o = new Obec(aa); // vytvorim smernik na obec, a dam do arraylist a vytvorim obec s parametrom nazvom
zo->add(o);
}
// nacitanie vymery so spravnym poctom riadkov
ifstream subor3("vymerav2.txt");
bool koniec = false;
while (!koniec) {
int celkova;
string riadok1 = "";
int a = 0, b = 0;
for (Obec *o : *zo) {
string nazov;
//pre prvu obec
if (a == 0) {
getline(subor3, riadok1); // nacitam jeden riadok
stringstream ss(riadok1); // stringstream to pomocou suboru
ss >> nazov;
for (int i = 1996; i < 2018; i++) {
ss >> celkova;
// vytovrim zaznam s celkovou vymerou a zvysne docastne nastavim na 0 a nastavim
//rok ako kluc v tabulke zaznamom pre danu obec
o->vlozZaznam(new ZaznamObce(celkova, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), i);
a++;
}
}
// pre 2.+obce
else if (riadok1.compare("") != 0) {
stringstream ss(riadok1);
ss >> nazov;
for (int i = 1996; i < 2018; i++) {
ss >> celkova;
o->vlozZaznam(new ZaznamObce(celkova, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), i);
}
}
// cyklus kde si zistim ake data nacitam a podla toho setnem hodnotu
// ak najdem celkovu vymeru znamena to ze pokracujem dalsou obcou
while (1) {
getline(subor3, riadok1);
stringstream ss(riadok1);
ss >> nazov;
if (nazov.compare("Celkovavymerauzemiaobce-mesta(vm2)") == 0) {
break;
}
else if (nazov.compare("Polnohospodarskapoda-spolu(vm2)") == 0) {
for (int i = 1996; i < 2018; i++) {
ss >> b;
o->getZaznam(i)->setPolnohospoPoda(b);
}
}
else if (nazov.compare("Polnohospodarskapoda-ornapoda(vm2)") == 0) {
for (int i = 1996; i < 2018; i++) {
ss >> b;
o->getZaznam(i)->setOrnaPoda(b);
}
}
else if (nazov.compare("Polnohospodarskapoda-chmelnica(vm2)") == 0) {
for (int i = 1996; i < 2018; i++) {
ss >> b;
o->getZaznam(i)->setChmelnica(b);
}
}
else if (nazov.compare("Polnohospodarskapoda-vinica(vm2)") == 0) {
for (int i = 1996; i < 2018; i++) {
ss >> b;
o->getZaznam(i)->setVinica(b);
}
}
else if (nazov.compare("Polnohospodarskapoda-zahrada") == 0) {
for (int i = 1996; i < 2018; i++) {
ss >> b;
o->getZaznam(i)->setZahrada(b);
}
}
else if (nazov.compare("Polnohospodarskapoda-ovocnysad(vm2)") == 0) {
for (int i = 1996; i < 2018; i++) {
ss >> b;
o->getZaznam(i)->setOvocnysad(b);
}
}
else if (nazov.compare("Polnohospodarskapoda-trvalytravnyporast(vm2)") == 0) {
for (int i = 1996; i < 2018; i++) {
ss >> b;
o->getZaznam(i)->setTrvalyTravnaty(b);
}
}
else if (nazov.compare("Nepolnohospodarskapoda-spolu") == 0) {
for (int i = 1996; i < 2018; i++) {
ss >> b;
o->getZaznam(i)->setNepolno(b);
}
}
else if (nazov.compare("Nepolnohospodarskapoda-lesnypozemok(vm2)") == 0) {
for (int i = 1996; i < 2018; i++) {
ss >> b;
o->getZaznam(i)->setLesny(b);
}
}
else if (nazov.compare("Nepolnohospodarskapoda-vodnaplocha(vm2)") == 0) {
for (int i = 1996; i < 2018; i++) {
ss >> b;
o->getZaznam(i)->setVodny(b);
}
}
else if (nazov.compare("Nepolnohospodarskapoda-zastavanaplochaanadvorie(vm2)") == 0) {
for (int i = 1996; i < 2018; i++) {
ss >> b;
o->getZaznam(i)->setZastavany(b);
}
}
else if (nazov.compare("Nepolnohospodarskapoda-ostatnaplocha(vm2)") == 0) {
for (int i = 1996; i < 2018; i++) {
ss >> b;
o->getZaznam(i)->setOstatna(b);
}
//chcem skoncit cyklus po poslednej obci lebo dalsia celkova vymera uz nie je
if (o->getNazov().compare("ZemplinskyBranc") == 0) {
koniec = true;
break;
}
}
}
}
}
//vsetky obce uz so setnutymi datami vlozim do utriedenej tabulky
ifstream subor4("okresy-kraje.txt");
for (Obec *o : *zo) {
string riadok = "", obec, okres, kraj;
bool existujeOkress = true;
bool existujeKrajj = true;
int kodOkresu, kodObce, kodKraja;
getline(subor4, riadok);
if (riadok.compare("") == 0) break;
stringstream ss(riadok);
ss >> kodObce>>obec >>kodOkresu >> okres >> kodKraja>> kraj;
// obci setujem aj id kraja a okresu koli lahsiemu vzhladavaniu v 6+
o->setId(kodObce);
o->setIdOkresu(kodOkresu);
o->setIdKraja(kodKraja);
// ak neexistuje okres vytvorim novy
if (!existujeOkres(okres)) {
Okres *ok = new Okres(okres);
ok->setId(kodOkresu);
ok->vlozObec(o);
vlozOkres(ok);
existujeOkress = false;
}
else {
zoznamOkresov->operator[](okres)->vlozObec(o);
}
// to iste co s okresmi
if (!existujeKraj(kraj)) {
Kraj *k = new Kraj(kraj);
k->setId(kodKraja);
k->vlozOkres(vratOkres(okres));
vlozKraj(k);
existujeKrajj = false;
}
if (!existujeOkress && existujeKrajj) {
zoznamKrajov->operator[](kraj)->vlozOkres(vratOkres(okres));
}
vlozObec(o);
}
// kazdej obci ktoru som uz nacital vlozim zaznam oby
ifstream subor5("oby2.txt");
while (!subor5.eof()) {
string riadok,nazov;
getline(subor5,riadok);
stringstream ss(riadok);
ss >> nazov;
int spolu, zeny, muzi,nezistene;
if (existujeObec(nazov)) {
for (int vek = 0; vek < 110; vek += 5) {
ss >> spolu >> muzi >> zeny>>nezistene;
zoznamObci->operator[](nazov)->vlozZaznamObyvatelstva(new ZaznamObyvatelstva(spolu, zeny, muzi), vek);
}
}
}
delete zo;
}
void Hlavna::vlozObec(Obec * o)
{
zoznamObci->insert(o->getNazov(), o);
}
void Hlavna::vlozOkres(Okres * o)
{
zoznamOkresov->insert(o->getNazov(),o);
}
void Hlavna::vlozKraj(Kraj * k)
{
zoznamKrajov->insert(k->getNazov(),k);
}
bool Hlavna::existujeObec(string o)
{
for (TableItem<string, Obec*> *tt : *zoznamObci) {
if (tt->getKey().compare(o) == 0) {
return true;
}
}
return false;
}
bool Hlavna::existujeOkres(string o)
{
for (TableItem<string,Okres*> *tt : *zoznamOkresov) {
if (tt->getKey().compare(o)==0) {
return true;
}
}
return false;
}
bool Hlavna::existujeKraj(string k)
{
for (TableItem<string,Kraj*> *tt : *zoznamKrajov) {
if (tt->getKey().compare(k) == 0) {
return true;
}
}
return false;
}
Obec * Hlavna::vratObec(string nazov)
{
return zoznamObci->operator[](nazov);
}
Okres * Hlavna::vratOkres(string nazov)
{
return zoznamOkresov->operator[](nazov);
}
//1
void Hlavna::vypisInformcieOObci(string nazov, int rok,int rok2)
{
// pre kazdy rok z rozpatia rokov si vratim dany zaznam a vytiahnem si z neho konkretne informacie
Obec *o = zoznamObci-> operator[](nazov);// z tabulky vyberam podla kluca, snerniku priradim obec ktoru som vybral
if (o != nullptr)
{
for (int i = rok; i < rok2 + 1; i++) {
ZaznamObce *z = o->getZaznam(i);
int vymera = z->getCelkovaVymera();
int orna = z->getornaPoda();
int ovocnesady = z->getovocnysad();
int vodnaPlocha = z->getvodnaPlocha();
int lesnnaPlocha = z->getlesnyPozemok();
int zastavana = z->getzastavanaPlocha();
double vodnaKuVymere = roundf(((double)((double)vodnaPlocha / (double)vymera) * 100) * 100) / 100; // roundf zaokruhluje nahor, vracia percenta
double lesneKuVymere = roundf(((double)((double)lesnnaPlocha / (double)vymera) * 100) * 100) / 100;// prva stovka je na percenta a potom na dve desatine miesta *100 /100
double zastavaneKuVymere = roundf(((double)((double)zastavana / (double)vymera) * 100) * 100) / 100;
cout << "Rok : " << i << endl;
cout << "Celkova vymera : " << vymera << "\nOrna poda : " << orna <<
"\nOvocne sady : " << ovocnesady << "\nPodiel vodnej k celkovej : " << vodnaKuVymere <<
"\nPodiel lesnej k celkovej : " << lesneKuVymere << "\nPodiel zastavanej k celkovej : " <<
zastavaneKuVymere << endl;
cout << endl;
}
}
}
//2a
void Hlavna::zoradPodlaCelkovejVymery(int rok, bool triedenie)
{
//true triedenie znamena zostupny
// docasna tabulka , potrebujem triedit ale nepotrebujem to triedit hned ako vlozim, potom utriedim
Table_ArrayList_Unsorted_Sort<string, int> *docTabulka = new Table_ArrayList_Unsorted_Sort<string, int>(functionCompare<string>);
// vytvorenie pomocnej tabulky a vlozenie dat,kluc bude nazov obci a data budu celkova vymera danej obce
// potom budem mat tabulku kde bude nazov obce a celkova vymera
for (TableItem<string,Obec*> *o : *zoznamObci) { //*o = table item, je to struktura kde mas nejaky kluc a nejake data
docTabulka->insert(o->getKey(),o->getData()->getZaznam(rok)->getCelkovaVymera());// getKey() vrati kluc obce cize jej nazov
// prejdem vsetky obce ktore mam v zozname obci a insertnem // o-> getData() vrati obec, komplet cela obec
}
//getZaznam(rok) vrati celkova vymera....(cely stlpec)
//zotriedenie quickom pomocou komparatorov
if (triedenie) {
docTabulka->sort(zostupnyKomparator); // komparator sa rozhoduje ci pri sortovani to ma prehodit alebo nie
}
else {
docTabulka->sort(vzostupnyKomparator);
}
// vypisat 3k obci na konzolu?
for (TableItem<string,int> *ti : *docTabulka) {
cout << ti->getKey() << endl;
cout << ti->getData() << endl;
}
delete docTabulka;
}
//2b
void Hlavna::zoradPodlaZastavenychKuCelkovej(int rok, bool triedenie)
{
// to iste ako 2a
//true triedenie znamena zostupny
Table_ArrayList_Unsorted_Sort<string, double> *docTabulka = new Table_ArrayList_Unsorted_Sort<string, double>(functionCompare<string>);
for (TableItem<string, Obec*> *o : *zoznamObci) {
int celkova = o->getData()->getZaznam(rok)->getCelkovaVymera(); // zoberiem to co potrebujem // o-: getData() vrati obec, obec vrati data v danom roku
int zastavana = o->getData()->getZaznam(rok)->getzastavanaPlocha();
if (celkova != 0) { // niektore obce mali nulu tak preto tam je ta podmienka
double pomer = (double)(((double)zastavana / (double)celkova)*100); // doublelebo je tam pomer
docTabulka->insert(o->getKey(), pomer); // a hotovy pomer insertnem do tabulky
}
}
if (triedenie) {
docTabulka->sort(zostupnyKomparatorDouble);
}
else {
docTabulka->sort(vzostupnyKomparatorDouble);
}
// vypisat 3k obci na konzolu?
for (TableItem<string, double> *ti : *docTabulka) {
cout << ti->getKey() << endl;
cout << ti->getData() << endl;
}
delete docTabulka;
}
//2c
void Hlavna::zoradPodlaZmenyOrnejKCelkovej(int rok1, int rok2, bool triedenie)
{
//uplne rovanky princip ako 2a
//true triedenie znamena zostupny
Table_ArrayList_Unsorted_Sort<string, double> *docTabulka = new Table_ArrayList_Unsorted_Sort<string, double>(functionCompare<string>);
for (TableItem<string, Obec*> *o : *zoznamObci) {
double pomer1 = 0.0, pomer2=0.0;
// vypocitam si pomer,moze byt aj v obci a potom staci vracat getter ale je to to iste
// moze sa stat ze celkova vymera moze byt 0 preto tie ify
if(o->getData()->getZaznam(rok1)->getCelkovaVymera() !=0)
pomer1 = (double)((double)o->getData()->getZaznam(rok1)->getornaPoda()/(double)o->getData()->getZaznam(rok1)->getCelkovaVymera())*100; // zoberiem z obce v konkretnom roku data ale chcem iba
if (o->getData()->getZaznam(rok2)->getCelkovaVymera() != 0) // ornu podu a celkovu vymeru, je to v percentach
pomer2 = (double)((double)o->getData()->getZaznam(rok2)->getornaPoda() / (double)o->getData()->getZaznam(rok2)->getCelkovaVymera()) * 100; // to iste ale pre druhy rok
docTabulka->insert(o->getKey(),(pomer1-pomer2)); // odpocitam a insertnem do tabulky
}
if (triedenie) {
docTabulka->sort(zostupnyKomparatorDouble);
}
else {
docTabulka->sort(vzostupnyKomparatorDouble);
}
// vypisat 3k obci na konzolu?
for (TableItem<string, double> *ti : *docTabulka) {
cout << ti->getKey() << endl;
cout << ti->getData() << endl;
}
delete docTabulka;
}
//3a
void Hlavna::najOkresOvocneSady(int rok)
{
// v okresoch si scitam pre vsetky obce ovocne sady a vlozim do tabulky s klucom nazvom okresu
Table_ArrayList_Unsorted<string, int> *doc = new Table_ArrayList_Unsorted<string, int>(functionCompare<string>); // kluc je nazov okresu
// v tom to pripade usorted lebo ju nebude sortovat ani nic
for (TableItem<string,Okres*> *tt : *zoznamOkresov) {
doc->insert(tt->getKey(),tt->getData()->getOvocneSady(rok)); // getData() je okres ale chcem to pre konkretny rok
}
int najmensi = INT_MAX;
int najvacsi = 0;
string najv, najm;
// prejdem vsetky data najdem max a min hodnotu zapisem si nazvy do pomocnych stringov a na konci vypisem
for (TableItem<string,int > *tt : *doc) { // int je co som poscitaval ovocne sady a dal do tabulky
if (najmensi > tt->getData()) {
najmensi = tt->getData();
najm = tt->getKey(); // aby som vedel ktory okres tak preto kluc
}
if (najvacsi < tt->getData()) {// to iste ale pre najvacsie
najvacsi = tt->getData();
najv = tt->getKey();
}
}
cout << "Najviac ovocnych sadov ma " << najv << " v pocte " << najvacsi << endl;
cout << "Najmenej ovocnych sadov ma " << najm << " v pocte " << najmensi << endl;
delete doc;
}
//3b
void Hlavna::najOrnaKuOvocnej(int rok)
{
//to iste ako 3a
Table_ArrayList_Unsorted<string, double> *doc = new Table_ArrayList_Unsorted<string, double>(functionCompare<string>);
for (TableItem<string, Okres*> *tt : *zoznamOkresov) {
if (tt->getKey(), tt->getData()->pomerOrnejkOvocnym(rok) != -1)
{
doc->insert(tt->getKey(), tt->getData()->pomerOrnejkOvocnym(rok));
} // do tabulky vkladam uz hotovy pomer, kolko okresov, tolko zaznamov
}
double najmensi = DBL_MAX;
double najvacsi = 0;
string najv, najm;
for (TableItem<string, double > *tt : *doc) { // to iste ako minule
if (najmensi > tt->getData()) {
najmensi = tt->getData();
najm = tt->getKey();
}
if (najvacsi < tt->getData()) {
najvacsi = tt->getData();
najv = tt->getKey();
}
}
cout << "Najvacsi pomer ma " << najv << " v pocte " << najvacsi << endl;
cout << "Najmensi pomer ma " << najm << " v pocte " << najmensi << endl;
delete doc;
}
// 3c
void Hlavna::najLesKuCelkovej(int rok)
{
//to iste ako 3a
Table_ArrayList_Unsorted<string, double> *doc = new Table_ArrayList_Unsorted<string, double>(functionCompare<string>);
for (TableItem<string, Okres*> *tt : *zoznamOkresov) {
doc->insert(tt->getKey(), tt->getData()->podielLesuKVymere(rok));
}
double najmensi = DBL_MAX;
double najvacsi = 0;
string najv, najm;
for (TableItem<string, double > *tt : *doc) {
if (najmensi > tt->getData()) {
najmensi = tt->getData();
najm = tt->getKey();
}
if (najvacsi < tt->getData()) {
najvacsi = tt->getData();
najv = tt->getKey();
}
}
cout << "Najvacsi pomer ma " << najv << " v pocte " << najvacsi << endl;
cout << "Najmensi pomer ma " << najm << " v pocte " << najmensi << endl;
delete doc;
}
//4a
void Hlavna::zoradOkresyPodlaOvocnychKCelkovej(int rok1, int rok2,bool zoradenie)
{
// v okrese si zistim rozdiel medzi rokmi vlozim do tabulky a pomocou komparatorov roztriedim
// metoda na najdeneie rozdielu je v okrese
Table_ArrayList_Unsorted_Sort<string, double> *doc = new Table_ArrayList_Unsorted_Sort<string, double>(functionCompare<string>);
for (TableItem<string,Okres*> *tt :*zoznamOkresov) {
doc->insert(tt->getKey(), tt->getData()->zmenaOvocnychKCelkovej(rok1, rok2)); // do tabulky vlozim udaje pre vsetky okresy, uz hotovu zmenu pomerov
}
if (zoradenie) {
doc->sort(zostupnyKomparatorDouble);
}
else {
doc->sort(vzostupnyKomparatorDouble);
}
for (TableItem<string,double> *tt : *doc) {
cout << tt->getKey() << " " << tt->getData() << endl;// sortnutu tabulku vypisem
}
delete doc;
}
//4b
void Hlavna::zoradOkresyPodlaOrnejKCelkovej(int rok1, int rok2, bool zoradenie)
{// to iste
// v okrese si zistim rozdiel medzi rokmi vlozim do tabulky a pomocou komparatorov roztriedim
// metoda na najdeneie rozdielu je v okrese
Table_ArrayList_Unsorted_Sort<string, double> *doc = new Table_ArrayList_Unsorted_Sort<string, double>(functionCompare<string>);
for (TableItem<string, Okres*> *tt : *zoznamOkresov) {
doc->insert(tt->getKey(), tt->getData()->zmenaOrnejKCelkovej(rok1, rok2));
}
if (zoradenie) {
doc->sort(zostupnyKomparatorDouble);
}
else {
doc->sort(vzostupnyKomparatorDouble);
}
for (TableItem<string, double> *tt : *doc) {
cout << tt->getKey() << " " << tt->getData() << endl;
}
delete doc;
}
//4c
void Hlavna::zoradOkresyPodlaLesovKCelkovej(int rok1, int rok2, bool zoradenie)
{// to iste
// v okrese si zistim rozdiel medzi rokmi vlozim do tabulky a pomocou komparatorov roztriedim
// metoda na najdeneie rozdielu je v okrese
Table_ArrayList_Unsorted_Sort<string, double> *doc = new Table_ArrayList_Unsorted_Sort<string, double>(functionCompare<string>);
for (TableItem<string, Okres*> *tt : *zoznamOkresov) {
doc->insert(tt->getKey(), tt->getData()->zmenaLesnychKCelkovej(rok1, rok2));
}
if (zoradenie) {
doc->sort(zostupnyKomparatorDouble);
}
else {
doc->sort(vzostupnyKomparatorDouble);
}
for (TableItem<string, double> *tt : *doc) {
cout << tt->getKey() << " " << tt->getData() << endl;
}
delete doc;
}
//5 b
void Hlavna::asponXOkresovLesKuCelkovej(int pocet, int rok, double percenta)
{
// prejdem kraj ,najdem kolko okresov splna a ak viac ako zadane tak vypisem
for (TableItem<string, Kraj*>*tt1 : *zoznamKrajov) {
int a = tt1->getData()->getPocetOkresovSplnujucich(percenta, rok);
if (a>= pocet) { // zavolam metodu a overim ci to splna dane kriterium ak ano tak to vypisem
tt1->getData()->vypisOkresy(); // vypisem kazdy kraj ktory to splna a aj pocet okresov v kraji ktore to splnaju
}
}
}
//5a
void Hlavna::podielCelkovejKLesupreKraj(int rok, double percenta)
{
// prejdem vsetky kraje a najdem ten s najvacsim poctom obci splnujucom kriterium
int pocet = 0,idKraja, pocet2 = INT_MAX, idKraja2;
for (TableItem<string,Kraj*> *tt : *zoznamKrajov) {
// v krajoch prejdem okresy a z toho zistim pocet obci, a prejdem vsetky kraje a viem kolko obci to splna hladam kraj kde to je najviac
int a = tt->getData()->pocetObciSlesKuCelkovej(rok,percenta);// pocet je kolko v obci v kraji splna to kriterium
if (tt->getData()->pocetObciSlesKuCelkovej(rok,percenta) > pocet) {
idKraja = tt->getData()->getId(); // tu zistim ktory kraj to bol
pocet = a;
}
if (tt->getData()->pocetObciSlesKuCelkovej(rok, percenta) < pocet2) { // pre kazdy kraj si zistim kolko obci splna kriterium a hladam taky kraj kde je obci najmenej
idKraja2 = tt->getData()->getId();
pocet2 = a;
}
}
cout << "Najviac obci v kraji ktore splnaju kriteria" << endl;
// vypisme obce v kraji ktore splnaju
for (TableItem<string,Obec*> *tt : *zoznamObci) { // mam zoznam obci a kazda obec si pamata id obce a id kraja
if (tt->getData()->getIdKraja() == idKraja && percenta <= tt->getData()->getPodielLesuKCelkovej(rok)) {
cout << tt->getKey() << " " << tt->getData()->getPodielLesuKCelkovej(rok) << endl;
}
}// prejdem vsetky obce a ak sa zhoduje id kraja ktore som nasiel pred tym a potom
// pre kazdu obec zistim to kriterium a ak je mansie tak vypisem aj s pomerom
cout << endl;
cout << "Najmenej obci v kraji ktore splnaju kriteria" << endl;
for (TableItem<string, Obec*> *tt : *zoznamObci) { // prejdem vsetky obce porovnam id z kraja s tym kde je najviac obci a ak ta obec splna kriteriom tak ju vypisem s tym pomerom
if (tt->getData()->getIdKraja() == idKraja2 && percenta <= tt->getData()->getPodielLesuKCelkovej(rok)) {
cout << tt->getKey() << " " << tt->getData()->getPodielLesuKCelkovej(rok) << endl;
}
}
}
//5c
void Hlavna::lesnaKuCelkovejKraj(int rok, double percenta)
{
// prejdem celkove pre kraj a ak viac ako percenta vypisem
for (TableItem<string,Kraj*> *tt : *zoznamKrajov) {
double p = tt->getData()->podielLesnejKCelkovej(rok);
if (p >= percenta) {
cout << tt->getKey() << " " << p << endl;
}
}
}
//6 prvy filter
void Hlavna::ekonomickyAktivniiObyPohlavie(int volba, bool zoradenie) // 0 nezadane1 muzi 2 zeny
{ // v obci mam tabulku ktora si pamata EAO obyvatelstva
//tabulka s klucom nazvom obce,obec ma metodu kde vrati pocet eoa oby 20-65 a uz to len pomocou komparatora sortnem
Table_ArrayList_Unsorted_Sort<string, int> *doc = new Table_ArrayList_Unsorted_Sort<string, int>(functionCompare<string>);
// tabulka si pamata pre vsetky obce EAO, kluc je nazov obce a datu su EAO
for (TableItem<string,Obec*> *tt : *zoznamObci) {
doc->insert(tt->getKey(), tt->getData()->getPocetEkonomickyAktivnych(volba));
// v obci mam metodu ktora podla volby vyberie
}
if (zoradenie) {
doc->sort(zostupnyKomparator); // zoradim
}
else {
doc->sort(vzostupnyKomparator);
}
for (TableItem<string,int> *tt : *doc) {// vypisem
cout << tt->getKey() << " " << tt->getData() << endl;
}
delete doc;
}
//6 druhy filter
void Hlavna::ekonomickyAktovnyVKraji(string kraj, string okres, int volba, bool zoradenie)
{
// zistim ci sa zadal nejaky kraj/okres ak nie prejdem vsetky inak najdem id konkretneho
int idKraja = -1, idOkresu = -1;
if (kraj.compare("") != 0) idKraja = zoznamKrajov->operator[](kraj)->getId(); // ak je zadany kraj tak si zistim id toho kraja, vyberam kraj s klucom, zistim a potom s tym pracujem
if (okres.compare("") != 0) idOkresu = zoznamOkresov->operator[](okres)->getId(); // tak isto
// povkladam do tabulky obce ktore splnaju podmienky
// obce si mapataju aj id svojho okresu a kraja
Table_ArrayList_Unsorted_Sort<string, int> *doc = new Table_ArrayList_Unsorted_Sort<string, int>(functionCompare<string>);
for (TableItem<string,Obec*> *tt : *zoznamObci) {
if (idKraja == -1 && idOkresu == -1) { // nezadal som ani kraj ani okres a vlozim vsetky obce SR
doc->insert(tt->getKey(),tt->getData()->getPocetEkonomickyAktivnych(volba));
}
else if (idKraja != -1 && idOkresu == -1) {// zadal som kraj a nezadal som okres tak vsetky obce kraja
if (idKraja == tt->getData()->getIdKraja()) {
doc->insert(tt->getKey(), tt->getData()->getPocetEkonomickyAktivnych(volba));
}
}
else if (idKraja != -1 && idOkresu != -1) {// ak zadam aj kraj aj okres tak vlozim iba obce z toho okresu
if (idKraja == tt->getData()->getIdKraja() && idOkresu == tt->getData()->getIdOkresu()) {// obec si pamata aj svoj kraj aj svoj okres
doc->insert(tt->getKey(), tt->getData()->getPocetEkonomickyAktivnych(volba)); // ak najdem obec ktora zodpoveda kraju aj okresu tak vtedy ju tam vlozim
}
}
}
if (zoradenie) {
doc->sort(zostupnyKomparator);
}else{
doc->sort(vzostupnyKomparator);
}
for (TableItem<string,int> *tt :*doc) {
cout << tt->getKey() << " " << tt->getData() << endl;
}
delete doc;
}
//7
void Hlavna::zapisDoTextaku(string nazov, string kraj, string okres,int volba,int rok)
{
// rovnaky princip ako v 6ke druhom filtri
int idKraja = -1, idOkresu = -1;
if (kraj.compare("") != 0) {
idKraja = zoznamKrajov->operator[](kraj)->getId(); // najdem id kraja
}
if (okres.compare("") != 0) {
idOkresu = zoznamOkresov->operator[](okres)->getId();// najdem id okresu
}
// vytvoim textak s nazvom aky sa zada v parametri
nazov += ".txt";
ofstream subor(nazov);
// vyhladam obec podla okresu,kraja
for (TableItem<string,Obec*> *tt : *zoznamObci) {
Obec *o = nullptr; // dal som null pointer, presiel som vsetky obce a ak splna podmienky tak som priradil do o
if (idKraja == -1 && idOkresu == -1) { // ak nebol null pointer tak som to zapisal, preto aby som vedel ze ci to zapisat
o = tt->getData();
}
else if (idKraja != - 1 && idOkresu == -1) {
if (tt->getData()->getIdKraja() == idKraja) {
o = tt->getData();
}
}
else if (idKraja != -1 && idOkresu != -1) { // zadal som aj kraj aj okres, tak vypisem obce z toho kraja
if (tt->getData()->getIdKraja() == idKraja && tt->getData()->getIdOkresu() == idOkresu) {
o = tt->getData();
}
}
// zapisem udaje o obci do suboru v danom formate
if (o != nullptr) {
subor << o->getId() << ";" << o->getIdOkresu() << ";" << o->getIdKraja() << ";"
<< o->getPocetEkonomickyAktivnych(volba) << ";" << o->getNazov() << ";" <<
o->getZaznam(rok)->getornaPoda() << ";" << o->getZaznam(rok)->getovocnysad() << endl;
}
}
subor.close();
}
void Hlavna::vyberObce(int jablone, int zemiaky, double percentaJ, double percentaZem,double eao ,string okres,string kraj,int rok)
{
Table_ArrayList_Unsorted_Sort<string, int> *doc1 = new Table_ArrayList_Unsorted_Sort<string, int>(functionCompare<string>); // tabulka obci ktore splnaju podmienky pre zemiaky
Table_ArrayList_Unsorted_Sort<string, int> *doc2 = new Table_ArrayList_Unsorted_Sort<string, int>(functionCompare<string>); // to iste ale pre sady
// to iste co v predchadzajucich 2 krokoch
int idKraja = -1, idOkresu = -1;// nezadal kraj
if (kraj.compare("") != 0) { // toto znamena ze ci si chcem vybrat ze v ktorom kraji a v ktorom okrese
idKraja = zoznamKrajov->operator[](kraj)->getId(); // zistim id kraja z parametra co som zadal
}
if (okres.compare("") != 0) {
idOkresu = zoznamOkresov->operator[](okres)->getId(); // to iste ale s okresom
}
// zistim ci je obec v danom kraji/okrese a ci eao splna zadane percenta
for (TableItem<string, Obec*> *t : *zoznamObci) {
Obec *o = nullptr;
if (idKraja == -1 && idOkresu == -1 && t->getData()->getPercentaEOA() >= eao) { // v obci mam vyratane kolko ich je vsetkych EAO a vypocitam percenta
o = t->getData(); // nezadal som kraj ani okres tak idem dalej
}
else if (idKraja != -1 && idOkresu == -1) {
if (idKraja == t->getData()->getIdKraja() && t->getData()->getPercentaEOA() >= eao) {
o = t->getData();
}
}
else if (idKraja != -1 && idOkresu != -1) {
if (idKraja == t->getData()->getIdKraja() && idOkresu == t->getData()->getIdOkresu() &&
t->getData()->getPercentaEOA() >= eao) {
o = t->getData();
}
}
// ak obec splna zistim ze ma dost percent pre EAO kriterium ktore som zadal
if (o != nullptr) {
if (o->getPercentaOrnejPody(rok) >= percentaZem) { // ak je pomer ornej pody k celkovej vacsi ako podiel ktory zadal biofarmar tak to vlozim do tabulky, je to pre zemiaky
doc1->insert(o->getNazov(), o->getOrnu(rok)); // vzdy v ktorom roku
}
if (o->getPercentaZahrady(rok) >= percentaJ) { // tato podmienka mi overuje ci pomer ovocnych sadov je vacsi ako zadane kriterium pre percentaJabloni
doc2->insert(o->getNazov(), o->getOvocnySad(rok)); // to iste ale pre ovocny sad
}
}
}
if (doc1->size() > 0)
// sortnem koli optimalizacii aby som vybral obec s najvacsou ornou/sadmi
{
doc1->sort(zostupnyKomparator); // kvoli optimalizacii som to zaradil od najvacsej obce po najmansiu
cout << "Obce pre zemiaky" << endl;
int orna = 0;// docasna premenna ktora znamena ze kolko uz biofarmar kupil od obci
for (TableItem<string, int> *t : *doc1) {
int a = t->getData(); // konkretne cislo ornej pody z tabulky pre zemiaky, kolko ma obec ornej pody
if (orna + a >= zemiaky) {
cout << t->getKey() << " " << (zemiaky - orna) << endl;
orna += (zemiaky - orna);
break;
// ak uz by som prekrocil s tou s ktorou kupujem tak kupim iba to co potrebujem
// aby som urobil optimalizaciu tak kupim vsetko co chcem kupit
// uz som kupil dost
}
orna += t->getData();// kolko som kupil pody od jednej obce, a prechdzam vsetky obce foreachom az kym nemam dost
cout << t->getKey() << " " << t->getData() << endl; // get key je nazov obce a get data kolko som kupil
}
if (orna < zemiaky) {
cout << "Nepodarilo sa nakupit dostatocne mnozstvo pre zemiaky " << endl;
}
}
else {
cout << "Ziadna obec nesplna pozadovane kriteria pre nakup pody pre zemiaky" << endl;
}
if (doc2->size() > 0) {
doc2->sort(zostupnyKomparator); // to iste ale pre ovocny sad
cout << "Obce pre jablone" << endl;
int ovocne = 0;
for (TableItem<string, int> *t : *doc2) {
int a = t->getData();
if (ovocne + a >= jablone) {
cout << t->getKey() << " " << (jablone - ovocne) << endl;
ovocne += (jablone - ovocne);
break;
}
ovocne += t->getData();
cout << t->getKey() << " " << t->getData() << endl;
}
if (ovocne < jablone) {
cout << "Nepodarilo sa nakupit dostatocne mnozstvo pre jablone" << endl;
}
}
else
{
cout << "Ziadna obec nesplna pozadovane kriteria pre nakup pody pre ovocne sady" << endl;
}
delete doc1;
delete doc2;
}
| true |
9b3f45a8100451e8335a213be96ea1dd2941a87a | C++ | Altudy/chang-rok | /Algorithm/swea/5293. 이진 문자열 복원.cpp | UTF-8 | 1,077 | 2.734375 | 3 | [] | no_license | #include<iostream>
#include<vector>
#include<algorithm>
#include<stack>
#include<set>
#include<queue>
#include<map>
#include<string>
#include<cstdlib>
#include<limits.h>
#include<cstring>
#include<math.h>
#include<string.h>
using namespace std;
int T;
int A, B, C, D;
string res;
void solve(int a, int b, int c, int d, string s) {
if (res != "")return;
if (a == 0 && b == 0 && c == 0 && d == 0) {
res = s;
return;
}
if (s[s.length() - 1] == '0') {
if (a > 0) {
solve(a - 1, b, c, d, s + '0');
}
if (b > 0 && b == c || b == c + 1) {
solve(a, b - 1, c, d, s + '1');
}
}
else {
if (c > 0 && c == b || c == b + 1) {
solve(a, b, c - 1, d, s + '0');
}
if (d > 0) {
solve(a, b, c, d - 1, s + '1');
}
}
}
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin >> T;
for (int t = 1; t <= T; t++) {
cin >> A >> B >> C >> D;
res = "";
solve(A, B, C, D, "0");
solve(A, B, C, D, "1");
if (res == "") {
cout << "#" << t << " impossible\n";
}
else {
cout << "#" << t << " " << res << "\n";
}
}
return 0;
}
| true |
5b4cb793508ea187a433b7db05a1186d6b458494 | C++ | cjlcarvalho/maratona | /URI/1276.cpp | UTF-8 | 948 | 2.703125 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int main(){
int b, e;
bool letras[26];
string s;
while(getline(cin, s)){
vector<string> v;
memset(letras, false, sizeof(letras));
for(int i = 0; i<int(s.size()); i++){
if(isalpha(s[i]))
letras[s[i] - 97] = true;
}
for(int i = 0; i<26; i++){
if(letras[i]){
string t;
b = i;
e = i + 1;
while(letras[e] && e < 26)
e++;
e--;
t.push_back(char(b + 97));
t.push_back(':');
t.push_back(char(e + 97));
v.push_back(t);
i = e;
}
}
for(int i = 0; i<int(v.size()); i++){
cout << v[i];
if(i != int(v.size()) - 1) cout << ", ";
}
cout << endl;
}
return 0;
}
| true |
b524708612aa2d5813ff0e87651cb02ce3dee0ae | C++ | dshipps/RadChipReleaseBin | /RadCli/CSE125/JSON_Parse.h | UTF-8 | 2,229 | 2.8125 | 3 | [] | no_license | #ifndef JSON_PARSE_H
#define JSON_PARSE_H
#include "rapidjson/document.h"
#include "rapidjson/filestream.h"
#include <stdio.h>
#include <iostream>
class JSON_Parser
{
public:
JSON_Parser(const char* FileName){
fopen_s(&pFile, FileName, "r");
rapidjson::FileStream is(pFile);
document.ParseStream<0>(is);
if (document.IsObject()){
printf("Parsing Map file: %s\n", FileName);
}
else{
printf("ERROR Parsing Map File: %s\n", FileName);
}
fclose(pFile);
}
string GetMapName(){
return document["map_name"].GetString();
}
//SHADERS
int GetShaderCount(){
return document["num_shaders"].GetInt();
}
string GetShaderName(int i){
rapidjson::Value& shaders = document["shaders"];
return shaders[(uint)i]["name"].GetString();
}
string GetShaderVert(int i){
rapidjson::Value& shaders = document["shaders"];
return shaders[(uint)i]["vert"].GetString();
}
string GetShaderFrag(int i){
rapidjson::Value& shaders = document["shaders"];
return shaders[(uint)i]["frag"].GetString();
}
//AUDIO
int GetAudioCount(){
return document["num_audio"].GetInt();
}
string GetAudioName(int i){
rapidjson::Value& audio = document["audio"];
return audio[(uint)i]["name"].GetString();
}
string GetAudioPath(int i){
rapidjson::Value& audio = document["audio"];
return audio[(uint)i]["path"].GetString();
}
//TEXTURE
int GetTextureCount(){
return document["num_texture"].GetInt();
}
string GetTextureName(int i){
rapidjson::Value& texture = document["texture"];
return texture[(uint)i]["name"].GetString();
}
string GetTexturePath(int i){
rapidjson::Value& texture = document["texture"];
return texture[(uint)i]["path"].GetString();
}
string GetTextureType(int i){
rapidjson::Value& texture = document["texture"];
return texture[(uint)i]["type"].GetString();
}
string GetTextureExt(int i){
rapidjson::Value& texture = document["texture"];
return texture[(uint)i]["ext"].GetString();
}
bool GetTextureCube(int i){
rapidjson::Value& texture = document["texture"];
if (texture[(uint)i]["cube"].GetInt()){
return true;
}
else{
return false;
}
}
private:
FILE *pFile;
rapidjson::Document document;
};
#endif /* JSON_PARSE_H */ | true |
ad9e264967225efed832ce7aeaec91114da5cbea | C++ | melihcicek/cpp-kursu-kodlar | /STL/optional/value_03.cpp | UTF-8 | 270 | 3.109375 | 3 | [] | no_license | #include <optional>
#include <iostream>
int main()
{
std::optional<int> opt = {};
try {
int ival = opt.value();
std::cout << "ival = " << ival << "\n";
}
catch (const std::bad_optional_access& e)
{
std::cout << "hata yakalandi : " << e.what() << '\n';
}
}
| true |
579e7e2ccf3f7833f3d5c767b50ae1b54c20c92f | C++ | ekaterin17/Leetcode | /22. Generate Parentheses.cpp | UTF-8 | 571 | 3.078125 | 3 | [] | no_license | class Solution {
public:
vector<string> parenthesis;
vector<string> generateParenthesis(int n) {
getParenthesis(n, 0, 0, "");
return parenthesis;
}
void getParenthesis(int n, int open, int close, string str) {
if (str.length() == 2*n) {
parenthesis.push_back(str);
return;
}
if (open < n) {
getParenthesis(n,open+1,close, str + "(");
}
if (close < open) {
getParenthesis(n,open, close+1, str + ")");
}
}
};
| true |
c3707b58231572d84fa0fccd59f65451e58a49b8 | C++ | joeyuan19/CodeEval | /moderate/cash_register_newtyn.cpp | UTF-8 | 1,888 | 3.203125 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;
void process(string line) {
int idx = line.find(";");
double pp, ch;
stringstream(line.substr(0,idx)) >> pp;
stringstream(line.substr(idx+1,line.size()-(idx+1))) >> ch;
int p = (int)(pp*100);
int c = (int)(ch*100);
if (c < p) {
cout << "ERROR" << endl;
} else if (c == p) {
cout << "ZERO" << endl;
} else {
string out = "";
int i;
c = c-p;
for (i = 0; i < c/10000; i++) {
out += "ONE HUNDRED,";
}
c = c%10000;
for (i = 0; i < c/5000; i++) {
out += "FIFTY,";
}
c = c%5000;
for (i = 0; i < c/2000; i++) {
out += "TWENTY,";
}
c = c%2000;
for (i = 0; i < c/1000; i++) {
out += "TEN,";
}
c = c%1000;
for (i = 0; i < c/500; i++) {
out += "FIVE,";
}
c = c%500;
for (i = 0; i < c/200; i++) {
out += "TWO,";
}
c = c%200;
for (i = 0; i < c/100; i++) {
out += "ONE,";
}
c = c%100;
for (i = 0; i < c/50; i++) {
out += "HALF DOLLAR,";
}
c = c%50;
for (i = 0; i < c/25; i++) {
out += "QUARTER,";
}
c = c%25;
for (i = 0; i < c/10; i++) {
out += "DIME,";
}
c = c%10;
for (i = 0; i < c/5; i++) {
out += "NICKEL,";
}
c = c%5;
for (i = 0; i < ((int)c); i++) {
out += "PENNY,";
}
cout << out.substr(0,out.size()-1) << endl;
}
}
int main(int argc, char *argv[]) {
ifstream f (argv[1]);
string line;
while (getline(f,line)) {
process(line);
}
f.close();
return 0;
}
| true |
7fa37a8e53a727881b049bbba855b6fb650ec879 | C++ | vstflugel/tinykactl | /test/tinystl/orig/10354.cpp | WINDOWS-1252 | 2,745 | 2.96875 | 3 | [] | no_license | /******************************************
*
* @JUDGE_ID: 25719RJ 10354 C++
*
* Problem 10354 "Avoiding the Boss"
*
* David Rydh, <f99-dry@nada.kth.se>
* POPUP Tvling 3 (Valladolid), 2002-09-13
*****************************************/
#include <iostream>
#include <cstdio>
#include <algorithm>
//#include <string>
#include <vector>
//#include <set>
//#include <map>
//#include <cmath>
using namespace std;
const int N = 0;
void init();
bool solve(int P);
template<class V, class M>
void dijkstra( const V &edges, M &min, int start, int n );
int main() {
init();
//while-solve
int n = 0;
while (solve(n))
n++;
return 0;
}
void init() {
}
vector< vector<pair<int,int> > > edges;
vector<pair<int,int> >::iterator edge_iter;
bool solve(int K) {
int P, R, BH, OF, YH, M;
cin >> P >> R >> BH >> OF >> YH >> M;
if (cin.fail()) return false;
BH--;
OF--;
YH--;
M--;
edges.clear();
edges.resize( P );
for( int i=0; i<R; i++ ) {
int n1, n2, cost;
cin >> n1 >> n2 >> cost;
n1--;
n2--;
edges[n1].push_back( make_pair(n2,cost) );
edges[n2].push_back( make_pair(n1,cost) );
}
vector< int > min, min2;
min.resize( P );
min2.resize( P );
dijkstra( edges, min, BH, P );
dijkstra( edges, min2, OF, P );
bool imp = false;
int bossMin = min[OF];
for( int i=0; i<P; i++ ) {
if( min[i]+min2[i] <= bossMin ) {
edges[i].clear();
// cout << "Removing " << i+1 << endl;
if( i==M )
imp = true;
}
}
dijkstra( edges, min, YH, P );
if( min[M] == -1 || imp )
cout << "MISSION IMPOSSIBLE." << endl;
else
cout << min[M] << endl;
return true;
}
template<class V, class M>
void dijkstra( const V &edges, M &min, int start, int n )
{
typedef typename V::value_type::const_iterator E_iter;
typedef typename M::value_type DIST;
const DIST inf = (DIST)0x20000000;
// Initialize min & from
for( int i=0; i<n; i++ )
min[i] = inf;
min[start] = 0;
// Initalize processed
vector<bool> processed;
processed.resize( n, false );
// Find shortest path
while( true ) {
int node;
DIST least = inf;
for( int i=0; i<n; i++ ) {
if( !processed[i] && min[i] < least ) {
node = i;
least = min[i];
}
}
if( least == inf ) // the rest of the nodes are unreachable
break;
// Process node
for( E_iter e=edges[node].begin(); e!=edges[node].end(); e++ ) {
int destNode = (*e).first;
if( !processed[destNode] && min[node]+(*e).second < min[destNode])
min[destNode] = min[node] + (*e).second;
}
processed[node] = true;
}
// Update min to -1 if inf
for( int i=0; i<n; i++ ) {
if( min[i] == inf )
min[i] = -1;
}
}
| true |
87f5b7cba74aaa6d689b2b17269857bfb7cd67af | C++ | mangopudding12/OpenFrameWorks_IAD2_PartTwo_2016 | /Nature_of_Code_oefeningen/Example_h4_3/src/Partical.cpp | UTF-8 | 609 | 2.96875 | 3 | [] | no_license | #include "Partical.h"
Partical::Partical(ofVec2f location_)
{
// Varible een waarde geven
accelaration.set(0, 0.05);
velocity.set(ofRandom(-1, 1), ofRandom(-2, 0));
location = location_;
lifespan = 255.0;
radius = 12;
}
void Partical::run()
{
move();
display();
}
void Partical::move()
{
velocity += accelaration;
location += velocity;
lifespan -= 2;
}
void Partical::display()
{
ofSetColor(lifespan, 200, lifespan, lifespan);
ofFill();
ofEllipse(location.x, location.y, radius, radius);
}
bool Partical::isDead()
{
if (lifespan < 0.0)
{
return true;
}
else {
return false;
}
}
| true |
fbf16bee83ab08e8bb99d41a11de9dcf4f453d67 | C++ | limengjie/leetcode | /cpp/51_2_3.cpp | UTF-8 | 1,651 | 3.328125 | 3 | [] | no_license | #include <iostream>
#include "bin_tree.h"
using namespace std;
////only print
//void preorderTrav(TreeNode * root) {
// //base condition
// if (root == nullptr) return;
// //print root first
// cout << root->_val << " ";
// //print left subtree
// preorderTrav(root->_left);
// //print right subtree
// preorderTrav(root->_right);
//}
void preorderTrav(TreeNode * pnode, vector<int> & res) {
//base condition
if (pnode == nullptr) return;
//save the curent node
res.push_back(pnode->_val);
//save the rest nodes
if (pnode->_left)
preorderTrav(pnode->_left, res);
if (pnode->_right)
preorderTrav(pnode->_right, res);
}
void inorderTrav(TreeNode * pnode, vector<int> & res) {
//base condition
if (pnode == nullptr) return;
//save the left node
if (pnode->_left)
inorderTrav(pnode->_left, res);
//save the curent node
res.push_back(pnode->_val);
//save the right node
if (pnode->_right)
inorderTrav(pnode->_right, res);
}
void postorderTrav(TreeNode * pnode, vector<int> & res) {
//base condition
if (pnode == nullptr) return;
//save the left node
if (pnode->_left)
inorderTrav(pnode->_left, res);
//save the right node
if (pnode->_right)
inorderTrav(pnode->_right, res);
//save the curent node
res.push_back(pnode->_val);
}
int main() {
// int array[] = {6, 4, 10, 2, 5, 7, 11, 1, 3, 0, 0, 9, 8};
int array[] = {1, 0, 2, 3};
TreeNode * root = buildBinTree(array, 4);
vector<int> result;
postorderTrav(root, result);
//print vector
for (size_t i = 0; i < result.size(); ++i)
cout << result[i] << " ";
cout << endl;
// only print
// preorderTrav(root);
// cout << endl;
return 0;
}
| true |
20cf5e7f5dc478acffba6f952bad6bdeec2be5e4 | C++ | kestoc/SisoperParcial2 | /sjf.h | UTF-8 | 3,943 | 3.5 | 4 | [] | no_license | /*
Algorithm: Shortest Job First (SJF)
Members:
- Santiago Collantes Zuluaga
- Kevin Steven Ocampo M.
*/
#include<bits/stdc++.h>
#include <thread>
using namespace std;
struct process3{
int pid; //ID process
int at; //Arrival Time
int bt; //Burst Time
};
// Function to sort the process to AT
bool comparison3(process3 a, process3 b){
return (a.at < b.at);
}
// Function to sort the process to BT
bool comparison4(process3 a, process3 b){
return (a.bt < b.bt);
}
// Function to calculate turn around time
void turnAroundTime(process3 proc[], int N, int wt[], int tat[]){
// calculating turnaround time by adding bt[i] + wt[i]
for (int i = 0; i < N ; i++)
tat[i] = proc[i].bt + wt[i];
}
// Function to find the waiting time for all processes
void waitingTime(process3 proc[], int N, int wt[]){
// Waiting time for first process is 0
wt[0] = 0;
// Calculating waiting time for each process from the given
// formula
for (int i = 1; i < N; i++)
wt[i] = (proc[i - 1].at + proc[i - 1].bt + wt[i - 1]) - proc[i].at;
}
// Function to display Gantt Chart
void dispGanttChart3(process3 proc[],int N, int wt[])
{
int temp, prev = 0;
process3* spaces = proc;
cout << "\n\nGantt Chart SJF :- \n\n+";
// For 1st row of gantt chart
for(int i = 0; i < N; i++) {
cout << string(to_string(spaces[i].pid).length()
+ (spaces[i].pid != -1)
+ 2 * spaces[i].bt,
'-')
<< "+";
}
cout << "\n|";
// For process no. in 2nd row
for(int i = 0; i < N; i++) {
cout << string(spaces[i].bt, ' ');
if (spaces[i].pid == -1)
cout << "IS" << string(spaces[i].bt, ' ') << '|';
else
cout << "P" << spaces[i].pid
<< string(spaces[i].bt, ' ') << '|';
}
cout << "\n+";
for(int i = 0; i < N; i++) {
cout << (string(to_string(spaces[i].pid).length()
+ (spaces[i].pid != -1)
+ 2 * spaces[i].bt,
'-'))
<< "+";
}
cout << "\n0";
//For 3rd row of gantt chart
for(int i = 0; i < N; i++) {
if(spaces[i].at + spaces[i].bt + wt[i] >= 10){
cout << (string(to_string(spaces[i].pid).length()
+ (spaces[i].pid != -1)
+ 2 * spaces[i].bt - 1,
' '))
<< spaces[i].at + spaces[i].bt + wt[i];
}
else {
cout <<(string(to_string(spaces[i].pid).length()
+ (spaces[i].pid != -1)
+ 2 * spaces[i].bt,
' '))
<< spaces[i].at + spaces[i].bt + wt[i];
}
}
cout << "\n\n";
}
// Function to Calculate waiting time and average waiting time
void sjfScheduling(process3 proc[], int N){
//Sorted process by Arrival time
sort(proc, proc + N, comparison3);
//Sorted process by Burst time
sort(proc + 1, proc + N, comparison4);
// Declare auxiliar variables
int wt[N], tat[N], total_wt = 0, total_tat = 0;
//Calculate Waiting Time
waitingTime(proc,N,wt);
//Calculate TurnAround Time
turnAroundTime(proc, N, wt, tat);
//Display processes along with all details
cout << "\nProcesses "<< " BT "
<< " WT/RT " << " TAT\n";
// Calculate total waiting time and total turn around time
for (int i=0; i<N; i++){
total_wt = total_wt + wt[i];
total_tat = total_tat + tat[i];
cout << " P" << proc[i].pid << "\t\t "
<< proc[i].bt << "\t\t" << wt[i]
<< "\t\t " << tat[i] <<endl;
}
cout << "\nAverage WT SJF = " << (float)total_wt / (float)N;
cout << "\nAverage TAT SJF = " << (float)total_tat / (float)N;
//Gantt Chart
dispGanttChart3(proc,N,wt);
} | true |
44678db98662d01d7b03a86997be18e4a6370c46 | C++ | mhotwagner/weather-server | /srv/srv.ino | UTF-8 | 2,687 | 2.625 | 3 | [] | no_license | #include <ESP8266WiFi.h>
#include <SimpleDHT.h>
#include <ESP8266WebServer.h>
const int dhtPin = D5;
// sensor info
SimpleDHT22 dhtSensor(dhtPin);
const int dhtSampleFrequency= 5000;
unsigned long dhtLastSampleTime = 0;
byte temperature = 0;
byte humidity = 0;
// wifi info
const char* wifi_ssid = "Hotswag Manor";
const char* wifi_pass = "xoxo<3!!";
// server info
const int serverPort = 80;
ESP8266WebServer server(serverPort);
String header;
const int ledPin = 2;
void blink(int n) {
for (int i = 0; i < n; i++) {
digitalWrite(ledPin, HIGH);
delay(50);
digitalWrite(ledPin, LOW);
delay(50);
}
}
void initializeWifi() {
Serial.print("[INFO] Connecting to ");
Serial.print(wifi_ssid);
Serial.println("...");
WiFi.begin(wifi_ssid, wifi_pass);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("[INFO] Connected");
Serial.print("[INFO] IP: ");
Serial.println(WiFi.localIP());
}
void initializeServer() {
Serial.println("[INFO] Initializaing server...");
server.on("/", [](){
Serial.println("[INFO] GET /");
String data = "{\"temperature\": " + String(temperature) + ", \"humidity\":" + String(humidity) + "}";
server.send(200, "application/json", data);
});
server.on("/temperature", [](){
Serial.println("[INFO] GET /temperature");
server.sendHeader("Location", "/temperature/", true);
server.send(302, "text/plain", "");
});
server.on("/temperature/", [](){
Serial.println("[INFO] GET /temperature/");
server.send(200, "application/json", String(temperature));
});
server.on("/humidity", [](){
Serial.println("[INFO] GET /humidity");
server.sendHeader("Location", "/humidity/", true);
server.send(302, "text/plain", "");
});
server.on("/humidity/", [](){
Serial.println("[INFO] GET /humidity/");
server.send(200, "application/json", String(humidity));
});
server.begin();
Serial.print("[INFO] Listening on port ");
Serial.println(serverPort);
}
void sampleTemperature() {
Serial.println("[INFO] Sampling...");
dhtSensor.read(&temperature, &humidity, NULL);
Serial.print("[INFO] Temperature: ");
Serial.println(temperature);
Serial.print("[INFO] Humidity: ");
Serial.println(humidity);
}
void temperatureLoop() {
unsigned long currentTime = millis();
if (currentTime - dhtLastSampleTime >= dhtSampleFrequency) {
dhtLastSampleTime = currentTime;
sampleTemperature();
}
}
void setup() {
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
initializeWifi();
initializeServer();
server.begin();
}
void loop() {
temperatureLoop();
server.handleClient();
}
| true |
fa1a347303e326dfd39fd9ce031823b67885f1a1 | C++ | sommars/DEMiCs | /polySys/polyGen/prism.cpp | UTF-8 | 2,249 | 2.890625 | 3 | [] | no_license | //////////////////////////// probGenerate.cpp ////////////////////////////
#include <fstream>
#include <iostream>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
using namespace std;
void outData1(int xDim, int height);
int main (int argc, char* argv[])
{
int i, xDim, height;
if (argc == 3){
xDim = atoi(argv[1]);
height = atoi(argv[2]);
}else{
cout << "Usage: " << argv[0] << " " << "dimension"
<< " " << "#supports" << endl;
exit(0);
}
/* output problem data */
outData1(xDim, height);
}
void outData1(int xDim, int height)
{
int i, j, k;
int zero = 0;
int one = 1;
int** eye;
eye = new int* [xDim];
for(i = 0; i < xDim; i++){
eye[i] = new int [xDim];
memset(eye[i], 0, sizeof(int) * xDim);
}
for(i = 0; i < xDim; i++){
eye[i][i] = 1;
}
//////////////////////////////
cout << "Dim = " << xDim << "\n";
cout << "Support = " << height << "\n\n";
cout << "Elem = ";
for(i = 0; i < height; i++){
cout << 2 * xDim << " ";
}
cout << "\n";
cout << "Type = ";
for(i = 0; i < height; i++){
cout << (double) xDim / (double) height << " ";
}
cout << "\n\n";
////////////////////////////////////////
for(k = 0; k < height; k++){
for(j = 0; j < xDim; j++){
cout << zero + eye[k][j] << " ";
}
cout << "\n";
for(i = 0; i < xDim - 1; i++){
for(j = 0; j < xDim; j++){
if(i == j){
cout << one + eye[k][j] << " ";
}else{
cout << zero + eye[k][j] << " ";
}
}
cout << "\n";
}
////////////////////////////////////////
////////////////////////////////////////
for(j = 0; j < xDim - 1; j++){
cout << zero + eye[k][j] << " ";
}
cout << one + eye[k][xDim - 1] << " \n";
for(i = 0; i < xDim - 1; i++){
for(j = 0; j < xDim - 1; j++){
if(i == j){
cout << one + eye[k][j] << " ";
}else{
cout << zero + eye[k][j] << " ";
}
}
cout << one + eye[k][xDim - 1] << " ";
cout << "\n";
}
cout << "\n";
}
////////////////////////////
if(eye){
for(i = 0; i < xDim; i++) delete [] eye[i];
delete [] eye;
eye = NULL;
}
}
| true |
02bf7ccf63cf00d8d00a09277c46bc22010f4068 | C++ | presscad/cib | /demo/client-calls/client/main.cpp | UTF-8 | 343 | 2.828125 | 3 | [
"MIT"
] | permissive | #include "A.h"
#include <iostream>
void TestClientCallingLibrary(A* pA)
{
std::cout << "a.F() returned " << pA->F() << std::endl;
std::cout << "a.F(5) returned " << pA->F(5) << std::endl;
std::cout << "a.V() returned " << pA->V() << std::endl;
}
int main(int argc, char* argv[])
{
A a;
TestClientCallingLibrary(&a);
return 0;
}
| true |
ced4ad00b56b15f2ef6415b1a7c3adf458646847 | C++ | Avdeenko-Dasha/1-cours | /Option 6/8.1/Vector.h | UTF-8 | 2,553 | 3.6875 | 4 | [] | no_license | #pragma once
template<typename T>
class Vector
{
int size;
T* arr;
public:
Vector();
Vector(int n);
Vector(int n, T value);
Vector(const Vector& other);
int Size();
void resize(int n);
void random();
void push_back(int value);
void pop_back();
void clear();
T& operator[] (int n);
const T& operator[] (int n) const;
~Vector();
};
template<typename T>
std::ostream& operator<<(std::ostream& output, Vector<T>& a)
{
for (int i = 0; i < a.Size(); ++i)
output << a[i] << " ";
output << '\n';
return output;
}
template<typename T>
std::istream& operator>>(std::istream& input, Vector<T>& a)
{
for (int i = 0; i < a.Size(); ++i)
input >> a[i];
return input;
}
template<typename T>
inline Vector<T>::Vector()
{
size = 0;
arr = NULL;
}
template<typename T>
inline Vector<T>::Vector(int n)
{
arr = new T[n];
size = n;
for (int i = 0; i < n; ++i)
arr[i] = 0;
}
template<typename T>
inline Vector<T>::Vector(int n, T value)
{
size = n;
arr = new T[n];
for (int i = 0; i < n; ++i)
arr[i] = value;
}
template<typename T>
inline Vector<T>::Vector(const Vector& other)
{
size = other.size;
arr = new T[size];
for (int i = 0; i < size; ++i)
arr[i] = other.arr[i];
}
template<typename T>
inline int Vector<T>::Size()
{
return size;
}
template<typename T>
inline void Vector<T>::resize(int n)
{
T* new_arr = new T[n];
if (n > size)
{
for (int i = 0; i < size; ++i)
new_arr[i] = arr[i];
for (int i = size; i < n; ++i)
new_arr[i] = 0;
}
else
for (int i = 0; i < n; ++i)
new_arr[i] = arr[i];
delete[] arr;
arr = new_arr;
size = n;
}
template<typename T>
inline void Vector<T>::random()
{
for (int i = 0; i < size; ++i)
arr[i] = rand() % 10;
}
template<typename T>
inline void Vector<T>::push_back(int value)
{
T* new_arr = new T[size + 1];
for (int i = 0; i < size; ++i)
new_arr[i] = arr[i];
new_arr[size] = value;
size++;
delete[] arr;
arr = new_arr;
}
template<typename T>
inline void Vector<T>::pop_back()
{
size--;
T* new_arr = new T[size];
for (int i = 0; i < size; ++i)
new_arr[i] = arr[i];
delete[] arr;
arr = new_arr;
}
template<typename T>
inline void Vector<T>::clear()
{
delete[] arr;
arr = NULL;
size = 0;
}
template<typename T>
inline T& Vector<T>::operator[](int n)
{
if (n < size && n >= 0)
return arr[n];
else
return arr[size - 1];
}
template<typename T>
inline const T& Vector<T>::operator[](int n) const
{
if (n < size && n >= 0)
return arr[n];
else
return arr[size - 1];
}
template<typename T>
inline Vector<T>::~Vector()
{
clear();
}
| true |
cb78c01da61d2a2b3aea1f66df080bffd4030642 | C++ | licarijd/udemy-advanced-cpp | /4. Operator Overloading/c. Complex Number Class/Complex.h | UTF-8 | 792 | 3.015625 | 3 | [] | no_license | #ifndef COMPLEX_H_
#define COMPLEX_H_
#include <iostream>
using namespace std;
namespace justinlicari {
class Complex {
private:
double real;
double imaginary;
public:
Complex();
Complex(double real, double imaginary);
Complex(const Complex &other);
const Complex &operator=(const Complex &other);
// We need to declare these as const so C++ knows we won't change the method
// (and so we can use 'const Complex &c' in the stream operator overload
// in Complex.cpp).
double getReal() const { return real; }
double getImaginary() const { return imaginary; }
};
// Prototype of the stream insertion operator.
ostream &operator<<(ostream &out, const Complex &c);
}
#endif /* COMPLEX_H_ */ | true |
d1ec14b0260a30691a0dbfd1b4ddbcb6856f333b | C++ | yuehuhu/POJ-dynamic-programming | /POJ3624 Charm Bracelet3.cpp | GB18030 | 581 | 2.671875 | 3 | [] | no_license | //ʹö̬滮һά飬emmmmmacceptˣ
#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;
int N, M;
int w[3500], d[3500];
int dp[12888];
int S = 0;
void solve()
{
for (int i = 0; i < N; i++)
{
for (int j = M; j >= 0; j--)
{
if (w[i] <= j)
{
dp[j] = max(dp[j], dp[j - w[i]] + d[i]);
}
}
}
}
int main()
{
scanf("%d %d", &N, &M);
for (int i = 0; i < N; i++)
{
scanf("%d %d", &w[i], &d[i]);
}
solve();
S = dp[M];
printf("%d", S);
return 0;
} | true |
9afb9ffecfa63e9cf16f0640dc44b34c62967138 | C++ | orel1108/hackerrank | /practice/cpp/classes/class_template_specialisation.cpp | UTF-8 | 675 | 2.890625 | 3 | [] | no_license | template<>
struct Traits<Color>
{
static string name(int i_idx)
{
if (i_idx == 0)
{
return "red";
}
if (i_idx == 1)
{
return "green";
}
if (i_idx == 2)
{
return "orange";
}
return "unknown";
}
};
template<>
struct Traits<Fruit>
{
static string name(int i_idx)
{
if (i_idx == 0)
{
return "apple";
}
if (i_idx == 1)
{
return "orange";
}
if (i_idx == 2)
{
return "pear";
}
return "unknown";
}
};
| true |
4cac3f0551b6ccea9f3f0163e21a1dfba1ca4eca | C++ | splinterofchaos/Gravity-Battle | /Config.h | UTF-8 | 810 | 2.921875 | 3 | [] | no_license |
#include <string>
#include <map>
#include <fstream>
class Config
{
//static std::ofstream out;
void set_defaults();
public:
typedef std::map< std::string, std::string > Vars;
Vars vars;
Config( const std::string& filename );
Config();
bool reload( const std::string& filename );
template< typename T >
bool get( const std::string& handle, T* x ) const;
std::string& operator [] ( const std::string& handle );
const std::string& operator [] ( const std::string& handle ) const;
};
template< typename T >
bool Config::get( const std::string& handle, T* x ) const
{
Vars::const_iterator it = vars.find( handle );
if( it != vars.end() ) {
std::stringstream ss( it->second );
ss >> (*x);
return true;
}
return false;
}
| true |
46d8c47a077dabf4433fd26401aa8ceab48d80b7 | C++ | iridium-browser/iridium-browser | /buildtools/third_party/libc++/trunk/test/std/utilities/any/any.nonmembers/any.cast/any_cast_pointer.pass.cpp | UTF-8 | 5,409 | 2.890625 | 3 | [
"BSD-3-Clause",
"NCSA",
"MIT",
"LLVM-exception",
"Apache-2.0"
] | permissive | //===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// UNSUPPORTED: c++03, c++11, c++14
// XFAIL: availability-bad_any_cast-missing && !no-exceptions
// <any>
// template <class ValueType>
// ValueType const* any_cast(any const *) noexcept;
//
// template <class ValueType>
// ValueType * any_cast(any *) noexcept;
#include <any>
#include <type_traits>
#include <cassert>
#include "test_macros.h"
#include "any_helpers.h"
// Test that the operators are properly noexcept.
void test_cast_is_noexcept() {
std::any a;
ASSERT_NOEXCEPT(std::any_cast<int>(&a));
const std::any& ca = a;
ASSERT_NOEXCEPT(std::any_cast<int>(&ca));
}
// Test that the return type of any_cast is correct.
void test_cast_return_type() {
std::any a;
ASSERT_SAME_TYPE(decltype(std::any_cast<int>(&a)), int*);
ASSERT_SAME_TYPE(decltype(std::any_cast<int const>(&a)), int const*);
const std::any& ca = a;
ASSERT_SAME_TYPE(decltype(std::any_cast<int>(&ca)), int const*);
ASSERT_SAME_TYPE(decltype(std::any_cast<int const>(&ca)), int const*);
}
// Test that any_cast handles null pointers.
void test_cast_nullptr() {
std::any *a = nullptr;
assert(nullptr == std::any_cast<int>(a));
assert(nullptr == std::any_cast<int const>(a));
const std::any *ca = nullptr;
assert(nullptr == std::any_cast<int>(ca));
assert(nullptr == std::any_cast<int const>(ca));
}
// Test casting an empty object.
void test_cast_empty() {
{
std::any a;
assert(nullptr == std::any_cast<int>(&a));
assert(nullptr == std::any_cast<int const>(&a));
const std::any& ca = a;
assert(nullptr == std::any_cast<int>(&ca));
assert(nullptr == std::any_cast<int const>(&ca));
}
// Create as non-empty, then make empty and run test.
{
std::any a(42);
a.reset();
assert(nullptr == std::any_cast<int>(&a));
assert(nullptr == std::any_cast<int const>(&a));
const std::any& ca = a;
assert(nullptr == std::any_cast<int>(&ca));
assert(nullptr == std::any_cast<int const>(&ca));
}
}
template <class Type>
void test_cast() {
assert(Type::count == 0);
Type::reset();
{
std::any a = Type(42);
const std::any& ca = a;
assert(Type::count == 1);
assert(Type::copied == 0);
assert(Type::moved == 1);
// Try a cast to a bad type.
// NOTE: Type cannot be an int.
assert(std::any_cast<int>(&a) == nullptr);
assert(std::any_cast<int const>(&a) == nullptr);
assert(std::any_cast<int const volatile>(&a) == nullptr);
// Try a cast to the right type, but as a pointer.
assert(std::any_cast<Type*>(&a) == nullptr);
assert(std::any_cast<Type const*>(&a) == nullptr);
// Check getting a unqualified type from a non-const any.
Type* v = std::any_cast<Type>(&a);
assert(v != nullptr);
assert(v->value == 42);
// change the stored value and later check for the new value.
v->value = 999;
// Check getting a const qualified type from a non-const any.
Type const* cv = std::any_cast<Type const>(&a);
assert(cv != nullptr);
assert(cv == v);
assert(cv->value == 999);
// Check getting a unqualified type from a const any.
cv = std::any_cast<Type>(&ca);
assert(cv != nullptr);
assert(cv == v);
assert(cv->value == 999);
// Check getting a const-qualified type from a const any.
cv = std::any_cast<Type const>(&ca);
assert(cv != nullptr);
assert(cv == v);
assert(cv->value == 999);
// Check that no more objects were created, copied or moved.
assert(Type::count == 1);
assert(Type::copied == 0);
assert(Type::moved == 1);
}
assert(Type::count == 0);
}
void test_cast_non_copyable_type()
{
// Even though 'any' never stores non-copyable types
// we still need to support any_cast<NoCopy>(ptr)
struct NoCopy { NoCopy(NoCopy const&) = delete; };
std::any a(42);
std::any const& ca = a;
assert(std::any_cast<NoCopy>(&a) == nullptr);
assert(std::any_cast<NoCopy>(&ca) == nullptr);
}
void test_cast_array() {
int arr[3];
std::any a(arr);
RTTI_ASSERT(a.type() == typeid(int*)); // contained value is decayed
// We can't get an array out
int (*p)[3] = std::any_cast<int[3]>(&a);
assert(p == nullptr);
}
void test_fn() {}
void test_cast_function_pointer() {
using T = void(*)();
std::any a(test_fn);
// An any can never store a function type, but we should at least be able
// to ask.
assert(std::any_cast<void()>(&a) == nullptr);
T fn_ptr = std::any_cast<T>(a);
assert(fn_ptr == test_fn);
}
int main(int, char**) {
test_cast_is_noexcept();
test_cast_return_type();
test_cast_nullptr();
test_cast_empty();
test_cast<small>();
test_cast<large>();
test_cast_non_copyable_type();
test_cast_array();
test_cast_function_pointer();
return 0;
}
| true |
6723c3d376a30c128d058f5d71966bbb0f1ebafa | C++ | steprevolution/stepmaniax-sdk | /sdk/Windows/SMXPanelAnimation.cpp | UTF-8 | 17,167 | 2.640625 | 3 | [
"MIT"
] | permissive | // Handle playing GIF animations from inside SMXConfig.
//
// This can load two GIF animations, one for when panels are released
// and one for when they're pressed, and play them automatically on the
// pad in the background. Applications that control lights can do more
// sophisticated things with the lights, but this gives an easy way for
// people to create simple animations.
//
// If you're implementing the SDK in a game, you don't need this and should
// use SMX.h instead.
//
// An animation is a single GIF with animations for all panels, in the
// following layout:
//
// 0000|1111|2222
// 0000|1111|2222
// 0000|1111|2222
// 0000|1111|2222
// --------------
// 3333|4444|5555
// 3333|4444|5555
// 3333|4444|5555
// 3333|4444|5555
// --------------
// 6666|7777|8888
// 6666|7777|8888
// 6666|7777|8888
// 6666|7777|8888
// x-------------
//
// The - | regions are ignored and are only there to space out the animation
// to make it easier to view.
//
// The extra bottom row is a flag row and should normally be black. The first
// pixel (bottom-left) optionally marks a loop frame. By default, the animation
// plays all the way through and then loops back to the beginning. If the loop
// frame pixel is white, it marks a frame to loop to instead of the beginning.
// This allows pressed animations to have a separate lead-in and loop.
//
// Each animation is for a single pad. You can load the same animation for both
// pads or use different ones.
#include "SMXPanelAnimation.h"
#include "SMXManager.h"
#include "SMXDevice.h"
#include "SMXThread.h"
using namespace std;
using namespace SMX;
namespace {
Mutex g_Lock;
}
#define LIGHTS_PER_PANEL 25
// XXX: go to sleep if there are no pads connected
struct AnimationState
{
SMXPanelAnimation animation;
// Seconds into the animation:
float fTime = 0;
// The currently displayed frame:
int iCurrentFrame = 0;
bool bPlaying = false;
double m_fLastUpdateTime = -1;
// Return the current animation frame.
const vector<SMXGif::Color> &GetAnimationFrame() const
{
// If we're not playing, return an empty array. As a sanity check, do this
// if the frame is out of bounds too.
if(!bPlaying || iCurrentFrame >= animation.m_aPanelGraphics.size())
{
static vector<SMXGif::Color> dummy;
return dummy;
}
return animation.m_aPanelGraphics[iCurrentFrame];
}
// Start the animation if it's not playing.
void Play()
{
bPlaying = true;
}
// Stop and disable the animation.
void Stop()
{
bPlaying = false;
Rewind();
}
// Reset to the first frame.
void Rewind()
{
fTime = 0;
iCurrentFrame = 0;
}
// Advance the animation by fSeconds.
void Update()
{
// fSeconds is the time since the last update:
double fNow = SMX::GetMonotonicTime();
double fSeconds = m_fLastUpdateTime == -1? 0: (fNow - m_fLastUpdateTime);
m_fLastUpdateTime = fNow;
if(!bPlaying || animation.m_aPanelGraphics.empty())
return;
// If the current frame is past the end, a new animation was probably
// loaded.
if(iCurrentFrame >= animation.m_aPanelGraphics.size())
Rewind();
// Advance time.
fTime += fSeconds;
// If we're still on this frame, we're done.
float fFrameDuration = animation.m_iFrameDurations[iCurrentFrame];
if(fTime - 0.00001f < fFrameDuration)
return;
// If we've passed the end of the frame, move to the next frame. Don't
// skip frames if we're updating too quickly.
fTime -= fFrameDuration;
if(fTime > 0)
fTime = 0;
// Advance the frame.
iCurrentFrame++;
// If we're at the end of the frame, rewind to the loop frame.
if(iCurrentFrame == animation.m_aPanelGraphics.size())
iCurrentFrame = animation.m_iLoopFrame;
}
};
struct AnimationStateForPad
{
// asLightsData is an array of lights data to send to the pad and graphic
// is an animation graphic. Overlay graphic on top of the lights.
void OverlayLights(char *asLightsData, const vector<SMXGif::Color> &graphic) const
{
// Stop if this graphic isn't loaded or is paused.
if(graphic.empty())
return;
for(int i = 0; i < graphic.size(); ++i)
{
if(i >= LIGHTS_PER_PANEL)
return;
// If this color is transparent, leave the released animation alone.
if(graphic[i].color[3] == 0)
continue;
asLightsData[i*3+0] = graphic[i].color[0];
asLightsData[i*3+1] = graphic[i].color[1];
asLightsData[i*3+2] = graphic[i].color[2];
}
}
// Return the command to set the current animation state as pad lights.
string GetLightsCommand(int iPadState, const SMXConfig &config) const
{
g_Lock.AssertLockedByCurrentThread();
// If AutoLightingUsePressedAnimations is set, use lights animations.
// If it's not (the config tool is set to step color), mimic the built-in
// step color behavior instead of using pressed animations. Any released
// animation will always be used.
bool bUsePressedAnimations = config.flags & PlatformFlags_AutoLightingUsePressedAnimations;
const int iBytesPerPanel = LIGHTS_PER_PANEL*3;
const int iTotalLights = 9*iBytesPerPanel;
string result(iTotalLights, 0);
for(int panel = 0; panel < 9; ++panel)
{
// The portion of lights data for this panel:
char *out = &result[panel*iBytesPerPanel];
// Skip this panel if it's not in autoLightPanelMask.
if(!(config.autoLightPanelMask & (1 << panel)))
continue;
// Add the released animation, then overlay the pressed animation if we're pressed.
OverlayLights(out, animations[SMX_LightsType_Released][panel].GetAnimationFrame());
bool bPressed = bool(iPadState & (1 << panel));
if(bPressed && bUsePressedAnimations)
OverlayLights(out, animations[SMX_LightsType_Pressed][panel].GetAnimationFrame());
else if(bPressed && !bUsePressedAnimations)
{
// Light all LEDs on this panel using stepColor.
double LightsScaleFactor = 0.666666f;
const uint8_t *color = &config.stepColor[panel*3];
for(int light = 0; light < LIGHTS_PER_PANEL; ++light)
{
for(int i = 0; i < 3; ++i)
{
// stepColor is scaled to the 0-170 range. Scale it back to the 0-255 range.
// User applications don't need to worry about this since they normally don't
// need to care about stepColor.
uint8_t c = color[i];
c = (uint8_t) lrintf(min(255.0f, c / LightsScaleFactor));
out[light*3+i] = c;
}
}
}
}
return result;
}
// State for both animations on each panel:
AnimationState animations[NUM_SMX_LightsType][9];
};
namespace
{
// Animations and animation states for both pads.
AnimationStateForPad pad_states[2];
}
namespace {
// The X,Y positions of each possible panel.
vector<pair<int,int>> graphic_positions = {
{ 0,0 },
{ 1,0 },
{ 2,0 },
{ 0,1 },
{ 1,1 },
{ 2,1 },
{ 0,2 },
{ 1,2 },
{ 2,2 },
};
// Given a 14x15 graphic frame and a panel number, return an array of 16 colors, containing
// each light in the order it's sent to the master controller.
void ConvertToPanelGraphic16(const SMXGif::GIFImage &src, vector<SMXGif::Color> &dst, int panel)
{
dst.clear();
// The top-left corner for this panel:
int x = graphic_positions[panel].first * 5;
int y = graphic_positions[panel].second * 5;
// Add the 4x4 grid.
for(int dy = 0; dy < 4; ++dy)
for(int dx = 0; dx < 4; ++dx)
dst.push_back(src.get(x+dx, y+dy));
// These animations have no data for the 3x3 grid, so just set them to transparent.
for(int dy = 0; dy < 3; ++dy)
for(int dx = 0; dx < 3; ++dx)
dst.push_back(SMXGif::Color(0,0,0,0));
}
// Given a 23x24 graphic frame and a panel number, return an array of 25 colors, containing
// each light in the order it's sent to the master controller.
void ConvertToPanelGraphic25(const SMXGif::GIFImage &src, vector<SMXGif::Color> &dst, int panel)
{
dst.clear();
// The top-left corner for this panel:
int x = graphic_positions[panel].first * 8;
int y = graphic_positions[panel].second * 8;
// Add the 4x4 grid first.
for(int dy = 0; dy < 4; ++dy)
for(int dx = 0; dx < 4; ++dx)
dst.push_back(src.get(x+dx*2, y+dy*2));
// Add the 3x3 grid.
for(int dy = 0; dy < 3; ++dy)
for(int dx = 0; dx < 3; ++dx)
dst.push_back(src.get(x+dx*2+1, y+dy*2+1));
}
}
// Load an array of animation frames as a panel animation. Each frame must
// be 14x15 or 23x24.
void SMXPanelAnimation::Load(const vector<SMXGif::SMXGifFrame> &frames, int panel)
{
m_aPanelGraphics.clear();
m_iFrameDurations.clear();
m_iLoopFrame = -1;
for(int frame_no = 0; frame_no < frames.size(); ++frame_no)
{
const SMXGif::SMXGifFrame &gif_frame = frames[frame_no];
// If the bottom-left pixel is white, this is the loop frame, which marks the
// frame the animation should start at after a loop. This is global to the
// animation, not specific to each panel.
SMXGif::Color marker = gif_frame.frame.get(0, gif_frame.frame.height-1);
if(marker.color[3] == 0xFF && marker.color[0] >= 0x80)
{
// We shouldn't see more than one of these. If we do, use the first.
if(m_iLoopFrame == -1)
m_iLoopFrame = frame_no;
}
// Extract this frame. If the graphic is 14x15 it's a 4x4 animation,
// and if it's 23x24 it's 25-light.
vector<SMXGif::Color> panel_graphic;
if(frames[0].width == 14)
ConvertToPanelGraphic16(gif_frame.frame, panel_graphic, panel);
else
ConvertToPanelGraphic25(gif_frame.frame, panel_graphic, panel);
// GIFs have a very low-resolution duration field, with 10ms units.
// The panels run at 30 FPS internally, or 33 1/3 ms, but GIF can only
// represent 30ms or 40ms. Most applications will probably output 30,
// but snap both 30ms and 40ms to exactly 30 FPS to make sure animations
// that are meant to run at native framerate do.
float seconds;
if(gif_frame.milliseconds == 30 || gif_frame.milliseconds == 40)
seconds = 1 / 30.0f;
else
seconds = gif_frame.milliseconds / 1000.0;
m_aPanelGraphics.push_back(panel_graphic);
m_iFrameDurations.push_back(seconds);
}
// By default, loop back to the first frame.
if(m_iLoopFrame == -1)
m_iLoopFrame = 0;
}
#include "SMXPanelAnimationUpload.h"
// Load a GIF into SMXLoadedPanelAnimations::animations.
bool SMX_LightsAnimation_Load(const char *gif, int size, int pad, SMX_LightsType type, const char **error)
{
// Parse the GIF.
string buf(gif, size);
vector<SMXGif::SMXGifFrame> frames;
if(!SMXGif::DecodeGIF(buf, frames) || frames.empty())
{
*error = "The GIF couldn't be read.";
return false;
}
// Check the dimensions of the image. We only need to check the first, the
// others will always have the same size.
if((frames[0].width != 14 || frames[0].height != 15) && (frames[0].width != 23 || frames[0].height != 24))
{
*error = "The GIF must be 14x15 or 23x24.";
return false;
}
// Load the graphics into SMXPanelAnimations.
SMXPanelAnimation animations[9];
for(int panel = 0; panel < 9; ++panel)
animations[panel].Load(frames, panel);
// Set up the upload for this graphic.
if(!SMX_LightsUpload_PrepareUpload(pad, type, animations, error))
return false;
// Lock while we access pad_states.
g_Lock.AssertNotLockedByCurrentThread();
LockMutex L(g_Lock);
// Commit the animation to pad_states now that we know there are no errors.
for(int panel = 0; panel < 9; ++panel)
{
SMXPanelAnimation &animation = pad_states[pad].animations[type][panel].animation;
animation = animations[panel];
}
return true;
}
namespace
{
double g_fStopAnimatingUntil = -1;
}
void SMXAutoPanelAnimations::TemporaryStopAnimating()
{
// Stop animating for 100ms.
double fStopForSeconds = 1/10.0f;
g_fStopAnimatingUntil = SMX::GetMonotonicTime() + fStopForSeconds;
}
// A thread to handle setting light animations. We do this in a separate
// thread rather than in the SMXManager thread so this can be treated as
// if it's external application thread, and it's making normal threaded
// calls to SetLights.
class PanelAnimationThread: public SMXThread
{
public:
static shared_ptr<PanelAnimationThread> g_pSingleton;
PanelAnimationThread():
SMXThread(g_Lock)
{
Start("SMX light animations");
}
private:
void ThreadMain()
{
m_Lock.Lock();
// Update lights at 30 FPS.
const int iDelayMS = 33;
while(!m_bShutdown)
{
// Check if we've temporarily stopped updating lights.
bool bSkipUpdate = g_fStopAnimatingUntil > SMX::GetMonotonicTime();
// Run a single panel lights update.
if(!bSkipUpdate)
UpdateLights();
// Wait up to 30 FPS, or until we're signalled. We can only be signalled
// if we're shutting down, so we don't need to worry about partial frame
// delays.
m_Event.Wait(iDelayMS);
}
m_Lock.Unlock();
}
// Return lights for the given pad and pad state, using the loaded panel animations.
bool GetCurrentLights(string &asLightsDataOut, int pad, int iPadState)
{
m_Lock.AssertLockedByCurrentThread();
// Get this pad's configuration.
SMXConfig config;
if(!SMXManager::g_pSMX->GetDevice(pad)->GetConfig(config))
return false;
// If this controller handles animation itself, don't handle it here too. It can
// lead to confusing situations if SMXConfig's animations don't match the ones stored
// on the pad.
if(config.masterVersion >= 4)
return false;
AnimationStateForPad &pad_state = pad_states[pad];
// Make sure the correct animations are playing.
for(int panel = 0; panel < 9; ++panel)
{
// The released animation is always playing.
pad_state.animations[SMX_LightsType_Released][panel].Play();
// The pressed animation only plays while the button is pressed,
// and rewind when it's released.
bool bPressed = iPadState & (1 << panel);
if(bPressed)
pad_state.animations[SMX_LightsType_Pressed][panel].Play();
else
pad_state.animations[SMX_LightsType_Pressed][panel].Stop();
}
// Set the current state.
asLightsDataOut = pad_state.GetLightsCommand(iPadState, config);
// Advance animations.
for(int type = 0; type < NUM_SMX_LightsType; ++type)
{
for(int panel = 0; panel < 9; ++panel)
pad_state.animations[type][panel].Update();
}
return true;
}
// Run a single light animation update.
void UpdateLights()
{
string asLightsData[2];
bool bHaveLights = false;
for(int pad = 0; pad < 2; pad++)
{
int iPadState = SMXManager::g_pSMX->GetDevice(pad)->GetInputState();
if(GetCurrentLights(asLightsData[pad], pad, iPadState))
bHaveLights = true;
}
// Update lights.
if(bHaveLights)
SMXManager::g_pSMX->SetLights(asLightsData);
}
};
void SMX_LightsAnimation_SetAuto(bool enable)
{
if(!enable)
{
// If we're turning off, shut down the thread if it's running.
if(PanelAnimationThread::g_pSingleton)
PanelAnimationThread::g_pSingleton->Shutdown();
PanelAnimationThread::g_pSingleton.reset();
return;
}
// Create the animation thread if it's not already running.
if(PanelAnimationThread::g_pSingleton)
return;
PanelAnimationThread::g_pSingleton.reset(new PanelAnimationThread());
}
shared_ptr<PanelAnimationThread> PanelAnimationThread::g_pSingleton;
| true |
90f5429644e77c8595f3a07dfe45d34a2db6cb30 | C++ | Dawid-Kaluzny/HomeBudget | /Finance.h | UTF-8 | 747 | 3.03125 | 3 | [] | no_license | #ifndef FINANCE_H
#define FINANCE_H
#include <cstdlib>
#include <iostream>
using namespace std;
class Finance {
int userId;
int date;
string item;
float amount;
public:
Finance(int userId = 0, int date = 0, string item = "", float amount = 0.0) {
this -> userId = userId;
this -> date = date;
this -> item = item;
this -> amount = amount;
}
bool operator < (const Finance& order) const {
return (date < order.date);
}
void setUserId(int userId);
void setDate(int date);
void setItem(string item);
void setAmount(float amount);
int getUserId();
int getDate();
string getItem();
float getAmount();
float enterFinanceAmount();
};
#endif
| true |
288e47e06115d509f7813fe3aecbf5e3c99c880d | C++ | notsocertain/PasswordManager | /projectOOP/include/newUser.h | UTF-8 | 1,088 | 2.703125 | 3 | [] | no_license | #ifndef NEWUSER_H
#define NEWUSER_H
#include <SFML/Graphics.hpp>
#include<string>
#define maxoption 2
using namespace sf;
class newUser
{
public:
void moveDown();
void moveUp();
int option()
{
return optionSelected;
}
newUser(float width,float height);
void draw_newUser(sf::RenderWindow &window);
void createFile(std::string& userFile,std::string& encryptPassword);
int returnKey()
{
return key;
}
virtual ~newUser();
protected:
private:
sf::Texture texture;
sf::Sprite sprite;
int optionSelected;
sf::Text main_menu[maxoption];
std::string encryptPassword;
int key=3; //key for encryption
sf::Font font;
sf::Text titleText[2];
sf::Text userText[4];
sf::Text text[2];
std::string username;
std::string password;
std::string display;
sf::Text text_proceed[2];
sf::Text details[2];
sf::RectangleShape rectangle[2];
sf::RectangleShape signin;
int signup=0;
};
#endif // NEWUSER_H
| true |
a2191459f468d8b356b3046f0522eea351716346 | C++ | jjocram/sydevs | /src/sydevs/systems/interactive_system.h | UTF-8 | 8,460 | 2.71875 | 3 | [
"BSL-1.0",
"Apache-2.0"
] | permissive | #pragma once
#ifndef SYDEVS_SYSTEMS_INTERACTIVE_SYSTEM_H_
#define SYDEVS_SYSTEMS_INTERACTIVE_SYSTEM_H_
#include <sydevs/systems/collection_node.h>
namespace sydevs {
namespace systems {
/**
* @brief A base class template for all interactive closed system nodes intended
* to be used at the highest level of a real time simulation model.
*
* @details
* The `interactive_system` abstract base class is inherited by classes that
* represent a system that interacts with either a user or a process external to
* the model hierarchy. Interaction is facilitated by an `interaction_data`
* object. This object supports the injection of information into the simulation
* model via an instance of type `InjData`. It also supports observations of the
* simulation model via an instance of type `ObsData`.
*
* The class inherits from the `collection_node`. This provides macro-level
* behavior supporting interaction and frames, and micro-level behavior
* represented by one (or possibly more) agents of type `Node`.
*
* Concrete derived classes must implement the following pure virtual member
* functions:
*
* - `time_precision`, which indicates the time quantum that must evenly divide
* all planned and elapsed durations associated with the node (the time
* precision should not be `no_scale`, since the intent is that a frame is
* produced whenever the planned duration elapses);
* - `macro_initialization_update`, which is called at the beginning of a
* simulation;
* - `micro_planned_update`, which is called whenever an agent sends a message;
* - `macro_planned_update`, which is called when the planned duration elapses;
* - `macro_finalization_update`, which is called at the end of a simulation.
*
* Each transition to the next frame at the macro-level is associated with the
* macro-level planned duration, which is returned from the
* `macro_initialization_update` and `macro_planned_update` member functions.
* The `micro_planned_update` member function does not return a planned
* duration because it is assumed that micro-level events should not directly
* affect the frame rate established at the macro level of the interactive
* system node.
*/
template<typename AgentID, typename Node, typename InjData, typename ObsData>
class interactive_system : public collection_node<AgentID, Node>
{
public:
using injection_type = InjData;
using observation_type = ObsData;
class interaction_data;
virtual ~interactive_system() = default; ///< Destructor
std::unique_ptr<interaction_data> acquire_interaction_data(); ///< Transfers ownership of the interaction data object to the caller.
int64 frame_index() const; ///< Returns the index of the most recently processed frame.
duration planned_duration() const; ///< Returns the planned duration until the next frame is to be processed.
protected:
/**
* @brief Constructs an `interactive_system` node.
*
* @details
* Constructs the interactive system node and associates it with the
* surrounding context. An exception is thrown if the node has any ports.
*
* @param node_name The name of the node within the encompassing context.
* @param external_context The context in which the node is constructed.
*/
interactive_system(const std::string& node_name, const node_context& external_context);
private:
void validate();
duration macro_initialization_event();
duration macro_unplanned_event(duration elapsed_dt);
duration micro_planned_event(const AgentID& agent_id, duration elapsed_dt);
duration macro_planned_event(duration elapsed_dt);
void macro_finalization_event(duration elapsed_dt);
virtual duration macro_initialization_update(InjData& injection) = 0;
virtual void micro_planned_update(const AgentID& agent_id, duration elapsed_dt) = 0;
virtual duration macro_planned_update(duration elapsed_dt, const InjData& injection, ObsData& observation) = 0;
virtual void macro_finalization_update(duration elapsed_dt) = 0;
InjData injection_;
ObsData observation_;
int64 frame_index_;
duration planned_dt_;
std::unique_ptr<interaction_data> interaction_data_;
};
template<typename AgentID, typename Node, typename InjData, typename ObsData>
class interactive_system<AgentID, Node, InjData, ObsData>::interaction_data
{
friend class interactive_system;
public:
InjData& injection();
const ObsData& observation();
private:
interaction_data(InjData& inj, ObsData& obs);
InjData& injection_;
ObsData& observation_;
};
template<typename AgentID, typename Node, typename InjData, typename ObsData>
std::unique_ptr<typename interactive_system<AgentID, Node, InjData, ObsData>::interaction_data> interactive_system<AgentID, Node, InjData, ObsData>::acquire_interaction_data()
{
return std::move(interaction_data_);
}
template<typename AgentID, typename Node, typename InjData, typename ObsData>
int64 interactive_system<AgentID, Node, InjData, ObsData>::frame_index() const
{
return frame_index_;
}
template<typename AgentID, typename Node, typename InjData, typename ObsData>
duration interactive_system<AgentID, Node, InjData, ObsData>::planned_duration() const
{
return planned_dt_;
}
template<typename AgentID, typename Node, typename InjData, typename ObsData>
void interactive_system<AgentID, Node, InjData, ObsData>::validate()
{
if (this->external_IO().flow_input_port_count() != 0 ||
this->external_IO().message_input_port_count() != 0 ||
this->external_IO().message_output_port_count() != 0 ||
this->external_IO().flow_output_port_count() != 0) {
throw std::invalid_argument("Interactive node (" + this->full_name() + ") must have no ports");
}
}
template<typename AgentID, typename Node, typename InjData, typename ObsData>
interactive_system<AgentID, Node, InjData, ObsData>::interactive_system(const std::string& node_name, const node_context& external_context)
: collection_node<AgentID, Node>(node_name, external_context)
, injection_()
, observation_()
, frame_index_(-1)
, planned_dt_()
, interaction_data_(new interaction_data(injection_, observation_))
{
validate();
}
template<typename AgentID, typename Node, typename InjData, typename ObsData>
duration interactive_system<AgentID, Node, InjData, ObsData>::macro_initialization_event()
{
planned_dt_ = macro_initialization_update(injection_);
return planned_dt_;
}
template<typename AgentID, typename Node, typename InjData, typename ObsData>
duration interactive_system<AgentID, Node, InjData, ObsData>::macro_unplanned_event(duration elapsed_dt)
{
return duration();
}
template<typename AgentID, typename Node, typename InjData, typename ObsData>
duration interactive_system<AgentID, Node, InjData, ObsData>::micro_planned_event(const AgentID& agent_id, duration elapsed_dt)
{
micro_planned_update(agent_id, elapsed_dt);
planned_dt_ -= elapsed_dt;
return planned_dt_;
}
template<typename AgentID, typename Node, typename InjData, typename ObsData>
duration interactive_system<AgentID, Node, InjData, ObsData>::macro_planned_event(duration elapsed_dt)
{
++frame_index_;
planned_dt_ = macro_planned_update(elapsed_dt, injection_, observation_);
if (planned_dt_ <= 0_s) throw std::logic_error("Planned duration between interact events in interactive system (" + this->full_name() + ") must be positive.");
return planned_dt_;
}
template<typename AgentID, typename Node, typename InjData, typename ObsData>
void interactive_system<AgentID, Node, InjData, ObsData>::macro_finalization_event(duration elapsed_dt)
{
macro_finalization_update(elapsed_dt);
}
template<typename AgentID, typename Node, typename InjData, typename ObsData>
InjData& interactive_system<AgentID, Node, InjData, ObsData>::interaction_data::injection()
{
return injection_;
}
template<typename AgentID, typename Node, typename InjData, typename ObsData>
const ObsData& interactive_system<AgentID, Node, InjData, ObsData>::interaction_data::observation()
{
return observation_;
}
template<typename AgentID, typename Node, typename InjData, typename ObsData>
interactive_system<AgentID, Node, InjData, ObsData>::interaction_data::interaction_data(InjData& inj, ObsData& obs)
: injection_(inj)
, observation_(obs)
{
}
} // namespace
} // namespace
#endif
| true |
7e0bd0eb4a5ee1c70d81d3d80e7fb3a23a922f07 | C++ | TenFifteen/SummerCamp | /lbc_leetcode/331-verify-preorder-serialization-of-a-binary-tree.cc | UTF-8 | 2,480 | 3.609375 | 4 | [] | no_license | /*
题目大意:
问一个字符串是否是一个二叉树的先序遍历的序列化的结果。
解题思路:
只是一个普通的二叉树,所以不需要比较各节点直接的大小,只是判断是否是一棵完整的二叉树即可。
我就是利用的当前有多少个空余的link来计算是否合理。如果当前是一个#,则说明link减一;
如果当前是一个数字,表示link加一
遇到的问题:
没有太大问题。
再次阅读:
看了一下DISCUSS,感觉这种解法已经算是不错的解法了。
*/
class Solution {
private:
vector<string> split(const string &str) {
stringstream ss(str);
string cur;
vector<string> ans;
while (getline(ss, cur, ',')) {
ans.push_back(cur);
}
return ans;
}
public:
bool isValidSerialization(string preorder) {
vector<string> nodes = split(preorder);
if (nodes.size() == 0) return false;
if (nodes.size() > 1 && nodes[0] == "#") return false;
int total = 1;
for (int i = 0; i < nodes.size(); ++i) {
if (nodes[i] == "#") {
total--;
if (total < 0) return false;
} else {
if (total == 0) return false;
total++;
}
}
return total == 0;
}
};
/*
第二次做:
没有太大问题。
*/
class Solution {
public:
bool isValidSerialization(string preorder) {
int need = 1, index = 0;
while (index < preorder.size() && need > 0) {
if (preorder[index] == '#') {
need--;
index += 2;
} else {
int end = index+1;
while (end < preorder.size() && preorder[end] != ',') end++;
need++;
index = end+1;
}
}
return need == 0 && index >= preorder.size();
}
};
/*
* ok
*/
class Solution {
public:
bool isValidSerialization(string preorder) {
int total = 1;
int index = 0;
stringstream ss(preorder);
string now;
bool finish = false;
while (getline(ss, now, ',')) {
if (now[0] == '#') {
total--;
if (total == 0) {
finish = true;
}
} else {
if (finish) return false;
total++;
}
}
return !total;
}
};
| true |
01f6d9536389b630f74ffea613f98d1b7c389d2c | C++ | leand-santos/Judge | /uri/1026.cpp | UTF-8 | 498 | 2.6875 | 3 | [] | no_license | #include <iostream>
#include <math.h>
// status: Accepted
// problem type: AD-HOC
using namespace std;
int main() {
long long int a, b;
while (scanf("%lld %lld", &a, &b) != EOF) {
long long int n = 0, result = 0;
while (a != 0 || b != 0) {
if ((a % 2 == 1 && b % 2 == 0) || (a % 2 == 0 && b % 2 == 1))
result += pow(2, n);
a /= 2;
b /= 2;
n++;
}
cout << result << endl;
}
return 0;
} | true |
3a1af25850ee8bfbbef6d85b636b7097b6db67b1 | C++ | Goldiorl/OJCodingPractice | /3Sum.cpp | UTF-8 | 1,146 | 3.234375 | 3 | [] | no_license | #include<iostream>
#include<algorithm>
#include<iterator>
#include<cmath>
#include<climits>
#include<map>
using namespace std;
class Solution {
public:
vector<vector<int> > threeSum(vector<int> &num) {
vector<vector<int> > result;
if(num.size()<3) return result;
sort(num.begin(), num.end());
//decide to use iterator because can use binary search
for(auto a= num.begin(); a < prev( num.end(),2); a = upper_bound( a, prev(num.end(),2), *a) ){
//don't forget to prune duplicate result, using the upper_bound() routine.
for( auto b = next(a); b< prev(num.end()); b= upper_bound(next(a), prev(num.end()),*b) ){
int searchValue = 0 - *a-*b;
if(binary_search(next(b), num.end(),searchValue)){
result.push_back(vector<int> {*a,*b,searchValue});
}
}
}
}
};
int main(){
Solution sol;
//TEST DATA
int test[] = {-1, 0, 1, 2, -1, -4};
//Solve
vector<int> testVector(test,test+6);
vector<vector<int> > n= sol.threeSum(testVector);
for( auto i : n){
for (auto j:i)
cout<<j<<" ";
cout<<endl;
}
}
| true |
4d33c3d4adae7717fcfe9b430d930e197cb1d30b | C++ | Fahroni/YRpp | /YRMathVector.h | UTF-8 | 4,078 | 3.46875 | 3 | [] | no_license | //pd's Vector classes (math sense)
#ifndef VECTOR_H
#define VECTOR_H
#include <math.h>
/*==========================================
============ 2D Vector =====================
==========================================*/
template <typename T> class Vector2D
{
public:
static const Vector2D Empty;
//no constructor, so this class stays aggregate and can be initialized using the curly braces {}
T X,Y;
//operator overloads
//assignment
void operator=(Vector2D a)
{
X=a.X;Y=a.Y;
}
//addition
Vector2D operator+(Vector2D a)
{
Vector2D v={X+a.X,Y+a.Y};
return v;
}
//addition
void operator+=(Vector2D a)
{
X+=a.X;Y+=a.Y;
}
//substraction
Vector2D operator-(Vector2D a)
{
Vector2D v={X-a.X,Y-a.Y};
return v;
}
//substraction
void operator-=(Vector2D a)
{
X-=a.X;Y-=a.Y;
}
//negation
Vector2D operator-()
{
Vector2D v={-X,-Y};
return v;
}
//equality
bool operator==(Vector2D a)
{
return (X==a.X && Y==a.Y);
}
//unequality
bool operator!=(Vector2D a)
{
return (X!=a.X || Y!=a.Y);
}
//scalar multiplication
Vector2D operator*(double r)
{
Vector2D v={(T)(X*r),(T)(Y*r)};
return v;
}
//scalar multiplication
void operator*=(double r)
{
X*=r;Y*=r;
}
//vector multiplication
double operator*(Vector2D a)
{
return (double)(X*a.X+Y*a.Y);
}
//magnitude
double Magnitude()
{
return sqrt((double)(X*X+Y*Y));
}
//distance from another vector
double DistanceFrom(Vector2D a)
{
return (a-(*this)).Magnitude();
}
//collinearity
bool IsCollinearTo(Vector2D a)
{
double r=(double)a.X/(double)X;
return ((T)(r*Y)==a.Y);
}
//find scalar
double FindScalar(Vector2D a)
{
double r=(double)a.X/(double)X;
if((T)(r*Y)==a.Y)
return r;
else
{
//the vectors are not collinear, return NaN!
unsigned long NaN[2]={0xFFFFFFFF,0x7FFFFFFF};
return *(double*)NaN;
}
}
};
template <typename T>
const Vector2D<T> Vector2D<T>::Empty = {T(), T()};
/*==========================================
============ 3D Vector =====================
==========================================*/
template <typename T> class Vector3D
{
public:
static const Vector3D Empty;
//no constructor, so this class stays aggregate and can be initialized using the curly braces {}
T X,Y,Z;
//operator overloads
//assignment
void operator=(Vector3D a)
{
X = a.X; Y = a.Y; Z = a.Z;
}
//addition
Vector3D operator+(Vector3D a)
{
Vector3D v={X+a.X,Y+a.Y,Z+a.Z};
return v;
}
//addition
void operator+=(Vector3D a)
{
X+=a.X;Y+=a.Y,Z+=a.Z;
}
//substraction
Vector3D operator-(Vector3D a)
{
Vector3D v={X-a.X,Y-a.Y,Z-a.Z};
return v;
}
//substraction
void operator-=(Vector3D a)
{
X-=a.X;Y-=a.Y;Z-=a.Z;
}
//negation
Vector3D operator-()
{
Vector3D v={-X,-Y,-Z};
return v;
}
//equality
bool operator==(Vector3D a)
{
return (X==a.X && Y==a.Y && Z==a.Z);
}
//unequality
bool operator!=(Vector3D a)
{
return (X!=a.X || Y!=a.Y || Z!=a.Z);
}
//scalar multiplication
Vector3D operator*(double r)
{
Vector3D v={(T)(X*r),(T)(Y*r),(T)(Z*r)};
return v;
}
//scalar multiplication
void operator*=(double r)
{
X*=r;Y*=r;Z*=r;
}
//vector multiplication
double operator*(Vector3D a)
{
return (double)(X*a.X+Y*a.Y+Z*a.Z);
}
//magnitude
double Magnitude()
{
return sqrt(((double)X)*X+((double)Y)*Y+((double)Z)*Z);
}
//distance from another vector
double DistanceFrom(Vector3D a)
{
return (a-(*this)).Magnitude();
}
//collinearity
bool IsCollinearTo(Vector3D a)
{
double r=(double)a.X/(double)X;
return ((T)(r*Y)==a.Y) && ((T)(r*Z)==a.Z);
}
//find scalar
double FindScalar(Vector3D a)
{
double r=(double)a.X/(double)X;
if(((T)(r*Y)==a.Y) && ((T)(r*Z)==a.Z))
return r;
else
{
//the vectors are not collinear, return NaN!
unsigned long NaN[2]={0xFFFFFFFF,0x7FFFFFFF};
return *(double*)NaN;
}
}
//cross product
Vector3D CrossProduct(Vector3D a)
{
Vector3D v={
Y*a.Z-Z*a.Y,
Z*a.X-X*a.Z,
X*a.Y-Y*a.X};
return v;
}
};
template <typename T>
const Vector3D<T> Vector3D<T>::Empty = {T(), T(), T()};
#endif
| true |
43bf895397172051e90627ab289c64bb200d750a | C++ | Huimintai/algorithm | /myC++/calculateScore.cpp | UTF-8 | 629 | 3.15625 | 3 | [] | no_license | #include<iostream>
using namespace std;
int calculateScore(int* score, int* judgeType, int n)
{
int judge1 = 0;
int score1 = 0;
int judge2 = 0;
int score2 = 0;
int finScore = 0;
for(int i=0; i<n; i++)
{
if(judgeType[i] == 1)
{
score1 = score1 + score[i];
judge1 ++;
}
else
{
score2 = score2 + score[i];
judge2 ++;
}
}
if(judge2 == 0)
{
finScore = score1 / judge1;
return finScore;
}
else
{
finScore = score1 / judge1 * 0.6 + score2 / judge2 * 0.4;
return finScore;
}
}
int main()
{
int a[5] = {2,5,1,8,9};
int judge[5] = {1,2,1,2,1};
cout<<calculateScore(a, judge, 5)<<endl;
}
| true |
d71ea44980f0fb0812f86ed295fd5a8d1c172490 | C++ | Cookiefan/ZigZag | /Template/1 Math/EulerFunction.cpp | UTF-8 | 202 | 2.71875 | 3 | [] | no_license | //欧拉函数
long long phi(long long x)
{
long long cnt=x;
for (long long i=2;i*i<=x;i++)
if (x%i==0)
{
cnt=cnt/i*(i-1);
while (x%i==0) x=x/i;
}
if (x>1) cnt=cnt/x*(x-1);
return cnt;
} | true |
ec3ba0488e4ce1e583f6ff34a2a0ad5fdb4188cc | C++ | PhebeJ/Learning-CPP | /single_inheritance.cpp | UTF-8 | 805 | 3.828125 | 4 | [] | no_license | #include<iostream>
using namespace std;
class employee
{
protected:
char n[20],d[20];
int sal;
public:
void name();
void desgn();
void display();
void sala();
};
void employee::name()
{
cout<<"enter name";
cin>>n;
}
void employee::desgn()
{
cout<<"enter designation";
cin>>d;
}
void employee::sala()
{
cout<<"enter monthly salary";
cin>>sal;
}
void employee::display()
{
cout<<"name is"<<n<<endl;
cout<<"designation is"<<d<<endl;
cout<<"salary for one month is"<<n<<endl;
}
class salary:public employee{
public:
int getsalary()
{
return(sal*12);
}
};
int main()
{
int a,i;
salary s[10];
cout<<"enter no. of employees";
cin>>a;
for(i=0;i<a;i++)
{
s[i].name();
s[i].desgn();
s[i].sala();
s[i].display();
cout<<"total salary"<<s[i].getsalary()<<endl;
}
}
| true |
fc4d92810d24afab4ff21be4c4e00d93abd768d8 | C++ | samruddhi-coder/datastructure | /exp4.cpp | UTF-8 | 1,788 | 3.453125 | 3 | [] | no_license | #include<iostream>
using namespace std;
int are[100],k;
void displayData(int n)
{
int i;
for(i=0;i<n;i++)
{
cout<<are[i]<<" ";
}
}
void linearSearch(int n)
{
int item,i,flag=0,pos;
cout<<"\nEnter the Element to be Searched\n";
cin>>item;
for(i=0;i<n;i++)
{
if(are[i]==item)
{
flag=1;
pos=i+1;
break;
}
else
{
flag=1;
}
}
if(flag==0)
{
cout<<"Number not found..!!";
}
else
{
cout<<item<<" found at position "<<pos;
}
}
void insertionSort(int n)
{
int i,key,j,k;
cout<<"\n------------Sorted Elements Descending------------";
for(i=1;i<n;i++)
{
key=are[i];
j=i-1;
while(j>=0 && key>are[j])
{
are[j+1]=are[j];
j=j-1;
}
are[j+1]=key;
cout<<"\n Pass"<<i<<":";
for(k=0;k<n;k++)
{
cout<<"\t"<<are[k];
}
cout<<"\n";
}
}
void selectionSort(int n)
{
int i,j,min,temp;
cout<<"\n------------Sorted Elements ascending------------";
for(i=0;i<n-1;i++)
{
min=i;
for(j=i+1;j<n;j++)
{
if(are[j]<are[min])
{
min=j;
}
}
temp=are[i];
are[i]=are[min];
are[min]=temp;
cout<<"\n Pass"<<i+1<<":";
for(k=0;k<n;k++)
{
cout<<"\t"<<are[k];
}
cout<<"\n";
}
}
int main()
{
int n,i,ch;
cout<<"\nEnter the number of elements: ";
cin>>n;
cout<<"\nEnter the Elements in Array: ";
for(i=0;i<n;i++)
{
cin>>are[i];
}
//getData(n);
do
{
cout<<"\n0-exit\n1-Sort Elements in Ascending order\n2-Sort Elements in Descending Order\n";
cout<<"3-Search Element\n4-Display Elements\n";
cout<<"\nEnter Your Choice: ";
cin>>ch;
switch(ch)
{
case 0:
cout<<"exit";
break;
case 1: selectionSort(n);
break;
case 2: insertionSort(n);
break;
case 3: linearSearch(n);
break;
case 4: displayData(n);
break;
default: cout<<"\nWrong Choice\n";
}
}while(ch>0);
}
| true |
5daf05120058ad8c639436faa675f64d3bd193b2 | C++ | iliyanavitanova/Cpp | /cpp_templates/task5.cpp | UTF-8 | 450 | 3.140625 | 3 | [] | no_license | #include<iostream>
#include<string>
#include<string.h>
using namespace std;
template<typename T>
double fmax(T f, T g, double x)
{
if(f(x)>g(x))
{
cout<<"f(x)=";
return f(x);
}
cout<<"g(x)=";
return g(x);
}
double g(double x)
{
return x*2;
}
double f(double x)
{
return x*20;
}
int main()
{
double (* func[2])(double);
func[0]=f;
func[1]=g;
cout<<fmax(func[0],func[1],2.2);
return 0;
}
| true |
3c82ff29e5ec772d9d3055d6e533fa1053861608 | C++ | Senryoku/BasicGUI | /src/GUIText.hpp | UTF-8 | 1,499 | 2.796875 | 3 | [] | no_license | #pragma once
#include <string>
#include <memory>
#include <functional>
#include <glm/glm.hpp>
#include <Buffer.hpp>
#include <VertexArray.hpp>
#include <Resources.hpp>
#include <GUIElement.hpp>
class Font
{
public:
struct Glyph
{
glm::vec2 dim = glm::vec2(0.0);
glm::vec2 offset = glm::vec2(0.0);
glm::vec2 uv_min = glm::vec2(0.0);
glm::vec2 uv_max = glm::vec2(0.0);
float advance = 0.0;
};
std::string Name;
Texture2D* Tex = nullptr;
std::vector<Glyph> Glyphs;
Font() =default;
Font(const std::string& path);
void load(const std::string& path);
};
/**
* Handles the rendering of distance field fonts.
**/
class GUIText : public GUIElement
{
public:
using TextFunc = std::function<std::string(void)>;
GUIText();
GUIText(const std::string& str);
GUIText(const TextFunc& func);
virtual ~GUIText();
void setText(const std::string& str);
void setFontSize(float s) { _fontSize = s; update(); }
void init();
void update();
void draw(const glm::vec2& resolution, const glm::vec2& position = glm::vec2(0.0)) override;
private:
TextFunc _func;
std::string _text;
Font* _font;
float _fontSize = 18.0;
struct VertexAttributes
{
glm::vec2 position;
glm::vec2 texcoord;
};
VertexArray _vao;
Buffer _vertex_buffer;
Buffer _index_buffer;
std::vector<VertexAttributes> _vertices;
std::vector<size_t> _triangles;
const Font::Glyph& getGlyph(char c) const;
// Static
static std::unique_ptr<Font> s_defaultFont;
};
| true |
940edd707e0b3790e497f953d53468f5380f536b | C++ | shivam04/codes | /code-interview-questions/first-duplicate-value.cpp | UTF-8 | 241 | 3.03125 | 3 | [] | no_license | #include <vector>
using namespace std;
int firstDuplicateValue(vector<int> array) {
for(int i=0;i<array.size();i++) {
int p = abs(array[i])-1;
if(array[p] < 0) {
return abs(array[i]);
}
array[p] = -1*array[p];
}
return -1;
}
| true |
d63dcf64e85fe623d8d2b84f7921b29ac98a3d5c | C++ | ASharpy/AI-Project | /project2D/Cohesion.cpp | UTF-8 | 872 | 2.515625 | 3 | [
"MIT"
] | permissive | #include "Cohesion.h"
#include "Setting.h"
Vector2 Cohesion::update(float deltaTime)
{
float speed = 100.0f;
int neighbourCount = 0;
for (auto &var : SETAPP->players)
{
if (SETAPP->playerCircleCheck(Myself, var, (300 + 300)*0.9f))
{
if (Myself == var)
{
continue;
}
point.x = point.x + var->position.x;
point.y = point.y + var->position.y;
neighbourCount++;
}
}
if (neighbourCount == 0)
{
Vector2 emptyvec;
return emptyvec;
}
else
{
point.x = point.x / neighbourCount;
point.y = point.y / neighbourCount;
Vector2 v = { point.x - Myself->position.x, point.y - Myself->position.y };
v.normalise();
v = v *speed * behaviourWeight;
return v;
}
Vector2 emptyvec;
return emptyvec;
}
Cohesion::Cohesion(Object * myself)
{
Myself = myself;
behaviourWeight = 0;
bTypes = COHESION;
}
Cohesion::~Cohesion()
{
}
| true |
9b129522119f1f825d3e0f5e4874544f406fc227 | C++ | DegtyarevPaul/vector-plus-plus | /cms/tasks_for_02_21/Warehouse/solver.cc | UTF-8 | 1,423 | 2.8125 | 3 | [
"Unlicense"
] | permissive | #include <bits/stdc++.h>
using namespace std;
map<int,vector<pair<int, int> > > data;
int k; // jump height
bool isNear(pair<int, int> p1, pair<int, int> p2){
return (p1.first-p2.first)*(p1.first-p2.first) +
(p1.second-p2.second)*(p1.second-p2.second) <= 2;
}
int path(int lvl, pair<int, int> point){
// cout << lvl << point.first << point.second<< endl;
int max_lvl = lvl;
int next = data.upper_bound(lvl)->first;
if (next - lvl > k || next <= lvl) return lvl;
for(int t=next; t<=lvl+min(k,data.upper_bound(next)->first); ++t)
if(data.find(t)!=data.end())
for(int i=0; i<data[t].size(); ++i){
if(isNear(point, data[t][i])){
max_lvl = max(max_lvl, path(t, data[t][i]));
}
}
return max_lvl;
}
int main(){
ios_base::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
int n,m, tmp, min=1000000000, max_col;
cin >> n >> m >> k;
for(int i=0;i<n; ++i){
for(int j=0;j<m;++j){
cin >> tmp;
if(tmp<min) min=tmp;
if(data.find(tmp)==data.end()){
data[tmp]={{i,j}};
}
else {
data[tmp].push_back({i,j});
}
}
}
max_col = min;
for(int i=0; i<data[min].size(); ++i){
max_col = max(max_col, path(min, data[min][i]));
}
cout << max_col;
return 0;
}
| true |
4041aec01da1a02a9bab0048e779d4c263208198 | C++ | kaat0/OpenLinTim | /src/core/cpp/include/exception/StatisticTypeMismatchException.hpp | UTF-8 | 426 | 2.609375 | 3 | [
"MIT"
] | permissive | /**
*/
#ifndef STATISTICTYPEMISMATCHEXCEPTION_HPP
#define STATISTICTYPEMISMATCHEXCEPTION_HPP
class StatisticTypeMismatchException : public std::runtime_error{
public:
StatisticTypeMismatchException(std::string key, std::string type, std::string value) :
std::runtime_error("Error ST1: Statistic key " + key + " should have type " + type +
" but has value " + value + "."){}
};
#endif
| true |
043cc31a786ce41c09768715353642b4083c3d97 | C++ | metaphysis/Code | /UVa Online Judge/volume008/833 Water Falls/program.cpp | UTF-8 | 2,458 | 3.078125 | 3 | [] | no_license | // Water Falls
// UVa ID: 833
// Verdict: Accepted
// Submission Date: 2016-12-09
// UVa Run Time: 0.000s
//
// 版权所有(C)2016,邱秋。metaphysis # yeah dot net
#include <bits/stdc++.h>
using namespace std;
struct point
{
int x, y;
};
struct segment
{
point left, right, lower;
int flag;
bool operator<(const segment &s) const
{
return max(left.y, right.y) > max(s.left.y, s.right.y);
}
};
// 叉积,判断点a,b,c组成的两条线段的转折方向。当叉积大于0,则形成一个右拐,
// 否则共线(cp = 0)或左拐(cp < 0)。
int cp(const point &a, const point &b, const point &c)
{
return (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x);
}
// 从点a向点b望去,点c位于线段ab的左侧或在线段上,返回true。
bool ccw(const point &a, const point &b, const point &c)
{
return cp(a, b, c) >= 0;
}
bool pointOnSegment(const point &p, const segment &s)
{
return p.x >= s.left.x && p.x <= s.right.x && ccw(s.left, s.right, p);
}
int main(int argc, char *argv[])
{
cin.tie(0); cout.tie(0); ios::sync_with_stdio(false);
int cases = 0;
cin >> cases;
point point1, point2, lower, point3;
for (int c = 1; c <= cases; c++)
{
if (c > 1) cout << '\n';
int NP;
cin >> NP;
vector<segment> segments;
for (int i = 1; i <= NP; i++)
{
cin >> point1.x >> point1.y >> point2.x >> point2.y;
if (point1.x > point2.x) swap(point1, point2);
if (point1.y < point2.y) lower = point1;
else lower = point2;
segments.push_back((segment){point1, point2, lower, 0});
}
sort(segments.begin(), segments.end());
int NS;
cin >> NS;
for (int i = 1; i <= NS; i++)
{
cin >> point3.x >> point3.y;
while (true)
{
bool updated = false;
for (int j = 0; j < segments.size(); j++)
if (segments[j].flag < i && pointOnSegment(point3, segments[j]))
{
point3 = segments[j].lower;
segments[j].flag = i;
updated = true;
break;
}
if (!updated) break;
}
cout << point3.x << '\n';
}
}
return 0;
}
| true |
8b1b4d18573519168adb53c6d842d81f4973fb31 | C++ | ramchandra94/datastructures_in_cpp | /pointer_stuff/null_pointers.cpp | UTF-8 | 363 | 3.109375 | 3 | [
"MIT"
] | permissive | #include<iostream>
using namespace std;
int main(){
int *i;
// this prints some garbage address
cout << i << endl;
// the below will print some garbage value in the garbage address
cout << *i << endl;
int *j = 0;
// this will print 0 i guess
cout << j << endl;
// this will compile but throws error at run time
cout << *j << endl;
return 0;
}
| true |
d9ffd4302ccd294c895e1e598167f5f92291715f | C++ | niuxu18/logTracker-old | /second/download/collectd/gumtree/collectd_repos_function_574_collectd-5.6.2.cpp | UTF-8 | 253 | 2.609375 | 3 | [] | no_license | static int my_asprintf(char **str, const char *fmt, ...) {
int size = 0;
va_list args;
// init variadic argumens
va_start(args, fmt);
// format and get size
size = my_vasprintf(str, fmt, args);
// toss args
va_end(args);
return size;
} | true |
0f1b4ffa3ed7a6bc6bb3a3ac70a4765e52960de2 | C++ | friskareliv/metal | /include/metal/number/if.hpp | UTF-8 | 2,035 | 2.765625 | 3 | [
"BSL-1.0"
] | permissive | // Copyright Bruno Dutra 2015-2016
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE.txt or copy at http://boost.org/LICENSE_1_0.txt
#ifndef METAL_NUMBER_IF_HPP
#define METAL_NUMBER_IF_HPP
#include <metal/config.hpp>
namespace metal
{
/// \cond
namespace detail
{
template<typename...>
struct _if_;
}
/// \endcond
/// \ingroup number
///
/// ### Description
/// A multi-clause conditional expression.
///
/// ### Usage
/// For any \numbers `num_0, ..., num_n-1` and \values `val_0, ..., val_n`
/// \code
/// using result = metal::if<
/// num_0, val_0,
/// ...,
/// num_n-1, val_n-1,
/// val_n
/// >;
/// \endcode
///
/// \returns: \value
/// \semantics:
/// If `num_i{} != false` and `num_j{} == false` for all `j < i`, then
/// \code
/// using result = val_i;
/// \endcode
/// otherwise, if `num_i{} == false` for all `i` in `[0, n-1]`, then
/// \code
/// using result = val_n;
/// \endcode
///
/// ### Example
/// \snippet number.cpp if_
///
/// ### See Also
/// \see number
template<typename cond, typename then_, typename... else_>
using if_ = typename detail::_if_<cond, then_, else_...>::type;
}
#include <metal/number/number.hpp>
namespace metal
{
/// \cond
namespace detail
{
template<typename...>
struct _if_
{};
template<typename then_, typename... else_>
struct _if_<false_, then_, else_...> :
_if_<else_...>
{};
template<typename then_, typename else_>
struct _if_<false_, then_, else_>
{
using type = else_;
};
template<int_ v, typename then_, typename... else_>
struct _if_<number<v>, then_, else_...>
{
using type = then_;
};
}
/// \endcond
}
#endif
| true |
fccf144a06b58cef56b517e4b73ab8fcf25313a5 | C++ | pwwpche/X-Locate-OpenCV | /clear.cpp | UTF-8 | 1,087 | 2.53125 | 3 | [] | no_license | #include"cv.h"
#include"highgui.h"
#include<iostream>
using namespace std;
double focus(IplImage* image);
int main_cl() {
IplImage* previous1;
previous1=cvLoadImage("E://Mask//zhishidao_mask.jpg",1);
if(previous1!=0) {
cvNamedWindow("previous1",1);
cvShowImage("previous1",previous1);
cout<<"The definition of the previous1 is: "<<focus(previous1)<<endl;
cvDestroyWindow("previous1");
cvReleaseImage(&previous1);
return 0;
}
return -1;
}
double focus(IplImage* image) {
IplImage* picone=cvCreateImage(cvGetSize(image),8,3);
cvCvtColor(image,picone,CV_BGR2YCrCb);
CvScalar gety;
double z=0,zy1=0,zy2=0,total=0;
double gety1=0,gety2=0;
double final=0;
for(int ix=0;ix<(picone->height);ix++)
{
gety1=0;
gety2=0;
zy1=0;
zy2=0;
for(int jy=0;jy<(picone->width);jy++)
{
gety=cvGet2D(picone,ix,jy);
z=0.5*gety.val[0]-gety1+0.5*gety2+zy1-0.5*zy2;
total=total+z;
gety2=gety1;
gety1=gety.val[0];
zy2=zy1;
zy1=z;
}
}
cvReleaseImage(&picone);
final=abs(total/((image->height)*(image->width)));
return final;
} | true |
bd12e35b95524c237372d15b093609d246792b1d | C++ | AntSan813/Google_Code_Jam_Solutions | /GCJ-Tidy_Numbers/main.cpp | UTF-8 | 5,505 | 3.78125 | 4 | [] | no_license | /******************************************************************************
* Antonio Santos
* 5/12/17
* Google Code Jam - 2017 Qulification Round B. Tidy Numbers. A tidy number as
* described in the problem, is a number that if you were to read from left to
* right, would be in ascending order. This program takes in numbers, and calc
* the last tidy number under each number.
*
* Difficulty: this program was not so difficult to start off; however once I got
* to the part for conversions (which is what made this program super hard IMO),
* it took me a while to figure out how to do the proper conversions. Once I had
* the conversions down, the next difficult task, which wasnt all that difficult,
* was figuring out how to opimize the tidy_up algorithm so that I am not decrementing
* a large number O(N^2) times to figure out what the last tidy number was. To solve
* this part of the program, all it took was a few minutes with a whiteboard and
* some basic logic thinking.
*
* What I learned: how to convert an int to a string was what I took away most
* from this project.
******************************************************************************/
#include <iostream>
#include <string>
#include <sstream>
#include <stdlib.h>
using namespace std;
bool is_tidy(string); //conditional to see if the number is tidy
string tidy_up(string); //tidy's the number
int main(){
int test_cases;
string last_num_counted;
bool cond;
cin >> test_cases; //first line of input is the amount of test cases
for(int i = 0; i < test_cases; i++){
cond = false;
cin >> last_num_counted; //now we start reading in the test cases
while(!cond){ //stops when tidy number is found for this Case
cond = is_tidy(last_num_counted); //checks tidyness
if(!cond) //not tidy? no problem...
last_num_counted = tidy_up(last_num_counted); //this function will
//tidy it up.
}
cout << "Case #" << i + 1 << ": " << last_num_counted << endl; //output result
last_num_counted.erase(last_num_counted.begin(), last_num_counted.end());
}
return 0;
}
/*****************************************************************************
* function: is_tidy(string)
* checks to see if the string/ case is tidy. returns a boolean yes or no.
******************************************************************************/
bool is_tidy(string arg_str){
bool is_tidy = true;
for(int x = 0; x < arg_str.size() - 1; x++) //O(N)
if((x + 1 != arg_str.size()) && (arg_str[x] > arg_str[x + 1]))
is_tidy = false;
return is_tidy;
}
/*****************************************************************************
* function: tidy_up(string)
* tidy's up the string by going to the last number before the number given
* where the number is ascending left to right. To do this efficiently, you must
* notice some rules about this problem. first rule I noticed was that if the
* first number in string is a 1, and the following number is a 0, then the result
* will be all 9's of size - 1. The second rule I noticed was that if i were to
* go left to right through the string of numbers, and the left number was smaller
* than the right number, than the result would be to make the right number a 9,
* and the left number itself - 1 ONLY if that is the first change in the sequence.
* if that is the second number in the sequence, then both the left and right
* numbers would be 9.
******************************************************************************/
string tidy_up(string arg_str){
bool b;
if((arg_str[0] == '1') && (arg_str[1] == '0')){ //first case: first number is
//1 and second is 0.
for(int i = 1; i < arg_str.size(); i++){ //then all numbers are 9
arg_str[i] = '9';
}
arg_str.erase(arg_str.begin()); //and we erase one element from the string
}
stringstream s;
int x = arg_str.size() - 1;
char temp;
int l, r;
b = false;
for(int i = 0; i < arg_str.size() - 1; i++){ //second case: go through the
//sequence and perform calculations
if(arg_str[i] > arg_str[i+1]){ //calculation needed if true
//following converts char to int
temp = arg_str.at(i); //first, I take a char from string and put it in holder
l = atoi(&temp); //then i convert it using preset C++ function, atoi
if(b){ //if we did a calculation already on this sequence, then all numbers
//will be 9 until the end of string
l = 9;
}
else{ //else this is our first calculation and we just want to decrement
l--;
}
//following is my method of converting a string to an int... which was
//surprisingly hard to figure out.
s.clear(); //first, I cleared the stringstream variable
s.str(""); //then I did this.. whatever it does
s << l; //and now I read in my first char into the stringstream
arg_str[i] = *(s.str().c_str()); //and now i convert the string into a char
//and now I repeat the series of converstions for the right char.
temp = arg_str.at(i+1);
r = atoi(&temp);
r = 9;
s.clear();
s.str("");
s << r;
arg_str[i + 1] = *(s.str().c_str());
b = true;
}
}
return arg_str; //once we kick out of loop, that means we went through string,
//(which is O(N) time) and now the string is tidy.
}
| true |
1ce52e003459bb3c9c83302893d6eddc5e998a02 | C++ | AlexApps99/sead | /modules/src/hostio/seadHostIONode.cpp | UTF-8 | 1,397 | 2.609375 | 3 | [] | no_license |
#include "hostio/seadHostIONode.h"
#include "hostio/seadHostIOReflexible.h"
#include "hostio/seadHostIOThreadLock.h"
namespace sead::hostio
{
Node::Node()
{
mTreeNode.value() = this;
}
Node::Node(Heap* heap, IDisposer::HeapNullOption heap_null_option)
: Reflexible(heap, heap_null_option)
{
mTreeNode.value() = this;
}
void Node::detachAll()
{
ThreadLock lock;
mTreeNode.detachAll();
}
void Node::detach()
{
ThreadLock lock;
mTreeNode.detachSubTree();
}
Node* Node::getParentNode() const
{
TTreeNode<Node*>* node = mTreeNode.parent();
if (node)
return node->value();
return nullptr;
}
Node* Node::getChildNode() const
{
TTreeNode<Node*>* node = mTreeNode.child();
if (node)
return node->value();
return nullptr;
}
Node* Node::getNextNode() const
{
TTreeNode<Node*>* node = mTreeNode.next();
if (node)
return node->value();
return nullptr;
}
Node* Node::getPrevNode() const
{
TTreeNode<Node*>* parent = mTreeNode.parent();
if (parent && parent->child() == &mTreeNode)
return nullptr;
TTreeNode<Node*>* node = mTreeNode.prev();
if (node)
return node->value();
return nullptr;
}
bool Node::isAppended() const
{
return mTreeNode.parent() || mTreeNode.next() || mTreeNode.prev();
}
void Node::disposeHostIOImpl_()
{
destroy();
}
} // namespace sead::hostio
| true |
3bcaa67d7ecd49ecaf85b71f53e02d9328a904a9 | C++ | kravtsun/au-opencl | /lection1/reduce/main.cpp | UTF-8 | 3,263 | 2.703125 | 3 | [
"MIT"
] | permissive | #define CL_HPP_ENABLE_EXCEPTIONS
#include <CL/cl.h>
#define CL_HPP_MINIMUM_OPENCL_VERSION 120
#define CL_HPP_TARGET_OPENCL_VERSION 120
#include "cl2.hpp"
#include <vector>
#include <fstream>
#include <iostream>
#include <iterator>
#include <iomanip>
#include "../vector_add/cl.hpp"
int main()
{
std::vector<cl::Platform> platforms;
std::vector<cl::Device> devices;
std::vector<cl::Kernel> kernels;
try {
// create platform
cl::Platform::get(&platforms);
platforms[0].getDevices(CL_DEVICE_TYPE_GPU, &devices);
// create context
cl::Context context(devices);
// create command queue
cl::CommandQueue queue(context, devices[0], CL_QUEUE_PROFILING_ENABLE);
// load opencl source
std::ifstream cl_file("reduce.cl");
std::string cl_string(std::istreambuf_iterator<char>(cl_file), (std::istreambuf_iterator<char>()));
cl::Program::Sources source({ cl_string });
// create program
cl::Program program(context, source);
// compile opencl source
program.build(devices);
// create a message to send to kernel
size_t const block_size = 512;
size_t const test_array_size = 4096 * 10;
size_t const output_size = test_array_size / block_size;
std::vector<int> input(test_array_size);
std::vector<int> output(output_size, 0);
for (size_t i = 0; i < test_array_size; ++i)
{
input[i] = i / block_size;
}
// allocate device buffer to hold message
cl::Buffer dev_input(context, CL_MEM_READ_ONLY, sizeof(int) * test_array_size);
cl::Buffer dev_output(context, CL_MEM_WRITE_ONLY, sizeof(int) * output_size);
// copy from cpu to gpu
queue.enqueueWriteBuffer(dev_input, CL_TRUE, 0, sizeof(int) * test_array_size, &input[0]);
// load named kernel from opencl source
queue.finish();
//cl::KernelFunctor<> reduce_gmem{ program, "gpu_reduce_gmem" };
//cl::EnqueueArgs enqueue_args{ queue, cl::NullRange, cl::NDRange(test_array_size), cl::NDRange(block_size) };
//cl::Event event = reduce_gmem(dev_input, dev_output);
cl::KernelFunctor<cl::Buffer, cl::Buffer, cl::LocalSpaceArg> reduce_lmem{ program, "gpu_reduce_lmem" };
cl::EnqueueArgs enqueue_args{ queue, cl::NullRange, cl::NDRange(test_array_size), cl::NDRange(block_size) };
cl::Event event = reduce_lmem(enqueue_args, dev_input, dev_output, cl::Local(sizeof(int)* block_size));
event.wait();
cl_ulong start_time = event.getProfilingInfo<CL_PROFILING_COMMAND_START>();
cl_ulong end_time = event.getProfilingInfo<CL_PROFILING_COMMAND_END>();
cl_ulong elapsed_time = end_time - start_time;
queue.enqueueReadBuffer(dev_output, CL_TRUE, 0, sizeof(int) * output_size, &output[0]);
for (size_t i = 0; i < output_size; ++i)
std::cout << output[i] << std::endl;
std::cout << std::endl;
std::cout << std::setprecision(2) << "Total time: " << elapsed_time / 1000000.0 << " ms" << std::endl;
}
catch (cl::Error e)
{
std::cout << std::endl << e.what() << " : " << e.err() << std::endl;
}
return 0;
}
| true |
72bb61ad0d3835b5433b1d7696651f10d73a98d1 | C++ | YusufDrymz/Cargo-Delivery-Company-Project | /Stack.hpp | UTF-8 | 687 | 3.375 | 3 | [] | no_license | #ifndef STACK_HPP
#define STACK_HPP
#include "List.hpp"
template<class T>
class Stack{
List<T> l;
public:
T top()const;
void pop();
void push(const T& data);
bool isEmpty()const;
};
template<class T>
T Stack<T>::top()const{
if(isEmpty())
throw "Hata : Stack::top() methodunda olustu (stack suanda bos)";
return l.begin()->data;
}
template<class T>
void Stack<T>::pop(){
if(isEmpty())
throw "Hata : Stack::pop() methodunda olustu (stack suanda bos)";
l.pop_front();
}
template<class T>
void Stack<T>::push(const T& data){
l.push_front(data);
}
template<class T>
bool Stack<T>::isEmpty()const{
return l.isEmpty();
}
#endif
| true |
430ff4bdd58cf308a152245d49588d5b88d48fba | C++ | cncoffer/CodingStudy | /Leetcode/Mid/SearchA2DMatrixII/solution.cpp | UTF-8 | 2,692 | 3.203125 | 3 | [] | no_license | class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
if (matrix.empty()) return false;
if (matrix[0].empty()) return false;
return recSearch(matrix, target, 0, 0, matrix.size(), matrix[0].size());
}
private:
bool recSearchMatrix(vector<vector<int>> &matric, int target, int left, int top, int right, int bottom) {
if (left > right || top > bottom)
return false;
if (matric[left][top] > target ||
matric[right][bottom] < target)
return false;
if (left == right || top == bottom)
return recBinarySearch(matric, target, left, top, right, bottom);
int CatercornerRight, CatercornerBottom;
int CatercornerLength = min(right - left, bottom - top);
CatercornerRight = left + CatercornerLength;
CatercornerBottom = top + CatercornerRight;
// search on catercorner
for (int i = 1; i < CatercornerLength; ++i) {
if (matric[left+i][top+i] > target)
break;
}
// search in left bottom and right top rect
bool ret = recSearchMatrix(matric, target, left, top+i, left+i-1, bottom) || recSearchMatrix(matric, target, left+i, top, right, top+i-1);
return ret;
}
bool recBinarySearch(vector<vector<int>> &matric, int target, int left, int top, int right, int bottom) {
if (left == right) {
while (top < bottom) {
int mid = static_cast<int>(((long)top + (long)bottom) / 2);
if (matric[left][mid] == target) return true;
else if (matric[left][mid] > target) bottom = mid-1;
else top = mid+1;
}
}
else if (top == bottom) {
while (left < right) {
int mid = static_cast<int>(((long)left + (long)right) / 2);
if (matric[mid][top] == target) return true;
else if (matric[mid][top] > target) right = mid-1;
else left = mid+1;
}
}
return false;
}
};
// solution2
class Solution {
public:
static bool searchMatrix(vector<vector<int>>& matrix, int target) {
if (matrix.size()==0||matrix[0].size()==0)
return false;
int n=matrix.size();
int m=matrix[0].size();
int row=n-1;
int col=0;
while(row>=0&&col<=m-1){
if(target==matrix[row][col]){
return true;
}else if(target<matrix[row][col]){
row--;
}else if(target>matrix[row][col]){
col++;
}
}
return false;
}
}; | true |
f9ebf56cca4707632c161252be613eb8e7d66af5 | C++ | gypsyfeng/CSC443-Assignments | /a1/test.cc | UTF-8 | 1,388 | 3.15625 | 3 | [] | no_license | #include "library.h"
#include <iostream>
#include <cstring>
using namespace std;
// void test_fixed_len_sizeof() {
// Record *r = new Record();
// int numattr = 100;
// char attr[10+1] = "aaaaaaaaaa";
// while (numattr > 0) {
// r->push_back(attr);
// numattr--;
// }
// cout << fixed_len_sizeof(r) << endl;
// delete r;
// }
// void test_fixed_len_page_capacity() {
// Page *p = new Page();
// p->page_size = 110;
// p->slot_size = 10;
// cout << fixed_len_page_capacity(p) << endl;
// delete[] p->data;
// delete p;
// }
void test_memcpy_int2char() {
int attr1, attr2, attr3;
attr1 = 0;
attr2 = 2;
attr3 = 123456;
char bytes_buf[sizeof(int)];
// cout << sizeof(int) << endl;
for (int i = 0; i < sizeof(int); ++i)
{
bytes_buf[i] = (attr3 >> 8*(i)) & 0xFF;
}
// memcpy(bytes_buf, &attr1, sizeof(int));
for (int i = 0; i < sizeof(int); ++i)
{
printf("%x\n", bytes_buf[i]);
}
int back;
memcpy(&back, bytes_buf, sizeof(int));
printf("%d\n", back);
printf("Test memcpy to and back\n");
char* bf = new char[sizeof(int)];
memcpy(bf, &attr3, sizeof(int));
int back2;
memcpy(&back2, bf, sizeof(int));
printf("%d\n", back2);
delete[] bf;
}
int main() {
test_memcpy_int2char();
return 0;
}
| true |
58989145c371be3a787ef735044c8ab8059ae88b | C++ | annaMagpie/semesterarbeitWS201718 | /tokenlib.cpp | UTF-8 | 6,704 | 2.796875 | 3 | [] | no_license | /*
#######################
Parser aus Vorlesung:
(12.12.2017 - BSP 9)
--------------------
Druckfunktion
(ab line 145):
#######################
*/
#include <iostream>
using namespace std;
#include <fstream>
#include <string.h>
#include "token.h"
#include <string>
ClToken::ClToken()
{
*tokenName='\0';
tokenChild=NULL;
tokenSibling=NULL;
tokenInhalt=new char[1];
*tokenInhalt='\0';
}
int ClToken::getToken(
ifstream &datei)
{
int zaehler;
enum zustand zustand;
char zeichen;
char puffer[100];
ClToken *child;
cleanToken();
for (zaehler=0;;)
{
datei.get(zeichen);
if (datei.eof())
{
if (*tokenName == '\0' && tokenChild == NULL && tokenInhalt == NULL)
return fillToken(0);
return fillToken(1);
}
switch(zeichen)
{
case '<':
datei.get(zeichen);
if (zeichen=='/')
{
zustand = istEndTag;
if (zaehler!=0)
{
puffer[zaehler]='\0';
tokenInhalt = new char[zaehler+1];
strcpy(tokenInhalt,puffer);
}
}
else
{
datei.putback(zeichen);
if (*tokenName!='\0')
{
datei.putback('<');
if (tokenChild==NULL)
{
tokenChild=new ClToken;
tokenChild->getToken(datei);
}
//Fall: tokenSibling hinzugefügt:
else
{
for (child=tokenChild;;child=child->tokenSibling)
{
if (child->tokenSibling==NULL)
{
child->tokenSibling=new ClToken;
child->tokenSibling->getToken(datei);
break;
}
}
}
}
else zustand=istStartTag;
}
zaehler=0;
break;
case '>':
puffer[zaehler]='\0';
if (zustand==istEndTag) return fillToken(1);
if (zustand==istStartTag)
{
att.getAttList(puffer);
strcpy(tokenName,puffer);
}
zaehler=0;
break;
case '\n':
break;
case '\t':
if(zeichen=='\t') break;
break;
default:
puffer[zaehler]=zeichen;
zaehler++;
break;
}
}
}
int ClToken::fillToken(
int mode)
{
if (*tokenName=='\0')
strcpy(tokenName,"Unbekanntes Element");
if (tokenInhalt==NULL)
{
tokenInhalt=new char[1];
*tokenInhalt='\0';
}
return mode;
}
void ClToken::cleanToken(void)
{
*tokenName='\0';
if (tokenChild!=NULL)
{
delete tokenChild;
tokenChild=NULL;
}
if (tokenInhalt!=NULL)
{
delete tokenInhalt;
tokenInhalt=NULL;
}
}
/*
######################
Druckfunktion:
######################
*/
void ClToken::druckeToken(ClText ObText, string datna) //ClText ObText ebene raus
{
/*
######################
Versuche:
######################
Test: Dateiname wird vorgegeben:
newFile.open("newDATA.xml", ios::app);
-->funktioniert !
---------------------------
char neueDatei[30];
ofstream fout;
cout << "Name new file:" << endl;
cin >> neueDatei;
fout.open(neueDatei, ofstream::app);
----------------------------
fout.open(dateiname);
getline (cin, dateiname);
dateiname += ".xml";
schreibt nur erste Zeile in neue Datei
----------------------------
-->durch Wiederholung wird Dateiname immer wieder abgefragt und nur eine Zeile gedruckt /überschrieben.
Daher: Dateiname muss aus main-Fubktion übergeben werden.
*/
ofstream newFile;
string fullName;
fullName = datna + ".xml"; // Damit immer eine XML-Datei erstellt wird.
newFile.open(fullName.c_str(), ios::out | ios::app); //geöffnet bzw. angelegt falls noch nicht vorhanden
//nach jedem Durchlauf der Funktion soll der Inhalt hinzugefügt werden und die Dati nicht überschreiben.
//Fehlermeldeung, falls keine Datei erstellt wurde. (Dieser Falls sollte aber nicht eintreffen.):
if (!newFile)
{
cerr << "can't open output file" << endl;
}
//Statt durch cout wird durch den Befehl des ofstreams (in dem Falle "newFile") der Inhalt in die Datei gedruckt:
newFile << "<" << name();
//Wenn Attribute vorhanden sind, werden sie gedruckt:
if (att.zahlAtt() > 0)
{
for (int i=0;i<att.zahlAtt();i++)
{
newFile << " " << att.zeigeAttName(i) << "="
<< '"' << att.zeigeAttWert(i) << '"' << '>';
//Metadaten aus TXT hinzufügen (Das Textobjekt wurde zuvor der Drukfunktion als Parameter übergeben):
for(int j=0;j<=11;j++)
{
if (!strcmp(att.zeigeAttWert(i),ObText.getMovieId(j)))
//IDs werden aus XML & TXT abgeglichen und somit an die richtige Stelle innerhalb der neuen Datei gedruckt.
{
newFile << "<meta>" << endl;
newFile << "<medium>" << ObText.getMediumKind(j) << "</medium>" << endl;
newFile << "<price>" << ObText.getPrice(j) << "</price>" << endl;
newFile << "<stock>" << ObText.getStock(j) << "</stock>" << endl;
newFile << "</meta>" << endl;
}
}
}
}
//neue Datei zunächst fehlerhaft, da:
//Starttags mit Attributen wurden doppelt geschlossen (">>") &
//Elternelement wurde erst am Ende geöffnet
//Fehlerbehebung:
else if (att.zahlAtt()==0)
{
newFile << ">";
if (tokenChild!=NULL)
{
newFile << endl;
}
}
newFile << tokenInhalt;
if (tokenChild!=NULL) tokenChild->druckeToken(ObText, datna);
newFile << "</" << name() << ">" << endl;
if (tokenSibling!=NULL) tokenSibling->druckeToken(ObText, datna);
//Wenn Kind- oder Geschwisterelemente vorhanden sind, beginnt der nächste Durchlauf der Druckfunktion.
//Wenn nicht, wird die Datei geschlossen:
newFile.close();
}
/*
####################
Versuch (Suche):
####################
*/
void ClToken::search(string searchCat, string searchCon){
cout << name() << ": " << inhalt() << endl;
if (tokenSibling!=NULL) tokenSibling->search(searchCat, searchCon);
/*
//ifstream newFile;
//newFile.open(fullName.c_str(), ios::in);
if (searchCat==name() && searchCon==inhalt()){
cout << name() << ": " << inhalt() << endl;
for (int s=0;tokenSibling!=NULL;s++){
cout << tokenSibling->tokenName[s] << ": " << tokenSibling->tokenInhalt[s] << endl;
}
}
// else {cout << "not found" << endl;}
*/
}
| true |
bae180db8408d9fa500529a07ebb7fb031696689 | C++ | Kavaldrin/adv | /przyklady/Przyklad 1 rodzaje referencji/main.cpp | UTF-8 | 1,332 | 3.578125 | 4 | [
"MIT"
] | permissive | #include <iostream>
#include <string>
struct A {
std::string m_napis = "Oryginal";
A() { std::cout<<"Tworze A\n"; }
~A() { std::cout<<"Kasuje A\n"; }
};
//ulatwienie notacji, moze przyjac i lvalue i rvalue i je wypisac!
std::ostream& operator<<(std::ostream& o,const A& a) {
o << a.m_napis << std::endl;
return o;
}
void f(const int& value) {
std::cout << "Wypisuje liczbe " << value << std::endl;
}
template <typename T>
class TypHelper;
int main()
{
A(); //obiekt tymczasowy, zostaje skasowany po tej linijce
//Mozliwosc modyfikacji obiektow (juz nie tymczasowych)
A&& a = A(); //przypisanie obiektu tymczasowego do r-wartosciowej referencji
std::cout << &a << std::endl;
std::cout << a;
a.m_napis = "Zmiana";
std::cout << a;
//TypHelper<decltype(a)> testa;
//Brak mozliwosci modyfikacji obiektow tymczasowych, tylko przedluzeniem im zywotnosci
//uzywajac tej notacji
const A& aa = A();
std::cout << aa;
//aa.m_napis = "Zmiana"; //no nie mozna bo jest const
int value = 5;
//wygoda uzytkownika, brak potrzeby pisania osobnych funkcji czy uzywania templatow
f(7); //przekazywany obiekt tymczasowy, zostaje przedluzona zywotnosc w funkcji
f(value); //przekazuje obiekt przez stala referencje, gwarancja braku modyfikacji obiektu
return 0;
} | true |
932c2a74c4f73927581ef864c91ab451267882da | C++ | adamtew/USU | /2014/CS1400/Challenges/Chapter 7/7.3_Widget_Factory/Widget_Factory.cpp | UTF-8 | 256 | 2.703125 | 3 | [] | no_license | #include "Widget_Factory.h"
using namespace std;
WidgetFactory::WidgetFactory(){
widgets = 0;
}
void WidgetFactory::setWidgets(int n){
widgets = n;
}
int WidgetFactory::daysToProduce(){
productionTime = (widgets / 160) + 1;
return productionTime;
} | true |
523bd8f0a0f3847586114af80bea141fd052965e | C++ | LuckyPigeon/LuckyPigeon | /Data_Hiding/程式/程式 3_JPEG/Version 2 (OK)/main.cpp | UTF-8 | 2,280 | 2.8125 | 3 | [] | no_license | //============================================================================
// Name : jpeg.cpp
// Author :
// Version :
// Copyright : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <iostream>
using namespace std;
//#include <windows.h>
#include <stdio.h> // sprintf(..), fopen(..)
#include <stdarg.h> // So we can use ... (in dprintf)
#include "loadjpg.h" // ConvertJpgFile(..)
#include "savejpg.h" // SaveJpgFile(..)
/***************************************************************************/
/* */
/* FeedBack Data */
/* */
/***************************************************************************/
//Saving debug information to a log file
void dprintf(const char *fmt, ...)
{
va_list parms;
char buf[256];
// Try to print in the allocated space.
va_start(parms, fmt);
vsprintf (buf, fmt, parms);
va_end(parms);
// Write the information out to a txt file
FILE *fp = fopen("output.txt", "a+");
fprintf(fp, "%s", buf);
fclose(fp);
}// End dprintf(..)
/***************************************************************************/
/* */
/* Entry Point */
/* */
/***************************************************************************/
int main(void){
// Create a jpg from a bmp
SaveJpgFile("smiley.bmp", "ex.jpg");
// Create a bmp from a jpg
ConvertJpgFile("ex.jpg", "out.bmp");
return 0;
}
/*int __stdcall WinMain (HINSTANCE hInst, HINSTANCE hPrev, LPSTR lpCmd, int nShow)
{
// Create a jpg from a bmp
//SaveJpgFile("smiley.bmp", "ex.jpg");
// Create a bmp from a jpg
ConvertJpgFile("smiley.jpg", "smiley.bmp");
//ConvertJpgFile("cross.jpg", "cross.bmp");
return 0;
}// End WinMain(..)*/
| true |
9fcd8185ea3d6c09abf1215d037f98595041ce8b | C++ | Leeseonwoo11/ProgrammersAlgorithm | /Level2/Fibonacci numbers/Fibonacci numbers/Fibonacci numbers.cpp | UTF-8 | 1,563 | 3.046875 | 3 | [] | no_license | // Fibonacci numbers.cpp : 이 파일에는 'main' 함수가 포함됩니다. 거기서 프로그램 실행이 시작되고 종료됩니다.
//
#include <string>
#include <vector>
using namespace std;
int fibo(int n)
{
long long pre = 0;
long long next = 1;
long long temp = 0;
int count = 1;
if (n == 0)
return 0;
else if (n == 1)
return 1;
while (count != n)
{
temp = pre + next;
pre = next;
next = temp;
count++;
if (temp > 1234567)
temp -= 1234567;
if (pre > 1234567)
pre -= 1234567;
if (next > 1234567)
next -= 1234567;
}
return temp;
}
int solution(int n) {
int answer = 0;
answer = fibo(n);
return answer;
}
int main()
{
solution(3);
}
// 프로그램 실행: <Ctrl+F5> 또는 [디버그] > [디버깅하지 않고 시작] 메뉴
// 프로그램 디버그: <F5> 키 또는 [디버그] > [디버깅 시작] 메뉴
// 시작을 위한 팁:
// 1. [솔루션 탐색기] 창을 사용하여 파일을 추가/관리합니다.
// 2. [팀 탐색기] 창을 사용하여 소스 제어에 연결합니다.
// 3. [출력] 창을 사용하여 빌드 출력 및 기타 메시지를 확인합니다.
// 4. [오류 목록] 창을 사용하여 오류를 봅니다.
// 5. [프로젝트] > [새 항목 추가]로 이동하여 새 코드 파일을 만들거나, [프로젝트] > [기존 항목 추가]로 이동하여 기존 코드 파일을 프로젝트에 추가합니다.
// 6. 나중에 이 프로젝트를 다시 열려면 [파일] > [열기] > [프로젝트]로 이동하고 .sln 파일을 선택합니다.
| true |
81cd84cfe7d31f5a6e3a40dfe1b572ad9cbac72a | C++ | jwfloyd42/Lab-03 | /Password.h | UTF-8 | 1,215 | 2.53125 | 3 | [] | no_license | #if !defined PASSWORD_H
#define PASSWORD_H
#include "CSC2110/ListArrayIterator.h"
#include "CSC2110/Permutation.h"
#include "CSC2110/ReadFile.h"
#include "CSC2110/Random.h"
#include "CSC2110/Integer.h"
#include "CSC2110/Double.h"
#include "CSC2110/ListArray.h"
#include "CSC2110/Text.h"
#include "CSC2110/HighPerformanceCounter.h"
#include "CSC2110/Keyboard.h"
#include "CSC2110/Matrix.h"
#include "CSC2110/Poly.h"
#include "CSC2110/WriteFile.h"
#include "CSC2110/Random.h"
#include <iostream>
class Password
{
private:
ListArray<String>* viable_words; //the list of words that can still be the password
ListArray<String>* all_words; //the original list of words
int len; //the length of the first word entered is stored to check that all subsequent words have the same length
//a private helper method to report the number of character matches between two Strings
int getNumMatches(String* curr_word, String* word_guess);
public:
Password();
~Password();
void addWord(String* wrd);
void guess(int try_password, int num_matches);
int getNumberOfPasswordsLeft();
void displayViableWords();
int bestGuess();
String* getOriginalWord(int index);
};
#endif
| true |
02be6a79c6333c698d7a26961e7adf913925794e | C++ | yzbx/opencv-qt | /linux/src/objectTracking/extern/UrbanTracker/include/IObject.h | UTF-8 | 987 | 2.859375 | 3 | [] | no_license | #ifndef IOBJECT_H
#define IOBJECT_H
#include <string>
#include "ObjectState.h"
#include <opencv2/opencv.hpp>
#include "Logger.h"
//Object interface
class ApplicationContext;
class ObjectModel;
class IObjectModel;
class IObject
{
public:
IObject(ApplicationContext* context, cv::Scalar color = cv::Scalar(0,0,255));
virtual ~IObject(){ /*LOGINFO("Destructor of " << getObjectId());*/}
ApplicationContext* getContext() const { return mContext;}
void setState(ObjectState state) { mState = state;}
void setObjectId(const std::string& id) { mObjectId = id;}
ObjectState getState() const { return mState;}
const std::string& getObjectId() const { return mObjectId;}
const cv::Scalar& getColor() const { return mColor;}
void setColor(cv::Scalar& color) { mColor = color;}
virtual IObjectModel* getIObjectModel() = 0;
virtual void draw(cv::Mat& image) = 0;
private:
ApplicationContext* mContext;
ObjectState mState;
std::string mObjectId;
cv::Scalar mColor;
};
#endif
| true |
ffeb98f9b13da493f549b7c7bb19cdf2b35eb826 | C++ | mr1r/Basic-Codes | /xor.cpp | UTF-8 | 353 | 3.765625 | 4 | [] | no_license | //evaluating XOR operation
//(x ^ y) = ~(x & y) & (~x & ~y)
#include <stdio.h>
int bitXor(int x,int y){
int a, b, result;
a = x & y; //AND
b = ~x & ~y; //NOR
result = ~a & ~b; //NOR
return result;
}
int main()
{
int x, y, result;
while(scanf("%d %d", &x, &y)==2){
result = bitXor(x,y);
printf("%d\n", result);
}
return 0;
}
| true |
44c5a229c0fc908b5146c15e2f062900b63282c0 | C++ | dinextw/snell_law | /cuboid.cpp | UTF-8 | 6,651 | 2.890625 | 3 | [] | no_license | //
// snell.cpp
// Snell_TeacherIII
//
// Created by 施俊宇 on 2016/10/18.
// Copyright © 2016年 NCU. All rights reserved.
//
#include <utility>
#include <cmath>
#include <vector>
#include <algorithm>
#include <stdlib.h>
#include "cuboid.hpp"
using namespace std;
void Cuboid::SetValue(double x_low,
double x_high,
double y_low,
double y_high,
double z_low,
double z_high,
double speed)
{
this->x_low = x_low;
this->x_high = x_high;
this->y_low = y_low;
this->y_high = y_high;
this->z_low = z_low;
this->z_high = z_high;
this->speed = speed;
}
pair<TCoordinate, TVector> Cuboid::ComputePath(TCoordinate position_in, TVector velocity_in) const
{
// Compute intersection position
double factor_multiply_x_high = (x_high - position_in.x) / velocity_in.x;
double factor_multiply_y_high = (y_high - position_in.y) / velocity_in.y;
double factor_multiply_z_high = (z_high - position_in.z) / velocity_in.z;
double factor_multiply_x_low = (x_low - position_in.x) / velocity_in.x;
double factor_multiply_y_low = (y_low - position_in.y) / velocity_in.y;
double factor_multiply_z_low = (z_low - position_in.z) / velocity_in.z;
TCoordinate position_intersect_x_high = position_in + velocity_in * factor_multiply_x_high;
TCoordinate position_intersect_y_high = position_in + velocity_in * factor_multiply_y_high;
TCoordinate position_intersect_z_high = position_in + velocity_in * factor_multiply_z_high;
TCoordinate position_intersect_x_low = position_in + velocity_in * factor_multiply_x_low;
TCoordinate position_intersect_y_low = position_in + velocity_in * factor_multiply_y_low;
TCoordinate position_intersect_z_low = position_in + velocity_in * factor_multiply_z_low;
// Compute Distance
double distance_x_high = -1;
if( position_intersect_x_high.y <= y_high &&
position_intersect_x_high.y >= y_low &&
position_intersect_x_high.z <= z_high &&
position_intersect_x_high.z >= z_low )
{
distance_x_high = sqrt( pow(position_in.x - position_intersect_x_high.x, 2)
+ pow(position_in.y - position_intersect_x_high.y, 2)
+ pow(position_in.z - position_intersect_x_high.z, 2) );
}
double distance_x_low = -1;
if( position_intersect_x_low.y <= y_high &&
position_intersect_x_low.y >= y_low &&
position_intersect_x_low.z <= z_high &&
position_intersect_x_low.z >= z_low )
{
distance_x_low = sqrt( pow(position_in.x - position_intersect_x_low.x, 2)
+ pow(position_in.y - position_intersect_x_low.y, 2)
+ pow(position_in.z - position_intersect_x_low.z, 2) );
}
double distance_y_high = -1;
if( position_intersect_y_high.x >= x_low &&
position_intersect_y_high.x <= x_high &&
position_intersect_y_high.z >= z_low &&
position_intersect_y_high.z <= z_high )
{
distance_y_high = sqrt( pow(position_in.x - position_intersect_y_high.x, 2)
+ pow(position_in.y - position_intersect_y_high.y, 2)
+ pow(position_in.z - position_intersect_y_high.z, 2) );
}
double distance_y_low = -1;
if( position_intersect_y_low.x >= x_low &&
position_intersect_y_low.x <= x_high &&
position_intersect_y_low.z >= z_low &&
position_intersect_y_low.z <= z_high )
{
distance_y_low = sqrt( pow(position_in.x - position_intersect_y_low.x, 2)
+ pow(position_in.y - position_intersect_y_low.y, 2)
+ pow(position_in.z - position_intersect_y_low.z, 2) );
}
double distance_z_high = -1;
if( position_intersect_z_high.x >= x_low &&
position_intersect_z_high.x <= x_high &&
position_intersect_z_high.y >= y_low &&
position_intersect_z_high.y <= y_high )
{
distance_z_high = sqrt( pow(position_in.x - position_intersect_z_high.x, 2)
+ pow(position_in.y - position_intersect_z_high.y, 2)
+ pow(position_in.z - position_intersect_z_high.z, 2) );
}
double distance_z_low = -1;
if( position_intersect_z_low.x >= x_low &&
position_intersect_z_low.x <= x_high &&
position_intersect_z_low.y >= y_low &&
position_intersect_z_low.y <= y_high )
{
distance_z_low = sqrt( pow(position_in.x - position_intersect_z_low.x, 2)
+ pow(position_in.y - position_intersect_z_low.y, 2)
+ pow(position_in.z - position_intersect_z_low.z, 2) );
}
// Compare Distance
double distance_plane[6] = {};
distance_plane[0] = distance_x_high;
distance_plane[1] = distance_x_low;
distance_plane[2] = distance_y_high;
distance_plane[3] = distance_y_low;
distance_plane[4] = distance_z_high;
distance_plane[5] = distance_z_low;
// Check if error happened in determining intersaction plane
int total_reflection_checker = 0;
for (int i = 0; i < 6 ; i++)
total_reflection_checker = total_reflection_checker + distance_plane[i];
if(total_reflection_checker == -6)
abort();
// Output Location
long index_largest_distance = distance(distance_plane,
max_element(distance_plane,
distance_plane + 6));
TCoordinate position_out;
TVector norm_plane;
switch (index_largest_distance) {
case 0:
position_out = position_intersect_x_high;
norm_plane.x = -1;
break;
case 1:
position_out = position_intersect_x_low;
norm_plane.x = 1;
break;
case 2:
position_out = position_intersect_y_high;
norm_plane.y = -1;
break;
case 3:
position_out = position_intersect_y_low;
norm_plane.y = 1;
break;
case 4:
position_out = position_intersect_z_high;
norm_plane.z = -1;
break;
case 5:
position_out = position_intersect_z_low;
norm_plane.z = 1;
break;
default:
break;
}
return pair<TCoordinate, TVector>(position_out, -norm_plane);
}
| true |
e335782b45313ad58b3d3ae165f241c5abc72fef | C++ | vslavik/poedit | /deps/boost/libs/utility/identity_type/test/paren.cpp | UTF-8 | 1,168 | 2.515625 | 3 | [
"GPL-1.0-or-later",
"MIT",
"BSL-1.0"
] | permissive |
// Copyright (C) 2009-2012 Lorenzo Caminiti
// Distributed under the Boost Software License, Version 1.0
// (see accompanying file LICENSE_1_0.txt or a copy at
// http://www.boost.org/LICENSE_1_0.txt)
// Home at http://www.boost.org/libs/utility/identity_type
#include <boost/utility/identity_type.hpp>
#include <boost/static_assert.hpp>
#include <boost/type_traits/is_const.hpp>
#include <map>
//[paren
#define TMP_ASSERT_PAREN(parenthesized_metafunction) \
/* use `BOOST_IDENTITY_TYPE` in macro definition instead of invocation */ \
BOOST_STATIC_ASSERT(BOOST_IDENTITY_TYPE(parenthesized_metafunction)::value)
#define TMP_ASSERT(metafunction) \
BOOST_STATIC_ASSERT(metafunction::value)
// Specify only extra parenthesis `((...))`.
TMP_ASSERT_PAREN((boost::is_const<std::map<int, char> const>));
// Specify both the extra parenthesis `((...))` and `BOOST_IDENTITY_TYPE` macro.
TMP_ASSERT(BOOST_IDENTITY_TYPE((boost::is_const<std::map<int, char> const>)));
//]
//[paren_always
TMP_ASSERT_PAREN((boost::is_const<int const>)); // Always extra `((...))`.
TMP_ASSERT(boost::is_const<int const>); // No extra `((...))` and no macro.
//]
int main() { return 0; }
| true |
cdb8e1bf18480cfdba0713ad8f2919f30e3b558e | C++ | Ginfoo/mystl | /mystl/mystl/malloc_i.h | UTF-8 | 2,112 | 3.3125 | 3 | [] | no_license | #pragma once
#include <new>
#include <cstdlib>
#ifndef _THROW_BAD_ALLOC
#if defined(__STL_NO_BAD_ALLOC) || !defined(__STL_USE_EXCEPTIONS)
#include <cstdio>
#include <cstdlib>
#define _THROW_BAD_ALLOC \
fprintf(stderr, "out of memory"); \
exit(1)
#else
#include <new>
#define _THROW_BAD_ALLOC throw std::bad_alloc()
#endif
#endif
class malloc_i
{
private:
static void (*oom_malloc_handler)();
static void *oom_malloc(const size_t);
static void *oom_realloc(void *, const size_t);
public:
static void *allocate(const size_t);
static void deallocate(void *, size_t);
static void *reallocate(void *, size_t, const size_t);
static void (*set_oom_malloc_handler(void (*_new_handler)()))();
};
void (*malloc_i::oom_malloc_handler)() = nullptr;
inline void *malloc_i::oom_malloc(const size_t _Size)
{
void (*cur_oom_malloc_handler)() = nullptr;
void *result = nullptr;
for (;;)
{
cur_oom_malloc_handler = oom_malloc_handler;
if (nullptr == cur_oom_malloc_handler)
{
_THROW_BAD_ALLOC;
}
(*cur_oom_malloc_handler)();
result = malloc(_Size);
if (result)
return result;
}
}
inline void *malloc_i::oom_realloc(void *_Block, const size_t _Size)
{
void (*cur_oom_malloc_handler)() = nullptr;
void *result = nullptr;
for (;;)
{
cur_oom_malloc_handler = oom_malloc_handler;
if (nullptr == cur_oom_malloc_handler)
{
_THROW_BAD_ALLOC;
}
(*cur_oom_malloc_handler)();
result = realloc(_Block, _Size);
}
}
inline void *malloc_i::allocate(const size_t _Size)
{
void *result = malloc(_Size);
if (nullptr == result)
{
result = oom_malloc(_Size);
}
return result;
}
inline void malloc_i::deallocate(void *_Block, size_t _Size)
{
free(_Block);
}
inline void *malloc_i::reallocate(void *_Block, size_t _old_Size, size_t _new_Size)
{
void *result = realloc(_Block, _new_Size);
if (nullptr == result)
{
result = oom_realloc(_Block, _new_Size);
}
return result;
}
inline void (*malloc_i::set_oom_malloc_handler(void (*_new_handler)()))()
{
void (*_old_handler)() = oom_malloc_handler;
oom_malloc_handler = _new_handler;
return (_old_handler);
}
| true |
bcc5677cb08e330063af5ff3386bcaced1ecdc99 | C++ | Archana550/SDE_30_180 | /DAY2/8_pascal_triangle_ll.cpp | UTF-8 | 788 | 3.640625 | 4 | [] | no_license | /*
Given an integer rowIndex, return the rowIndexth row of the Pascal's triangle.
Notice that the row index starts from 0.
In Pascal's triangle, each number is the sum of the two numbers directly above it.
Follow up:
Could you optimize your algorithm to use only O(k) extra space?
Example 1:
Input: rowIndex = 3
Output: [1,3,3,1]
Example 2:
Input: rowIndex = 0
Output: [1]
Example 3:
Input: rowIndex = 1
Output: [1,1]
Constraints:
0 <= rowIndex <= 33
*/
class Solution {
public:
vector<int> getRow(int rowIndex) {
vector<int> ans;
ans.push_back(1);
long long res=1;
for(int i =0; i<rowIndex; i++){
res *= (rowIndex-i);
res /= (i+1);
ans.push_back(res);
}
return ans;
}
};
| true |
38970c1017c08608bbe6772f6a300191841e7e4e | C++ | coderwhocode/ccrma | /256a/flyingdream/Matrix.h | UTF-8 | 3,232 | 3.453125 | 3 | [] | no_license | /* 4x4 Matrix
Last Modified 14/4/00
*/
#ifndef __MATRIX_H_
#define __MATRIX_H_
class Vector3D;
class Point3D;
//////////////////////////////
class Matrix
{
private:
float m[16]; // RIGHT HANDED column major matrix
inline void Verify_Matrix(); // force last row of matrix to be 0 0 0 1 to be a homogenous matrix
public:
Matrix(); // creates an 4x4 identity matrix
Matrix(const float m[16]);
Matrix(const Vector3D &v); // generate a transformation matrix of translation v
Matrix(const float angle, const Vector3D &v); // generate a rotation matrix of angle (rad) around an axis of rotation v
// ~Matrix();
///////////
void Zero_Clamp(void); // clamp any values in the matrix to 0
void GetValues(float m[16]) const; // get the values of this matrix
void GetTranslation(Point3D &p) const; // get the translation portion of the 4x4 homogenous transformation matrix
//%%%%%%%%%%%%%
// NOT WORKING
//%%%%%%%%%%%%%
void GetEulerAngles(float &x, float &y, float &z) const; // get euler values of rotation order x,y,z of matrix
void SetValues(const float m[16]); // set the values of this matrix, last row always 0 0 0 1 regardless of what is passed in
void SetValues(const Point3D &p); // create a transformation matrix that translates to the position p
void SetValues(const Vector3D &v); // create a transformation matrix with the translation vector
void SetValues(const float angle, const Vector3D &v); // create a rotation matrix with angle (rad) around axis of rotation vector
void SetValues_RotX(const float angle); // generate a 4x4 rotation matrix with angle (degree) around respective axis
void SetValues_RotY(const float angle);
void SetValues_RotZ(const float angle);
void SetValues_Rot(const float x, const float y, const float z); // generates a final 4x4 transformation matrix of rotation around x ,y, z axis (deg)
///////////
//%%%%%%%%%%%%%%%%%
// NOT IMPLEMENTED
//%%%%%%%%%%%%%%%%%
void Inverse(void); // inverse the matrix
void LoadIdentity(void); // set this matrix to the identity matrix
void Negate(void); // negate the matrix;
void Transpose(void); // transpose the matrix
///////////
Matrix operator*(const Matrix &m) const; // multiplication with a matrix
Matrix operator*(const float s) const; // scale matrix by s
// Matrix operator+(const Matrix &m) const;
// Matrix operator-(const Matrix &m) const;
Matrix operator-() const; // negation
Vector3D operator*(const Vector3D &v) const; // pre-multiply by column vector
Point3D operator*(const Point3D &p) const; // pre-multiply by point
Matrix& operator=(const Matrix &m); // copy constructor
// Matrix& operator+=(const Matrix &m);
// Matrix& operator-=(const Matrix &m);
Matrix& operator*=(const Matrix &m);
Matrix& operator*=(const float s); // scale matrix by s
int operator==(const Matrix &m) const; // equality
int operator!=(const Matrix &m) const;
//------- debug
void Print() const;
}; // end class Matrix
//////////////////////////////
#endif // __MATRIX_H_
| true |
69a83a508d5df29f7e34c6b6fd8e38c84ad2a2a9 | C++ | YongHoonJJo/BOJ | /2564.cpp | UTF-8 | 806 | 3.0625 | 3 | [] | no_license | #include <stdio.h>
int abs(int x)
{
return x > 0 ? x : -x;
}
int Min(int a, int b)
{
return a < b ? a : b;
}
int main()
{
int row, col, n, ans=0;
int i, r[101], c[101];
scanf("%d%d%d", &col, &row, &n);
// dir == 1:north, 2:south, 3:west, 4:east
for(i=0; i<=n; i++) {
int dir, dist;
scanf("%d%d", &dir, &dist);
switch(dir) {
case 1: r[i]=0; c[i]=dist; break;
case 2: r[i]=row; c[i]=dist; break;
case 3: r[i]=dist; c[i]=0; break;
case 4: r[i]=dist; c[i]=col; break;
}
}
for(i=0; i<n; i++) {
ans += (abs(r[n]-r[i])+abs(c[n]-c[i]));
if(abs(r[n]-r[i]) == row)
ans += (Min(Min(abs(col-c[n]), c[n]), Min(abs(col-c[i]),c[i]))*2);
if(abs(c[n]-c[i]) == col) {
ans += (Min(Min(abs(row-r[n]), r[n]), Min(abs(row-r[i]),r[i]))*2);
}
}
printf("%d\n", ans);
return 0;
}
| true |
2ed0b7352120f53e801bcf518b835fcc298d194a | C++ | gravfu/OOP_arcade_2019 | /lib/SFML/Lib_arcade_sfml.cpp | UTF-8 | 4,796 | 2.671875 | 3 | [] | no_license | /*
** EPITECH PROJECT, 2020
** Visual Studio Live Share (Workspace)
** File description:
** Lib_arcade_ncurse
*/
#include "Lib_arcade_sfml.hpp"
#include <string>
#include "Print_mat.cpp"
#define LEFTMARGINE 40
void Lib_arcade_sfml::printInColor(int index, sf::RectangleShape &box)
{
printlib(index, game, box);
}
Event Lib_arcade_sfml::Keypressed(){
assign_game(game);
sf::Event event;
while (window->pollEvent(event))
{
if (event.type == sf::Event::Closed || (event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::Escape))
window->close();
if (event.type == sf::Event::KeyPressed)
{
if (event.key.code == sf::Keyboard::Up)
return Event::UP;
if (event.key.code == sf::Keyboard::Down)
return Event::DOWN;
if (event.key.code == sf::Keyboard::Right)
return Event::RIGHT;
if (event.key.code == sf::Keyboard::Left)
return Event::LEFT;
if (event.key.code == sf::Keyboard::Space)
return Event::SHOOT;
if (event.key.code == sf::Keyboard::O)
return Event::NEXT_GAME;
if (event.key.code == sf::Keyboard::P)
return Event::NEXT_GRAPH;
if (event.key.code == sf::Keyboard::L)
return Event::PREV_GAME;
if (event.key.code == sf::Keyboard::M)
return Event::PREV_GRAPH;
if (event.key.code == sf::Keyboard::Escape || !window->isOpen())
return Event::QUIT;
}
}
return Event::ENTER;
}
void Lib_arcade_sfml::destroy(){
window->close();
}
void Lib_arcade_sfml::init(int x, int y)
{
window = new sf::RenderWindow(sf::VideoMode(x*20, y*20), "Arcade");
window->setFramerateLimit(30);
}
Lib_arcade_sfml::Lib_arcade_sfml()
{
init(50, 50);
}
Lib_arcade_sfml::~Lib_arcade_sfml()
{
delete window;
}
void Lib_arcade_sfml::clear()
{
window->clear();
}
void Lib_arcade_sfml::refresh(Games game)
{
clear();
assign_game(game);
sf::Font font;
sf::Text text;
sf::RectangleShape box(sf::Vector2f(7, 7));
if (game.name != "Select")
{
for (int i = 0; i < game.height; i++) {
for (int j = 0; j < game.width; j++) {
box.setPosition(j * 7, 100 + i * 7);
printInColor(game.mat[i][j], box);
window->draw(box);
}
}
if (font.loadFromFile("lib/SFML/arial.ttf"))
{
std::string score = "Score: " + std::to_string(game.score);
text.setString(score);
text.setFont(font);
text.setCharacterSize(15);
text.setFillColor(sf::Color::Red);
text.setPosition(0, 0);
text.setStyle(sf::Text::Bold);
}
}
else
printSelect(game, window);
window->display();
}
#include <iostream>
#include <fstream>
void Lib_arcade_sfml::endgame(std::string name)
{
sf::Font font;
sf::Text text;
sf::Event event;
if (game.name == "Select")
return;
while (1)
{
while (window->pollEvent(event))
{
if (event.type == sf::Event::Closed || event.type == sf::Event::KeyPressed) {
window->close();
return;
}
}
window->clear();
if (font.loadFromFile("lib/SFML/arial.ttf"))
{
std::string score = "Score: " + std::to_string(game.score);
text.setString(score);
text.setFont(font);
text.setCharacterSize(50);
text.setFillColor(sf::Color::Red);
text.setPosition(50, 50);
text.setStyle(sf::Text::Bold);
window->draw(text);
if (game.name != "Pacman") {
text.setPosition(50, 150);
std::fstream ifs("./playerprofile/" + name, std::fstream::out | std::fstream::in);
std::string thescore;
int line = 0;
int currentline = 0;
if (game.name == "Pacman")
line = 1;
if (game.name == "Nibbler")
line = 2;
while (line != currentline)
getline(ifs, thescore);
getline(ifs, thescore);
if (thescore == "" )
thescore = "0";
text.setString(("Highscore : " + thescore).data());
ifs.close();
window->draw(text);
}
}
window->draw(text);
window->display();
}
}
extern "C" IgraphicLib* create() {
return new Lib_arcade_sfml;
}
extern "C" void destroy(IgraphicLib* p) {
delete p;
} | true |
e85fff6a472462e532acf4fcebbee51ae7a74810 | C++ | tnsts/IndexFiles | /methods.cpp | UTF-8 | 4,166 | 2.828125 | 3 | [] | no_license | #include "files.h"
Index_files::Index_files(){
proc = 5, amount = 10; // proc of zapas, amount of blocks
block_interval = 1000;
size = 0;
}
Index_files::~Index_files(){
for(int i = 0; i < proc*amount; i++){
delete [] index[i];
}
delete [] index;
for(int i = 0; i < size; i++){
delete [] main_data[i];
}
delete [] main_data;
delete [] filled;
}
void Index_files::insert(int key, int data){
if (filled[key / block_interval] >= proc){
Index_files::temp_index = new int*[(proc + 1)*amount];
for(int i = 0; i < (proc + 1)*amount; i++){
Index_files::temp_index[i] = new int[2];
}
for(int i = 0; i < proc*amount; i++){
Index_files::temp_index[i + i/proc][0] = index[i][0];
Index_files::temp_index[i + i/proc][1] = index[i][1];
}
for(int i = 0; i < proc*amount; i++){
delete [] index[i];
}
delete [] index;
proc++;
index = new int*[proc*amount];
for(int i = 0; i < proc*amount; i++){
index[i] = new int[2];
}
for(int i = 0; i < proc*amount; i++){
index[i][0] = Index_files::temp_index[i][0];
index[i][1] = Index_files::temp_index[i][1];
}
for (int i = 1; i <= amount; i++){
index[i*proc - 1][0] = INT_MAX;
index[i*proc - 1][1] = INT_MAX;
}
for(int i = 0; i < proc*amount; i++){
delete [] Index_files::temp_index[i];
}
delete [] Index_files::temp_index;
}
if (filled[key / block_interval] == 0){
index[proc*(key/block_interval)][0] = key;
index[proc*(key/block_interval)][1] = size;
} else {
int curr = 0;
for(int i = proc*(key/block_interval); i < proc*(key/block_interval + 1); i++){
curr = i;
if (index[i][0] > key){
break;
}
}
for(int i = proc*(key/block_interval + 1) - 1; i > curr; i--){
index[i][0] = index[i - 1][0];
index[i][1] = index[i - 1][1];
}
index[curr][0] = key;
index[curr][1] = size;
}
if (size == 0){
main_data = new int*[1];
main_data[0] = new int[2];
main_data[0][1] = data;
main_data[0][0] = key;
size++;
}
else {
Index_files::temp_main = new int*[++size];
for(int i = 0; i < size; i++){
Index_files::temp_main[i] = new int[2];
}
for(int i = 0; i < size - 1; i++){
Index_files::temp_main[i][0] = main_data[i][0];
Index_files::temp_main[i][1] = main_data[i][1];
}
for(int i = 0; i < size - 1; i++){
delete [] main_data[i];
}
delete [] main_data;
main_data = new int*[size];
for(int i = 0; i < size; i++){
main_data[i] = new int[2];
}
for(int i = 0; i < size; i++){
main_data[i][0] = Index_files::temp_main[i][0];
main_data[i][1] = Index_files::temp_main[i][1];
}
for(int i = 0; i < size; i++){
delete [] Index_files::temp_main[i];
}
delete [] Index_files::temp_main;
main_data[size-1][0] = key;
main_data[size-1][1] = data;
filled[key/block_interval]++;
}
}
int Index_files::search(int key){
int count = 0;
int mid;
int left = (key/block_interval)*proc;
int right = (key/block_interval)*proc + proc - 1;
while (index[left][0] <= key && index[right][0] >= key){
mid = left + ((key - index[left][0])*(right - left))/(index[right][0] - index[left][0]);
count++;
if (index[mid][0] < key) left = mid+1;
else if (index[mid][0] > key) right = mid - 1;
else{
// cout << "Count of comparing: " << count << endl;
return mid;
}
}
if (index[left][0] == key){
// cout << ++count << endl;
return left;
}
else return -1;
}
void Index_files::change(int key, int new_data){
main_data[index[search(key)][1]][1] = new_data;
}
void Index_files::delete_key(int key){
int block = key/block_interval;
int index_to_delete = search(key);
if (index_to_delete != proc*(block + 1) - 1){
for(int i = index_to_delete; i < proc*(block + 1) - 1; i++){
index[i][0] = index[i + 1][0];
index[i][1] = index[i + 1][1];
}
index[proc*(block + 1) - 1][0] = INT_MAX;
index[proc*(block + 1) - 1][1] = INT_MAX;
} else {
index[index_to_delete][0] = INT_MAX;
index[index_to_delete][1] = INT_MAX;
}
}
| true |
953b9388aef780736096ca1ab022f1741da2e477 | C++ | ShayanMirzaei/Utrip | /code/hotel/RoomManager.cpp | UTF-8 | 5,854 | 3.28125 | 3 | [] | no_license | #include "RoomManager.hpp"
#include "Room.hpp"
#include "StandardRoom.hpp"
#include "DeluxeRoom.hpp"
#include "LuxuryRoom.hpp"
#include "PremiumRoom.hpp"
#include <vector>
#include <string>
#include "../Exception.hpp"
#include "Reservation.hpp"
#include <iostream>
#define STANDARD "standard"
#define DELUXE "deluxe"
#define LUXURY "luxury"
#define PREMIUM "premium"
using namespace std;
enum RoomData {standard_num = 9, deluxe_num, luxury_num, premium_num, standard_price, deluxe_price, luxury_price, premium_price};
typedef vector<Room*> _rooms;
typedef pair<int,int> RoomInfoPair;
typedef std::vector<std::string> _room_ids;
RoomManager::RoomManager(vector<string> room_data)
{
add_rooms(room_data);
set_room_numbers(room_data);
set_room_prices(room_data);
reset_room_ids();
}
RoomManager::~RoomManager()
{
for (auto it = rooms.begin(); it != rooms.end(); it++)
{
delete *it;
*it = nullptr;
}
}
bool RoomManager::room_price_is_lower(RoomManager* room_manager, RoomType type)
{
switch (type)
{
case standard:
return room_prices[standard] < room_manager->room_prices[standard];
case deluxe:
return room_prices[deluxe] < room_manager->room_prices[deluxe];
case luxury:
return room_prices[luxury] < room_manager->room_prices[luxury];
case premium:
return room_prices[premium] < room_manager->room_prices[premium];
}
}
double RoomManager::get_reservation_one_night_price(string room_type, int quantity)
{
double total_price = 0;
RoomType type = get_room_type(room_type);
for (int i = 0; i < quantity; i++)
total_price += room_prices[type];
return total_price;
}
void RoomManager::cancel_reservation(Reservation* reservation)
{
for (auto it = rooms.begin(); it != rooms.end(); it++)
(*it)->cancel_reservation(reservation);
}
Reservation* RoomManager::reserve_rooms(string room_type, int quantity, int check_in, int check_out)
{
RoomType type = get_room_type(room_type);
_room_ids reserved_rooms = find_available_rooms(type, quantity, check_in, check_out);
check_enough_rooms(reserved_rooms.size(), quantity);
double total_price = get_reservation_one_night_price(room_type, quantity) * (check_out - check_in + 1);
Reservation* reservation = new Reservation(check_in, check_out, reserved_rooms, total_price, room_type, quantity);
add_reservation_to_rooms(reservation, reserved_rooms);
return reservation;
}
bool RoomManager::has_available_rooms(string room_type, int quantity, int check_in, int check_out)
{
RoomType type = get_room_type(room_type);
_room_ids available_rooms = find_available_rooms(type, quantity, check_in, check_out);
if (available_rooms.size() < quantity)
return false;
return true;
}
void RoomManager::add_reservation_to_rooms(Reservation* reservation, _room_ids room_ids)
{
for (auto id_it = room_ids.begin(); id_it != room_ids.end(); id_it++)
for (auto room_it = rooms.begin(); room_it != rooms.end(); room_it++)
if ((*room_it)->get_id() == *id_it)
(*room_it)->add_reservation(reservation);
}
void RoomManager::check_enough_rooms(int reserved_rooms, int quantity)
{
if (reserved_rooms != quantity)
throw NotEnoughRoom();
}
_room_ids RoomManager::find_available_rooms(RoomType type, int quantity, int check_in, int check_out)
{
_room_ids reserved_rooms;
for (auto it = rooms.begin(); it != rooms.end(); it++)
if ((*it)->is_available(type, check_in, check_out) && reserved_rooms.size() != quantity)
reserved_rooms.push_back((*it)->get_id());
return reserved_rooms;
}
RoomType RoomManager::get_room_type(string room_type)
{
if (room_type == STANDARD)
return standard;
else if (room_type == DELUXE)
return deluxe;
else if (room_type == LUXURY)
return luxury;
else if (room_type == PREMIUM)
return premium;
else
throw BadRequest();
}
double RoomManager::get_average_room_price()
{
double average_price = 0;
int type_of_rooms = 0;
for (auto it = room_prices.begin(); it != room_prices.end(); it++)
if ((*it).second != 0)
{
type_of_rooms++;
average_price += (*it).second;
}
if (type_of_rooms == 0)
return 0;
return average_price / type_of_rooms;
}
void RoomManager::set_room_numbers(_room_data room_data)
{
room_numbers.insert(RoomInfoPair(standard, stoi(room_data[standard_num])));
room_numbers.insert(RoomInfoPair(deluxe, stoi(room_data[deluxe_num])));
room_numbers.insert(RoomInfoPair(luxury, stoi(room_data[luxury_num])));
room_numbers.insert(RoomInfoPair(premium, stoi(room_data[premium_num])));
}
void RoomManager::set_room_prices(_room_data room_data)
{
room_prices.insert(RoomInfoPair(standard, stoi(room_data[standard_price])));
room_prices.insert(RoomInfoPair(deluxe, stoi(room_data[deluxe_price])));
room_prices.insert(RoomInfoPair(luxury, stoi(room_data[luxury_price])));
room_prices.insert(RoomInfoPair(premium, stoi(room_data[premium_price])));
}
void RoomManager::reset_room_ids()
{
for (auto it = rooms.begin(); it != rooms.end(); it++)
(*it)->reset_id();
}
void RoomManager::add_rooms(vector<string> room_data)
{
for (int i = 0; i < stoi(room_data[standard_num]); i++)
rooms.push_back(new StandardRoom(stoi(room_data[standard_price])));
for (int i = 0; i < stoi(room_data[deluxe_num]); i++)
rooms.push_back(new DeluxeRoom(stoi(room_data[deluxe_price])));
for (int i = 0; i < stoi(room_data[luxury_num]); i++)
rooms.push_back(new LuxuryRoom(stoi(room_data[luxury_price])));
for (int i = 0; i < stoi(room_data[premium_num]); i++)
rooms.push_back(new PremiumRoom(stoi(room_data[premium_price])));
}
| true |
4b31e95c992baede1175d2e333576cfd0134c82e | C++ | veer11997/DSA | /CB-stl/Unordered map/hasfuncustomclass.cpp | UTF-8 | 1,099 | 3.28125 | 3 | [] | no_license | #include<iostream>
#include<cstring>
#include<unordered_map>
using namespace std;
class student
{
public:
string firstname;
string lastname;
string rollno;
student(string f,string l, string no)
{
firstname=f;
lastname=l;
rollno=no;
}
bool operator==(const student &s) const
{
return rollno==s.rollno?true:false;
}
};
class Hashfun{
public:
size_t operator()(const student &s) const
{
return s.firstname.length()+s.lastname.length();
}
};
int main()
{
unordered_map<student,int,Hashfun> student_map;
student s1("prateek","narang","010");
student s2("rahul","kumar","023");
student s3("prateek","gupta","030");
student s4("rahul","kumar","120");
//Add student marks to hashmap
student_map[s1]=100;
student_map[s2]=120;
student_map[s3]=11;
student_map[s4]=45;
// find the marks
cout<<student_map[s3]<<endl;
//iterate over all student
for(auto s: student_map)
{
cout<<s.first.firstname<<" "<<s.first.rollno<<" "<<s.second<<endl;
}
}
| true |
99b948b5ae50770df5de585d441d2e3fab8150e5 | C++ | xxvms/MemberVariable | /Resource.h | UTF-8 | 553 | 3.0625 | 3 | [] | no_license | //
// Created by tombr on 17/08/2017.
//
#ifndef CASTING_RESOURCE_H
#define CASTING_RESOURCE_H
#include <string>
class Resource {
private:
std::string name;
public:
Resource(std::string n); // default constructor that takes string
Resource(const Resource& r); // copy constructor to make one resoure from other
Resource& operator=(const Resource& r); // copy assignment operator to set values of one resource
~Resource(); // Destructor
std::string Get_Name() const { return name; }
};
#endif //CASTING_RESOURCE_H
| true |
9c477163871b93443278a5bd08b32207b3f32469 | C++ | michalg9/WPT | /PowercastSolutions/libraries/PowercastReceiver/PowercastTxMeasurementLayer.cpp | UTF-8 | 2,842 | 2.6875 | 3 | [] | no_license | #include "PowercastTxMeasurementLayer.h"
PowercastTxMeasurementLayer::PowercastTxMeasurementLayer()
{
timerMeasurement = 0;
currentState = STATE_IDLE;
measurementObject = NULL;
}
void PowercastTxMeasurementLayer::setMeasurementObject(MeasurementObject *measObject)
{
measurementObject = measObject;
}
void PowercastTxMeasurementLayer::processPacket(ProtocolPacket *xBeePacket)
{
//Serial.println("processPacket");
if (xBeePacket->packetType == TYPE_TIME_SYNCH) {
eventReceivedTimeSynch(xBeePacket);
}
}
void PowercastTxMeasurementLayer::eventReceivedTimeSynch(ProtocolPacket *xBeePacket)
{
processState(EVENT_RECEIVED_TIME_SYNCH, xBeePacket);
}
void PowercastTxMeasurementLayer::eventTimeoutMeasurement()
{
processState(EVENT_TIMEOUT_MEASUREMENT, NULL);
}
void PowercastTxMeasurementLayer::processState(Event currentEvent, ProtocolPacket *xBeePacket)
{
//Serial.println("processState");
int nextState = currentState;
switch (currentState)
{
case STATE_IDLE:
if (currentEvent == EVENT_RECEIVED_TIME_SYNCH)
{
actionSaveTimeSynch(xBeePacket);
}
else if (currentEvent == EVENT_TIMEOUT_MEASUREMENT)
{
actionSaveResultsToSd();
}
break;
default:
break;
}
}
void PowercastTxMeasurementLayer::doTimerActions()
{
unsigned long currentTime = getCurrentTimeMiliseconds();
if (currentTime - timerMeasurement >= DELAY_MEASUREMENT) {
eventTimeoutMeasurement();
timerMeasurement = currentTime;
}
}
void PowercastTxMeasurementLayer::actionSaveTimeSynch(ProtocolPacket *xBeePacket)
{
byte byteArray[4];
byteArray[0] = xBeePacket->packetData[0];
byteArray[1] = xBeePacket->packetData[1];
byteArray[2] = xBeePacket->packetData[2];
byteArray[3] = xBeePacket->packetData[3];
unsigned long longInt = convertByteArrayToLong(byteArray);
measurementObject->recentReceivedTimestamp = longInt;
measurementObject->localTimestampOnSynch = getCurrentTimeMiliseconds();
/*Serial.println("Received timestamp synch:");
Serial.println(measurementObject->recentReceivedTimestamp);
Serial.println("Current timestamp:");
Serial.println(measurementObject->localTimestampOnSynch);*/
}
void PowercastTxMeasurementLayer::actionSaveResultsToSd() {
measurementObject->saveTransmitterDataToFile();
}
//void PowercastTxMeasurementLayer::convertLongToByteArray(long longInt, byte byteArray[]) {
//
// byteArray[0] = (byte)((longInt >> 24) & 0xFF);
// byteArray[1] = (byte)((longInt >> 16) & 0xFF);
// byteArray[2] = (byte)((longInt >> 8) & 0XFF);
// byteArray[3] = (byte)((longInt & 0XFF));
//
//}
long PowercastTxMeasurementLayer::convertByteArrayToLong(byte byteArray[]) {
unsigned long longInt;
longInt = ((unsigned long)byteArray[0]) << 24;
longInt |= ((unsigned long)byteArray[1]) << 16;
longInt |= ((unsigned long)byteArray[2]) << 8;
longInt |= ((unsigned long)byteArray[3]);
return longInt;
} | true |
bfc3ddb6df9fb30141e10fa59a88bd6105850dfd | C++ | anastasiak2512/CLion2016.3Demo | /Doxygen/Doxygen_generation.cpp | UTF-8 | 642 | 2.96875 | 3 | [] | no_license |
template<typename T>
struct Maybe;
template<typename T>
Maybe<T> maybe(T *context)
{
return Maybe<T>(context);
}
// Press /// and type Enter to get Doxygen comments generated
template<typename T>
struct Maybe {
T *context;
Maybe(T *context) : context(context)
{}
// Press /// and type Enter to get Doxygen comments generated
template<typename TFunc>
auto With(TFunc evaluator)
{
return context != nullptr ? maybe(evaluator(context)) : nullptr;
};
template<typename TFunc>
auto Do(TFunc action)
{
if (context != nullptr) action(context);
return *this;
}
};
| true |
f280ea4da878b047cd2cdb348ebeb61214f60a80 | C++ | ziglang/zig | /lib/tsan/sanitizer_common/sanitizer_lfstack.h | UTF-8 | 2,130 | 2.609375 | 3 | [
"LLVM-exception",
"Apache-2.0",
"MIT"
] | permissive | //===-- sanitizer_lfstack.h -=-----------------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// Lock-free stack.
// Uses 32/17 bits as ABA-counter on 32/64-bit platforms.
// The memory passed to Push() must not be ever munmap'ed.
// The type T must contain T *next field.
//
//===----------------------------------------------------------------------===//
#ifndef SANITIZER_LFSTACK_H
#define SANITIZER_LFSTACK_H
#include "sanitizer_internal_defs.h"
#include "sanitizer_common.h"
#include "sanitizer_atomic.h"
namespace __sanitizer {
template<typename T>
struct LFStack {
void Clear() {
atomic_store(&head_, 0, memory_order_relaxed);
}
bool Empty() const {
return (atomic_load(&head_, memory_order_relaxed) & kPtrMask) == 0;
}
void Push(T *p) {
u64 cmp = atomic_load(&head_, memory_order_relaxed);
for (;;) {
u64 cnt = (cmp & kCounterMask) + kCounterInc;
u64 xch = (u64)(uptr)p | cnt;
p->next = (T*)(uptr)(cmp & kPtrMask);
if (atomic_compare_exchange_weak(&head_, &cmp, xch,
memory_order_release))
break;
}
}
T *Pop() {
u64 cmp = atomic_load(&head_, memory_order_acquire);
for (;;) {
T *cur = (T*)(uptr)(cmp & kPtrMask);
if (!cur)
return nullptr;
T *nxt = cur->next;
u64 cnt = (cmp & kCounterMask);
u64 xch = (u64)(uptr)nxt | cnt;
if (atomic_compare_exchange_weak(&head_, &cmp, xch,
memory_order_acquire))
return cur;
}
}
// private:
static const int kCounterBits = FIRST_32_SECOND_64(32, 17);
static const u64 kPtrMask = ((u64)-1) >> kCounterBits;
static const u64 kCounterMask = ~kPtrMask;
static const u64 kCounterInc = kPtrMask + 1;
atomic_uint64_t head_;
};
} // namespace __sanitizer
#endif // SANITIZER_LFSTACK_H
| true |
d2a6542719dae3841af27a93feda6cf82ceb6233 | C++ | ivan-magda/cppClassProjects | /SortUsingBinaryTree/SortUsingBinaryTree/main.cpp | UTF-8 | 3,006 | 3.875 | 4 | [] | no_license | #include <iostream>
#include <cmath>
#include <algorithm>
#include <ctime>
using namespace std;
template <class T> class BinaryTree {
private:
struct node {
node *left, *right;
T data;
node () : left(NULL), right(NULL) {}
node (T x) : left(NULL), right(NULL), data(x) {}
};
node *root;
size_t size = 0;
void p_add (node*& cur, T x);
bool p_find (node* cur, T x);
public:
void add (T x);
bool find (T x);
size_t getSize () { return size; }
void tree_to_array(node* tree, T a[]);
void sort_tree(T a[], int elem_total);
};
template <class T> void BinaryTree <T> :: p_add (node*& cur, T x) {
if (!cur) {
cur = new node (x);
return;
}
if (x < cur->data) {
if (!cur->left)
cur->left = new node (x);
else
p_add (cur->left, x);
}
else if (x > cur->data) {
if (!cur->right)
cur->right = new node (x);
else
p_add (cur->right, x);
}
}
template <class T> bool BinaryTree <T> :: p_find (node* cur, T x) {
if (!cur)
return false;
if (x < cur->data) {
if (!cur->left)
return false;
return p_find (cur->left, x);
}
else if (x > cur->data) {
if (!cur->right)
return false;
return p_find (cur->right, x);
}
return true;
}
template <class T> void BinaryTree <T> :: add (T x) {
size++;
p_add (root, x);
}
template <class T> bool BinaryTree <T> :: find (T x) {
return p_find (root, x);
}
template <class T> void BinaryTree <T> :: tree_to_array(node* tree, T a[]) {
static int max2 = 0; // счетчик элементов нового массива
if (tree == NULL) return; // условие окончания - нет сыновей
tree_to_array(tree->left, a); // обход левого поддерева
a[max2++] = tree->data;
tree_to_array(tree->right, a); // обход правого поддерева
}
template <class T> void BinaryTree <T> :: sort_tree(T a[], int elem_total) {
node *root = NULL;
for (int i = 0; i < elem_total; i++) { // проход массива и заполнение дерева
p_add(root, a[i]);
size++;
}
tree_to_array(root, a); // заполнение массива
}
int main () {
srand((unsigned int)time(0));
BinaryTree <int> myTree;
int a[14]={0,7,8,3,52,14,16,18,15,13,42,30,35,26};
myTree.sort_tree(a, 14);
cout << "Sorted array of int variables:\n";
for (int i = 0; i < 14; i++)
cout << a[i] << " ";
cout << endl;
BinaryTree<string> stringTree;
string arrayStrings[2] = {"world!", "hello"};
stringTree.sort_tree(arrayStrings, 2);
cout << "Sorted array of string instances:\n";
for (int i = 0; i < 2; i++)
cout << arrayStrings[i] << " ";
cout << endl;
return 0;
}
| true |
d31af3fb3ed89b0f12e9e15a1fa47d0072ec7197 | C++ | stepanmracek/face | /src/appAutoTrainer/src/settingsbase.h | UTF-8 | 4,013 | 2.765625 | 3 | [] | no_license | #pragma once
#include <string>
#include "faceCommon/helpers/cmdlineargsparser.h"
#include "faceCommon/settings/settings.h"
namespace Face {
namespace AutoTrainer {
class SettingsBase
{
public:
enum class AlignType { None, ICP, Landmark };
AlignType alignType;
int ICPiters;
float smoothCoef;
int smoothIters;
std::string alignTypeToString(AlignType alignType)
{
switch (alignType) {
case AlignType::ICP:
return "ICP";
case AlignType::Landmark:
return "Landmark";
default:
return "None";
}
}
SettingsBase() {}
virtual ~SettingsBase() {}
void printHelp()
{
std::cout << " --landmarks landmarks.yml" << std::endl;
std::cout << " --meanFaceForAlign model.obj" << std::endl;
std::cout << " --preAlignTemplate template.yml" << std::endl;
std::cout << " --ICPiters 100" << std::endl;
std::cout << " --smoothCoef 0.01" << std::endl;
std::cout << " --smoothIters 10" << std::endl;
}
void printSettings()
{
Face::Settings &s = Face::Settings::instance();
std::cout << " --align " << alignTypeToString(alignType) << std::endl;
if (alignType == AlignType::ICP)
{
std::cout << " --meanFaceForAlign " << s.settingsMap[s.MeanFaceModelPathKey].convert<std::string>() << std::endl;
std::cout << " --preAlignTemplate " << s.settingsMap[s.PreAlignTemplatePathKey].convert<std::string>() << std::endl;
std::cout << " --ICPiters " << ICPiters << std::endl;
}
else if (alignType == AlignType::Landmark)
{
std::cout << " --landmarks " << s.settingsMap[s.MeanFaceModelLandmarksPathKey].convert<std::string>() << std::endl;
}
std::cout << " --smoothCoef " << smoothCoef << std::endl;
std::cout << " --smoothIters " << smoothIters << std::endl;
}
protected:
bool parseAlignType(Face::Helpers::CmdLineArgsParser &cmdLineParser)
{
bool ok;
std::string alignTypeS = cmdLineParser.getParamValue("--align", ok); if (!ok) return false;
if (alignTypeS.compare("none") == 0)
alignType = AlignType::None;
else if (alignTypeS.compare("icp") == 0)
alignType = AlignType::ICP;
else if (alignTypeS.compare("landmark") == 0)
alignType = AlignType::Landmark;
else
{
return false;
}
return true;
}
void parseIcpSettings(Face::Helpers::CmdLineArgsParser &cmdLineParser)
{
Face::Settings &s = Face::Settings::instance();
bool ok;
std::string meanFaceForAlign = cmdLineParser.getParamValue("--meanFaceForAlign", ok);
if (ok) s.settingsMap[s.MeanFaceModelPathKey] = meanFaceForAlign;
std::string preAlignTemplate = cmdLineParser.getParamValue("--preAlignTemplate", ok);
if (ok) s.settingsMap[s.PreAlignTemplatePathKey] = preAlignTemplate;
ICPiters = cmdLineParser.getParamValueInt("--ICPiters", ok);
if (!ok) ICPiters = 100;
}
void parseLandmarkSettings(Face::Helpers::CmdLineArgsParser &cmdLineParser)
{
Face::Settings &s = Face::Settings::instance();
bool ok;
std::string landmarks = cmdLineParser.getParamValue("--landmarks", ok);
if (ok) s.settingsMap[s.MeanFaceModelLandmarksPathKey] = landmarks;
}
void parseSmoothSettings(Face::Helpers::CmdLineArgsParser &cmdLineParser)
{
bool ok;
smoothCoef = cmdLineParser.getParamValueFloat("--smoothCoef", ok);
if (!ok) smoothCoef = 0.01;
smoothIters = cmdLineParser.getParamValueInt("--smoothIters", ok);
if (!ok) smoothIters = 10;
}
void parseSettings(Face::Helpers::CmdLineArgsParser &cmdLineParser)
{
parseIcpSettings(cmdLineParser);
parseLandmarkSettings(cmdLineParser);
parseSmoothSettings(cmdLineParser);
}
};
}
}
| true |
b29f8754006458e134eec3959db0f2ccdbb55103 | C++ | m1h4/AudioAnalyzer | /Font.cpp | UTF-8 | 6,899 | 2.640625 | 3 | [
"MIT"
] | permissive | // Copyright 2004/2006 Marko Mihovilic
#include "Globals.h"
#include "Kernel.h"
#include "Font.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
Font::Font(void) :
mCreated(false)
{
ZeroMemory(&mHeader,sizeof(mHeader));
ZeroMemory(mElements,sizeof(mElements));
}
Font::~Font(void)
{
Destroy();
}
bool Font::Create(const unsigned char* data,unsigned long size)
{
ASSERT(!mCreated);
if(size < sizeof(mHeader))
{
TRACE(L"Font data size smaller than font header.\n");
return false;
}
CopyMemory(&mHeader,data,sizeof(mHeader));
data += sizeof(mHeader);
size -= sizeof(mHeader);
if(mHeader.magic != FontMagic)
{
TRACE(L"Font header magic mismatch.\n");
return false;
}
if(mHeader.version != FontVersion)
{
TRACE(L"Font header version mismatch.\n");
return false;
}
if(!mHeader.tsize)
{
TRACE(L"Font has no texture.\n");
return false;
}
ZeroMemory(mElements,sizeof(mElements));
if(size < sizeof(mElements[0]) * mHeader.chars)
{
TRACE(L"Font header char count mismatch.\n");
return false;
}
for(unsigned long i = 0; i < mHeader.chars; ++i)
{
CopyMemory(&mElements[i],data,sizeof(mElements[i]));
data += sizeof(mElements[i]);
size -= sizeof(mElements[i]);
}
if(size < mHeader.tsize)
{
TRACE(L"Font header texture size mismatch.\n");
return false;
}
if(!mTexture.Create(data,mHeader.tsize,NULL,NULL,NULL,Texture::UsageNone,Texture::FormatA8R8G8B8,Texture::PoolDefault))
return false;
mCreated = true;
return true;
}
bool Font::Create(const wchar_t* path)
{
ASSERT(!mCreated);
File file;
if(!file.Open(path,File::AccessModeRead,File::ShareModeRead,File::OpenModeExisting))
{
TRACE(L"Font file cannot be opened.\n");
return false;
}
unsigned long size = file.GetSize();
if(!size)
{
TRACE(L"Font file size mismatch.\n");
return false;
}
unsigned char* buffer = new unsigned char[size];
if(!buffer)
{
TRACE(L"Font file buffer failed to allocate %u bytes.\n",size);
return false;
}
ZeroMemory(buffer,size);
if(file.Read(buffer,size) != size)
{
delete[] buffer;
TRACE(L"Font read %u bytes mismatch.\n",size);
return false;
}
file.Close();
if(!Create(buffer,size))
{
delete[] buffer;
return false;
}
delete[] buffer;
return true;
}
bool Font::Create(const wchar_t* id,const wchar_t* group)
{
ASSERT(!mCreated);
HRSRC resource = FindResource(NULL,id,group);
if(!resource)
{
TRACE(L"Failed to find font resource.\n");
return false;
}
HGLOBAL global = LoadResource(NULL,resource);
if(!global)
{
TRACE(L"Failed to load font resource.\n");
return false;
}
LPBYTE data = (LPBYTE)LockResource(global);
if(!data)
{
TRACE(L"Failed to lock font resource.\n");
return false;
}
if(!Create(data,SizeofResource(NULL,resource)))
{
UnlockResource(global);
FreeResource(global);
return false;
}
UnlockResource(global);
FreeResource(global);
return true;
}
void Font::Destroy(void)
{
mCreated = false;
mTexture.Destroy();
ZeroMemory(&mHeader,sizeof(mHeader));
ZeroMemory(mElements,sizeof(mElements));
}
void Font::DrawColorText(const Point& point,const wchar_t* string,unsigned long length,const Color* colors) const
{
if(!length)
length = (unsigned int)wcslen(string);
long x = point.x;
long y = point.y + mHeader.ascent;
unsigned int colorIndex = 0;
unsigned int ch;
for(unsigned int i = 0; i < length; ++i)
{
ch = *(unsigned char*)&string[i];
if(ch < L'\n')
colorIndex = ch - 1;
else if(ch == L'\n')
{
x = point.x;
y += mHeader.height;
}
if(ch < 32)
continue;
ch -= 32;
DrawElement(Point(x,y),ch,colors[colorIndex]);
x += mElements[ch].advancex;
}
}
void Font::DrawText(const Point& point,const wchar_t* string,unsigned long length,const Color& color) const
{
if(!length)
length = (unsigned int)wcslen(string);
long x = point.x;
long y = point.y + mHeader.ascent;
unsigned int ch;
for(unsigned int i = 0; i < length; ++i)
{
ch = *(unsigned char*)&string[i];
if(ch == L'\n')
{
x = point.x;
y += mHeader.height;
}
if(ch < 32)
continue;
ch -= 32;
DrawElement(Point(x,y),ch,color);
x += mElements[ch].advancex;
}
}
void Font::DrawElement(const Point& point,unsigned long element,const Color& color) const
{
// Don't draw if fully transparent
if(color.a <= 0.0f)
return;
Rect rect(mElements[element].x - (long)mHeader.outmargl,mElements[element].y - (long)mHeader.outmargt,mElements[element].x + mElements[element].width + mHeader.outmargr,mElements[element].y + mElements[element].height + mHeader.outmargb);
D3DSURFACE_DESC desc;
mTexture.GetTexture()->GetLevelDesc(0,&desc);
Vector2 topleft,topright,bottomright,bottomleft;
topleft.x = bottomleft.x = (float)point.x - (float)mHeader.outmargl*mHeader.uscale + (float)mElements[element].left*mHeader.uscale;
topleft.y = topright.y = (float)point.y - (float)mHeader.outmargt*mHeader.uscale + (float)mElements[element].top*mHeader.uscale;
topright.x = bottomright.x = topleft.x + (rect.right - rect.left) * mHeader.uscale;
bottomleft.y = bottomright.y = topleft.y + (rect.bottom - rect.top) * mHeader.uscale;
GetKernel()->GetGraphics()->SpriteWrite(topleft,topright,bottomright,bottomleft,Vector2(rect.left / (float)desc.Width,rect.top / (float)desc.Height),Vector2(rect.right / (float)desc.Width,rect.bottom / (float)desc.Height),color,color,color,color,mTexture.GetTexture());
}
void Font::GetTextRect(const wchar_t* string,unsigned long length,Rect* rect) const
{
ASSERT(rect);
Size size;
GetTextSize(string,length,&size);
rect->right = rect->left + size.cx;
rect->bottom = rect->top + size.cy;
}
void Font::GetTextSize(const wchar_t* string,unsigned long length,Size* size) const
{
ASSERT(size);
if(!length)
length = (unsigned int)wcslen(string);
long x = 0;
long y = 0;
unsigned int ch;
size->cx = x;
size->cy = y;
for(unsigned int i = 0; i < length; ++i)
{
ch = *(unsigned char*)&string[i];
if(ch == L'\n')
{
x = 0;
y += mHeader.height;
}
if(ch < 32)
continue;
ch -= 32;
if(i == length-1)
x += mElements[ch].left + mElements[ch].width;
else
x += mElements[ch].advancex;
size->cx = max(size->cx,x);
}
size->cy = y + mHeader.height;
}
void Font::GetTextBlock(const wchar_t* string,unsigned long length,Point* block) const
{
ASSERT(block);
if(!length)
length = (unsigned int)wcslen(string);
block->x = 0;
block->y = 0;
unsigned int ch;
for(unsigned int i = 0; i < length; ++i)
{
ch = *(unsigned char*)&string[i];
if(ch == L'\n')
{
block->x = 0;
block->y += mHeader.height;
}
if(ch < 32)
continue;
ch -= 32;
if(i == length-1)
block->x += mElements[ch].left + mElements[ch].width;
else
block->x += mElements[ch].advancex;
}
}
bool Font::OnLostDevice(void)
{
mTexture.OnLostDevice();
return true;
}
bool Font::OnResetDevice(void)
{
mTexture.OnResetDevice();
return true;
} | true |
df0623cd00527913a2411c8a83e221ae405271be | C++ | Jimallan/CxlCap | /taksi-code-187/main/src/dll/HotKeys.h | UTF-8 | 1,797 | 2.515625 | 3 | [] | no_license | //
// HotKeys.h
//
#ifndef _INC_Input
#define _INC_Input
#if _MSC_VER > 1000
#pragma once
#endif
#ifdef USE_DIRECTI
struct CTaksiDI : public CDllFile
{
// Direct input keys.
// NOTE: Process/thread specific interface.
public:
CTaksiDI();
HRESULT SetupDirectInput();
void ProcessDirectInput();
void CloseDirectInput();
public:
bool m_bSetup;
private:
// key states (for DirectInput)
BYTE m_bScanExt[3]; // VK_SHIFT, VK_CONTROL, VK_MENU scan codes.
bool m_abHotKey[TAKSI_HOTKEY_QTY];
};
extern CTaksiDI g_UserDI;
#endif // USE_DIRECTI
struct CTaksiKeyboard
{
// keyboard hook
// (Use ONLY If the DI interface doesnt work)
// NOTE: Process and Thread-specific keyboard hook.
public:
CTaksiKeyboard()
: m_hHookKeys(NULL)
, m_bHotMask(0)
{
}
bool InstallHookKeys(bool bDummy);
void UninstallHookKeys(void);
protected:
static LRESULT CALLBACK DummyKeyboardProc(int code, WPARAM wParam, LPARAM lParam);
static LRESULT CALLBACK KeyboardProc(int code, WPARAM wParam, LPARAM lParam);
public:
// keyboard hook handle
HHOOK m_hHookKeys;
BYTE m_bHotMask; // the state of HOTKEYF_CONTROL and HOTKEYF_SHIFT
};
extern CTaksiKeyboard g_UserKeyboard;
struct CTaksiHotKeys
{
// Taksi DLL HotKey state information
// Changed by user pressing specific keys.
public:
CTaksiHotKeys()
: m_bAttachedHotKeys(false)
, m_dwHotKeyMask(0)
{
}
void ScheduleHotKey( TAKSI_HOTKEY_TYPE eHotKey )
{
// process the key when we get around to it.
m_dwHotKeyMask |= (1<<eHotKey);
}
HRESULT AttachHotKeysToApp(); // to current app/process.
void DetachHotKeys();
void DoHotKey( TAKSI_HOTKEY_TYPE eHotKey );
public:
bool m_bAttachedHotKeys; // hooked the keyboard or DI for this process.
DWORD m_dwHotKeyMask; // TAKSI_HOTKEY_TYPE mask
};
extern CTaksiHotKeys g_HotKeys;
#endif
| true |
ffc439a07961cc6604ea62d17d73232b5e5fa897 | C++ | rizwan3413/RizwanSampleRepo | /exercise1.cpp | UTF-8 | 790 | 3.25 | 3 | [] | no_license | #include<iostream>
using namespace std;
/*Static,Const Cast,Re-Interpret Casting,Dynamic Cassting*/
/*Static Cast- Mostly used for Implicit Conversion */
class GooglePlus
{
public:
string Name;
void print(string name) const
{
const_cast<GooglePlus*>(this)->Name = name;
cout<< " This is GooglePlus Sample..." << endl;
}
};
class Gmail:public GooglePlus
{
public:
void print1()
{
cout<< " This is Gmail Sample... " << endl;
}
};
int main()
{
/* Static Cast
GooglePlus *ptr = new GooglePlus;
ptr->print();
Gmail *p = new Gmail;
ptr = p;
ptr->print1();
// p = static_cast<Gmail*>(ptr);
p->print();
*/
GooglePlus *ptr = new GooglePlus;
ptr->print("Rizwan");
const Gmail g1;
Gmail g2;
g2 = *const_cast<Gmail*>(&g1)
return 0;
}
| true |
bf6dc5998fe96dbf9ea4d369a934d98ea20cb9c0 | C++ | shuyabin/x5mgc | /x5mgcBase/NetWork/NetBuffer/MemoryPool.h | UTF-8 | 2,096 | 3.21875 | 3 | [] | no_license | #ifndef MEMORY_POOL_H
#define MEMORY_POOL_H
#include <climits>
#include <cstddef>
template <typename T, size_t BlockSize = 4096>
class MemoryPool
{
public:
/* Member types */
typedef T value_type;
typedef T* pointer;
typedef T& reference;
typedef const T* const_pointer;
typedef const T& const_reference;
typedef size_t size_type;
typedef ptrdiff_t difference_type;
typedef std::false_type propagate_on_container_copy_assignment;
typedef std::true_type propagate_on_container_move_assignment;
typedef std::true_type propagate_on_container_swap;
template <typename U> struct rebind {
typedef MemoryPool<U> other;
};
/* Member functions */
MemoryPool() noexcept;
MemoryPool(const MemoryPool& memoryPool) noexcept;
MemoryPool(MemoryPool&& memoryPool) noexcept;
template <class U> MemoryPool(const MemoryPool<U>& memoryPool) noexcept;
~MemoryPool() noexcept;
MemoryPool& operator=(const MemoryPool& memoryPool) = delete;
MemoryPool& operator=(MemoryPool&& memoryPool) noexcept;
pointer address(reference x) const noexcept;
const_pointer address(const_reference x) const noexcept;
// Can only allocate one object at a time. n and hint are ignored
pointer allocate(size_type n = 1, const_pointer hint = 0);
void deallocate(pointer p, size_type n = 1);
size_type max_size() const noexcept;
template <class U, class... Args> void construct(U* p, Args&&... args);
template <class U> void destroy(U* p);
template <class... Args> pointer newElement(Args&&... args);
void deleteElement(pointer p);
private:
union Slot_ {
value_type element;
Slot_* next;
};
typedef char* data_pointer_;
typedef Slot_ slot_type_;
typedef Slot_* slot_pointer_;
slot_pointer_ currentBlock_;
slot_pointer_ currentSlot_;
slot_pointer_ lastSlot_;
slot_pointer_ freeSlots_;
size_type padPointer(data_pointer_ p, size_type align) const noexcept;
void allocateBlock();
static_assert(BlockSize >= 2 * sizeof(slot_type_), "BlockSize too small.");
};
#include "MemoryPool.cpp"
#endif // MEMORY_POOL_H | true |
e5d90655ed6452b0570f22aa3aedf17ff51d3ddb | C++ | asdlei99/ggj16 | /src/app/Globals.h | UTF-8 | 1,763 | 2.53125 | 3 | [
"MIT"
] | permissive | #pragma once
#include <vector>
#include <random>
#include "onut.h"
class Player;
class DanceMove;
class Entity;
typedef std::vector<Player*> PlayerVect;
typedef std::vector<DanceMove> DanceMoveVect;
typedef std::vector<onut::GamePad::eGamePad> DanceMoveButtonVect;
typedef std::vector<Entity*> EntityVect;
// Randomizes the content of the vector passed in
template<typename T>
static void RandomizeVector(std::vector<T>& inOut_vectorToRandomize)
{
std::random_device rd;
std::mt19937 g(rd());
std::shuffle(inOut_vectorToRandomize.begin(), inOut_vectorToRandomize.end(), g);
}
template<typename T>
static T CubicBezier(const std::vector<T>& in_controlPoints, float in_t)
{
// paranthesis added for clarity
const float t = 1.f - in_t;
return ((t)(t)(t)* in_controlPoints[0]) +
(3 ((t)(t)) in_t in_controlPoints[1]) +
(3 (t)(in_t in_t) in_controlPoints[2]) +
((in_t*in_t*in_t) * in_controlPoints[3]);
}
#define SPRITE_SCALE (1.f / 16.f)
#define NIGHT_DURATION 42.f
#define DAWN_DURATION 5.f
#define DAY_DURATION 10.f
#define DUSK_DURATION 5.f
#define DAY_TOTAL_DURATION (NIGHT_DURATION + DAWN_DURATION + DAY_DURATION + DUSK_DURATION)
#define DAWN_START (NIGHT_DURATION * .5f)
#define DAWN_END (NIGHT_DURATION * .5f + DAWN_DURATION)
#define DUSK_START (NIGHT_DURATION * .5f + DAWN_DURATION + DAY_DURATION)
#define DUSK_END (NIGHT_DURATION * .5f + DAWN_DURATION + DAY_DURATION + DUSK_DURATION)
#define MIDNIGHT 0.f
#define NOON (NIGHT_DURATION * .5f + DAWN_DURATION + DAY_DURATION * .5f)
#define MAX_MONSTER_COUNT 50
enum class DropType
{
INVALID,
Wood,
Rock,
};
extern bool g_activePlayer[4];
extern int g_daysSurvived;
| true |
f8c93e5b700c76f1fc44f86b9e71e327ac813529 | C++ | fabiolaborchi/Lavori_Cpp | /MasterMind.cpp | UTF-8 | 1,206 | 3.234375 | 3 | [] | no_license | #include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
/*
*MasterMind
*Author: Fabiola Borchi
*Date: 05/03/2021
*/
class MasterMind{
private:
int test[5];
int mappa[5];
void init(){
srand(time(NULL));
for(int i=0; i<5; i++){
mappa[i]=(rand()%10)+1;
for (int j=0; j<i; j++){
if (mappa[i]==mappa[j]){
i--;
break;
}
}
}
}
public:
MasterMind(){
init();
}
void stampa(){
for(int i=0; i<5; i++){
cout<<mappa[i]<<"\t";
}
cout<<endl;
}
void play(){
cout<<"inserisci 5 numeri interi"<<endl;
for(int i=0; i<5; i++){
cin>>test[i];
}
for(int i=0; i<5; i++){
cout<<test[i]<<"\t";
}
}
bool check(){
int strike=0, ball=0;
for(int i=0; i<5; i++){
for(int j=0; j<5; j++){
if(test[i]==mappa[j]){
if (i==j){
strike++;
}
else{
ball++;
}
}
}
}
cout<<endl;
cout<<"strike: "<<strike<<endl<<"ball: "<<ball<<endl;
return strike==5;
}
};
int main ()
{
MasterMind m;
m.stampa();
do{
m.play();
} while(!m.check());
return 0;
}
| true |
7014ce9bc4e060a53ca649bbb8ab5a7b612c485b | C++ | ganeshbhandarkar/leetcode | /shuffle-the-array/shuffle-the-array.cpp | UTF-8 | 340 | 2.796875 | 3 | [] | no_license | class Solution {
public:
vector<int> shuffle(vector<int>& nums, int n) {
//int x = nums.size();
vector<int> sol;
int i=0;
int j=n;
while(i<n && j<2*n){
sol.push_back(nums[i]);
sol.push_back(nums[j]);
i++;
j++;
}
return sol;
}
}; | true |