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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
8fb299b5a028899f3907c32a0f74106018f3f823 | C++ | elf11/client_server_application | /MessageArchive.cpp | UTF-8 | 3,640 | 2.765625 | 3 | [] | no_license | #include <arpa/inet.h>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <utility>
#include "MessageArchive.h"
#include "commons.h"
using namespace std;
bool MessageArchive::addMessage(const struct user_info &info, const char* message) {
FILE *f;
char buffer[256];
char port_str[50];
bool ret_val;
sprintf(port_str, "%d", info.port);
strcpy(buffer, "log_");
strcat(buffer, info.name);
strcat(buffer, "_");
strcat(buffer, inet_ntoa(info.address));
strcat(buffer, "_");
strcat(buffer, port_str);
f = fopen(buffer, "at");
if(msg[info].size() == 0 || msg[info].back().back().compare(".") == 0) {
msg[info].push_back(vector<string> ());
fprintf(f, "<mesaj %d>\n", msg[info].size());
#ifdef DEBUG
printf("\ndebug (archive): a whole other message is being received\n");
printf("debug> ");
fflush(stdout);
#endif
}
msg[info].back().push_back(string(message));
ret_val = (strcmp(message, ".") == 0);
#ifdef DEBUG
printf("\ndebug (archive): new message line added to the archive\n");
printf("debug (archive): info for the sender (from the list) ->\n");
printf("debug (archive): <- name=%s address=%s port=%d\n", info.name, inet_ntoa(info.address), info.port);
printf("debug (archive): the message received reads \"%s\"\n", message);
printf("debug> ");
fflush(stdout);
#endif
if(ret_val)
printf("\nA fost primit mesaj din partea utilizatorului %s...\n", info.name);
else
fprintf(f, "%s\n", message);
fclose(f);
return ret_val;
}
void MessageArchive::resetMessagesFrom(const struct user_info &info) {
msg.erase(info);
}
void MessageArchive::printAllAvailableMessages() {
map<struct user_info, vector < vector < string > >, less_info>::iterator iter;
for(iter = msg.begin(); iter != msg.end(); ++iter) {
int no = (*iter).second.size();
if(no == 1)
printf("%s: %d mesaj\n", (*iter).first.name, no);
else
printf("%s: %d mesaje\n", (*iter).first.name, no);
}
}
void MessageArchive::printAvailableMessagesFrom(const struct user_info &info) {
int no = msg[info].size();
if(no == 1)
printf("%s: %d mesaj\n", info.name, no);
else
printf("%s: %d mesaje\n", info.name, no);
}
void MessageArchive::printAvailableMessagesFrom(const char* name) {
map<struct user_info, vector < vector < string > >, less_info>::iterator iter;
for(iter = msg.begin(); iter != msg.end(); ++iter)
if(strcmp((*iter).first.name, name) == 0) {
int no = (*iter).second.size();
if(no == 1)
printf("%s: %d mesaj\n", (*iter).first.name, no);
else
printf("%s: %d mesaje\n", (*iter).first.name, no);
}
}
void MessageArchive::printMessageFromNo(const struct user_info &info, int number) {
int size;
vector < vector < string > > all_msgs = msg[info];
size = all_msgs.size();
if(number <= 0 || number > size) {
printf("Comanda invalida. Mesajele userului %s sunt numerotate de la 1 la %d\n", info.name, size);
return;
}
vector<string> text = all_msgs[number - 1];
size = text.size();
for(int i = 0; i < size - 1; i++)
printf("%s\n", text[i].c_str());
const char *str = text[size - 1].c_str();
if(strcmp(str, ".") != 0)
printf("%s\n", str);
}
| true |
915b9e2c6d5d4d82c97b352f4499b5205f048f4e | C++ | NicholasFan235/Codewars | /SymbolicDifferentiationOfPrefixEquations.cpp | UTF-8 | 12,119 | 3.546875 | 4 | [] | no_license | #include <bits/stdc++.h>
class term{
public:
std::string value;
term *t1 = nullptr, *t2 = nullptr;
public:
term(){
t1 = nullptr;
t2 = nullptr;
};
term(const term& t) = default;
term(std::string v){
value = v;
t1 = nullptr;
t2 = nullptr;
}
~term(){
//std::cout << "Deleting " << value << std::endl;
delete t1;
delete t2;
};
term* diff();
std::string toString();
void trim();
void deepCopy(const term &src);
};
term *operation;
std::vector<std::string> singleArgOperations = { "sin", "cos", "ln", "exp", "tan" };
bool isNum(const std::string &s){
return std::isdigit(s.front()) || std::isdigit(s.back());
}
void term::deepCopy(const term &src){
value = src.value;
delete t1; delete t2;
if (src.t1 != nullptr){
t1 = new term();
t1->deepCopy(*src.t1);
}
if (src.t2 != nullptr) {
t2 = new term();
t2->deepCopy(*src.t2);
}
}
term* MakeCopy(const term& src){
term* t = new term();
t->deepCopy(src);
return t;
}
std::string trimString(std::string s){
if (s.find('.') != s.npos){
while (s.back() == '0'){
s.pop_back();
}
if (s.back() == '.'){
s.pop_back();
}
}
return s;
}
void term::trim(){
//std::cout << toString() << std::endl;
if (t1 != nullptr) t1->trim();
if (t2 != nullptr) t2->trim();
if (value.compare("*")==0){
if (t1->value.compare("0") == 0 || t2->value.compare("0") == 0){
//std::cout << t1 << ", " << t2 << std::endl;
delete t1;
delete t2;
t1 = nullptr;
t2 = nullptr;
value = "0";
return;
}
if (isNum(t1->value) && isNum(t2->value)){
double a = std::stod(t1->value);
double b = std::stod(t2->value);
delete t1;
delete t2;
t1 = nullptr;
t2 = nullptr;
value = trimString(std::to_string(a*b));
return;
//std::cout << a << " * " << b << " = " << value << std::endl;
}
if (t2->value.compare("1") == 0){
value = t1->value;
delete t2;
t2 = nullptr;
t2 = t1->t2;
t1 = t1->t1;
return;
}
if (t1->value.compare("1") == 0){
value = t2->value;
delete t1;
t1 = nullptr;
t1 = t2->t1;
t2 = t2->t2;
return;
}
}
else if(value.compare("/") == 0){
if (t2->value.compare("1") == 0){
value = t1->value;
delete t2;
t2 = nullptr;
t2 = t1->t2;
t1 = t1->t1;
return;
}
if (t1->value.compare("0") == 0){
delete t1;
delete t2;
t1 = nullptr;
t2 = nullptr;
value = "0";
return;
}
if (isNum(t1->value) && isNum(t2->value)){
double a = std::stod(t1->value);
double b = std::stod(t2->value);
delete t1;
delete t2;
t1 = nullptr;
t2 = nullptr;
value = trimString(std::to_string(a/b));
return;
//std::cout << a << " / " << b << " = " << value << std::endl;
}
}
else if(value.compare("+") == 0){
if (t2->value.compare("0") == 0){
value = t1->value;
delete t2;
t2 = nullptr;
t2 = t1->t2;
t1 = t1->t1;
return;
}
if (t1->value.compare("0") == 0){
value = t2->value;
delete t1;
t1 = nullptr;
t1 = t2->t1;
t2 = t2->t2;
return;
}
if (isNum(t1->value) && isNum(t2->value)){
double a = std::stod(t1->value);
double b = std::stod(t2->value);
delete t1;
delete t2;
t1 = nullptr;
t2 = nullptr;
value = trimString(std::to_string(a+b));
return;
//std::cout << a << " + " << b << " = " << value << std::endl;
}
}
else if(value.compare("-") == 0){
if (t2->value.compare("0") == 0){
value = t1->value;
delete t2;
t2 = nullptr;
t2 = t1->t2;
t1 = t1->t1;
return;
}
if (isNum(t1->value) && isNum(t2->value)){
double a = std::stod(t1->value);
double b = std::stod(t2->value);
delete t1;
delete t2;
t1 = nullptr;
t2 = nullptr;
value = trimString(std::to_string(a-b));
return;
//std::cout << a << " - " << b << " = " << value << std::endl;
}
}
else if(value.compare("^") == 0){
if (isNum(t1->value) && isNum(t2->value)){
double a = std::stod(t1->value);
double b = std::stod(t2->value);
delete t1;
delete t2;
t1 = nullptr;
t2 = nullptr;
value = trimString(std::to_string(pow(a,b)));
return;
//std::cout << a << " ^ " << b << " = " << value << std::endl;
}
if (t2->value.compare("0") == 0){
//std::cout << t1 << ", " << t2 << std::endl;
delete t1;
delete t2;
t1 = nullptr;
t2 = nullptr;
value = "1";
return;
}
if (t1->value.compare("0") == 0){
//std::cout << t1 << ", " << t2 << std::endl;
delete t1;
delete t2;
t1 = nullptr;
t2 = nullptr;
value = "0";
return;
}
if (t2->value.compare("1") == 0){
value = t1->value;
delete t2;
t2 = nullptr;
t2 = t1->t2;
t1 = t1->t1;
return;
}
}
return;
}
std::string term::toString(){
std::string result;
if (t1 != nullptr){
result += "(" + value + " ";
result += t1->toString();
if (t2 != nullptr){
result += " " + t2->toString();
}
result += ")";
}
else{
result += value;
}
return result;
}
term* term::diff(){
if (value.compare("*") == 0){
term* result = new term("+");
result->t1 = new term("*");
result->t1->t1 = MakeCopy(*t1);
result->t1->t2 = MakeCopy(*t2->diff());
result->t2 = new term("*");
result->t2->t1 = MakeCopy(*t1->diff());
result->t2->t2 = MakeCopy(*t2);
return result;
}
else if (value.compare("/") == 0){
if (isdigit(t2->value[0])){
double b = std::stod(t2->value);
b = 1/b;
term* result = new term("*");
result->t1 = t1->diff();
result->t2 = new term(trimString(std::to_string(b)));
return result;
}
term* result = new term("/");
result->t1 = new term("-");
result->t1->t1 = new term("*");
result->t1->t2 = new term("*");
result->t1->t1->t1 = MakeCopy(*t1->diff());
result->t1->t1->t2 = MakeCopy(*t2);
result->t1->t2->t1 = MakeCopy(*t1);
result->t1->t2->t2 = MakeCopy(*t2->diff());
result->t2 = new term("^");
result->t2->t1 = MakeCopy(*t2);
result->t2->t2 = new term("2");
return result;
}
else if (value.compare("+") == 0){
term* result = new term("+");
result->t1 = MakeCopy(*t1->diff());
result->t2 = MakeCopy(*t2->diff());
return result;
}
else if (value.compare("-") == 0){
term* result = new term("-");
result->t1 = MakeCopy(*t1->diff());
result->t2 = MakeCopy(*t2->diff());
return result;
}
else if(value.compare("^") == 0){
double b = std::stod(t2->value);
term* result = new term("*");
result->t1 = new term(trimString(std::to_string(b)));
result->t2 = new term("*");
result->t2->t1 = new term("^");
result->t2->t1->t1 = MakeCopy(*t1);
result->t2->t1->t2 = new term(trimString(std::to_string(b-1)));
result->t2->t2 = MakeCopy(*t1->diff());
return result;
}
else if(value.compare("sin") == 0){
term* result = new term("*");
result->t1 = MakeCopy(*t1->diff());
result->t2 = new term("cos");
result->t2->t1 = MakeCopy(*t1);
return result;
}
else if(value.compare("cos") == 0){
term* result = new term("*");
result->t1 = new term("*");
result->t1->t1 = new term("-1");
result->t1->t2 = MakeCopy(*t1->diff());
result->t2 = new term("sin");
result->t2->t1 = MakeCopy(*t1);
return result;
}
else if(value.compare("tan") == 0){
term* result = new term("*");
result->t1 = MakeCopy(*t1->diff());
result->t2 = new term("^");
result->t2->t1 = new term("cos");
result->t2->t1->t1 = MakeCopy(*t1);
result->t2->t2 = new term("-2");
return result;
}
else if(value.compare("exp") == 0){
term* result = new term("*");
result->t1 = MakeCopy(*t1->diff());
result->t2 = new term("exp");
result->t2->t1 = MakeCopy(*t1);
return result;
}
else if (value.compare("ln") == 0){
term* result = new term("/");
result->t1 = MakeCopy(*t1->diff());
result->t2 = MakeCopy(*t1);
return result;
}
else if(value.compare("x") == 0){
return new term("1");
}
else{
//std::cout << value << std::endl;
return new term("0");
}
}
std::string getTerm(std::stringstream &ss){
std::string result;
std::string t;
int brackets = 0;
while (1){
ss >> t;
result += t + " ";
for (int i = 0; i < t.length(); i++){
if (t[i] != '(') break;
brackets++;
}
for (int i = t.length()-1; i >= 0; i--){
if (t.back() != ')') break;
t.pop_back();
brackets--;
}
while (brackets <= 0){
if (brackets == 0){
result.pop_back();
return result;
}
brackets++;
result.pop_back();
}
}
return result;
}
void makeOperation(term* currentTerm, const std::string s){
//std::cout << "\"" << s << "\"" << std::endl;
if (s[0] == '('){
std::stringstream ss;
ss.str(s);
std::string t;
ss >> t;
currentTerm -> value = t.substr(1);
currentTerm -> t1 = new term();
makeOperation(currentTerm->t1, getTerm(ss));
if (std::find(singleArgOperations.begin(), singleArgOperations.end(), currentTerm->value) == singleArgOperations.end()){
currentTerm -> t2 = new term();
makeOperation(currentTerm->t2, getTerm(ss));
}
}
else{
currentTerm -> value = s;
}
}
std::string diff(const std::string &s){
std::cout << s << "\t->\t";
operation = new term();
makeOperation(operation, s);
term *dO = operation->diff();
//std::cout << operation->toString();
//std::cout << "\t" << dO->toString() << std::endl;
dO->trim();
std::stringstream oss;
oss << dO->toString();
std::string result = oss.str();
std::cout << result << std::endl;
return result;
}
std::vector<std::string> queries = {
"5",
"x",
"(+ x x)",
"(- x x)",
"(* x 2)",
"(/ x 2)",
"(^ x 2)",
"(cos x)",
"(sin x)",
"(exp x)",
"(ln x)",
"(+ x (+ x x))",
"(- (+ x x) x)",
"(* 2 (+ x 2))",
"(/ 2 (+ 1 x))",
"(cos (+ x 1))",
"(sin (+ x 1))",
"(sin (* 2 x))",
"(exp (* 2 x))",
"(tan (* 2 x)",
"(cos (* 96 x))",
};
int main(){
for (const auto q : queries){
diff(q);
}
return 0;
} | true |
81df7c7e225932302bbf61a36f810c06d39a44cb | C++ | pasbi/Splines | /Tools/tangenttool.cpp | UTF-8 | 1,743 | 2.625 | 3 | [] | no_license | #include "tangenttool.h"
#include "Objects/spline.h"
#include <QDebug>
#include "Dialogs/pointeditdialog.h"
REGISTER_DEFN_TYPE(Tool, TangentTool);
Point* TangentTool::_currentPoint = 0;
TangentTool::TangentTool()
{
}
bool TangentTool::canPerform(const Object *o) const
{
if (!o->inherits(CLASSNAME(Spline))) return false;
if (((Spline*) o)->type() != Spline::Bezier) return false;
if (interaction().button() == Qt::LeftButton) return true;
if (interaction().type() == Interaction::Move) return true;
return false;
}
void TangentTool::reset()
{
if (_currentPoint) {
_currentPoint->selectTangent(Point::NoTangent);
}
_currentPoint = 0;
}
void TangentTool::perform_virtual(Object *o)
{
Spline* spline = (Spline*) o;
if (interaction().click() == Interaction::DoubleClick) {
Point* p = spline->pointAt(interaction(o).point());
if (!p) return;
PointEditDialog::exec_static(p, spline->type() == Spline::Bezier,
parentWidget());
return;
}
switch (interaction().type()) {
case Interaction::Press:
_currentPoint = spline->selectTangentAt(interaction(o).point());
if (!_currentPoint) return;
break;
case Interaction::Release:
reset();
break;
case Interaction::Move:
if (_currentPoint) {
_currentPoint->moveTangent(interaction(o).point(),
(interaction().modifiers() & Qt::SHIFT) ?
Point::Single : Point::Simultan
);
spline->emitChanged();
}
case Interaction::Invalid:
default:
break;
}
}
| true |
a0602450288b4a21846986649ece0ed39afcd783 | C++ | Ipiano/Maze-Runners | /Maze/Interfaces/mazepartitioner.h | UTF-8 | 1,106 | 3 | 3 | [] | no_license | #ifndef _MAZEPARTITIONER_H
#define _MAZEPARTITIONER_H
#include "../types.h"
#include "backend_types.h"
template<class PlayerDataType, class Tile>
class MazePartitioner
{
public:
virtual ~MazePartitioner(){}
/*
* Returns an array which contains a subsection of a maze
*
* width, height - Dimensions of section returned
* these are strictly [out] variables if reuse is a nullptr, else they are [in]
* to specify the size of the array pointed to by reuse
* player - Id of the player the section is for
* relative_loc - x, y location of target_loc in the returned section
* m - Maze container to get section of
* reuse - Pointer to already allocated array. If this is not nullptr, it must be at least
* as big as width*height. If this is nullptr, then function will allocate a new array of size width*height
*/
virtual Tile* getMazeSection(unsigned int& width, unsigned int& height,
PlayerDataType& playerData, point& relative_loc,
maze<Tile>& m) = 0;
};
#endif | true |
a77f2b457636dd6bc2997fe840f378f5a2584ed5 | C++ | aswingler1/TopTenList | /TopTenList.cpp | UTF-8 | 599 | 3.1875 | 3 | [] | no_license | //Manages a list of top ten hyperlinks
#include <string>
#include <iostream>
#include "TopTenList.h"
#include "Hyperlink.h"
#include "IDirectionable.h"
using namespace std;
TopTenList::TopTenList()
{
_list.resize(10);
}
void TopTenList::set_at(int index, Hyperlink link)
{
_list[index-1] = link;
}
Hyperlink TopTenList::get(int index)
{
return _list[index-1];
}
void TopTenList::display_forward()
{
for(int i = 0; i < _list.size(); i++)
{
cout<<_list[i].text<<endl;
}
}
void TopTenList::display_backward()
{
for(int i = _list.size(); i > 0; i--)
{
cout<<_list[i].text<<endl;
}
} | true |
8263f7af1f9599f6c4b1dd53dea799bcac41450d | C++ | iamarjun45/leetcode | /Dynamic Programming/Unique Paths II.cpp | UTF-8 | 839 | 2.625 | 3 | [] | no_license | class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
int rows=obstacleGrid.size();
if(rows==0)
return 0;
int cols=obstacleGrid[0].size();
long long dp[rows][cols];
memset(dp,0,sizeof(dp));
for(int i=rows-1;i>=0;i--){
if(obstacleGrid[i][cols-1])
break;
dp[i][cols-1]=1;
}
for(int j=cols-1;j>=0;j--){
if(obstacleGrid[rows-1][j])
break;
dp[rows-1][j]=1;
}
for(int i=rows-2;i>=0;i--){
for(int j=cols-2;j>=0;j--){
if(obstacleGrid[i][j])
continue;
dp[i][j]=dp[i+1][j]+dp[i][j+1];
}
}
return dp[0][0];
}
};
| true |
f8bb4d76b26aade0938f97ae6bc8e7e890c932e8 | C++ | manso-pedro/2021-1-exercicio-revisao-refatoracao | /Imovel.cpp | UTF-8 | 926 | 2.90625 | 3 | [] | no_license | #include "Imovel.hpp"
Imovel::Imovel(double area, int quartos, int banheiros, int vagas, double valorm2, Cliente *vendedor, string corretor){
this->area = area;
this->quartos = quartos;
this->banheiros = banheiros;
this->vagas = vagas;
this->valorm2 = valorm2;
this->vendedor = vendedor;
this->corretor = std::move(corretor);
this->valorTotal = valorm2 * area;
}
void Imovel::print(double porcentagem) const {
cout << "[Vendedor]" << endl;
vendedor->print();
cout << "[Corretor]" << endl;
cout << " " + corretor << endl
<< "Area: " << area << endl
<< " Quartos: " << quartos << endl
<< " Banheiros: " << banheiros << endl
<< " Vagas: " << vagas << endl
<< "Taxa de Comissão: " << porcentagem << "%" << endl
<< "valorVenda Comissão: R$ " << fixed << setprecision(2) << valorComissao << endl
<< "valorVenda de Venda: R$ " << fixed << setprecision(2) << valorVenda << endl;
}
| true |
1d9db7743853bef26377bad831080f1d284894f9 | C++ | RafaelFabris/Intepretador-E-Tradutor-MiniPascal | /BasicIntAST/teste.cpp | UTF-8 | 240 | 2.65625 | 3 | [] | no_license | #include<iostream>
#include<string>
using namespace std;
int main(){
int x[5-0];
int y;
x[1]=3;
if(x[1]>2){x[1]=4;
while(x[1]>3){
cout<<"curry"<<endl;
x[1]=x[1]-1;
cout<<x[1]<<endl;
}for(;x[1]<3;x[1]=x[1]+1){cout<<"OLA"<<endl;
}}return 0;}
| true |
2f2b7d125be0c8d6a7cc944f6c8ac5cd79f15bb6 | C++ | LauZyHou/Algorithm-To-Practice | /LintCode/101.cpp | UTF-8 | 598 | 3.171875 | 3 | [
"MIT"
] | permissive | class Solution {
public:
/**
* @param A: a list of integers
* @return : return an integer
*/
int removeDuplicates(vector<int> &v) {
const int lx = 2;//连续的个数
int len = v.size();
if(len<lx)
return 0;
int r = lx;//新插入的位置
//判断前面的有几个连续,连续的是谁
int cnt = 1;
int t = v[r-1];
for(int i=r-2;i>=0;i--){
if(v[i]!=t)
break;
cnt++;
}
for(int i=r;i<len;i++){
if(v[i]==t){
cnt++;
}else{
cnt = 1;
t = v[i];
}
if(cnt<=2)
v[r++] = v[i];
}
v.resize(r);
return r;
}
}; | true |
452a0653afc49b06f5350b1b3f9116bcffa43846 | C++ | Voley/Algorithmic-Problems | /Strings/IsPermutation/main.cpp | UTF-8 | 889 | 3.8125 | 4 | [
"MIT"
] | permissive |
// main.cpp
// IsUnique
#include <iostream>
#include <map>
#include <string>
bool isPermutation(const std::string& first, const std::string& second);
int main() {
std::cout << isPermutation("hello", "ehlol") << std::endl;
std::cout << isPermutation("First", "striF") << std::endl;
std::cout << isPermutation("123 ", "32 2") << std::endl;
std::cout << isPermutation("666 ", "555") << std::endl;
return 0;
}
bool isPermutation(const std::string& first, const std::string& second) {
if (first.length() != second.length()) {
return false;
}
char* array = new char[256];
for (const char& c: first) {
array[c] = ++array[c];
}
for (const char& c: second) {
if (array[c] <= 0) {
return false;
} else {
array[c] = --array[c];
}
}
return true;
}
| true |
a1c56fa96b52917003530e74d49c0df4497bd996 | C++ | radtek/PDV | /labs/2/benchmark.cpp | UTF-8 | 2,935 | 2.90625 | 3 | [
"MIT"
] | permissive | //
// Created by karel on 12.2.18.
//
#include <chrono>
#include <iostream>
#include <thread>
#include "PDVCrypt.h"
#include "decryption.h"
using namespace std;
using namespace std::chrono;
typedef vector<pair<string, enc_params>> messages_t;
int main(int argc, char **argv) {
// Inicializace pomoci nahodneho tajneho klice
// Tajny klic slouzi k porovnani jednotlivych paralizacnich metod
PDVCrypt crypt(" ABCDEFGHIJKLMNOPQRSTUVWXYZ");
crypt.generateSecret();
// Nastaveni parametru: pocet zprav, jejich delka a pouzita prvocisla
const unsigned long n_messages = argc > 1 ? atol(argv[1]) : 20000000;
const unsigned int message_length = 13;
const unsigned long long p1 = 11;
const unsigned long long p2 = 23;
// Generuje zasifrovane zpravy
messages_t encrypted;
for (unsigned long i = 0; i < n_messages; i++) {
string s(message_length, ' ');
for (unsigned int j = 0; j < message_length; j++) {
unsigned char rnd = rand() % 27;
s[j] = rnd ? rnd + 64 : ' ';
}
enc_params params(p1, p2, 0, rand() % 5);
encrypted.emplace_back(s, params);
}
// Spocita referencni reseni pomoci OpenMP
messages_t reference = encrypted;
decrypt_openmp(crypt, reference, std::thread::hardware_concurrency());
constexpr unsigned int n_methods = 6;
decrypt_t methods[] = {
decrypt_sequential,
decrypt_openmp,
decrypt_threads_1,
decrypt_threads_2,
decrypt_threads_3,
decrypt_threads_4
};
const char *method_names[] = {
"decrypt_sequential(...)",
"decrypt_openmp(...) ",
"decrypt_threads_1(...) ",
"decrypt_threads_2(...) ",
"decrypt_threads_3(...) ",
"decrypt_threads_4(...) "
};
// Porovna kazdou z Vami implementovanych metod
for (unsigned int i = 0; i < n_methods; i++) {
messages_t messages = encrypted;
try {
// Desifruje a zmeri, jak dlouho to trvalo
std::chrono::steady_clock::time_point begin = std::chrono::steady_clock::now();
(*methods[i])(crypt, messages, std::thread::hardware_concurrency());
std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();
// Zkontroluje korektnost reseni
unsigned long incorrect = 0;
#pragma omp parallel for
for (unsigned long j = 0; j < n_messages; j++) {
if (messages[j].first != reference[j].first) incorrect++;
}
printf("%s %7ldms (%ld/%ld decryptions incorrect)\n",
method_names[i], duration_cast<milliseconds>(end - begin).count(), incorrect, n_messages);
} catch (...) {
printf("%s ------ not implemented yet ------\n", method_names[i]);
}
}
return EXIT_SUCCESS;
}
| true |
5eee4d239ee1fb7e3df281cfc241eaa274e94215 | C++ | prakaashghimire/C_C- | /Programming/recursive.cpp | UTF-8 | 283 | 3.09375 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
int add(int,int);
int main(){
int a,b,c;
printf("enter any two no.");
scanf("%d%d",&a,&b);
c=add(a,b);
printf("sum=%d",c);
return 0;
}
int add(int x,int y)
{
if(x==0&&y==0){
return 0;
}else{
return x%10+y%10+add (x/10, y/10);
}
}
| true |
9c9544a2cd806bb0573d6ffa0c25028745f42b84 | C++ | Asganafer/Arduino | /INVIO_RICEV_INFRAROSSI/invio_infra/Infrarossi.ino | UTF-8 | 2,337 | 2.609375 | 3 | [] | no_license | #define I2 3
#define I1 2
#define A 13
#define B 12
#define C 11
#define D 10
#define time 500
void setup() {
Serial.begin(9600);
pinMode(A, INPUT);
digitalWrite(A, LOW);
pinMode(B, INPUT);
digitalWrite(B, LOW);
pinMode(C, INPUT);
digitalWrite(C, LOW);
pinMode(D, INPUT);
digitalWrite(D, LOW);
pinMode(I1,OUTPUT);
pinMode(I2,OUTPUT);
digitalWrite(I1, LOW);
digitalWrite(I2, LOW);
}
void loop() {
int av = digitalRead(A);
int bv = digitalRead(B);
int cv = digitalRead(C);
int dv = digitalRead(D);
Serial.print(av);
Serial.print(", ");
Serial.print(bv);
Serial.print(", ");
Serial.print(cv);
Serial.print(", ");
Serial.print(dv);
Serial.println("");
if(av == 1){
digitalWrite(I1, HIGH);
digitalWrite(I2, HIGH);
delay(time);
digitalWrite(I1, LOW);
digitalWrite(I2, LOW);
delay(time);
digitalWrite(I1, LOW);
digitalWrite(I2, LOW);
delay(time);
digitalWrite(I1, LOW);
digitalWrite(I2, LOW);
delay(time);
digitalWrite(I1, LOW);
digitalWrite(I2, LOW);
}
else if(bv == 1){
digitalWrite(I1, HIGH);
digitalWrite(I2, HIGH);
delay(time);
digitalWrite(I1, LOW);
digitalWrite(I2, LOW);
delay(time);
digitalWrite(I1, LOW);
digitalWrite(I2, LOW);
delay(time);
digitalWrite(I1, HIGH);
digitalWrite(I2, HIGH);
delay(time);
digitalWrite(I1, LOW);
digitalWrite(I2, LOW);
}
else if(cv == 1){
digitalWrite(I1, HIGH);
digitalWrite(I2, HIGH);
delay(time);
digitalWrite(I1, LOW);
digitalWrite(I2, LOW);
delay(time);
digitalWrite(I1, HIGH);
digitalWrite(I2, HIGH);
delay(time);
digitalWrite(I1, LOW);
digitalWrite(I2, LOW);
delay(time);
digitalWrite(I1, LOW);
digitalWrite(I2, LOW);
}
else if(dv == 1){
digitalWrite(I1, HIGH);
digitalWrite(I2, HIGH);
delay(time);
digitalWrite(I1, LOW);
digitalWrite(I2, LOW);
delay(time);
digitalWrite(I1, HIGH);
digitalWrite(I2, HIGH);
delay(time);
digitalWrite(I1, HIGH);
digitalWrite(I2, HIGH);
delay(time);
digitalWrite(I1, LOW);
digitalWrite(I2, LOW);
}
}
| true |
9dc437ac6496d30040fc56ed52d21e67c75bf313 | C++ | inouetmhr/FitbikeConnector | /arduino/cadence-counter.ino | UTF-8 | 991 | 2.9375 | 3 | [] | no_license | #include <avr/sleep.h>
int PIN = 3;
int rpm_max = 150;
int wait = 60 * 1000.0 / rpm_max ;
void setup()
{
Serial.begin(9600);
pinMode(PIN, INPUT_PULLUP); // default High
//Serial.print(wait);
set_sleep_mode(SLEEP_MODE_PWR_DOWN); //スリープモードの設定
//attachInterrupt(1, wakeUpNow, FALLING); // use interrupt 1 (pin 3) and run function
//attachInterrupt(1, wakeUpNow, LOW); // use interrupt 1 (pin 3) and run function
}
void loop()
{
//Serial.print("loop\n");
//https://playground.arduino.cc/Learning/ArduinoSleepCode/
attachInterrupt(1, wakeUpNow, FALLING); // use interrupt 1 (pin 3) and run function
sleep_mode(); // here the device is actually put to sleep!!
// THE PROGRAM CONTINUES FROM HERE AFTER WAKING UP
//sleep_disable(); // first thing after waking from sleep:
detachInterrupt(1);
Serial.print(1);
Serial.print("\n");
delay(wait);
}
void wakeUpNow(){
// awake only. do nothing.
// back to main loop()
}
| true |
18c151e28e7d6b6d3a89ab2d22002dbf6115eb8a | C++ | Lugswo/PokeMMO | /PokeMMO/Camera.cpp | UTF-8 | 1,141 | 2.515625 | 3 | [] | no_license | #include "Camera.h"
#include <gtc/matrix_transform.hpp>
#include "GameObjectFactory.h"
#include "Transform.h"
#include "Editor.h"
#include "InputManager.h"
Camera* Camera::instance;
void Camera::Init()
{
position = glm::vec3(0.f, 0, 3);
jumbo = glm::vec3(0.f, 0, -2);
}
Camera* Camera::GetInstance()
{
if (!instance)
{
instance = new Camera();
}
return instance;
}
void Camera::Update(float dt)
{
if (!Editor::GetInstance())
{
auto player = GameObjectFactory::GetInstance()->GetPlayer();
if (player)
{
position = GetComponent(Transform, player)->GetPosition();
position.z = 3;
}
}
else
{
if (InputManager::GetInstance()->KeyDown(GLFW_KEY_W))
{
position.y += .05f;
}
if (InputManager::GetInstance()->KeyDown(GLFW_KEY_A))
{
position.x -= .05f;
}
if (InputManager::GetInstance()->KeyDown(GLFW_KEY_S))
{
position.y -= .05f;
}
if (InputManager::GetInstance()->KeyDown(GLFW_KEY_D))
{
position.x += .05f;
}
}
view = glm::lookAt(position, position + jumbo, glm::vec3(0, 1, 0));
}
void Camera::Shutdown()
{
}
| true |
97e53d01ff317346fa9a0a4432ca4495e183b119 | C++ | RAHULSHARMA63/Basic-salary | /Basic salary.cpp | UTF-8 | 586 | 3.171875 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main()
{
float s,b,n=0;
cout<<"enter your salary";
cin>>s;
if(s>=15000)
{
b=(s*10)/100;
n=s+b;
cout<<"your salary is:"<<s;
cout<<"\nyour bonus is:"<<b;
cout<<"\nyour net salary is:"<<n;
}
if(s>=10000&&s<15000)
{
b=(s*b)/100;
n=s+b;
cout<<"your salary is:"<<s;
cout<<"\nyour bonus is:"<<b;
cout<<"\nyour net salary is:"<<n;
}
if(s<10000)
{
b=(s*0)/100;
n=s+b;
cout<<"your salary is:"<<s;
cout<<"\nyour bonus is:"<<b;
cout<<"\nyour net salary is:"<<n;
}
return 0;
}
| true |
c49b758a722badd1dd1192825c065a8926276a10 | C++ | kanhaiyatripathi/cplusplusKP2 | /Mathematics/multiplicative_inverse.cpp | UTF-8 | 351 | 3.6875 | 4 | [] | no_license | #include<iostream>
using namespace std;
int modInverse(int a, int m)
{
a = a%m;
for (int x=1; x<m; x++)
if ((a*x) % m == 1)
return x;
}
int main()
{
int a,m;
cout<<"Enter the value of a : ";
cin>>a;
cout<<"Enter the value of m : ";
cin>>m;
cout << modInverse(a, m)<<endl;
return 0;
} | true |
b804881d86f89ba44ccc864410d10ac6db8fd32d | C++ | Ankit152/my_codes | /codes/c++_codes/self_practice/linked_lists/queue_ll.cpp | UTF-8 | 1,587 | 3.859375 | 4 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
class node{
public:
int data;
node *next;
node(int data){
this->data=data;
next=NULL;
}
};
void insert_end(node *&head,int data){
if(head==NULL){
head=new node(data);
return;
}
node *temp=head;
while(temp->next!=NULL){
temp=temp->next;
}
temp->next=new node(data);
return;
}
void del_beg(node *&head){
if(head==NULL){
cout<<"\nUNDERFLOW!!!\n";
return;
}
node *t=head;
head=head->next;
delete(t);
return;
}
void display(node *head){
if(head==NULL){
cout<<"\nEMPTY!!!\n";
return;
}
cout<<"\nQueue elements: ";
while(head!=NULL){
cout<<head->data<<"->";
}
cout<<"NULL\n";
return;
}
int main(){
int ch,data;
node *head=NULL;
do{
cout<<"1. Insert element\n";
cout<<"2. Delete element\n";
cout<<"3. Display element\n";
cout<<"0. Exit\n";
cout<<"Enter the choice: ";
cin>>ch;
if(ch==0){
exit(0);
}
switch(ch){
case 1:
cout<<"\nEnter the element: ";
cin>>data;
insert_end(head,data);
break;
case 2:
del_beg(head);
break;
case 3:
display(head);
break;
default:
cout<<"\nWrong choice!!!\n";
break;
}
}while(ch!=0);
return 0;
}
| true |
4bf1f090cf6799e019220fc198e4f62ff731628c | C++ | Trietptm-on-Coding-Algorithms/leetcode-4 | /src/Implement strStr()/Implement strStr().cpp | UTF-8 | 555 | 3.171875 | 3 | [] | no_license | class Solution {
public:
int strStr(char *haystack, char *needle) {
if(!needle || !haystack ) return -1;
char *p1 = haystack;
while(1)
{
char *now = p1, *p2 = needle;
while(1)
{
// reach the end of needle, has substring, return index
if(!(*p2)) return (int)(p1-haystack);
// if it reach the end of haystack but not end of the needle
// then there's no substring, return -1
if(!(*now)) return -1;
if(*now++ != *p2++) break;
}
p1++; //next index of haystack
}
return -1;
}
};
| true |
b80f6492255c3578f6d110f1a96d080e28a6386d | C++ | grork/MixpanelClient | /MixpanelCppCX/PayloadEncoder.cpp | UTF-8 | 2,323 | 2.90625 | 3 | [
"MIT"
] | permissive | #include "pch.h"
#include "payloadencoder.h"
using namespace Platform;
using namespace Windows::Security::Cryptography;
using namespace Windows::Data::Json;
using namespace Windows::Foundation;
using namespace Windows::Globalization::DateTimeFormatting;
using namespace Codevoid::Utilities::Mixpanel;
String^ Codevoid::Utilities::Mixpanel::EncodeJson(IJsonValue^ payload)
{
auto payloadAsString = payload->Stringify();
auto payloadAsBuffer = CryptographicBuffer::ConvertStringToBinary(payloadAsString, BinaryStringEncoding::Utf8);
auto encodedPayload = CryptographicBuffer::EncodeToBase64String(payloadAsBuffer);
return encodedPayload;
}
String^ Codevoid::Utilities::Mixpanel::DateTimeToMixpanelDateFormat(const DateTime time)
{
// Format from mixpanel:
// YYYY-MM-DDThh:mm:ss
//
// YYYY = four-digit year
// MM = two-digit month (01=January, etc.)
// DD = two-digit day of month (01 through 31)
// T = a literal 'T' character
// hh = two digits of hour (00 through 23)
// mm = two digits of minute (00 through 59)
// ss = two digits of second (00 through 59)
//-{month.full}-{day.integer(2)}T:{longtime}
static DateTimeFormatter^ formater = ref new DateTimeFormatter(L"{year.full}-{month.integer(2)}-{day.integer(2)}T{hour.integer(2)}:{minute.integer(2)}:{second.integer(2)}");
String^ result = nullptr;
try
{
// Based on a report from a wonderful customer, it appears that there
// are certain situations where this call -- when supplied with the
// Etc/UTC timezone will cause the platform to throw a 'Catastrophic
// Error' COMException. It's unclear why -- the customer reported it
// on Windows 10, 1803 when in the Australian region/timezone. While
// unable to repro locally on any of my devices, it was confirmed that
// using the 'no timezone adjustment' version of the API results in a
// successful stringification. So, lets try the 'right way' (Since
// Mixpanel says to supply this information in UTC), and if it fails,
// accept that the time could be off by ~12 hours in either direction
result = formater->Format(time, L"Etc/UTC");
}
catch (COMException^ e) {
result = formater->Format(time);
}
return result;
} | true |
9bb5d1e8384937bb923791056901aff48bcf80a3 | C++ | Pimed23/Practica | /Practica 2/1_AdditionalMaterial/1_4_GlobalScope/1_4_1_GlobalVariable.cpp | UTF-8 | 156 | 2.609375 | 3 | [] | no_license | #include <iostream>
using namespace std;
int A = 15;
void sumar() {
cout << A + 1 << endl;
}
int main() {
cout << A << endl;
sumar();
} | true |
32773249c6ff78585709fdd0ad9bf9a97c827c8f | C++ | NPgreatest/Lost-In-World-War-II | /Lost In World War II beta version 1.2.0/Lib/Sql.h | UTF-8 | 1,559 | 3.03125 | 3 | [] | no_license | #ifndef SQL_H
#define SQL_H
#include "All.h"
#include <QRect>
#include<QImage>
#include <QList>
class Sql
{
private:
Player_Sql P1,P2;
//QList<Player> Player_List;
QList<Object_Sql> Object_List;
QList<Object_Sql> Partical_List;
QList<Enemy_Sql> Enemy_List;
public:
Sql();
~Sql(){Object_List.~QList();Enemy_List.~QList();Partical_List.~QList();}
void AddObject(Object_Sql object);
void AddPartical(Object_Sql Partical);
void AddEnemy(Enemy_Sql enemy);
/*void PoPObject(Object_Sql object);
void PoPObject(int x){Object_List.removeAt(x);}
void AddPartical(Object_Sql Partical);
void PoPPartical(Object_Sql Partical);
void AddEnemy(Enemy_Sql enemy);
void PopEnemy(Enemy_Sql enemy);*/
Object_Sql GetObject(int x){return Object_List.at(x);}
Enemy_Sql GetEnemey(int x){return Enemy_List.at(x);}
Object_Sql GetPartical(int x){return Object_List.at(x);}
int GetObject_Num() const {return Object_List.count();}
int GetEnemy_Num() const {return Enemy_List.count();}
int GetPartical_Num() const {return Partical_List.count();}
void ObjectClear(){Object_List.clear();}
void PartivalClear(){Partical_List.clear();}
void EnemyClear(){Enemy_List.clear();}
//bool GetIsObject(Object_Sql& object){return Object_List.contains(object);}
//bool GetIsEnemy(Enemy_Sql Enemy){return Enemy_List.contains(Enemy);}
//bool GetIsPartical(Object_Sql Partical){return Object_List.contains(Partical);}
};
#endif // SQL_H
| true |
ee535214be19aca310ad98e92dc224a8102cad15 | C++ | Murilo-ZC/FATEC-MECATRONICA-MURILO | /Microcontroladores-2020-2/Pratica11/prog03.ino | UTF-8 | 3,047 | 2.578125 | 3 | [] | no_license | /*
Programa para trabalhar com a comunicação serial
*/
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
const int LED_LIGADO = LOW;
const int LED_DESLIGADO = HIGH;
const int ENTRADA_ACIONADA = LOW;
const int ENTRADA_DESACIONADA = HIGH;
const int LED1 = D5;
const int LED2 = D6;
const int LED3 = D7;
const int ENTRADA_01 = D1;
const int ENTRADA_02 = D2;
const int T_ON[] = {0,25,50,75,99,122,144,164,183,200,216,229,240,248,254,258,259,258,255,248,240,229,216,201,184,165,144,122,99,75,51,25};
const int T_total = 260;
//Variáveis globais
char msg[30];
//Variável utilizada com o millis()
unsigned long tempoAnterior;
unsigned long tempoAnteriorCiclo;
//Indica que a variável será utilizada dentro de uma interrupção
volatile int posicao = 0;
//Variável utilizada para realizar debounce no botão
volatile unsigned long tempoBotao;
//Variáveis para comunicação Wifi
const char* URL_SERVIDOR = "http://viacep.com.br/ws/01001000/json/";
//Cliente para realizar a requisição
WiFiClient client;
HTTPClient http;
//Funções de interrupção - ISR
void ICACHE_RAM_ATTR conta_pulsos(){
if(micros()-tempoBotao >= 100){
posicao = 0;
tempoBotao = micros();
}
}
void inicializa_hardware(){
pinMode(LED1, OUTPUT);
pinMode(LED2, OUTPUT);
pinMode(LED3, OUTPUT);
digitalWrite(LED1, LED_DESLIGADO);
digitalWrite(LED2, LED_DESLIGADO);
digitalWrite(LED3, LED_DESLIGADO);
pinMode(ENTRADA_01, INPUT_PULLUP);
pinMode(ENTRADA_02, INPUT_PULLUP);
//Configura a interrupção externa
attachInterrupt(digitalPinToInterrupt(ENTRADA_01), conta_pulsos,RISING);
//Inicializar a comunicação
Serial.begin(115200); //9600, 19200, 38400, 115200
//Inicializa a comunicação Wifi
inicializar_wifi();
}
void inicializar_wifi(){
//Conecta com o nome e a senha da rede
//LEMBRAR DE APAGAR ESSA INFORMAÇÃO AO SUBIR NO GITHUB!!
WiFi.begin("SEU_REDE", "SUA_SENHA");
//Aguarda a comunicação estar pronta
Serial.print("Conectando");
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
Serial.println();
Serial.print("Conectado,Dados da Conexão (IP): ");
Serial.println(WiFi.localIP());
}
void realiza_requisicao_wifi(){
//Verifica se a conexão foi realizada
if(http.begin(client, URL_SERVIDOR)){
Serial.print("Conectado!\n");
//Pede os dados utilizando o método GET do HTTP
int httpCode = http.GET();
//Verifica se o código é valido
if(httpCode > 0){
Serial.print("Codigo HTTP:");
Serial.println(httpCode);
//Verifica se o código foi de requisicao realizad com sucesso e trata essas informações
if(httpCode == HTTP_CODE_OK){
//Pega os dados
String payload = http.getString();
Serial.println(payload);
}
} else {
Serial.print("Algo deu errado!\n");
}
} else {
Serial.print("Nao foi possivel conectar!\n");
}
}
void setup() {
inicializa_hardware();
}
void loop() {
realiza_requisicao_wifi();
delay(2000);
while(1) delay(50);
}
| true |
a5379a2ca79db8847733cfeea23f02f5358490b3 | C++ | NENCAO/TANK | /NewTank/EnmeyTank.cpp | GB18030 | 5,792 | 2.90625 | 3 | [] | no_license | #include "stdafx.h"
#include "EnmeyTank.h"
#include "Bullet.h"
#define MAX_STEP 12 //ת䲽
CEnmeyTank::CEnmeyTank()
{
int x = (rand() % (CGraphic::GetBattleGround().GetWidth() - 50)) + 50;
if (x % 25 > 13)
{
x = x + 25 - x % 25;
}
else
{
x = x - x % 25;
}
m_Pos.SetX(x);
m_Pos.SetY(20);
m_step = rand() % 2 + 1;
m_color = 1 == m_step? WHITE : LIGHTGREEN;
m_dir = Dir::DOWN;
this->CalculateSphere();
m_StepCount = 0;
m_bDisapper = false;
m_bCanMove = true;
m_ShootCount = 0;
}
CEnmeyTank::~CEnmeyTank()
{
}
/*̹ƶķ*/
void CEnmeyTank::SetDir(Dir dir)
{
m_dir = dir;
}
/*̹˵ʾ*/
void CEnmeyTank::Display()
{
COLORREF fill_color_save = getfillcolor();
COLORREF color_save = getfillcolor();
setfillcolor(m_color);
switch (m_dir)
{
case UP:
DrawTankBody(); //ʾĴ
line(m_Pos.GetX(), m_Pos.GetY(), m_Pos.GetX(), m_Pos.GetY() - 15); //ʾڹ
break;
case DOWN:
DrawTankBody();
line(m_Pos.GetX(), m_Pos.GetY(), m_Pos.GetX(), m_Pos.GetY() + 15);
break;
case LEFT:
DrawTankBody();
line(m_Pos.GetX(), m_Pos.GetY(), m_Pos.GetX() - 15, m_Pos.GetY());
break;
case RIGHT:
DrawTankBody();
line(m_Pos.GetX(), m_Pos.GetY(), m_Pos.GetX() + 15, m_Pos.GetY());
break;
default:
break;
}
setfillcolor(color_save);
setfillcolor(fill_color_save);
}
void CEnmeyTank::MoveUp()
{
SetDir(Dir::UP);
if (m_Pos.GetY() - m_step - 12 < BATTEL_GROUND_Y1)
{
return;
}
m_Pos.SetY(m_Pos.GetY() - m_step);
CalculateSphere();
}
void CEnmeyTank::MoveDown()
{
SetDir(Dir::DOWN);
if (m_Pos.GetY() + m_step + 12 > BATTEL_GROUND_Y2)
{
return;
}
m_Pos.SetY(m_Pos.GetY() + m_step);
CalculateSphere();
}
void CEnmeyTank::MoveLeft()
{
SetDir(Dir::LEFT);
if (m_Pos.GetX() - m_step - 12 < BATTEL_GROUND_X1)
{
return;
}
m_Pos.SetX(m_Pos.GetX() - m_step);
CalculateSphere();
}
void CEnmeyTank::MoveRight()
{
SetDir(Dir::RIGHT);
if (m_Pos.GetX() + m_step + 12 > BATTEL_GROUND_X2)
{
return;
}
m_Pos.SetX(m_Pos.GetX() + m_step);
CalculateSphere();
}
void CEnmeyTank::Move()
{
//if (!Canmove())
//{
// switch (m_dir)
// {
// case UP:
// m_dir = DOWN;
// break;
// case DOWN:
// m_dir = UP;
// break;
// case LEFT:
// m_dir = RIGHT;
// break;
// case RIGHT:
// m_dir = LEFT;
// break;
// default:
// break;
// }
// SetCanmove(true);
//}
switch (m_dir)
{
case UP:
if (!Canmove())
{
SetCanmove(true);
MoveDown();
SetDir(DOWN);
break;
}
MoveUp();
break;
case DOWN:
if (!Canmove())
{
SetCanmove(true);
MoveUp();
SetDir(UP);
break;
}
MoveDown();
break;
case LEFT:
if (!Canmove())
{
SetCanmove(true);
MoveRight();
SetDir(RIGHT);
break;
}
MoveLeft();
break;
case RIGHT:
if (!Canmove())
{
SetCanmove(true);
MoveLeft();
SetDir(LEFT);
break;
}
MoveRight();
break;
default:
break;
}
m_StepCount++;
if (rand() % 10 == 0) //Զӵ
{
m_AutoShoot = true;
}
if (//MAX_STEP <= m_StepCount
rand() % 20 == 0
)//ת
{
m_StepCount = 0;
this->RandomDir();
}
}
void CEnmeyTank::Shoot(std::list<CMyObject*>& LstBullets)
{
//if (LstBullets.size() > 16)
//{
// return;
//}
CBullet* pBullet = new CBullet(m_Pos, m_dir, m_color);
LstBullets.push_back(pBullet);
m_AutoShoot = false;
}
/*̹˵ ԴĴ*/
void CEnmeyTank::CalculateSphere()
{
switch (m_dir)
{
case UP:
case DOWN:
m_RectSphere.Set(m_Pos.GetX() - 12, m_Pos.GetY() - 12,
m_Pos.GetX() + 12, m_Pos.GetX() + 12);
case LEFT:
case RIGHT:
m_RectSphere.Set(m_Pos.GetX() - 12, m_Pos.GetY() - 12,
m_Pos.GetX() + 12, m_Pos.GetY() + 12);
break;
default:
break;
}
}
/*ת*/
void CEnmeyTank::RandomDir()
{
Dir dir = (Dir)(Dir::UP + rand() % 4);
SetDir(dir);
}
void CEnmeyTank::DrawTankBody()
{
/*̹*/
fillrectangle(m_Pos.GetX() - 6, m_Pos.GetY() - 6, m_Pos.GetX() + 6, m_Pos.GetY() + 6);
/*Ĵ*/
switch (m_dir)
{
case UP:
case DOWN:
fillrectangle(m_RectSphere.GetStartPoint().GetX(), m_RectSphere.GetStartPoint().GetY(),
m_RectSphere.GetStartPoint().GetX() + 4, m_RectSphere.GetEndPoint().GetY());
fillrectangle(m_RectSphere.GetEndPoint().GetX() - 4, m_RectSphere.GetStartPoint().GetY(),
m_RectSphere.GetEndPoint().GetX(), m_RectSphere.GetEndPoint().GetY());
break;
case LEFT:
case RIGHT:
fillrectangle(m_RectSphere.GetStartPoint().GetX(), m_RectSphere.GetStartPoint().GetY(),
m_RectSphere.GetEndPoint().GetX(), m_RectSphere.GetStartPoint().GetY() + 4);
fillrectangle(m_RectSphere.GetStartPoint().GetX(), m_RectSphere.GetEndPoint().GetY() - 4,
m_RectSphere.GetEndPoint().GetX(), m_RectSphere.GetEndPoint().GetY());
break;
default:
break;
}
} | true |
23796d601a45ce42b9f1bcd931fb5dcc57173c3c | C++ | jiadaizhao/LeetCode | /1101-1200/1189-Maximum Number of Balloons/1189-Maximum Number of Balloons.cpp | UTF-8 | 361 | 2.734375 | 3 | [
"MIT"
] | permissive | class Solution {
public:
int maxNumberOfBalloons(string text) {
vector<int> table(26);
for (char c : text) {
++table[c - 'a'];
}
table['l' - 'a'] /= 2;
table['o' - 'a'] /= 2;
return min({table['b' - 'a'], table['a' - 'a'], table['l' - 'a'], table['o' - 'a'], table['n' - 'a']});
}
};
| true |
031c586011e3780a3b40d4407019191a740656b1 | C++ | aburifat/ProblemSolving | /Solve-By-Topic/Algebra/Number Theoretic Functions/Euler's Totient Function/Farey Sequence-UVA-12995.cpp | UTF-8 | 725 | 2.75 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll MX=1000000;
vector<ll>phi;
vector<ll>sumPhi;
void phiAll(ll n)
{
phi.resize(n+1);
phi[0]=0;
phi[1]=1;
for(ll i=2; i<=n; i++)
phi[i]=i;
for(ll i=2; i<=n; i++){
if(phi[i]==i){
for(ll j=i; j<=n; j+=i){
phi[j]-=(phi[j]/i);
}
}
}
}
void sum(ll n)
{
sumPhi.resize(n+1);
sumPhi[0]=0;
for(ll i=1;i<=n; i++){
sumPhi[i]=sumPhi[i-1]+phi[i];
}
}
int main()
{
phiAll(MX);
sum(MX);
ll n;
while(cin>>n){
if(n==0)break;
cout<<(sumPhi[n]-1)<<endl;
}
return 0;
}
| true |
bcff37a5a8b0a97e5eb4571e1f444363936c2eff | C++ | AlekseiMaide/HackerRankCPP | /algorithms/sorting/quicksort_1_partition.cpp | UTF-8 | 715 | 3.265625 | 3 | [] | no_license | //
// Quicksort 1 Partition.
//
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int n{};
int p{};
int x{};
cin >> n >> p;
vector<int> left{};
vector<int> right{};
vector<int> equal{};
equal.push_back(p);
while (cin >> x) {
if (x > p) {
right.push_back(x);
} else if (x < p) {
left.push_back(x);
} else {
equal.push_back(x);
}
}
for (auto z : left) {
cout << z << " ";
}
for (auto z : equal) {
cout << z << " ";
}
for (auto z : right) {
cout << z << " ";
}
return 0;
} | true |
af2df182f4164ba5338bb4d92424b3469a177d9a | C++ | TimTargaryen/GoldenMiner | /re Golden Miner/gold.h | GB18030 | 1,045 | 2.96875 | 3 | [] | no_license |
#include"object.h"
class gold: public object
{
public:
int gender;//
bool being;//Ƿץ
gold() {
switch (rand() % 6) {
case 0:
display = all + 3; length = 60; width = 60; gender = 0;
backup = all + 32; break;//ɴ
case 1:
display = all + 8; length = 40; width = 40; gender = 1;
backup = all + 38; break;//ʯͷ
case 2:
display = all + 15; length = 40; width = 40; gender = 2;
backup = all + 37; break;//С
case 3:
display = all + 11; length = 30; width = 25; gender = 3;
backup = all + 35; break;//ʯ
case 4:
display = all + 15; length = 40; width = 40; gender = 2;
backup = all + 37; break;//С飬ʼӴ
case 5:
display = all + 8; length = 40; width = 40; gender = 1;
backup = all + 38; break;//ʯͷʼӴ
};
x = rand()%900; y = 150+rand()%500;
xc = x + length / 2; yc = y + width / 2;
being = false;
}//ι
~gold() {};
};
| true |
72c81d8f2e3285b4004f92a0ced097536fde5842 | C++ | parkhaeseon/boj | /10451.cpp | UTF-8 | 917 | 2.578125 | 3 | [] | no_license | #include <iostream>
#include <queue>
#include <stack>
#include <cstdio>
#include <vector>
#include <cstring>
#include <string>
#include <math.h>
#include <algorithm>
#include <map>
using namespace std;
vector<int> v[1001];
bool visit[1001] = { false, };
int connect = 0;
void DFS(int start)
{
visit[start] = true;
for (auto next : v[start])
{
if (!visit[next]) DFS(next);
}
}
int main(void)
{
int T = 0, cnt = 0, n = 0;
scanf("%d", &T);
while (T--)
{
connect = 0;
memset(visit, false, sizeof(visit));
scanf("%d", &cnt);
for (int i = 1; i <= cnt; i++)
{
scanf("%d", &n);
v[i].push_back(n);
}
for (int i = 1; i <= cnt; i++)
{
if (!visit[i])
{
++connect;
DFS(i);
}
}
for (int i = 1; i <= cnt; i++)
{
if (!v[i].empty()) v[i].clear();
}
printf("%d\n", connect);
}
return 0;
} | true |
315534b37e0a214c41a36818492a3b27f4a0433b | C++ | ciknowles/CircularFlashWriter | /CircularFlashWriter.cpp | UTF-8 | 3,530 | 3.3125 | 3 | [] | no_license | #include "Arduino.h"
#include "CircularFlashWriter.h"
CircularFlashWriter::CircularFlashWriter() {
}
void CircularFlashWriter::begin(uint8_t csPin) {
flash = new SPIFlash(csPin);
flash->begin();
capacity = flash->getCapacity();
next = getNextAddress();
first = getFirstAddress();
#ifdef CFW_DEBUG
Serial.print("PIN: ");
Serial.println(flash->csPin);
Serial.print("CAPACITY:");
Serial.println(capacity);
Serial.print("Next:");
Serial.println(next);
Serial.print("First:");
Serial.println(first);
#endif
}
/**
Toggle the flash on/off
@param yes true is on, false is off
*/
void CircularFlashWriter::flashToggle(bool yes) {
if (yes) {
flash->powerUp();
}
else
flash->powerDown();
}
uint32_t CircularFlashWriter::size() {
return (next-first)/PAGE_SIZE;
}
/**
Writes a variable length packet of no more than 255
bytes to the rolling log
@param data_buffer[] the bytes to write
@param bufferSize the size of data_buffer
*/
void CircularFlashWriter::putPacket(byte* data_buffer, int buffer_size) {
//if we are at the start of a block then
//erase the first page of this block
//and the next block
if (next%BLOCK_SIZE==0) {
#ifdef CFW_DEBUG
Serial.print("ERASE:");
Serial.println(next);
#endif
flash->writeByte(next, 0xFF); //flag as started
flash->eraseSector( (next)%capacity);
flash->writeByte(next + BLOCK_SIZE, 0xFF); //flag as started
flash->eraseSector( (next + BLOCK_SIZE)%capacity);
}
flash->writeByte(next, 0x7F); //flag as started
//flash->writeByte(next+1, buffer_size);
flash->writeByteArray(next+1, data_buffer, buffer_size);
flash->writeByte(next, 0x3F); //flag as written
#ifdef CFW_DEBUG
Serial.print("WRITTEN:");
Serial.println(next);
#endif CFW_DEBUG
next = (next + PAGE_SIZE) % capacity;
}
/**
Examines the SerialFlash finds the next empty page. Is called
once on startup. A reference is then kept to this
address.
@return the next available address
*/
uint32_t CircularFlashWriter::getNextAddress() {
//search blocks to find last that is written
uint32_t ad = search(0,capacity, BLOCK_SIZE);
//now seach pages to find next free page
return (search(ad, ad+BLOCK_SIZE, PAGE_SIZE)+ PAGE_SIZE)%capacity;
}
/**
Examines the SerialFlash finds the first non-empty page. Must
be called after getNextAddress. It should be called once
once on startup. A reference is then kept to this
address.
@return the next available address
*/
uint32_t CircularFlashWriter::getFirstAddress() {
//search blocks to find last that is written
uint32_t ad = search((next - PAGE_SIZE)%capacity,0, -BLOCK_SIZE);
//now seach pages to find first that was written
return (search(ad, 0, -PAGE_SIZE))%capacity;
}
/**
Examines the first byte in a chunk of flash to determine if
page has been written.
@param from the from address
@param to the to address
@param ss the step size, normally BLOCK or PAGE
@param headermask mask to apply to first byte of PAGE
@return the last written address
*/
uint32_t CircularFlashWriter::search(uint32_t from,uint32_t to, uint32_t ss) {
byte lb = 255;//isnt written
uint32_t pt;
if (ss>0) {
for ( pt = from;pt<=to;pt=pt+ss) {
byte b = flash->readByte(pt);
if ((b==255) && (lb!=255)) {
return pt-ss;
}
lb = b;
}
return pt;
}
for ( pt = from;pt>=to;pt=pt-ss) {
byte b = flash->readByte(pt);
if ((b==255) && (lb!=255)) {
return pt-ss;
}
lb = b;
}
return pt;
} | true |
351a5b65d90f8195574652d855251f865eb70f69 | C++ | JanneRemes/janityengine | /JanneRemesEngine/Engine/jni/Mesh.cpp | UTF-8 | 5,800 | 2.703125 | 3 | [] | no_license | #include <Mesh.h>
#include <cmath>
#include <Debug.h>
#include <Camera.h>
using namespace JanityEngine;
Mesh::Mesh(int X, int Y, int Z, float scale, const char* objPath)
{
x = X;
y = Y;
z = Z;
LoadObj(objPath);
Debug::CheckGlError("load obj: ");
HandleData();
GenBuffer();
Move(x, y, z);
Resize(scale, scale, scale);
Rotate(0, 1,1,1);
model.identity();//glm::mat4(1.0f);
}
Mesh::Mesh(int Size, float* _data)
{
x = 0;
y = 0;
z = 0;
Data = (float*)malloc(Size*sizeof(float)*8);
Debug::WriteLog("_data mesh: %d\n", _data);
Data = _data;
Debug::WriteLog("Data mesh: %d\n", Data);
_size = Size;
int j=0;
for(int i=0; i<_size;i++)
{
Data[j+0] = _data[j+0];
Data[j+1] = _data[j+1];
Data[j+2] = _data[j+2];
Data[j+3] = _data[j+3];
Data[j+4] = _data[j+4];
Data[j+5] = _data[j+5];
Data[j+6] = _data[j+6];
Data[j+7] = _data[j+7];
Data[j+8] = _data[j+8];
Debug::WriteLog("_data: %f - Data: %f\n",_data[j+0], Data[j+0]);
Debug::WriteLog("_data: %f - Data: %f\n",_data[j+1], Data[j+1]);
Debug::WriteLog("_data: %f - Data: %f\n",_data[j+2], Data[j+2]);
Debug::WriteLog("_data: %f - Data: %f\n",_data[j+3], Data[j+3]);
Debug::WriteLog("_data: %f - Data: %f\n",_data[j+4], Data[j+4]);
Debug::WriteLog("_data: %f - Data: %f\n",_data[j+5], Data[j+5]);
Debug::WriteLog("_data: %f - Data: %f\n",_data[j+6], Data[j+6]);
Debug::WriteLog("_data: %f - Data: %f\n",_data[j+7], Data[j+7]);
j=j+8;
//Sleep(1000);
}
GenBuffer();
Move(x, y, z);
Resize(0.1f,0.1f,0.1f);
Rotate(0, 1,1,1);
model.identity();//glm::mat4(1.0f);
}
Mesh::Mesh(std::vector<Vector3> _vertices, std::vector<Vector2> _uvs, std::vector<Vector3> _normals)
{
x = 0;
y = 0;
z = 0;
vertices = _vertices;
uvs = _uvs;
normals = _normals;
HandleData();
GenBuffer();
Move(x, y, z);
Resize(0.1f, 0.1f, 0.1f);
Rotate(0,1,1,1);
model.identity(); // glm::mat4(1.0f);
}
Mesh::~Mesh()
{
glDeleteBuffers(1, &vbo);
free(Data);
}
// PRIVATE
void Mesh::LoadObj(const char* _objPath)
{
obj = new ObjLoader();
bool a = obj->LoadOBJ(_objPath, vertices, uvs, normals);
assert(a==1);
delete obj;
}
void Mesh::HandleData()
{
Data = (float*)malloc(vertices.size()*sizeof(float)*8);
int j = 0;
for(int i = 0; i < vertices.size(); i++)
{
Data[j] = vertices[i][0];
Data[j+1] = vertices[i][1];
Data[j+2] = vertices[i][2];
Data[j+3] = uvs[i][0];
Data[j+4] = uvs[i][1];
Data[j+5] = normals[i][0];
Data[j+6] = normals[i][1];
Data[j+7] = normals[i][2];
//Debug::WriteLog("Data mesh hanska: %f\n", Data[j+0]);
//Debug::WriteLog("Data mesh hanska: %f\n", Data[j+1]);
//Debug::WriteLog("Data mesh hanska: %f\n", Data[j+2]);
//Debug::WriteLog("Data mesh hanska: %f\n", Data[j+3]);
//Debug::WriteLog("Data mesh hanska: %f\n", Data[j+4]);
//Debug::WriteLog("Data mesh hanska: %f\n", Data[j+5]);
//Debug::WriteLog("Data mesh hanska: %f\n", Data[j+6]);
//Debug::WriteLog("Data mesh hanska: %f\n", Data[j+7]);
//Sleep(1000);
j = j+8;
}
_size = vertices.size();
}
void Mesh::GenBuffer()
{
glGenBuffers(1, &vbo);
Debug::CheckGlError("glGenBuffers: ");
glBindBuffer(GL_ARRAY_BUFFER, vbo);
Debug::CheckGlError("glBindBuffer: ");
glBufferData(GL_ARRAY_BUFFER,_size*sizeof(float)*8,Data,GL_DYNAMIC_DRAW);
Debug::CheckGlError("glBufferData: ");
}
// PUBLIC
void Mesh::Move(float X, float Y, float Z)
{
x = X; y = Y; z = Z;
translation.createTranslation(Vector3(x, y, z));
}
void Mesh::Move(Vector3 vector)
{
Move(vector.x, vector.y, vector.z);
}
void Mesh::Resize(float W, float H, float D)
{
scale.createScaling(W,H,D);
}
void Mesh::Rotate(float r, int X, int Y, int Z)
{
float rX, rY, rZ;
rX = X;
rY = Y;
rZ = Z;
rotation.createRotationAxis(Vector3(rX,rY,rZ).normal(), r);
}
void Mesh::Rotate(float r, float X, float Y, float Z)
{
rotation.createRotationAxis(Vector3(X,Y,Z).normal(), r);
}
void Mesh::SetTexture(const char* Texture)
{
texture = Texture::Load(Texture);
}
void Mesh::SetProgram(GLuint program)
{
this->program = program;
position = glGetAttribLocation(program,"vPosition");
uv = glGetAttribLocation(program,"vUv");
loc = glGetUniformLocation(program, "s_texture");
loc2 = glGetUniformLocation(program, "Projection");
loc3 = glGetUniformLocation(program, "Translation");
loc4 = glGetUniformLocation(program, "Rotation");
loc5 = glGetUniformLocation(program, "Scale");
loc6 = glGetUniformLocation(program, "View");
loc7 = glGetUniformLocation(program, "Model");
}
void Mesh::SetProjection(int desiredWidth, int desiredHeight)
{
float dW = desiredWidth;
float dH = desiredHeight;
projection = Camera::MainCamera()->GetProjMat(45.0f, dW/dH, 0.1f, 1000.0f);
}
void Mesh::Draw()
{
view = Camera::MainCamera()->GetViewMat();
model = translation * rotation * scale;
glUseProgram(program);
glFrontFace(GL_CCW);
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
glDepthFunc(GL_LEQUAL);
glEnable(GL_DEPTH_TEST);
glEnable (GL_BLEND);
glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
// VBO
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texture->GetID());
glUniform1i(loc, 0);
glVertexAttribPointer(position,3,GL_FLOAT,GL_FALSE,8*sizeof(GL_FLOAT),0);
glVertexAttribPointer(uv,2,GL_FLOAT,GL_FALSE,8*sizeof(GL_FLOAT),(void*)(sizeof(GL_FLOAT)*3));
glEnableVertexAttribArray(position);
glEnableVertexAttribArray(uv);
glUniformMatrix4fv(loc2,1,GL_FALSE,&projection[0][0]);
glUniformMatrix4fv(loc6,1,GL_FALSE,&view[0][0]);
glUniformMatrix4fv(loc7,1,GL_FALSE,&model[0][0]);
glDrawArrays(GL_TRIANGLES,0,vertices.size());
glDisableVertexAttribArray(position);
glDisableVertexAttribArray(uv);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glDisable(GL_CULL_FACE);
glDisable(GL_DEPTH_TEST);
glDisable(GL_BLEND);
} | true |
fa19ad519213167ad84c90dcab48d0b2764b00c7 | C++ | katerina632/Constructor_destructor | /Student.h | UTF-8 | 543 | 2.90625 | 3 | [] | no_license | #pragma once
class Student
{
private:
char* name;
int age;
float avgMark;
int* marksArr;
int countMarks;
bool IsValidAge(int age) const
{
return age >= 0 && age <= 100;
}
void CalcAverageMark();
void DelMemory() const;
public:
Student();
Student(const char* _name, int _age);
~Student()
{
DelMemory();
}
const char* GetName() const;
int GetAge() const;
void SetName(const char* _name);
void SetAge(int _age);
void AddMark(int value);
void Print() const;
void Save();
void Load();
};
| true |
d5a77d73359a99578d15c69a257dbc6e6a404991 | C++ | quartuxz/Cryoscom-src | /serializationUtils.cpp | UTF-8 | 4,509 | 2.953125 | 3 | [] | no_license | #include "serializationUtils.h"
std::vector<std::pair<size_t, size_t>> getOutermostBlocks(std::string data){
std::vector<std::pair<size_t, size_t>> retVal;
if(data.find("}") != std::string::npos && data.find("{") != std::string::npos){
}else{
return retVal;
}
std::string cutData = data;
size_t tempStartPos;
size_t startPos;
size_t endPos;
int blockStartCounter = 0;
size_t tempPos;
while(cutData.find("}") != std::string::npos){
tempPos = cutData.find("}");
cutData[tempPos] = '!';
if(cutData.find("}") != std::string::npos){
}
}
cutData = data;
cutData[cutData.find("{")] = '!';
cutData[tempPos] = '!';
while(cutData.find("}") != std::string::npos){
//while(true){
//}
if(cutData.find("{") < cutData.find("}")){//if start block is before end block; adds to the start block counter
tempStartPos = cutData.find("{");
if(blockStartCounter == 0){
startPos = tempStartPos;
}
cutData[tempStartPos] = '!';
blockStartCounter++;
//std::cout << "startBlock" << std::endl;
}else if(cutData.find("}") != std::string::npos){//if endblock is before next start block, and is ending a previously detected start block
blockStartCounter--;
endPos = cutData.find("}");
cutData[endPos] = '!';
//std::cout << "endBlock" << std::endl;
}
if(blockStartCounter == 0){//if start blocks match end blocks
retVal.push_back(std::pair<size_t, size_t>(startPos, endPos));
//std::cout << "block added!" << std::endl;
}
}
return retVal;
}
std::vector<std::string> processBlock(std::string data){
std::vector<std::string> retVal;
std::vector<std::pair<size_t, size_t>> outermostBlocks = getOutermostBlocks(data);
if(outermostBlocks.size() >= 1){
retVal.push_back(data.substr(data.find("{") + 1, (outermostBlocks[0].first - data.find("{")) - 1 ));
}else{
retVal.push_back(data.substr(data.find("{") + 1, (data.find("}") - data.find("{")) - 1 ));
}
for(int i = 0; i < outermostBlocks.size(); i++){
retVal.push_back(data.substr(outermostBlocks[i].first, (outermostBlocks[i].second - outermostBlocks[i].first)+1));
}
return retVal;
// std::vector<std::string> retVal;
// size_t pos = data.find("{");
// if(data.find("{") < data.find("}")){
// retVal.push_back(data.substr(pos, data.find("{")));
//
// }else{
// retVal.push_back(data.substr(pos, data.find("}")));
// }
//
//
// while(blockStartCounter>0){
// cutData[cutData.find("}")] = '!';
// }
//
//
// return retVal;
}
std::vector<char const *> processBlockRetChar(std::string data){
std::vector<char const *> retVal;
std::vector<std::pair<size_t, size_t>> outermostBlocks = getOutermostBlocks(data);
if(outermostBlocks.size() >= 1){
retVal.push_back(data.substr(data.find("{") + 1, (outermostBlocks[0].first - data.find("{")) - 1 ).c_str());
}else{
retVal.push_back(data.substr(data.find("{") + 1, (data.find("}") - data.find("{")) - 1 ).c_str());
}
for(int i = 0; i < outermostBlocks.size(); i++){
retVal.push_back(data.substr(outermostBlocks[i].first, (outermostBlocks[i].second - outermostBlocks[i].first)+1).c_str());
}
return retVal;
}
boost::python::list processBlockForPython(char const* data){
//std::vector<char const *> temp = processBlockRetChar(data);
std::vector<std::string> temp = processBlock(data);
return std_vector_to_py_list(temp);
//return boost::python::list();
}
std::vector<std::string> tokenizeDecomposedDataData(std::string data, std::string delimiter){
std::vector<std::string> tokens;
size_t pos = 0;
pos = data.find(delimiter);
while (pos != std::string::npos) {
tokens.push_back(data.substr(0, pos));
data.erase(0, pos + delimiter.length());
pos = data.find(delimiter);
}
return tokens;
}
boost::python::list tokenizeDecomposedDataDataForPython(char const* data, char const* delimiter){
return std_vector_to_py_list(tokenizeDecomposedDataData(data, delimiter));
}
BOOST_PYTHON_MODULE(gameSerializationUtils){
using namespace boost::python;
def("processBlock", processBlockForPython);
def("tokenizeDecomposedDataData", tokenizeDecomposedDataDataForPython);
}
| true |
511dd96aedf1de5d62a820c9af56939eafb6840f | C++ | j3camero/checkers | /bit-string.cc | UTF-8 | 5,085 | 3.390625 | 3 | [] | no_license | #include "bit-string.h"
#include "std.h"
Bitstring::Bitstring() : size(0) {
// Do nothing.
}
Bitstring::Bitstring(bool b) : size(0) {
Append(b);
}
Bitstring::Bitstring(uint64 length) : size(0) {
Resize(length);
}
Bitstring::Bitstring(const Bitstring& b) : size(0) {
Append(b);
}
Bitstring::Bitstring(const string& s) : size(0) {
Append(s);
}
Bitstring::Bitstring(const char *s) : size(0) {
Append(string(s));
}
bool Bitstring::Get(uint64 index) const {
const int page_index = index / bits_per_page;
const Page& page = data[page_index];
const int index_within_page = index % bits_per_page;
const int word_index = index_within_page / bits_per_page;
const uint64 word = page[word_index];
const int index_within_word = index_within_page % 64;
return (word >> index_within_word) & 1;
}
void Bitstring::Set(uint64 index, bool b) {
const int page_index = index / bits_per_page;
Page& page = data[page_index];
const int index_within_page = index % bits_per_page;
const int word_index = index_within_page / bits_per_page;
const int index_within_word = index_within_page % 64;
if (b) {
// Set the bit.
page[word_index] |= uint64(1) << index_within_word;
} else {
// Clear the bit.
page[word_index] &= ~(uint64(1) << index_within_word);
}
}
void Bitstring::Clear(uint64 index) {
Set(index, false);
}
void Bitstring::Flip(uint64 index) {
Set(index, !Get(index));
}
uint64 Bitstring::Size() const {
return size;
}
void Bitstring::Resize(uint64 new_size) {
size = new_size;
// Add or remove pages.
const int new_page_count = size / bits_per_page + 1;
const Page blank_page(words_per_page);
data.resize(new_page_count, blank_page);
// Change the size of the last page.
const int last_page_bits = size % bits_per_page;
const int new_word_count = last_page_bits / 64 + 1;
Page& last_page = data.back();
last_page.resize(new_word_count);
}
void Bitstring::Append(bool b) {
const uint64 i = size;
Resize(i + 1);
Set(i, b);
}
void Bitstring::Append(const Bitstring& b) {
for (uint64 i = 0; i < b.Size(); ++i) {
bool bit = b.Get(i);
Append(bit);
}
}
void Bitstring::Append(const string& s) {
// Process digits in right to left order in accordance with math convention.
for (int i = s.size() - 1; i >= 0; --i) {
char c = s[i];
Append(c);
}
}
void Bitstring::Append(char c) {
switch (c) {
case '0':
case 'F':
case 'f':
case '-':
Append(false);
break;
case '1':
case 'T':
case 't':
case '+':
Append(true);
break;
};
}
uint64 Bitstring::ToUInt64() {
if (size > 64) {
return 0;
}
uint64 sum = 0;
uint64 mag = 1;
for (uint64 i = 0; i < size; ++i) {
if (Get(i)) {
sum += mag;
}
mag *= 2;
}
return sum;
}
void Bitstring::Increment() {
bool done = false;
for (uint64 i = 0; i < size; ++i) {
if (Get(i)) {
Clear(i);
} else {
Set(i);
done = true;
break;
}
}
if (!done) {
Append(true);
}
}
bool Bitstring::StartsWith(const Bitstring& b) const {
if (b.Size() > Size()) {
return false;
}
for (uint64 i = 0; i < b.Size(); ++i) {
if (Get(i) != b.Get(i)) {
return false;
}
}
return true;
}
Bitstring Bitstring::Reverse() const {
Bitstring r;
for (uint i = 0; i < size; ++i) {
r.Append(Get(size - i - 1));
}
return r;
}
bool Bitstring::IsPrefixFree(const vector<Bitstring>& v) {
for (int i = 0; i < v.size(); ++i) {
for (int j = 0; j < v.size(); ++j) {
if (i == j) {
continue;
}
const Bitstring& a = v[i];
const Bitstring& b = v[j];
if (a.StartsWith(b)) {
return false;
}
}
}
return true;
}
bool Bitstring::operator==(const Bitstring& b) const {
if (b.size != size) {
return false;
}
for (uint64 i = 0; i < size; ++i) {
if (Get(i) != b.Get(i)) {
return false;
}
}
return true;
}
bool Bitstring::operator!=(const Bitstring& b) const {
return !(*this == b);
}
bool Bitstring::operator<(const Bitstring& b) const {
if (size < b.Size()) {
return true;
}
if (b.Size() < size) {
return false;
}
if (size == 0) {
// This case can't be handled nicely by the loop below, so it is
// handled individually here.
return false;
}
for (uint64 i = size - 1; i >= 0; --i) {
if (Get(i)) {
if (!b.Get(i)) {
return false;
}
} else {
if (b.Get(i)) {
return true;
}
}
// Needs to be here because the loop condition doesn't work.
if (i == 0) {
break;
}
}
return false;
}
Bitstring& Bitstring::operator+=(const Bitstring& b) {
Append(b);
return *this;
}
Bitstring operator+(const Bitstring& a, const Bitstring& b) {
// Make a copy of a.
Bitstring c(a);
// Append b to the copy.
c.Append(b);
return c;
}
ostream& operator<<(ostream &out, const Bitstring& b) {
for (uint64 i = b.Size(); i > 0; --i) {
if (b.Get(i - 1)) {
out << "1";
} else {
out << "0";
}
}
return out;
}
| true |
594edf9f90701d511983e778981b53a4b2644d23 | C++ | sujiwo/VMML | /vmml/vision_core/src/FeatureTrack.cpp | UTF-8 | 3,130 | 2.671875 | 3 | [] | no_license | /*
* FeatureTrack.cpp
*
* Created on: Mar 10, 2020
* Author: sujiwo
*/
#include <exception>
#include <opencv2/imgproc.hpp>
#include "vmml/FeatureTrack.h"
using namespace std;
namespace Vmml {
void
FeatureTrack::add(const uint& frameNum, const cv::Point2f &pt)
{
frameNumbers.insert(frameNum);
mPoints[frameNum] = pt;
}
vector<cv::Point2f>
FeatureTrack::getPoints(int smax) const
{
vector<cv::Point2f> points;
if (smax==0)
smax=size();
vector<FrameId> tg(frameNumbers.begin(), frameNumbers.end());
vector<FrameId> tgSubs(tg.begin()+(tg.size()-smax), tg.end());
for (auto &pr: tg) {
points.push_back(mPoints.at(pr));
}
return points;
}
cv::Mat
FeatureTrack::getPointsAsMat(int smax) const
{
auto vpt = getPoints(smax);
cv::Mat ptMat(vpt.size(), 2, CV_32S);
for (uint r=0; r<vpt.size(); ++r) {
ptMat.at<int>(r,0) = int(vpt[r].x);
ptMat.at<int>(r,1) = int(vpt[r].y);
}
return ptMat;
}
void
FeatureTrackList::add (const FeatureTrack& ft)
{
mFeatTracks.push_back(ft);
TrackId currentTrackId=mFeatTracks.size()-1;
for (auto &f: ft.frameNumbers) {
if (frameToFeatureTracks.find(f)==frameToFeatureTracks.end()) {
frameToFeatureTracks.insert(make_pair(f, set<TrackId>({currentTrackId})));
}
else {
frameToFeatureTracks.at(f).insert(currentTrackId);
}
}
}
vector<const FeatureTrack*>
FeatureTrackList::getFeatureTracksAt(const FrameId& frId) const
{
vector<const FeatureTrack*> rft;
for (auto &tId: frameToFeatureTracks.at(frId)) {
rft.push_back(&mFeatTracks.at(tId));
}
return rft;
}
cv::Mat
FeatureTrackList::trackedFeaturesAtFrame(const FrameId& fr) const
{
auto &tracks = frameToFeatureTracks.at(fr);
cv::Mat rtrackMat(tracks.size(), 2, CV_32F);
uint i=0;
for(auto t: tracks) {
auto &track = mFeatTracks.at(t);
auto &point = track.mPoints.at(fr);
rtrackMat.at<float>(i,0) = point.x;
rtrackMat.at<float>(i,1) = point.y;
++i;
}
return rtrackMat;
}
cv::Mat
FeatureTrackList::createFeatureMask(const cv::Mat& baseMask, const FrameId &f)
const
{
assert(baseMask.empty()==false);
auto mask = baseMask.clone();
for (auto &_tr: getFeatureTracksAt(f)) {
auto &tr = *_tr;
for (auto pt: tr.getPoints()) {
cv::circle(mask, pt, 5, cv::Scalar(0), -1);
}
}
return mask;
}
void
FeatureTrackList::addTrackedPoint(const FrameId &fr, const TrackId &tr, const cv::Point2f &pt)
{
mFeatTracks.at(tr).add(fr, pt);
if (frameToFeatureTracks.find(fr)==frameToFeatureTracks.end()) {
frameToFeatureTracks.insert(make_pair(fr, set<TrackId>({tr})));
}
else {
frameToFeatureTracks.at(fr).insert(tr);
}
}
void
FeatureTrackList::reset()
{
frameToFeatureTracks.clear();
mFeatTracks.clear();
}
void
FeatureTrackList::cleanup()
{
ftLock.lock();
set<TrackId> toBeRemoved;
for (TrackId i=0; i<mFeatTracks.size(); ++i) {
if (mFeatTracks[i].frameNumbers.size() < minTrackSize)
toBeRemoved.insert(i);
}
for (auto &pr: frameToFeatureTracks) {
// if (pr.second.)
for (auto &t: toBeRemoved) {
if (pr.second.find(t)!=pr.second.end())
pr.second.erase(t);
}
}
// XXX: unfinished
ftLock.unlock();
}
} /* namespace Vmml */
| true |
a0b355cd9f177888b8daeb5928762f315981bc17 | C++ | rlj1202/problemsolving | /baekjoon/1620/main.cpp | UTF-8 | 635 | 2.703125 | 3 | [] | no_license | #include <iostream>
#include <unordered_map>
#include <string>
#include <sstream>
using namespace std;
unordered_map<string, string> mapping;
int main() {
ios::ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int N, M;
cin >> N >> M;
for (int n = 1; n <= N; n++) {
string str;
cin >> str;
stringstream stream;
stream << n;
string index = stream.str();
mapping[index] = str;
mapping[str] = index;
}
for (int m = 0; m < M; m++) {
string cmd;
cin >> cmd;
cout << mapping[cmd] << "\n";
}
return 0;
}
| true |
a598ef6ee147f9bfc9e35585ffbc4a1cd4cabe71 | C++ | mahendra-ramajayam/MultiPhaseField | /Grain_Growth/2D/indexed/sorting/sortp.cpp | UTF-8 | 740 | 2.78125 | 3 | [] | no_license |
// find 6 largest eta from the claculation list and assign them back to eta and inds matrix
int sortp(double* maxetas,int* maxinds,double* eta2, int* inds2,int size2, int p,int i, int jn)
{
int ni,ii,maxi;
double maxeta;
for (ni=0;ni<p;ni++)
{
maxeta=maxetas[0];
maxi=0;
for (ii=0;ii<10;ii++)
{
if (maxetas[ii]>maxeta)
{
maxeta=maxetas[ii];
maxi=ii;
}
}
//so we set vaule of maximum eta in the maxetas to -1 which is smaller than all of the rest so next time second maximum wil be selected
maxetas[maxi]=-1;
eta2[i+jn+ni*size2]=maxeta; //output
inds2[i+jn+ni*size2]=maxinds[maxi];
}
for (ii=0;ii<10;ii++)
{
maxetas[ii]=0;
}
return 0;
}
| true |
a09e114f0e22264665100b1bdfb5997eccad7bab | C++ | DavesCodeMusings/b64 | /example.ino | UTF-8 | 850 | 2.8125 | 3 | [
"Unlicense"
] | permissive | /*
* Sample Arduino sketch to encode and decode messages.
*/
#include <b64.h>
void setup() {
Serial.begin(115200);
delay(1000);
// Encoding example.
char msg[] = "Hello Cleveland!";
char enc_result[b64enclen(sizeof msg)];
b64enc(msg, enc_result, sizeof msg);
Serial.println(msg);
Serial.println("...is encoded as...");
Serial.println(enc_result);
Serial.println();
// Decoding example.
char enc_msg[] = "SGVsbG8gQ2xldmVsYW5kIQA=";
char dec_result[b64declen(enc_msg, sizeof enc_msg)];
int declen = b64dec(enc_msg, dec_result, sizeof enc_msg);
Serial.print("Bytes decoded: ");
Serial.println(declen, DEC);
for (int k=0; k<declen; k++) {
Serial.print(dec_result[k], DEC);
Serial.print(" ");
}
Serial.println();
Serial.print("Decoded message: ");
Serial.println(dec_result);
}
void loop() {
} | true |
991a701391a7a80169f1bcf99ef05c051d295f45 | C++ | djanuskaite/Cplus_darbai | /Vector/prekes-cekis/prekes1.cpp | UTF-8 | 1,694 | 2.796875 | 3 | [] | no_license | #include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;
struct preke{
string pav;
int kiek;
double kaina;
double suma;
};
ifstream in("prekes.txt");
ofstream out("cekis.txt");
void skaitom (preke P[], int kiekis);
void rasom (preke P[], int kiekis);
void rikiavimas (preke P[], int kiekis);
int main()
{
int n; //prekiu kiekis
in>>n;
preke Sar[n];
skaitom(Sar, n);
rasom(Sar, n);
rikiavimas(Sar, n);
in.close();
out.close();
return 0;
}
//-------------------Skaito---------------------
void skaitom (preke P[], int kiekis)
{
for(int i = 0; i<kiekis; i++){
in>>P[i].pav;
in>>P[i].kiek;
in>>P[i].kaina;
}
}
//------------------------------------------
void rasom (preke P[], int kiekis)
{
float moketi(0);
for(int i = 0; i<kiekis; i++){
P[i].suma =P[i].kaina*P[i].kiek;
moketi+=P[i].suma;
out<<left<<setw(20)<<P[i].pav<<right<<setw(6)<<P[i].kiek<<setw(6)<<P[i].kaina<<setw(8)<<P[i].suma;
out<<endl;
}
out<<setw(40)<<moketi;
}
//-----------------------------------------
//-----------------------------
void rikiavimas (preke P[], int kiekis)
{
preke laik[1];
int k;
for(int i=0; i<kiekis-1; i++){
k=i+1;
for(int j=i; j<kiekis; j++)
if(P[j].pav<P[k].pav) k=j;
laik[0]= P[k];
P[k]=P[i];
P[i]=laik[0];
}
out<<"\nSurikiuotas \n";
rasom(P, kiekis);
}
| true |
a68f0cc4673f04da68fe64794025516531be2830 | C++ | amplab/zipg | /core/src/GraphLogStore.cpp | UTF-8 | 5,058 | 2.671875 | 3 | [] | no_license | #include "GraphLogStore.h"
#include "GraphFormatter.hpp"
void GraphLogStore::construct() {
node_table_ = std::make_shared<KVLogStore>(4294967296ULL);
LOG_E("GraphLogStore: Constructing Edge table\n");
edge_table_.construct();
LOG_E("GraphLogStore: Edge table constructed\n");
}
void GraphLogStore::load() {
LOG_E("Loading GraphLogStore");
node_table_ = std::make_shared<KVLogStore>(4294967296ULL);
}
// Serialize into the "[lengths] [attrs]" format, and call append().
int64_t GraphLogStore::append_node(const std::vector<std::string>& attrs) {
std::string delimed(GraphFormatter::format_node_attrs_str( { attrs }));
std::string val(GraphFormatter::attach_attr_lengths(delimed));
int64_t node = node_table_->append(val);
return node;
}
int GraphLogStore::append_edge(int64_t src, int64_t dst, int64_t atype,
int64_t timestamp, const std::string& attr) {
if (edge_table_.num_edges() >= max_num_edges_) {
LOG_E("append_edge failed: Edge table log store already has %d edges\n",
max_num_edges_);
return -1;
}
edge_table_.add_assoc(src, dst, atype, timestamp, attr);
return 0;
}
void GraphLogStore::get_attribute(std::string& result, int64_t node_id,
int attr) {
result.clear();
std::string str;
assert(attr < SuccinctGraph::MAX_NUM_NODE_ATTRS);
node_table_->get_value(str, node_id); // TODO: handle non-existent?
// get the initial dist first
int i = 0, dist = 0;
while (str[i] != SuccinctGraph::NODE_TABLE_HEADER_DELIM) {
dist = dist * 10 + (str[i] - '0');
++i;
}
++i;
int init_dist = dist;
dist += attr + 1; // skip past the delims as well
for (int j = 1; j <= attr; ++j) {
int tmp = 0;
while (str[i] != SuccinctGraph::NODE_TABLE_HEADER_DELIM) {
tmp = tmp * 10 + (str[i] - '0');
++i;
}
++i;
dist += tmp;
}
// also skip the dist and its delim as well
dist += SuccinctGraph::num_digits(init_dist) + 1;
while (str[dist] != static_cast<char>(SuccinctGraph::DELIMITERS[attr + 1])) {
result += str[dist]; // TODO: probably exists a better way to write this
++dist;
}
}
void GraphLogStore::get_nodes(std::set<int64_t>& result, int attr,
const std::string& search_key) {
result.clear();
node_table_->search(
result, std::move(SuccinctGraph::mk_node_attr_key(attr, search_key)));
}
void GraphLogStore::get_nodes(std::set<int64_t>& result, int attr1,
const std::string& search_key1, int attr2,
const std::string& search_key2) {
result.clear();
std::set<int64_t> s1, s2;
node_table_->search(
s1, std::move(SuccinctGraph::mk_node_attr_key(attr1, search_key1)));
node_table_->search(
s2, std::move(SuccinctGraph::mk_node_attr_key(attr2, search_key2)));
COND_LOG_E("s1 size %d, s2 size %d\n", s1.size(), s2.size());
// result.end() is a hint that supposedly is faster than .begin()
std::set_intersection(s1.begin(), s1.end(), s2.begin(), s2.end(),
std::inserter(result, result.end()));
}
void GraphLogStore::obj_get(std::vector<std::string>& result, int64_t obj_id) {
LOG_E("obj_get(%lld)\n", obj_id);
result.clear();
std::string str;
node_table_->get_value(str, obj_id); // TODO: handle non-existent?
// get the initial dist first
int i = 0, dist = 0;
while (str[i] != SuccinctGraph::NODE_TABLE_HEADER_DELIM) {
dist = dist * 10 + (str[i] - '0');
++i;
}
++i;
char next_delim;
int last_non_empty;
dist += i + 1; // pointing to the start of attr1
for (int attr = 0; attr < SuccinctGraph::MAX_NUM_NODE_ATTRS; ++attr) {
next_delim = static_cast<char>(SuccinctGraph::DELIMITERS[attr + 1]);
i = dist;
while (str[i] != next_delim) {
++i;
}
if (i > dist) {
last_non_empty = attr;
}
assert(i <= str.length());
result.emplace_back(str.substr(dist, i - dist));
dist = i + 1;
}
}
// LinkBench API
bool GraphLogStore::getNode(std::string& data, int64_t id) {
std::string str = "";
node_table_->get_value(str, id);
if (str == "") {
return false;
}
// get the initial dist first
int i = 0, dist = 0;
while (str[i] != SuccinctGraph::NODE_TABLE_HEADER_DELIM) {
dist = dist * 10 + (str[i] - '0');
++i;
}
++i;
char end = '\n';
dist += i + 1; // pointing to the start of attr1
i = dist;
while (str[i] != end) {
++i;
}
assert(i <= str.length());
data.assign(str.substr(dist, i - dist));
return true;
}
int64_t GraphLogStore::addNode(const int64_t id, const std::string& data) {
COND_LOG_E("Adding new node (id=%lld) to LogStore.\n", id);
size_t distance = num_digits(data.length()) + 1;
std::string value = std::to_string(distance)
+ SuccinctGraph::NODE_TABLE_HEADER_DELIM
+ std::to_string(data.length())
+ SuccinctGraph::NODE_TABLE_HEADER_DELIM
+ static_cast<char>(SuccinctGraph::DELIMITERS[0]) + data + "\n";
return node_table_->insert(id, value);
}
| true |
efa4bf9e6489efa9c97c842f8f0b030eaab70a39 | C++ | janfranco27/spoj | /basics/12205.cpp | UTF-8 | 1,515 | 3.5625 | 4 | [] | no_license | /**
* HS12MBR
* Minimum Bounding Rectangle
**/
#include <iostream>
#include <vector>
#include <utility>
typedef std::pair<int, int> point;
typedef std::vector<point> vectorPoints;
void printBoundingRect(vectorPoints& points) {
int min_x = 1001, min_y = 1001, max_x = -1001, max_y = -1001;
vectorPoints::iterator it;
for (it = points.begin(); it != points.end(); ++it) {
point current = *it;
if (current.first < min_x) min_x = current.first;
if (current.first > max_x) max_x = current.first;
if (current.second < min_y) min_y = current.second;
if (current.second > max_y) max_y = current.second;
}
std::cout<<min_x<<" "<<min_y<<" "<<max_x<<" "<<max_y<<std::endl;
}
int main() {
int t, n;
char kind;
std::cin>>t;
while(t--) {
std::cin>>n;
vectorPoints points;
while(n--) {
int a, b, c, d;
std::cin>>kind;
switch(kind) {
case 'p':
std::cin>>a>>b;
points.push_back(std::make_pair(a, b));
break;
case 'c':
std::cin>>a>>b>>c;
points.push_back(std::make_pair(a - c, b));
points.push_back(std::make_pair(a + c, b));
points.push_back(std::make_pair(a, b - c));
points.push_back(std::make_pair(a, b + c));
break;
case 'l':
std::cin>>a>>b>>c>>d;
points.push_back(std::make_pair(a, b));
points.push_back(std::make_pair(c, d));
break;
}
}
printBoundingRect(points);
}
return 0;
} | true |
b4192dbeaba8fc51e779c92b2a962140138b02bf | C++ | batsnap/eduacation | /programming/c++/labs/lab5/pampampam.cpp | UTF-8 | 3,097 | 3.140625 | 3 | [] | no_license | #include <iostream>
#include <cstdlib>
#include <clocale>
#include <ctime>
#include <cmath>
#include <fstream>
using namespace std;
const int n = 4, m = 8;
ofstream fout("file.txt");
void FullfillMatrix(float** a) {
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++) a[i][j] = -10 + rand() % (10 - (-10) + 1);
}
void PrintMatrix(float** a) {
cout << endl;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cout << a[i][j] << " " << "\t";
}
cout << endl;
}
cout << endl;
}
void FindPlusAverage(float** a) {
int k = 0;
float sum = 0;
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++) {
if (a[i][j] >= 0) {
k++;
sum += a[i][j];
}
}
cout << "\n среднее арифметическое = " << sum / k << endl;
fout << "\n среднее арифметическое = " << sum / k << endl;
}
void CountPlusNumberInEachLine(float** a) {
int k;
fout << "\n количество неотрицательных элементов в каждой строке:" << endl << endl;
cout << "\n количество неотрицательных элементов в каждой строке:" << endl << endl;
for (int i = 0; i < n; i++) {
cout << "\n в строке #" << i + 1 << "таких элементов " << k;
fout << "\n в строке #" << i + 1 << "таких элементов " << k;
k = 0;
for (int j = 0; j < m; j++) if (a[i][j] >= 0) k++;
}
}
void FullfillSettingArray(float** a) {
cout << "\n массив из 0 и 1 по заданному условию" << endl << endl;
int f;
float* b = new float[m];
for (int i = 0; i < n; i++) {
f = 1;
for (int j = 0; j < m; j++) if (a[i][i] < a[i][j]) f = 0;
b[i] = f;
cout << " | " << b[i] << " | ";
}
cout << endl;
}
void SumMatrix(float** a) {
int sum = 0;
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++) sum += a[i][j];
cout << "\n сумма элементов матрицы = " << sum << endl;
}
void ChangeToAbsPartOfMatrix(float** a) {
cout << "\n матрица с абослютными значениями элементов, выше главной диагонали:" << endl;
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++) if (i < j) a[i][j] = abs(a[i][j]);
PrintMatrix(a);
}
void SumMainDiagonal(float** a) {
cout << "\n сумма элементов главной диагонали матрицы = ";
int sum = 0;
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++) if (i = j) sum += a[i][j];
cout << sum << endl;
}
int main() {
setlocale(LC_ALL, "Russian");
srand(time(NULL));
float** a=new float* [n];
for (int i = 0; i < n; i++) a[i] = new float[m];
PrintMatrix(a);
fout << "Работа с файлами в С++"; // запись строки в файл
FindPlusAverage(a);
CountPlusNumberInEachLine(a);
fout.close();
FullfillSettingArray(a);
SumMatrix(a);
ChangeToAbsPartOfMatrix(a);
SumMainDiagonal(a);
system("pause");
return 0;
} | true |
c62492f166e5481eb980644a480b4857ed03114c | C++ | santosh500/Cplusplus_Projects | /Maze_Game/main.cpp | UTF-8 | 3,490 | 3.125 | 3 | [] | no_license | /**
File Name: main.cpp
Author: Paul Charles
Date: 11.18.2015
Purpose: File that contains the main.cpp
**/
#include <iostream>
#include <cstdlib>
#include <string>
#include <stdexcept>
#include "MazeReader.h"
#include "MazeWalker.h"
#include "Test.h"
#include "MazeCreationException.h"
#include "Position.h"
using namespace std;
int main(int argc, char** argv)
{
string mode="";
MazeReader* b;
MazeWalker* g;
if(argc>1)
{
mode=argv[1];
string mode2="";
if(mode == "-bfs")
{
mode2=argv[2];
try
{
b=new MazeReader(mode2);
const char* const* j=b->getMaze();
int k=b->getCols();
int l=b->getRows();
int m=b->getStartCol();
int n=b->getStartRow();
Search o=Search::BFS;
g=new MazeWalker(j, n, m, l, k, o);
g->walkMaze();
const int* const* visit=g->getVisited();
cout << "Starting position: " << b->getStartRow() << "," << b->getStartCol() << endl;
cout << "Size: " << b->getRows() << "," << b->getCols() << endl;
for(int i=0; i< g->getVisitedRows(); i++)
{
for(int j=0; j<g->getVisitedCols(); j++)
{
cout << visit[i][j] << " ";
}
cout << endl;
}
if(g->isGoalReached())
{
cout << "We escaped!" << endl;
}
else
{
cout << "No way out!" << endl;
}
delete b;
delete g;
}
catch(exception& e)
{
cout << e.what() << endl;
}
}
else if(mode=="-dfs")
{
mode2=argv[2];
try
{
b=new MazeReader(mode2);
const char* const* j=b->getMaze();
int k=b->getCols();
int l=b->getRows();
int m=b->getStartCol();
int n=b->getStartRow();
Search o=Search::DFS;
g=new MazeWalker(j, n, m, l, k, o);
g->walkMaze();
const int* const* visit=g->getVisited();
cout << "Starting position: " << b->getStartRow() << "," << b->getStartCol() << endl;
cout << "Size: " << b->getRows() << "," << b->getCols() << endl;
for(int i=0; i< g->getVisitedRows(); i++)
{
for(int j=0; j<g->getVisitedCols(); j++)
{
cout << visit[i][j] << " ";
}
cout << endl;
}
if(g->isGoalReached())
{
cout << "We escaped!" << endl;
}
else
{
cout << "No way out!" << endl;
}
delete b;
delete g;
}
catch(exception& e)
{
cout << e.what() << endl;
}
}
else if (mode == "-test")
{
Test a;
a.runTests();
}
}
else
{
cout << "Please give at least two command arguments." << endl;
}
}
| true |
b77de6ce643236b409373fdd87a49d7a2bceb0cd | C++ | alen0216056/Image_search_by_sketch | /grid.h | UTF-8 | 6,117 | 3.265625 | 3 | [] | no_license | #ifndef __GRID_H__
#define __GRID_H__
#include <queue>
#include <cmath>
#include <vector>
using namespace std;
template<class T>
class grid
{
private:
int w,h,size;
vector<T> map;
public:
grid(int); //given size(default square)
grid(int,int); //given width & height
grid(const vector<T>&); //given vector
int width() const;
int height() const;
void set(int,T);
void set(int,int,T);
T get(int) const;
T get(int,int) const;
T& operator[](int);
T sum() const;
int findNearest(int,int,int) const;
bool operator<(const grid&) const;
bool operator==(const grid&) const;
bool legal(int,int) const;
bool border(int,int) const;
grid<T> mul(const grid<T>&) const;
grid<T> operator+(const grid<T>&) const;
grid<T> operator*(int) const;
grid<T> operator*(double) const;
T operator*(const grid<T>&) const;
void max(const grid<T>&);
void propagate(int, T[]);
void closedFill();
void save(ostream&) const;
};
template<class T>
ostream& operator<<(ostream &os, const grid<T> &rhs);
template<class T>
grid<T>::grid(int s) : size(s)
{
map = vector<T>(size, 0);
w = round(sqrt(size));
h = size / w;
}
template<class T>
grid<T>::grid(int height, int width) : w(width), h(height)
{
size = w*h;
map = vector<T>(size, 0);
}
template<class T>
grid<T>::grid(const vector<T>& vec)
{
map = vec;
size = vec.size();
w = sqrt(size);
h = size / w;
}
template<class T>
int grid<T>::width() const
{
return w;
}
template<class T>
int grid<T>::height() const
{
return h;
}
template<class T>
void grid<T>::set(int idx, T val)
{
map[idx] = val;
}
template<class T>
void grid<T>::set(int i, int j, T val)
{
map[i*w + j] = val;
}
template<class T>
T grid<T>::get(int idx) const
{
return map[idx];
}
template<class T>
T grid<T>::get(int i, int j) const
{
return map[i*w + j];
}
template<class T>
T& grid<T>::operator[](int idx)
{
return map[idx];
}
template<class T>
T grid<T>::sum() const
{
T res = 0;
for (int i = 0; i < size; i++)
res += map[i];
return res;
}
template<class T>
int grid<T>::findNearest(int x, int y, int limit) const
{
int res = limit + 1;
for (int nx = x - limit; nx <= x + limit; nx++)
{
int rem = limit - abs(nx - x);
for (int ny = y - rem; ny <= y + rem; ny++)
if (legal(nx, ny) && get(nx, ny) == 1)
res = min(res, abs(nx - x) + abs(ny - y));
}
return res;
}
template<class T>
bool grid<T>::operator<(const grid& rhs) const
{
if (w != rhs.w || h != rhs.h)
return false;
for (int i = 0; i < w; i++)
for (int j = 0; j < h; j++)
if (get(i, j) != rhs.get(i, j))
return get(i, j) < rhs.get(i, j);
return false;
}
template<class T>
bool grid<T>::operator==(const grid& rhs) const
{
if ( w != rhs.w || h != rhs.h )
return false;
for (int i = 0; i < w; i++)
for (int j = 0; j < h; j++)
if( get(i,j) != rhs.get(i,j) )
return false;
return true;
}
template<class T>
bool grid<T>::legal(int i, int j) const
{
return i < h && j < w && i >= 0 && j >= 0;
}
template<class T>
bool grid<T>::border(int i, int j) const
{
return i == 0 || i == h - 1 || j == 0 || j == w - 1;
}
template<class T>
grid<T> grid<T>::mul(const grid<T>& rhs) const
{
grid<T> res(map.size());
for (int i = 0; i < map.size(); i++)
res[i] = map[i] * rhs.get(i);
return res;
}
template<class T>
grid<T> grid<T>::operator+(const grid<T>& rhs) const
{
grid<T> res(map.size());
for (int i = 0; i < map.size(); i++)
res[i] = map[i] + rhs.get(i);
return res;
}
template<class T>
grid<T> grid<T>::operator*(int fac) const
{
grid<T> res(map.size());
for (int i = 0; i < map.size(); i++)
res[i] = map[i] * fac;
return res;
}
template<class T>
grid<T> grid<T>::operator*(double fac) const
{
grid<T> res(map.size());
for (int i = 0; i < map.size(); i++)
res[i] = map[i] * fac;
return res;
}
template<class T>
T grid<T>::operator*(const grid<T>& rhs) const
{
T res = 0;
for (int i = 0; i < size; i++)
res += map[i] * rhs.get(i);
return res;
}
template<class T>
void grid<T>::max(const grid<T>& rhs)
{
for (int i = 0; i < size; i++)
{
if (map[i] <= 0 && rhs.get(i) <= 0)
map[i] = map[i]<rhs.get(i)? map[i] : rhs.get(i);
else
map[i] = map[i]>rhs.get(i)? map[i] : rhs.get(i);
}
}
template<class T>
void grid<T>::propagate(int depth, T decay[])
{
grid<T> tmp = *this;
for (int i = 0; i < size; i++)
{
int cx = i / w;
int cy = i%w;
for (int x = cx - depth; x <= cx + depth; x++)
{
int rem = depth - abs(x - cx);
for (int y = cy - rem; y <= cy + rem; y++)
{
if (legal(x, y) && (tmp.get(x, y) < decay[abs(x - cx) + abs(y - cy)] * map[i]))
tmp.set(x, y, decay[abs(x - cx) + abs(y - cy)] * map[i]);
}
}
}
for (int i = 0; i < size; i++)
set(i, tmp[i]);
}
template<class T>
void grid<T>::closedFill()
{
const static int neiborX[] = { 1, -1, 0, 0 };
const static int neiborY[] = { 0, 0, 1, -1 };
vector<vector<bool>> visited(h, vector<bool>(w, false));
for (int i = 0; i < h; i++)
for (int j = 0; j < w; j++)
{
if (visited[i][j] || get(i,j) != 0)
continue;
bool needFill = !border(i,j);
T neiMin = 1;
queue<int> Q;
queue<int> fill;
fill.push(i*w+j);
Q.push(i*w + j);
while (!Q.empty())
{
int top = Q.front();
Q.pop();
visited[top/w][top%w] = true;
for (int k = 0; k < 4; k++)
{
int nx = top/w + neiborX[k], ny = top%w + neiborY[k];
if (legal(nx, ny))
{
if (get(nx,ny) != 0)
neiMin = min(neiMin,get(nx,ny));
else if (!visited[nx][ny])
{
Q.push(nx*w + ny);
if (needFill &= !border(nx, ny))
fill.push(nx*w + ny);
}
}
}
}
needFill &= neiMin >= 0.5;
if (needFill)
{
while (!fill.empty())
{
map[fill.front()] = 1;
fill.pop();
}
}
}
}
template<class T>
void grid<T>::save (ostream &file) const
{
for (int i = 0; i < size; i++)
file << setprecision(3) << get(i) << " ";
}
template<class T>
ostream& operator<< (ostream &out, const grid<T>& rhs)
{
for (int i = 0; i < rhs.height(); i++)
{
for (int j = 0; j < rhs.width(); j++)
out << setprecision(3) << rhs.get(i, j) << ",";
out << endl;
}
out << endl;
return out;
}
#endif | true |
fe67f7ad9796c8fb0aed96477f2f69999a5eff56 | C++ | mirnasumopawiro/Challenges-chapter-3 | /8.cpp | UTF-8 | 1,075 | 3.640625 | 4 | [] | no_license | //
// 8.cpp
// Chapter 3 Programming Challenges
//
// Created by Mirna Sumopawiro on 10/12/16.
// Copyright © 2016 Mirna Sumopawiro. All rights reserved.
// The Yukon Widget Company manufactures widgets that weigh 12.5 pounds each. Write a program that calculates how many widgets are stacked on a pallet, based on the total weight of the pallet. The program should ask the user how much the pallet weighs by itself and with the widgets stacked on it. It should then calculate and display the number of widgets stacked on the pallet.
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
const float WIDGET_WEIGHT = 12.5;
float palletWeight;
float palletWeightWidget;
int numWidget;
cout << "How much does the pallet weigh by itself? ";
cin >> palletWeight;
cout << "How much does the pallet weigh with the widgets stacked? ";
cin >> palletWeightWidget;
numWidget = (palletWeightWidget - palletWeight) / WIDGET_WEIGHT;
cout << "There are " << numWidget << " widgets on the pallet.";
return 0;
} | true |
a4077ef684c5043d811cf680376a2322ada749df | C++ | pokutan/eng_train | /EnglishTraining/gen_random.h | UTF-8 | 1,348 | 3.140625 | 3 | [] | no_license | #pragma once
#include <random>
#ifndef CLASS_NO_COPY_NO_MOVE
#define CLASS_NO_COPY_NO_MOVE(__class_name__) \
__class_name__(const __class_name__&) = delete; \
__class_name__& operator =(const __class_name__&) = delete; \
__class_name__& operator =(__class_name__&&) = delete; \
__class_name__(__class_name__&&) = delete;
#endif // CLASS_NO_COPY_NO_MOVE
template<typename t> class gen_random final {
public:
gen_random() : _mt(_rd()), _dist(nullptr){
static_assert(std::is_integral<t>::value, "Integral type required");
static_assert(std::is_arithmetic<t>::value, "Arithmetic type required");
}
gen_random(t min_/*inclusive*/, t max_/*not inclusive*/) : gen_random(){ set_range(min_, max_); }
void set_range(t min_/*inclusive*/, t max_/*not inclusive*/){
if(_dist){
delete _dist;
_dist = nullptr;
}
if(max_ > min_)
_dist = new std::uniform_real_distribution<double>(min_, max_);
}
~gen_random(){ if(_dist)delete _dist; }
operator t(){ return _dist ? (t)(*_dist)(_mt) : 0; }
t rand(){ return (t)*this; }
// copy / move is prohibited
CLASS_NO_COPY_NO_MOVE(gen_random)
private:
std::random_device _rd;
std::mt19937 _mt;
std::uniform_real_distribution<double>* _dist;
};
| true |
cb3e72948547e1e85376334b35eab4912049148d | C++ | hariganesan/zombie-roll | /src/Battle.hpp | UTF-8 | 1,334 | 2.8125 | 3 | [] | no_license | // Hari Ganesan 3/20/13
// zombie-roll: Battle library file
#include "Actor.hpp"
#include <vector>
#include <list>
using std::vector;
using std::list;
class Game;
class View {
string id;
};
class Area {
public:
double averageEnemyLevel;
double battlePercent;
Area(double b) {
battlePercent = b;
}
unsigned int calcEnemyCount() {return rand() % 3 + 1; };
};
class Battle {
unsigned int music;
unsigned int background;
enum {
BMENU_ATTACK,
BMENU_DEFEND,
BMENU_SKILL,
BMENU_ITEM
};
public:
Game *g; // access to public game members (party, etc.)
Area *a; // access to public area members
vector<PartyMember> party; // party list copied from game
vector<Enemy> enemies; // enemy list
list<FightingCharacter> bQueue;// battle queue
FightingCharacter *activeFC; // current FC turn
vector<int> battleMenu; // battle menu for PMs
int selectedBattleMenuItem; // highlighted item
Battle(int ec);
~Battle();
void bQueuePush();
FightingCharacter* bQueuePop();
bool checkHit(const FightingCharacter& c1, const FightingCharacter& c2);
unsigned int calculateDamage(const FightingCharacter& c1,
const FightingCharacter& c2);
// returns true if should advance to next turn
bool attack(FightingCharacter& c1, FightingCharacter& c2, int mp);
string getMenuItemName(const int& item) const;
};
| true |
ede62bcecdb82e3f599fbaf31e3aeca732b98128 | C++ | ag2888/C-- | /code-4/pair.cc | UTF-8 | 1,893 | 3.375 | 3 | [] | no_license | /*
* Object-Oriented Programming
* Copyright (C) 2013 Thomas Wies
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*/
#include <iostream>
template<typename T, typename S>
class pair {
T fst;
S snd;
public:
pair(T f, S s) : fst(f), snd(s) {
std::cout << "pair(" << fst << ", " << snd << ")" << std::endl;
}
pair(const pair& other) : fst(other.fst), snd(other.snd) {
std::cout << "pair(" << other << ")" << std::endl;
}
~pair() {
std::cout << "~pair()" << std::endl;
}
pair& operator=(const pair& other) {
std::cout << "pair::operator=(" << other << ")" << std::endl;
// Check for Self Assignment
if (this != &other) {
fst = other.fst;
snd = other.snd;
}
return *this;
}
template<typename T1, typename S1>
friend std::ostream& operator<<(std::ostream& out, const pair<T1,S1>& p);
};
template<typename T, typename S>
std::ostream& operator<<(std::ostream& out, const pair<T,S>& p) {
out << "<" << p.fst << ", " << p.snd << ">";
return out;
}
pair<int,char> f(int x, char c) {
int z = 3;
pair<int,char> p(x, c);
pair<int,char>* q = new pair<int, char>(p);
delete q;
return p;
}
int main() {
pair<int, char> r = f(3, 'A');
std::cout << "f's return value: " << r << std::endl;
return 0;
}
| true |
3b7471f240ec5e3f81e4006eb6d612b45d527c97 | C++ | magdyali7/gosu | /Gosu/Image.hpp | UTF-8 | 6,076 | 2.875 | 3 | [
"MIT"
] | permissive | //! \file Image.hpp
//! Interface of the Image class and helper functions.
#ifndef GOSU_IMAGE_HPP
#define GOSU_IMAGE_HPP
#include <Gosu/Fwd.hpp>
#include <Gosu/Color.hpp>
#include <Gosu/GraphicsBase.hpp>
#include <Gosu/TR1.hpp>
#include <memory>
#include <vector>
namespace Gosu
{
//! Provides functionality for drawing rectangular images.
class Image
{
std::tr1::shared_ptr<ImageData> data;
public:
//! Loads an image from a given filename.
//!
//! A color key of #ff00ff is automatically applied to BMP image files.
//! For more flexibility, use the corresponding constructor that uses a Bitmap object.
explicit Image(const std::wstring& filename,
unsigned imageFlags = ifSmooth);
//! Loads a portion of the the image at the given filename..
//!
//! A color key of #ff00ff is automatically applied to BMP image files.
//! For more flexibility, use the corresponding constructor that uses a Bitmap object.
Image(const std::wstring& filename, unsigned srcX,
unsigned srcY, unsigned srcWidth, unsigned srcHeight,
unsigned imageFlags = ifSmooth);
//! Converts the given bitmap into an image.
explicit Image(const Bitmap& source,
unsigned imageFlags = ifSmooth);
//! Converts a portion of the given bitmap into an image.
Image(const Bitmap& source, unsigned srcX,
unsigned srcY, unsigned srcWidth, unsigned srcHeight,
unsigned imageFlags = ifSmooth);
//! Creates an Image from a user-supplied instance of the ImageData interface.
explicit Image(GOSU_UNIQUE_PTR<ImageData> data);
unsigned width() const;
unsigned height() const;
//! Draws the image so its upper left corner is at (x; y).
void draw(double x, double y, ZPos z,
double factorX = 1, double factorY = 1,
Color c = Color::WHITE,
AlphaMode mode = amDefault) const;
//! Like draw(), but with modulation colors for all four corners.
//! TODO: This can be an overload of draw() - in any case the name is terrible.
void drawMod(double x, double y, ZPos z,
double factorX, double factorY,
Color c1, Color c2, Color c3, Color c4,
AlphaMode mode = amDefault) const;
//! Draws the image rotated by the given angle so that its rotation
//! center is at (x; y). Note that this is different from how all the
//! other drawing functions work!
//! \param angle See Math.hpp for an explanation of how Gosu interprets
//! angles.
//! \param centerX Relative horizontal position of the rotation center
//! on the image. 0 is the left border, 1 is the right border, 0.5 is
//! the center (and default).
//! \param centerY See centerX.
void drawRot(double x, double y, ZPos z,
double angle, double centerX = 0.5, double centerY = 0.5,
double factorX = 1, double factorY = 1,
Color c = Color::WHITE,
AlphaMode mode = amDefault) const;
#ifndef SWIG
//! Provides access to the underlying image data object.
ImageData& getData() const;
GOSU_DEPRECATED Image(Graphics& graphics, const std::wstring& filename,
bool tileable = false);
GOSU_DEPRECATED Image(Graphics& graphics, const std::wstring& filename, unsigned srcX,
unsigned srcY, unsigned srcWidth, unsigned srcHeight,
bool tileable = false);
GOSU_DEPRECATED Image(Graphics& graphics, const Bitmap& source,
bool tileable = false);
GOSU_DEPRECATED Image(Graphics& graphics, const Bitmap& source, unsigned srcX,
unsigned srcY, unsigned srcWidth, unsigned srcHeight,
bool tileable = false);
#endif
};
#ifndef SWIG
//! Convenience function that slices an image file into a grid and creates images from them.
//! \param tileWidth If positive, specifies the width of one tile in pixels.
//! If negative, the bitmap is divided into -tileWidth rows.
//! \param tileHeight See tileWidth.
std::vector<Gosu::Image> loadTiles(const Bitmap& bmp,
int tileWidth, int tileHeight, unsigned imageFlags = ifSmooth);
//! Convenience function that slices a bitmap into a grid and creates images from them.
//! \param tileWidth If positive, specifies the width of one tile in pixels.
//! If negative, the bitmap is divided into -tileWidth rows.
//! \param tileHeight See tileWidth.
std::vector<Gosu::Image> loadTiles(const std::wstring& filename,
int tileWidth, int tileHeight, unsigned imageFlags = ifSmooth);
GOSU_DEPRECATED std::vector<Gosu::Image> loadTiles(Graphics& graphics, const Bitmap& bmp, int tileWidth, int tileHeight, bool tileable);
GOSU_DEPRECATED std::vector<Gosu::Image> loadTiles(Graphics& graphics, const std::wstring& bmp, int tileWidth, int tileHeight, bool tileable);
template<typename Container>
GOSU_DEPRECATED void imagesFromTiledBitmap(Graphics& graphics, const std::wstring& filename, int tileWidth, int tileHeight, bool tileable, Container& appendTo)
{
std::vector<Gosu::Image> tiles = loadTiles(graphics, filename, tileWidth, tileHeight, tileable);
for (int i = 0, num = tiles.size(); i < num; ++i)
appendTo.push_back(typename Container::value_type(new Gosu::Image(tiles[i])));
}
template<typename Container>
GOSU_DEPRECATED void imagesFromTiledBitmap(Graphics& graphics, const Bitmap& bmp,
int tileWidth, int tileHeight, bool tileable, Container& appendTo)
{
std::vector<Gosu::Image> tiles = loadTiles(graphics, bmp, tileWidth, tileHeight, tileable);
for (int i = 0, num = tiles.size(); i < num; ++i)
appendTo.push_back(typename Container::value_type(new Gosu::Image(tiles[i])));
}
#endif
}
#endif
| true |
87602c044dc73b7f52cf16018f3a1b616fd2f7ac | C++ | aaniket/CNS | /playfair.cpp | UTF-8 | 1,389 | 2.65625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
char grid[5][5];
int marked[26];
void fill(string key){
for(int f=0;f<26;f++){
marked[f]=0;
}
for(int i=0;i<5;i++){for(int j=0;j<5;j++){grid[i][j]='`';}}
int i=0,j=0;
int l=key.length();
for(int k=0;k<l;k++){
if(marked[key[k]-'a']==0){
marked[key[k]-'a']=1;
grid[i][j]=key[k];
j++;
if(j==5){
i++;
j=0;
}
}
}
for(int x=0;x<5;x++){
for(int y=0;y<5;y++){
if(grid[x][y]=='`'){
for(int k=0;k<26;k++){
if(marked[k]==0){
marked[k]=1;
grid[x][y]=(char)(k+'a');
break;
}
}
}
}
for(int i=0;i<5;i++){for(int j=0;j<5;j++){cout<<grid[i][j]<<" ";}cout<<endl;}
}
}
/*
string playfairE(string s){
int l=s.length();
string ret,res;
for(int i=0;i<l-1;i++){
if(s[i]==s[i+1]){
ret[i]=s[i];
ret[i+1]='x';
}
else{
ret[i]=s[i];
ret[i+1]=s[i+1];
i++;
}
}
int l1=ret.length();
if(ret.length()%2==1)ret+='x';
for(int i=0;i<l1;i++){
int r1=getRow(ret[i]);
int c1=getCol(ret[i]);
int r2=getRow(ret[i+1]);
int c2=getCol(ret[i+1]);
if(r1==r2){
res[i]=grid[r1][(c1+1)%5];
res[i+1]=grid[r2][(c2+1)%5];
}
else if(c1==c2){
res[i]=grid[(r1+1)%5][c1];
res[i+1]=grid[(r2+1)%5][c2];
}
else{
res[i]=grid[r1][c2];
res[i+1]=grid[r2][c1];
}
}
}*/
int main(){
string key;
cout<<"Enter key: ";
cin>>key;
fill(key);
return 0;
}
| true |
bb5e11cd56d7162c06373a0bb263002574e2011b | C++ | masdevas/algostruct-old | /algostruct/tests/unit/sort/k_merge_sort.cpp | UTF-8 | 1,172 | 2.984375 | 3 | [] | no_license | #include <gtest/gtest.h>
#include <algorithm>
#include "sort/k_merge_sort.h"
#include "data_generation.h"
TEST(TEST_K_MERGE_SORT, RANDOM_TEST) {
size_t size = 1000;
size_t count_parts = 100;
using DataType = double;
double lower_bound = 0, upper_bound = 10000;
auto data = GenerateRandomVectorReal(size, lower_bound, upper_bound);
auto copy_of_data = data;
auto comp = [](const DataType& data_first, const DataType& data_second) {
return data_first < data_second;
};
KMergeSort(data.begin(), data.end(), comp, count_parts);
std::sort(copy_of_data.begin(), copy_of_data.end(), comp);
EXPECT_EQ(data, copy_of_data);
}
TEST(TEST_DHEAP_SORT, RANDOM_TEST_STRING) {
size_t size = 1000, count_symbols = 20;
size_t count_parts = 100;
auto data = GenerateRandomStrings(size, count_symbols);
auto copy_of_data = data;
auto comp = [](const std::string& data_first, const std::string& data_second) {
return data_first < data_second;
};
KMergeSort(data.begin(), data.end(), comp, count_parts);
std::sort(copy_of_data.begin(), copy_of_data.end(), comp);
EXPECT_EQ(data, copy_of_data);
}
| true |
40b89d2605bc8e42257723297102a000dd2848f7 | C++ | James3039/OhMyCodes | /Others/Mssctf2020/PPC3.cpp | UTF-8 | 642 | 2.578125 | 3 | [
"MIT"
] | permissive | #include <cstdio>
#include <iostream>
using namespace std;
string s, subs[100005];
int t, n, len, les;
int main(){
scanf("%d", &t);
for(int i=0; i<t; i++){
scanf("%d", &n);
cin >> s;
len=s.length();
les=len-((len/n)*n);
for(int i=0; i<les; i++){
subs[i]=s.substr(i*(len/n+1), len/n+1);
}
for(int i=les; i<n; i++){
subs[i]=s.substr(les*(len/n+1)+(i-les)*(len/n), len/n);
}
for(int i=0; i<len/n; i++){
for(int j=0; j<n; j++){
cout << subs[j][i];
}
}
for(int i=0; i<les; i++){
cout << subs[i][len/n];
}
cout << endl;
/* for(int i=0; i<n; i++){
cout << subs[i] << endl;
}*/
}
return 0;
}
| true |
c0e4c4b670ff0a90cc33db3de1a5cbb3fb564757 | C++ | Xerewulf/Summerize-your-money-with-file | /Summerize your money/lab8filesneredeydimbenböyle/Source.cpp | ISO-8859-9 | 1,008 | 3.015625 | 3 | [] | no_license | #define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
// banlnot sayc
void divade(int num,int *num1, int *num2, int *num3, int *num4, int *num5) {
*num1 = num/100;
*num2 = num % 100 / 50;
*num3 = num % 50 / 20;
*num4 = num % 20 / 10;
*num5 = num % 10 / 5;
}
int main() {
int stat,num,num1,num2,num3,num4,num5;
FILE* money;
money = fopen("Amount.txt", "r");
if (money == 0)
printf("i didnt even hear that files");
else {
stat = fscanf(money, "%d", &num);
while (stat != EOF) {
if (num % 5 != 0) {
printf("it isnt divide by 5");
}
else
divade(num, &num1, &num2, &num3, &num4, &num5);
if (num1 != 0)
printf("%d-hundert||", num1);
if (num2 != 0)
printf("%d-fifty||", num2);
if (num3 != 0)
printf("%d-twenty||", num3);
if (num4 != 0)
printf("%d-ten||", num4);
if (num5 != 0)
printf("%d-five\n", num5);
stat = fscanf(money, "%d", &num);
}
fclose(money);
}
return 0;
} | true |
e99c3d3e9e334bc0bf220bf57c28493986304200 | C++ | goofi0211/datastructure | /ncku oj/探望麻衣.cpp | UTF-8 | 1,261 | 2.703125 | 3 | [] | no_license | #include<iostream>
#include<vector>
#include<queue>
#include<algorithm>
const int maxn=500000;
using namespace std;
int main(){
vector<vector<int>> adj;
int city,edge;
cin>>city>>edge;
vector<pair<int,int>>dis;
for(int i=0;i<=city;i++){
vector<int> temp;
for (int j=0;j<=city;j++){
if(i==j)
temp.push_back(0);
else
temp.push_back(maxn);
}
adj.push_back(temp);
}
for(int i=0;i<edge;i++){
int c1,c2,range;
cin>>c1>>c2>>range;
adj[c1][c2]=range;
adj[c2][c1]=range;
}
for(int i=0;i<city;i++){
dis.push_back({maxn,i});
}
dis[0]=make_pair(0,0);
int t=0;
for(int i=1;i<=city-1;i++){
//choose small
sort(dis.begin(),dis.end());
int scity=dis[t].second;
int scitycost=dis[t].first;
for(int i=0;i<city;i++)
{
if(dis[i].first>adj[scity][dis[i].second]+scitycost){
dis[i].first=adj[scity][dis[i].second]+scitycost;
}
}
t+=1;
}
for(int i=0;i<city;i++)
for(auto it:dis){
if (it.second==i)
cout<<it.first<<" ";
}
cout<<endl;
}
| true |
6cf8ded26d9131658b6f713874bd9caee4792578 | C++ | Stukeley/spoj-csharp | /SUMAN.cpp | WINDOWS-1252 | 226 | 2.6875 | 3 | [] | no_license | // Obviously this isn't C# either, but that wasn't my choice \_(?)_/
//131 points
#include <iostream>
using namespace std;
int main()
{
int n;
while (cin>>n)
cout<<((1+n)/(float)2)*n<<endl;
return 0;
}
| true |
0e7b9d1fd1e57df61e47863e87b087b445db0be4 | C++ | menanagy/Algorithms | /C++/Linear_Search/main.cpp | UTF-8 | 723 | 4.03125 | 4 | [] | no_license | #include <iostream>
using namespace std;
int search(int arr[], int sizeArray, int element)
{
int index;
for (index = 0; index < sizeArray; index++)
if (arr[index] == element)
return index;
return -1;
}
// Driver code
int main(void)
{
int arr[] = { 2, 3, 4, 10, 40 };
int element = 0;
cout<<"Enter the Element you want to search for it :: ";
cin>>element;
int sizeArray = sizeof(arr) / sizeof(arr[0]);
// Function call
int result = search(arr, sizeArray, element);
if(result == -1){
cout << "Element is not present in array...";
}
else{
cout << "Yes it Here :) Element is present at index : " << result<<"...";
}
return 0;
}
| true |
5a07cd5ea94d96ca2427f51fd2d493a8a57fccd7 | C++ | HardPlant/DataStructure | /ConsoleApplication3/1.cpp | UHC | 881 | 3.359375 | 3 | [] | no_license | #include <iostream>
#include <string>
using namespace std;
class Coffee {
public:
Coffee()
{
cout << "<Ŀ>" << endl;
}
};
class Latte : public Coffee {
public:
Latte()
{
print("");
}
void print(string n) // κ̹Ƿ Coffee ű .
{
cout << n << " Դϴ." << endl;
}
};
class Mocha : public Coffee {
public:
Mocha()
{
print("ī");
}
void print(string n)
{
cout << n << " Դϴ." << endl;
}
};
class Cappuccino : public Coffee {
public:
Cappuccino()
{
print("īǪġ");
}
void print(string n)
{
cout << n << " Դϴ." << endl;
}
};
class Americano : public Coffee {
public:
Americano()
{
print("Ƹī");
}
void print(string n)
{
cout << n << " Դϴ." << endl;
}
};
int main()
{
Americano a;
Cappuccino c;
Latte l;
Mocha m;
return 0;
}
| true |
9138a8595da164a216e57b67a72cfea492a947d4 | C++ | aphill70/ckWC1984 | /inc/StopWords.h | UTF-8 | 914 | 2.890625 | 3 | [] | no_license |
#ifndef STOPWORDS_H
#define STOPWORDS_H
#include <string>
#include <iostream>
#include <fstream>
using namespace std;
/*
*
*
*
*
*
*/
class StopWords{
private:
int containerSize;
string* stopwords;
int lineCount;
public:
// default constructor
StopWords();
// default constructor
StopWords(string fileName);
// destructor
~StopWords();
int getsize();
// uses bsearch to figure out if the array
// contains the word or not return
bool contains(string word);
bool test(ostream & os);
private:
// give the file name for the stop words file
// loads up the stop words file in an ordered array
// handles growing the array as needed
bool loadfile(string fileName);
void growarray();
//int comparestrs(const void * a, const void * b);
};
#endif
| true |
b9724acc8d40b7dd54b1696d4ed571a7748c0ea0 | C++ | sopyer/Shadowgrounds | /game/UnitInventory.h | UTF-8 | 1,595 | 3.109375 | 3 | [] | no_license |
#ifndef UNITINVENTORY_H
#define UNITINVENTORY_H
namespace game
{
class Game;
class Unit;
class Item;
class UnitInventory
{
public:
// returns true on success, if an item was added
static bool giveUnitItem(Game *game, Unit *unit, const char *itemName);
// returns true on success, if an item was removed
static bool removeUnitItem(Game *game, Unit *unit, const char *itemName);
// returns true on success, if an item was used
static bool useSelectedUnitItem(Game *game, Unit *unit);
// returns true on success, if an item was used
static bool useUnitItem(Game *game, Unit *unit, const char *itemName);
// returns item count or zero if unit has no such item - or if item by that name does not exist (error)
static int getUnitItemCount(Game *game, Unit *unit, const char *itemName);
// returns items unit is holding
static void getUnitItems(Game *game, Unit *unit, std::vector<std::string> &itemNames);
// sets item count to given value (and removes/adds items if necessary, if zero/nonzero)
static void setUnitItemCount(Game *game, Unit *unit, const char *itemName, int amount);
// returns true on success
static bool selectUnitItem(Game *game, Unit *unit, const char *itemName);
// should always succeed, thus no return value)
static void deselectUnitItem(Game *game, Unit *unit);
// returns true if selected item is of given type name
static bool isSelectedUnitItem(Game *game, Unit *unit, const char *itemName);
private:
static void useUnitItemImpl(Game *game, Unit *unit, int itemNumber);
};
}
#endif
| true |
2032e1580ad35d13bafcc80d6e86519ae641ec77 | C++ | wuolayuju/BluetoothArduinoShowcase | /arduino/BT_Android_Control_LEDS/BT_Android_Control_LEDS.ino | UTF-8 | 989 | 3.15625 | 3 | [] | no_license | String readString;
char c;
int redLED = 10;
int yellowLED = 11;
int greenLED = 12;
void setup() {
pinMode(redLED,OUTPUT);
pinMode(yellowLED,OUTPUT);
pinMode(greenLED,OUTPUT);
Serial.begin(115200);
Serial.println("Ready for connection");
Serial.println("Go on, type something");
}
void loop() {
while(Serial.available()){
delay(3);
c = Serial.read();
readString += c;
}
if (readString.length() > 0) {
Serial.print("Char ----> ");
Serial.write(c);
Serial.println("\nString ----> " + readString);
parseCommand(readString);
readString = "";
}
}
void parseCommand(String command) {
char whichLED = command.charAt(0);
String actionString = command.substring(1);
int pinLED;
switch (whichLED) {
case 'r':
pinLED = redLED;
break;
case 'y':
pinLED = yellowLED;
break;
case 'g':
pinLED = greenLED;
break;
}
int brigthness = actionString.toInt();
analogWrite(pinLED, brigthness);
}
| true |
01bd994833f2d8661aafde602b0c6be655b97536 | C++ | meniossin/src | /third_party/angle/src/tests/gl_tests/AttributeLayoutTest.cpp | UTF-8 | 12,889 | 2.8125 | 3 | [
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | //
// Copyright 2018 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// AttributeLayoutTest:
// Test various layouts of vertex attribute data:
// - in memory, in buffer object, or combination of both
// - float, integer, or combination of both
// - sequential or interleaved
#include <array>
#include <vector>
#include "test_utils/ANGLETest.h"
#include "test_utils/gl_raii.h"
using namespace angle;
namespace
{
// Test will draw these four triangles.
// clang-format off
const GLfloat triangleData[] = {
// xy rgb
0,0, 1,1,0,
-1,+1, 1,1,0,
+1,+1, 1,1,0,
0,0, 0,1,0,
+1,+1, 0,1,0,
+1,-1, 0,1,0,
0,0, 0,1,1,
+1,-1, 0,1,1,
-1,-1, 0,1,1,
0,0, 1,0,1,
-1,-1, 1,0,1,
-1,+1, 1,0,1,
};
// clang-format on
constexpr size_t kNumVertices = ArraySize(triangleData) / 5;
// A container for one or more vertex attributes.
class Container
{
public:
static constexpr size_t kSize = 1024;
void open(void) { memset(mMemory, 0xff, kSize); }
void fill(size_t numItem, size_t itemSize, const char *src, unsigned offset, unsigned stride)
{
while (numItem--)
{
ASSERT(offset + itemSize <= kSize);
memcpy(mMemory + offset, src, itemSize);
src += itemSize;
offset += stride;
}
}
virtual void close(void) {}
virtual ~Container() {}
virtual const char *getAddress() = 0;
virtual GLuint getBuffer() = 0;
protected:
char mMemory[kSize];
};
// Vertex attribute data in client memory.
class Memory : public Container
{
public:
const char *getAddress() override { return mMemory; }
GLuint getBuffer() override { return 0; }
};
// Vertex attribute data in buffer object.
class Buffer : public Container
{
public:
void close(void) override
{
glBindBuffer(GL_ARRAY_BUFFER, mBuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(mMemory), mMemory, GL_STATIC_DRAW);
}
const char *getAddress() override { return nullptr; }
GLuint getBuffer() override { return mBuffer; }
protected:
GLBuffer mBuffer;
};
// clang-format off
template<class Type> struct GLType {};
template<> struct GLType<GLbyte > { static constexpr GLenum kGLType = GL_BYTE; };
template<> struct GLType<GLubyte > { static constexpr GLenum kGLType = GL_UNSIGNED_BYTE; };
template<> struct GLType<GLshort > { static constexpr GLenum kGLType = GL_SHORT; };
template<> struct GLType<GLushort> { static constexpr GLenum kGLType = GL_UNSIGNED_SHORT; };
template<> struct GLType<GLfloat > { static constexpr GLenum kGLType = GL_FLOAT; };
// clang-format on
// Encapsulates the data for one vertex attribute, where it lives, and how it is layed out.
class Attrib
{
public:
template <class T>
Attrib(std::shared_ptr<Container> container, unsigned offset, unsigned stride, const T &data)
: mContainer(container),
mOffset(offset),
mStride(stride),
mData(reinterpret_cast<const char *>(data.data())),
mDimension(data.size() / kNumVertices),
mAttribSize(mDimension * sizeof(typename T::value_type)),
mGLType(GLType<typename T::value_type>::kGLType)
{
// Compiler complains about unused variable without these.
(void)GLType<GLbyte>::kGLType;
(void)GLType<GLubyte>::kGLType;
(void)GLType<GLshort>::kGLType;
(void)GLType<GLushort>::kGLType;
(void)GLType<GLfloat>::kGLType;
}
void openContainer(void) const { mContainer->open(); }
void fillContainer(void) const
{
mContainer->fill(kNumVertices, mAttribSize, mData, mOffset, mStride);
}
void closeContainer(void) const { mContainer->close(); }
void enable(unsigned index) const
{
glBindBuffer(GL_ARRAY_BUFFER, mContainer->getBuffer());
glVertexAttribPointer(index, static_cast<int>(mDimension), mGLType, GL_FALSE, mStride,
mContainer->getAddress() + mOffset);
glEnableVertexAttribArray(index);
}
bool inClientMemory(void) const { return mContainer->getAddress() != nullptr; }
protected:
std::shared_ptr<Container> mContainer;
unsigned mOffset;
unsigned mStride;
const char *mData;
size_t mDimension;
size_t mAttribSize;
GLenum mGLType;
};
typedef std::vector<Attrib> TestCase;
void PrepareTestCase(const TestCase &tc)
{
for (const Attrib &a : tc)
{
a.openContainer();
}
for (const Attrib &a : tc)
{
a.fillContainer();
}
for (const Attrib &a : tc)
{
a.closeContainer();
}
unsigned i = 0;
for (const Attrib &a : tc)
{
a.enable(i++);
}
}
template <class Type, size_t Dimension>
using VertexData = std::array<Type, Dimension * kNumVertices>;
class AttributeLayoutTest : public ANGLETest
{
protected:
AttributeLayoutTest() : mProgram(0)
{
setWindowWidth(128);
setWindowHeight(128);
setConfigRedBits(8);
setConfigGreenBits(8);
setConfigBlueBits(8);
setConfigAlphaBits(8);
}
void PrepareVertexData(void);
void GetTestCases(void);
void SetUp() override
{
ANGLETest::SetUp();
glClearColor(.2f, .2f, .2f, .0f);
glClear(GL_COLOR_BUFFER_BIT);
glDisable(GL_DEPTH_TEST);
const std::string vertexSource =
"attribute mediump vec2 coord;\n"
"attribute mediump vec3 color;\n"
"varying mediump vec3 vcolor;\n"
"void main(void)\n"
"{\n"
" gl_Position = vec4(coord, 0, 1);\n"
" vcolor = color;\n"
"}\n";
const std::string fragmentSource =
"varying mediump vec3 vcolor;\n"
"void main(void)\n"
"{\n"
" gl_FragColor = vec4(vcolor, 0);\n"
"}\n";
mProgram = CompileProgram(vertexSource, fragmentSource);
ASSERT_NE(0u, mProgram);
glUseProgram(mProgram);
glGenBuffers(1, &mIndexBuffer);
PrepareVertexData();
GetTestCases();
}
void TearDown() override
{
mTestCases.clear();
glDeleteProgram(mProgram);
glDeleteBuffers(1, &mIndexBuffer);
ANGLETest::TearDown();
}
virtual bool Skip(const TestCase &) { return false; }
virtual void Draw(int firstVertex, unsigned vertexCount, const GLushort *indices) = 0;
void Run(bool drawFirstTriangle)
{
glViewport(0, 0, getWindowWidth(), getWindowHeight());
glUseProgram(mProgram);
for (unsigned i = 0; i < mTestCases.size(); ++i)
{
if (Skip(mTestCases[i]))
continue;
PrepareTestCase(mTestCases[i]);
glClear(GL_COLOR_BUFFER_BIT);
std::string testCase;
if (drawFirstTriangle)
{
Draw(0, kNumVertices, mIndices);
testCase = "draw";
}
else
{
Draw(3, kNumVertices - 3, mIndices + 3);
testCase = "skip";
}
testCase += " first triangle case ";
int w = getWindowWidth() / 4;
int h = getWindowHeight() / 4;
if (drawFirstTriangle)
{
EXPECT_PIXEL_EQ(w * 2, h * 3, 255, 255, 0, 0) << testCase << i;
}
else
{
EXPECT_PIXEL_EQ(w * 2, h * 3, 51, 51, 51, 0) << testCase << i;
}
EXPECT_PIXEL_EQ(w * 3, h * 2, 0, 255, 0, 0) << testCase << i;
EXPECT_PIXEL_EQ(w * 2, h * 1, 0, 255, 255, 0) << testCase << i;
EXPECT_PIXEL_EQ(w * 1, h * 2, 255, 0, 255, 0) << testCase << i;
}
}
static const GLushort mIndices[kNumVertices];
GLuint mProgram;
GLuint mIndexBuffer;
std::vector<TestCase> mTestCases;
VertexData<GLfloat, 2> mCoord;
VertexData<GLfloat, 3> mColor;
VertexData<GLbyte, 3> mBColor;
};
const GLushort AttributeLayoutTest::mIndices[kNumVertices] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
void AttributeLayoutTest::PrepareVertexData(void)
{
mCoord.fill(0);
mColor.fill(0);
mBColor.fill(0);
for (unsigned i = 0; i < kNumVertices; ++i)
{
GLfloat x = triangleData[i * 5 + 0];
GLfloat y = triangleData[i * 5 + 1];
GLfloat r = triangleData[i * 5 + 2];
GLfloat g = triangleData[i * 5 + 3];
GLfloat b = triangleData[i * 5 + 4];
mCoord[i * 2 + 0] = x;
mCoord[i * 2 + 1] = y;
mColor[i * 3 + 0] = r;
mColor[i * 3 + 1] = g;
mColor[i * 3 + 2] = b;
mBColor[i * 3 + 0] = r;
mBColor[i * 3 + 1] = g;
mBColor[i * 3 + 2] = b;
}
}
void AttributeLayoutTest::GetTestCases(void)
{
std::shared_ptr<Container> M0 = std::make_shared<Memory>();
std::shared_ptr<Container> M1 = std::make_shared<Memory>();
std::shared_ptr<Container> B0 = std::make_shared<Buffer>();
std::shared_ptr<Container> B1 = std::make_shared<Buffer>();
// 0. two buffers
mTestCases.push_back({Attrib(B0, 0, 8, mCoord), Attrib(B1, 0, 12, mColor)});
// 1. two memory
mTestCases.push_back({Attrib(M0, 0, 8, mCoord), Attrib(M1, 0, 12, mColor)});
// 2. one memory, sequential
mTestCases.push_back({Attrib(M0, 0, 8, mCoord), Attrib(M0, 96, 12, mColor)});
// 3. one memory, interleaved
mTestCases.push_back({Attrib(M0, 0, 20, mCoord), Attrib(M0, 8, 20, mColor)});
// 4. buffer and memory
mTestCases.push_back({Attrib(B0, 0, 8, mCoord), Attrib(M0, 0, 12, mColor)});
// 5. stride != size
mTestCases.push_back({Attrib(B0, 0, 16, mCoord), Attrib(B1, 0, 12, mColor)});
if (IsVulkan())
{
std::cout << "cases skipped on Vulkan: integer data, non-zero buffer offsets" << std::endl;
return;
}
// 6. one buffer, sequential
mTestCases.push_back({Attrib(B0, 0, 8, mCoord), Attrib(B0, 96, 12, mColor)});
// 7. one buffer, interleaved
mTestCases.push_back({Attrib(B0, 0, 20, mCoord), Attrib(B0, 8, 20, mColor)});
// 8. memory and buffer, float and integer
mTestCases.push_back({Attrib(M0, 0, 8, mCoord), Attrib(B0, 0, 12, mBColor)});
// 9. buffer and memory, unusual offset and stride
mTestCases.push_back({Attrib(B0, 11, 13, mCoord), Attrib(M0, 23, 17, mColor)});
}
class AttributeLayoutNonIndexed : public AttributeLayoutTest
{
void Draw(int firstVertex, unsigned vertexCount, const GLushort *indices) override
{
glDrawArrays(GL_TRIANGLES, firstVertex, vertexCount);
}
};
class AttributeLayoutMemoryIndexed : public AttributeLayoutTest
{
void Draw(int firstVertex, unsigned vertexCount, const GLushort *indices) override
{
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
glDrawElements(GL_TRIANGLES, vertexCount, GL_UNSIGNED_SHORT, indices);
}
};
class AttributeLayoutBufferIndexed : public AttributeLayoutTest
{
void Draw(int firstVertex, unsigned vertexCount, const GLushort *indices) override
{
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mIndexBuffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(*mIndices) * vertexCount, indices,
GL_STATIC_DRAW);
glDrawElements(GL_TRIANGLES, vertexCount, GL_UNSIGNED_SHORT, nullptr);
}
};
TEST_P(AttributeLayoutNonIndexed, Test)
{
Run(true);
if (IsWindows() && IsAMD() && IsOpenGL())
{
std::cout << "test skipped on Windows ATI OpenGL: non-indexed non-zero vertex start"
<< std::endl;
return;
}
Run(false);
}
TEST_P(AttributeLayoutMemoryIndexed, Test)
{
Run(true);
if (IsWindows() && IsAMD() && (IsOpenGL() || GetParam() == ES2_D3D11_FL9_3()))
{
std::cout << "test skipped on Windows ATI OpenGL and D3D11_9_3: indexed non-zero vertex start"
<< std::endl;
return;
}
Run(false);
}
TEST_P(AttributeLayoutBufferIndexed, Test)
{
Run(true);
if (IsWindows() && IsAMD() && (IsOpenGL() || GetParam() == ES2_D3D11_FL9_3()))
{
std::cout << "test skipped on Windows ATI OpenGL and D3D11_9_3: indexed non-zero vertex start"
<< std::endl;
return;
}
Run(false);
}
#define PARAMS \
ES2_VULKAN(), ES2_OPENGL(), ES2_D3D9(), ES2_D3D11(), ES2_D3D11_FL9_3(), ES3_OPENGL(), \
ES2_OPENGLES(), ES3_OPENGLES()
ANGLE_INSTANTIATE_TEST(AttributeLayoutNonIndexed, PARAMS);
ANGLE_INSTANTIATE_TEST(AttributeLayoutMemoryIndexed, PARAMS);
ANGLE_INSTANTIATE_TEST(AttributeLayoutBufferIndexed, PARAMS);
} // anonymous namespace
| true |
eb7a9f02f3360bc038e63ee51d728d57e8151b46 | C++ | Han-songyang/cpp | /c++.3.20/c++.3.20/c++.3.20.cpp | GB18030 | 678 | 3.515625 | 4 | [] | no_license | #include <iostream>
#include <string>
using namespace std;
void test1()
{
string str = "12345";
//ʼλõĵ
string::iterator it = str.begin();
for (; it != str.end(); it++)
{
//Ľ
cout << *it << " " ;
}
}
void test2()
{
string str="12345";
string::reverse_iterator it = str.rbegin();
while (it != str.rend())
{
cout << *it << " ";
++it;
}
string str2 = "12345";
string::const_reverse_iterator cit = str.crbegin();
//*cit = 'a';
}
void test3()
{
//Χfor
string str = "12345";
for ( auto& ch : str)
{
cout << ch << " " << endl;
ch = 'a';
}
cout << str << endl;
}
int main()
{
test3();
return 0;
} | true |
c5c87c4998e600dbf285618aa123fd2e76c548e1 | C++ | manishmotwani2002/30dayschallenge | /day 13 (DP)/knapsack 0 1 recursive.cpp | UTF-8 | 1,080 | 3.328125 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
// } Driver Code Ends
// Returns the maximum value that
// can be put in a knapsack of capacity W
int max(int a,int b)
{
return a>b ? a : b;
}
int knapSack(int W, int wt[], int val[], int n)
{
if(n==0 || W==0)
return 0;
if(wt[n-1]<=W)
{
return max(val[n-1]+knapSack(W-wt[n-1],wt,val,n-1), knapSack(W,wt,val,n-1));
}
else
return knapSack(W,wt,val,n-1);
}
// { Driver Code Starts.
int main()
{
//taking total testcases
int t;
cin>>t;
while(t--)
{
//reading number of elements and weight
int n, w;
cin>>n>>w;
int val[n];
int wt[n];
//inserting the values
for(int i=0;i<n;i++)
cin>>val[i];
//inserting the weights
for(int i=0;i<n;i++)
cin>>wt[i];
//calling method knapSack()
cout<<knapSack(w, wt, val, n)<<endl;
}
return 0;
} // } Driver Code Ends
| true |
3015a3b1403a9b9934bda86e37404ebaa5ad64d9 | C++ | RainforZurich/CCpp2017 | /practices/cpp/level1/p01_Queue/main.cpp | UTF-8 | 453 | 3 | 3 | [] | no_license | #include "queue.h"
#include <iostream>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char** argv) {
Queue queue;
int data[100];
int i=0;
while(1)
{
queue.isEmpty();
cout <<"please input the numbers";
cin >> data[i];
if(!queue.isFull())
{
i++;
}
if(queue.isFull())
{
queue.append(data[i]);
}
queue.Show();
}
return 0;
}
| true |
ce976ddb2ff731fff1e7f4dfa0701bbb0bde9378 | C++ | gowtham1197/ncrwork | /Data Structures/cqueue.cpp | UTF-8 | 2,003 | 3.796875 | 4 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
class queuee
{
int *arr,size,rear,front;
public:
queuee()
{
rear=front=-1;
size=0;
arr=NULL;
}
void getsize(int n)
{
arr=new int[n];
size=n;
}
bool underflow()
{
if(rear==front&&front==-1)
return true;
else
return false;
}
bool overflow()
{
if(front==(rear+1)%size)
return true;
else
return false;
}
void enque(int ele)
{
if(overflow())
{
cout<<"Queue is Full\n";
}
else
{
if(underflow())
{
rear=front=0;
arr[rear]=ele;
}
else
{
rear=(rear+1)%size;
arr[rear]=ele;
}
}
}
int deque()
{
int x=-99;
if(underflow())
{
cout<<"Queue is Empty\n";
}
else
{
if(rear==front)
{
x=arr[rear];
rear=front=-1;
}
else
{
x=arr[front];
front=(front+1)%size;
}
}
return x;
}
void display()
{
int i;
if(!underflow()){
for(i=front;i!=rear;i=(i+1)%size)
{
cout<<arr[i]<<" ";
}
cout<<arr[i]<<" ";
cout<<endl;
}
else{
cout<<"Queue is Empty\n";
}
}
~queuee(){
delete arr;
}
};
int main()
{
queuee q;
int s;
cout<<"Enter the size of the queue : ";
cin>>s;
cout<<"You have entered the size as "<<s<<endl;
q.getsize(s);
while(1)
{
int ch;
cout<<"Enter the operation to be performed\n1.Enque\n2.Deque\n3.Is overflow\n4.Is underflow\n5.Display\n6.Exit\n";
cin>>ch;
switch(ch)
{
case 1:int ele;
cout<<"Enter the element to enque : ";
cin>>ele;
q.enque(ele);
break;
case 2: int x;
x=q.deque();
cout<<x<<" is dequeued\n";
break;
case 3: if(q.overflow())
cout<<"It is overflowed\n";
else
cout<<"Not overflowed\n";
break;
case 4: if(q.underflow())
cout<<"It is underflowed\n";
else
cout<<"Not underflowed\n";
break;
case 5:q.display();
break;
case 6:exit(0);
default:cout<<"Enter correct option\n";
break;
}
}
return 0;
}
| true |
6e6370412cc4d93c55531f62f8e793afd8d1acf9 | C++ | kennykyliu/sudoku-solver | /unitest-SudokuValidator.cpp | UTF-8 | 1,205 | 3.53125 | 4 | [] | no_license | #include "util.h"
#include "sudoku-validator.h"
int main() {
ifstream dataFile;
dataFile.open("sudoku-data.txt");
vector<vector<int> > board(9, vector<int>(9, 0));
int row = 0;
int col = 0;
int num = 0;
if (!dataFile.good()) {
cout << "Fail to open file [sudoku-data.txt]." << endl;
return -1;
}
while (row < 9 && col < 9 && dataFile >> num) {
board[row][col++] = num;
// Reset column index, get data for next row
if (col == 9) {
row++;
col = 0;
}
}
// Got all data
if (row == 9) {
cout << "Sudoku board get to verify: " << endl;
for (int i = 0; i < 9; ++i) {
for (int j = 0; j < 9; ++j) {
cout << board[i][j] << " ";
}
cout << endl;
}
} else {
cout << "Invalid data inside sudoku-data.txt";
return -2;
}
cout << endl;
// Call function for verification
int ret = isValidSudoku(board);
if (ret) {
cout << "This is a valid sudoku board!!!" << endl;
} else {
cout << "Fail!!! This is not a valid sudoku board." << endl;
}
return 0;
}
| true |
ce8e9328fdce48493573fca816e2f8268132ed58 | C++ | tvdinh1008/Thuat_toan_ung_dung | /Duong_Di_NN_Priovity_Queue.cpp | UTF-8 | 3,546 | 2.984375 | 3 | [] | no_license | #include<iostream>
#include<vector>
#define MAX 100001
using namespace std;
vector<int> A[MAX];//ds kề
vector<int> C[MAX]; //trọng số của cạnh
int N, M;
int s, t;//tìm đường đi ngắn nhất từ s->t
int result;
//mỗi 1 node trên cây sẽ chứa đỉnh v và d[v]
int node[MAX];//chứa đỉnh v
int idx[MAX];//là chỉ số của v trong mảng node
int d[MAX];//trọng số đường đi tại đỉnh v: d[v]
bool fixed_v[MAX];//đánh dấu đỉnh v đã được chọn trong đường đi hay chưa
int sH;//size của heap
//priority queues
void swap(int i, int j)
{
//đổi đỉnh trong node
int tmp = node[i];
node[i] = node[j];
node[j] = tmp;
//đổi chỉ số v trong mảng
idx[node[i]] = i;
idx[node[j]] = j;
}
//cập nhật từ con(chỉ số i->cha sẽ là i-1/2) đến root
void upheap(int i)
{
if (i == 0) return;
while(i>0)
{
int parent_i = (i - 1) / 2;
if (d[node[parent_i]] > d[node[i]])
{
swap(parent_i, i);
}
else
{
break;
}
i = parent_i;//cập nhật từ vị trí parent lên tới root
}
}
//cập nhật từ cha đến các con
void downheap(int i)
{
int L = 2 * i + 1;
int R = 2 * i + 2;
//tìm phần tử nhỏ nhất trong cha và 2 con
int midx = i;
if (L<sH && d[node[L]] < d[node[midx]]) midx = L;
if (R<sH && d[node[R]] < d[node[midx]]) midx = R;
if (midx != i)
{
swap(i, midx);
//do đẩy vị trí con lên trên -> có thể tại vị trí con đó cần cập nhật trong TH cha là midx lớn hơn con của midx
downheap(midx);
}
}
void insert(int v,int dv)
{
d[v] = dv;
node[sH] = v;
idx[v] = sH;
//quy tắc insert là lấp đầy cây, insert từ trái qua phải-> khi insert vào lá thì cha của nó có thể ko thỏa mãn
upheap(sH);
sH++;
}
//cập nhật dv của đỉnh v trong cây
void updateKey(int v, int k)
{
if (d[v] > k)
{
d[v] = k;
//vì dv nhỏ hơn -> có thể cha của nó ko thỏa mãn
upheap(idx[v]);
}
else
{
d[v] = k;
//dv lớn hơn->có thể con của nó nhỏ hơn dv-> cập nhật
downheap(idx[v]);
}
}
//ktra đỉnh v có trong heap?
bool inheap(int v)
{
return idx[v] >= 0;
}
//delete trả về đỉnh v mà nó vừa xóa khỏi cây
int deleteMin()
{
int sel_node = node[0];
swap(0, sH - 1);
sH--;
downheap(0);
return sel_node;
}
//end priority queues
void input()
{
cin >> N >> M;
int u, v, w;
for (int i = 0; i < M; i++)
{
cin >> u >> v >> w;
A[u].push_back(v);
C[u].push_back(w);
}
cin >> s >> t;
}
void init(int s)
{
sH = 0;
for (int i = 1; i <= N; i++)
{
idx[i] = -1;
fixed_v[i] = false;
}
d[s] = 0;
fixed_v[s] = true;
for (int i = 0; i < A[s].size(); i++)
{
int u = A[s][i];
insert(u, C[s][i]);
}
}
void solve()
{
init(s);
while (sH > 0)
{
int u = deleteMin();
fixed_v[u] = 1;//dánh dấu đã cho vào đường đi
for (int i = 0; i < A[u].size(); i++)
{
int v = A[u][i];
if (fixed_v[v] == true)
{
continue;
}
//v chưa có trong heap
if (inheap(v) == 0)
{
int w = d[u] + C[u][i];
insert(v, w);
}
else
{
if(d[v]>d[u]+C[u][i])
updateKey(v, d[u] + C[u][i]);
}
}
}
result = d[t];
if (fixed_v[t] == false)
{
result = -1;
}
cout << result;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
input();
solve();
return 0;
} | true |
981021df51092d5e4580c70d83cfab9b268727e5 | C++ | alirezafour/practice | /cpp/Practice/Seasen 1/Section 1/MojsazanPractice/18-count function.cpp | UTF-8 | 254 | 3 | 3 | [] | no_license | #include <cstdio>
int main(int argc, char const *argv[])
{
int x,y;
printf("insert X: ");
scanf("%d", &x);
if(x < 0)
{
y = 1 - (2 * x);
}
else if(x = 0)
{
y = 0;
}
else
{
y = 1 + (2 * x);
}
printf("\ny = %d\n", y);
return 0;
} | true |
4d4415eab1bcb1c45319fae6a29c1cb97663bc44 | C++ | MagicSen/C_Plus_Plus_Primer | /test_11_2_3_1.cpp | UTF-8 | 657 | 3.015625 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
#include <numeric>
#include <iterator>
#include <vector>
#include <list>
#include <map>
#include <set>
#include <string>
#include <utility>
using namespace std;
int main()
{
vector<pair<string, int>> string_sequence;
string temp_str;
int temp_int;
while(cin >> temp_str >> temp_int)
{
// string_sequence.push_back(make_pair(temp_str, temp_int));
// string_sequence.push_back(pair<string, int>(temp_str, temp_int));
pair<string, int> temp_pair(temp_str, temp_int);
string_sequence.push_back(temp_pair);
}
for(const auto &i : string_sequence)
cout << i.first << " " << i.second << endl;
return 0;
}
| true |
423c15a48714584aa36d08df57b42c843413c90c | C++ | oasiskharkov/Blackjack | /person.cpp | UTF-8 | 821 | 3.453125 | 3 | [] | no_license | #include "person.h"
Person::Person(std::string&& name) :
m_name{std::move(name)}
{
}
Hand& Person::hand()
{
return m_hand;
}
const Hand& Person::hand() const
{
return m_hand;
}
const std::string Person::name() const
{
return m_name;
}
bool Person::isBusted() const
{
return m_hand.total() > GameParams::blackjack;
}
void Person::showWin() const
{
std::cout << m_name << ' ' << "wins!" << std::endl;
}
std::ostream& operator << (std::ostream& out, const Person& person)
{
out << person.name() << ":\t";
const auto& hand = person.hand();
if (!hand.empty())
{
hand.printCards(out);
if (hand.total() != 0)
{
out << "(" << hand.total() << ")";
}
}
else
{
throw std::logic_error("Hand is empty. Can't show cards!");
}
return out;
}
| true |
06c2f79833b94468c7dfcf774b2bb5509e01acfb | C++ | E-BAO/SimpleGL | /simpleGL/SimpleMath.cpp | UTF-8 | 669 | 3.03125 | 3 | [] | no_license | //
// SimpleMath.cpp
// simpleGL
//
// Created by EBAO on 2017/5/27.
// Copyright © 2017年 EBAO. All rights reserved.
//
#include "SimpleMath.h"
void swap(int &a,int &b){
int c = a;
a = b;
b = c;
}
void swap(float &a,float &b){
float c = a;
a = b;
b = c;
}
void swap(color_s &a,color_s &b){
color_s c = a;
a = b;
b = c;
}
void swap(vertex2i &a,vertex2i &b){
vertex2i c = a;
a = b;
b = c;
}
//
//template<class T>
//void swap(T& a,T& b){
// T c = a;
// a = b;
// b = c;
//}
float degree2Radio(float degree){
return degree * M_PI / 180.0f;
}
float max(float a,float b){
return a > b ? a:b;
}
| true |
5313f5d4c85a986ae6c141d7b860dbac79d2689b | C++ | luongpd2000/Data-structures-and-algorithms | /ConTest1(Demo)/B15.cpp | UTF-8 | 459 | 2.84375 | 3 | [] | no_license | #include<iostream>
#include<math.h>
using namespace std;
void xuly(int a[100000],int n){
int ktra=0;
for(int i=0;i<n;i++){
for(int j=i+1;j<n-1;j++){
if(a[i]==a[j]){
cout<<a[i]<<endl;
ktra=1;
break;
}
}
if(ktra==1) break;
}
if(ktra==0) cout<<"NO"<<endl;
}
int main(){
int t;
cin>>t;
while(t--){
int a[100000] ={0};
int n;
cin>>n;
for(int i=0;i<n;i++){
cin>>a[i];
}
xuly(a,n);
}
}
| true |
35ce98890f81ca5f9c58cf7bb0015bc52036bc6e | C++ | Nakio195/OSSAM-20 | /Items/Weapons/Bullet.h | UTF-8 | 1,923 | 2.75 | 3 | [] | no_license | #ifndef BULLET_H
#define BULLET_H
#include <string>
#include <iostream>
#include <SFML/Graphics.hpp>
#include "Entities/Entity.h"
#include "System/Animation.h"
using namespace std;
class Weapon;
class Spaceship;
class Bullet : public Entity
{
public:
enum Type{Laser, Missile};
public:
Bullet(Bullet *copy);
Bullet(Spaceship *pParent, string pName = "Laser Simple", unsigned int pHit = 10, string PathToBulletTexture = "Ressources/Sprite/LaserBleu.png", string PathToBlastTexture = "Ressources/Sprite/missile-blast.png");
~Bullet();
bool isBlastAnimRunning();
bool isExploded();
bool NeedRemove(); // To be moved upward in Entity
unsigned int getType();
unsigned int getHit();
void setHit(unsigned int pHit);
virtual void Move();
void setDirection(sf::Vector2f pDirection);
sf::Vector2f getDirection();
void setSpeed(float pSpeed);
float getSpeed();
void setBlastTexture(string Path);
void setBlastTexture(sf::Texture *pBlast);
void setBulletTexture(string Path);
void setBulletTexture(sf::Texture *pBullet);
void setParent(Spaceship *pParent);
Spaceship *getParent();
virtual void draw(sf::RenderWindow *Window);
void RefreshElapsedTime(bool Release);
virtual void Hitting(Spaceship *Shooter, Spaceship *Shooted);
//Actions
void BlastAnim_EndAction();
protected:
unsigned int Type; // Identifie la sous classe de munition
unsigned int Hit; // Dégats en HP/tirs
sf::Vector2f Direction;
float Speed; // Vitesse de déplacment en pixels/s
Spaceship *Parent;
Animation<Bullet> *BlastAnim;
sf::Texture *BlastTexture;
sf::Texture *BulletTexture;
bool Exploded;
bool Remove;
};
#endif // BULLET_H
| true |
6c25ccf88b8fc260baa9b225efab5677d3b20a1e | C++ | wwt17/BZOJ | /1629 [Usaco2007 Demo]Cow Acrobats.cpp | UTF-8 | 460 | 2.53125 | 3 | [
"Apache-2.0"
] | permissive | #include <cstdio>
#include <algorithm>
#define inf 2000000000
int N,i;
struct cow {
int w,s,sum;
void read() {
scanf("%d%d",&w,&s);
sum=w+s;
}
} c[50000];
inline bool cmp(const cow &a,const cow &b) {
return a.sum<b.sum;
}
int main() {
scanf("%d",&N);
for (i=0;i<N;++i) c[i].read();
std::sort(c,c+N,cmp);
int sum=0,ans=-inf;
for (i=0;i<N;++i) {
sum-=c[i].s;
ans=std::max(ans,sum);
sum+=c[i].sum;
}
printf("%d\n",ans);
//system("pause");
}
| true |
b4ded0cb920c6fda381d19e6ba8e8fd003f2bef3 | C++ | lunarnuts/numerical-methods | /Project/montecarlo.cpp | UTF-8 | 4,445 | 2.59375 | 3 | [] | no_license | #include "montecarlo.h"
unsigned seed = (unsigned)std::chrono::system_clock::now().time_since_epoch().count(); //setup seed for RV generator
std::mt19937 generator;
std::normal_distribution<double> normal(0, 1.0);
Asian_vanilla_call_option::Asian_vanilla_call_option(const int &n, // n of divisions
const double &q, // dividend yield
const double &S, // initial Option price
const double &K, // Strike price
const double &r, // Risk-free rate
const double &v, //volatility
const double &T, //expiration time;
const double &L, // n of Les
const double &m) // n of timesteps)
{
this->n = n;
this->L = L;
this->m = m;
this->q = q;
this->S = S;
this->K = K;
this->r = r;
this->v = v;
this->T = T;
};
double Asian_vanilla_call_option::max(double a, double b)
{
return (b < a) ? a : b;
}
double Asian_vanilla_call_option::N(const double &z)
{
if (z > 6.0)
{
return 1.0;
}; // this guards against overflow
if (z < -6.0)
{
return 0.0;
};
double b1 = 0.31938153;
double b2 = -0.356563782;
double b3 = 1.781477937;
double b4 = -1.821255978;
double b5 = 1.330274429;
double p = 0.2316419;
double c2 = 0.3989423;
double a = fabs(z);
double t = 1.0 / (1.0 + a * p);
double b = c2 * exp((-z) * (z / 2.0));
double n = ((((b5 * t + b4) * t + b3) * t + b2) * t + b1) * t;
n = 1.0 - b * n;
if (z < 0.0)
n = 1.0 - n;
return n;
};
double Asian_vanilla_call_option::get_gbm()
{
double x = 0.0;
double y = 0.0;
double euclid_sq = 0.0;
do
{
x = 2.0 * rand() / static_cast<double>(RAND_MAX) - 1;
y = 2.0 * rand() / static_cast<double>(RAND_MAX) - 1;
euclid_sq = x * x + y * y;
} while (euclid_sq >= 1.0);
return x * sqrt(-2 * log(euclid_sq) / euclid_sq);
}
double Asian_vanilla_call_option::get_sobol(int index, int dimension, double number)
{
const double s = sobol::sample(index + 1, dimension);
//double inter = s + number - floor(s + number);
return get_gbm(0, s) / s;
}
double Asian_vanilla_call_option::get_gbm(const double &stddev)
{
return get_gbm() * stddev;
}
double Asian_vanilla_call_option::get_gbm(const double &mean, const double &stddev)
{
return get_gbm(stddev) + mean;
}
double Asian_vanilla_call_option::option_price_call_black_scholes()
{
double time_sqrt = sqrt(T);
double d1 = (log(S / K) + (r - q) * T) / (v * time_sqrt) + 0.5 * v * time_sqrt;
double d2 = d1 - (v * time_sqrt);
return S * exp(-q * T) * N(d1) - K * exp(-r * T) * N(d2);
};
void Asian_vanilla_call_option::quasi_monte_carlo_call_price()
{
double y = 0; // Yi
double y2 = 0; //Yi^2
double deltaT = T / (double)m; //timestep
double drift = (r - q - v * v * 0.5) * deltaT;
for (int j = 0; j < L; j++) //generate L Les
{
double x = 0;
double U[m]; //uniform dist vector
for (int i = 0; i < m; i++)
{
srand(((int)time(0) * 10000 * (j + 1)) * L);
U[i] = normal(generator);
}
for (int i = 0; i < n; i++) //generate n samples
{
double Price[m];
double RV = get_sobol(i, 0, U[0]); //generate quasi random variable using sobol sequence
Price[0] = S * exp(drift + v * sqrt(deltaT) * RV);
for (int d = 1; d < m; d++) //generate path
{
RV = get_sobol(i, d, U[d]);
Price[d] = Price[d - 1] * exp(drift + v * sqrt(deltaT) * RV);
}
double sum = 0;
for (int k = 0; k < m; k++)
{
sum += Price[k];
}
double Price_avg = sum / (double)(m);
Price_avg = max(Price_avg - K, 0);
x += Price_avg;
}
x = x / (double)(n);
y += x;
y2 += x * x;
}
double payoff = y / (double)(L);
this->call_price = payoff * exp(-r * T);
this->SE = sqrt(((y2 / L) - payoff * payoff) / (L - 1)); //
};
| true |
38a397c532717a815fbc5891017469e673ac604c | C++ | tangodown1934/Algorithm-judge | /source/1ton1/1648014_AC_0.08SEC.cpp | UTF-8 | 245 | 2.96875 | 3 | [] | no_license | #include <stdio.h>
int main()
{
int number;
int result=0;
scanf("%d", &number);
for (int i = 1; i <= number; i++)
{
printf("%d", i);
result += i;
if (number == i) break;
printf("+");
}
printf("=%d \n", result);
return 0;
} | true |
ae914501ab2bd6fa3c9e6f4df46a5a15f0ab2476 | C++ | microsoft/CCF | /src/apps/tpcc/app/tpcc_setup.h | UTF-8 | 15,149 | 2.78125 | 3 | [
"Apache-2.0"
] | permissive | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the Apache 2.0 License.
#pragma once
#include "tpcc_common.h"
#include "tpcc_tables.h"
#include <exception>
#include <set>
#include <stdint.h>
namespace tpcc
{
class SetupDb
{
private:
ccf::endpoints::EndpointContext& args;
bool already_run;
int32_t new_orders_per_district;
std::mt19937 rand_generator;
float random_float(float min, float max)
{
return tpcc::random_float(min, max, rand_generator);
}
uint32_t random_int(uint32_t min, uint32_t max)
{
return tpcc::random_int(min, max, rand_generator);
}
int32_t random_int_excluding(int lower, int upper, int excluding)
{
return tpcc::random_int_excluding(
lower, upper, excluding, rand_generator);
}
template <size_t T>
void create_random_string(
std::array<char, T>& str, uint32_t min, uint32_t max)
{
uint32_t rand;
if (min == max)
{
rand = min;
}
else
{
rand = random_int(min, max);
}
create_random_string(str, rand);
}
template <size_t T>
void create_random_string(std::array<char, T>& str, uint32_t length)
{
for (uint32_t i = 0; i < length - 1; ++i)
{
str[i] = 97 + random_int(0, 26); // lower case letters
}
str[length - 1] = '\0';
}
template <size_t T>
void create_random_int(std::array<char, T>& str, uint32_t length)
{
for (uint32_t i = 0; i < length - 1; ++i)
{
str[i] = 48 + random_int(0, 10); // lower case letters
}
str[length - 1] = '\0';
}
std::unordered_set<uint32_t> select_unique_ids(
uint32_t num_items_, uint32_t num_unique)
{
std::unordered_set<uint32_t> r;
for (uint32_t i = 0; i < num_items_; ++i)
{
r.insert(i);
}
while (r.size() > num_unique)
{
r.erase(r.begin());
}
return r;
}
template <size_t T>
void set_original(std::array<char, T>& s)
{
int position = random_int(0, T - 8);
memcpy(s.data() + position, "ORIGINAL", 8);
}
Stock generate_stock(uint32_t item_id, uint32_t wh_id, bool is_original)
{
Stock s;
s.i_id = item_id;
s.w_id = wh_id;
s.quantity = random_int(Stock::MIN_QUANTITY, Stock::MAX_QUANTITY);
s.ytd = 0;
s.order_cnt = 0;
s.remote_cnt = 0;
for (int i = 0; i < District::NUM_PER_WAREHOUSE; ++i)
{
create_random_string(s.dist[i], sizeof(s.dist[i]));
}
if (is_original)
{
set_original(s.data);
}
else
{
create_random_string(
s.data, random_int(Stock::MIN_DATA, Stock::MAX_DATA));
}
return s;
}
void make_stock(uint32_t wh_id)
{
// Select 10% of the stock to be marked "original"
std::unordered_set<uint32_t> selected_rows =
select_unique_ids(num_items, num_items / 10);
for (uint32_t i = 1; i <= num_items; ++i)
{
bool is_original = selected_rows.find(i) != selected_rows.end();
Stock s = generate_stock(i, wh_id, is_original);
auto stocks = args.tx.rw(tpcc::TpccTables::stocks);
stocks->put(s.get_key(), s);
}
}
void generate_warehouse(int32_t id, Warehouse* warehouse)
{
warehouse->id = id;
warehouse->tax = random_float(Warehouse::MIN_TAX, Warehouse::MAX_TAX);
warehouse->ytd = Warehouse::INITIAL_YTD;
create_random_string(
warehouse->name, random_int(Warehouse::MIN_NAME, Warehouse::MAX_NAME));
create_random_string(
warehouse->street_1,
random_int(Address::MIN_STREET, Address::MAX_STREET));
create_random_string(
warehouse->street_2,
random_int(Address::MIN_STREET, Address::MAX_STREET));
create_random_string(
warehouse->city, random_int(Address::MIN_CITY, Address::MAX_CITY));
create_random_string(warehouse->state, Address::STATE, Address::STATE);
create_random_string(warehouse->zip, Address::ZIP);
}
void generate_district(int32_t id, int32_t w_id, District* district)
{
district->id = id;
district->w_id = w_id;
district->tax = random_float(District::MIN_TAX, District::MAX_TAX);
district->ytd = District::INITIAL_YTD;
district->next_o_id = customers_per_district + 1;
create_random_string(
district->name, District::MIN_NAME, District::MAX_NAME);
create_random_string(
district->street_1, Address::MIN_STREET, Address::MAX_STREET);
create_random_string(
district->street_2, Address::MIN_STREET, Address::MAX_STREET);
create_random_string(
district->city, Address::MIN_CITY, Address::MAX_CITY);
create_random_string(district->state, Address::STATE, Address::STATE);
create_random_string(district->zip, Address::ZIP);
}
void generate_customer(
int32_t id,
int32_t d_id,
int32_t w_id,
bool bad_credit,
Customer* customer)
{
customer->id = id;
customer->d_id = d_id;
customer->w_id = w_id;
customer->credit_lim = Customer::INITIAL_CREDIT_LIM;
customer->discount =
random_float(Customer::MIN_DISCOUNT, Customer::MAX_DISCOUNT);
customer->balance = Customer::INITIAL_BALANCE;
customer->ytd_payment = Customer::INITIAL_YTD_PAYMENT;
customer->payment_cnt = Customer::INITIAL_PAYMENT_CNT;
customer->delivery_cnt = Customer::INITIAL_DELIVERY_CNT;
create_random_string(
customer->first, Customer::MIN_FIRST, Customer::MAX_FIRST);
std::copy_n("OE", 2, customer->middle.begin());
if (id <= 1000)
{
make_last_name(id - 1, customer->last.data());
}
else
{
make_last_name(random_int(0, 1000), customer->last.data());
}
create_random_string(
customer->street_1, Address::MIN_STREET, Address::MAX_STREET);
create_random_string(
customer->street_2, Address::MIN_STREET, Address::MAX_STREET);
create_random_string(
customer->city, Address::MIN_CITY, Address::MAX_CITY);
create_random_string(customer->state, Address::STATE, Address::STATE);
create_random_string(customer->zip, Address::ZIP);
create_random_int(customer->phone, Customer::PHONE);
customer->since = tx_time;
if (bad_credit)
{
std::copy_n(
Customer::BAD_CREDIT,
sizeof(Customer::BAD_CREDIT),
customer->credit.data());
}
else
{
std::copy_n(
Customer::GOOD_CREDIT,
sizeof(Customer::GOOD_CREDIT),
customer->credit.data());
}
create_random_string(
customer->data, Customer::MIN_DATA, Customer::MAX_DATA);
}
void generate_history(
int32_t c_id, int32_t d_id, int32_t w_id, History* history)
{
history->c_id = c_id;
history->c_d_id = d_id;
history->d_id = d_id;
history->c_w_id = w_id;
history->w_id = w_id;
history->amount = History::INITIAL_AMOUNT;
history->date = tx_time;
create_random_string(history->data, History::MIN_DATA, History::MAX_DATA);
}
std::vector<int> make_permutation(int lower, int upper)
{
std::vector<int> array;
array.resize(upper);
for (int i = 0; i <= upper - lower; ++i)
{
array[i] = lower + i;
}
for (int i = 0; i < upper - lower; ++i)
{
int index = random_int(i, upper - lower);
int temp = array[i];
array[i] = array[index];
array[index] = temp;
}
return array;
}
void generate_order(
int32_t id,
int32_t c_id,
int32_t d_id,
int32_t w_id,
bool new_order,
Order* order)
{
order->id = id;
order->c_id = c_id;
order->d_id = d_id;
order->w_id = w_id;
if (!new_order)
{
order->carrier_id =
random_int(Order::MIN_CARRIER_ID, Order::MAX_CARRIER_ID);
}
else
{
order->carrier_id = Order::NULL_CARRIER_ID;
}
order->ol_cnt = random_int(Order::MIN_OL_CNT, Order::MAX_OL_CNT);
order->all_local = Order::INITIAL_ALL_LOCAL;
order->entry_d = tx_time;
}
void generate_order_line(
int32_t number,
int32_t o_id,
int32_t d_id,
int32_t w_id,
bool new_order,
OrderLine* orderline)
{
orderline->o_id = o_id;
orderline->d_id = d_id;
orderline->w_id = w_id;
orderline->number = number;
orderline->i_id = random_int(OrderLine::MIN_I_ID, OrderLine::MAX_I_ID);
orderline->supply_w_id = w_id;
orderline->quantity = OrderLine::INITIAL_QUANTITY;
if (!new_order)
{
orderline->amount = 0.00;
orderline->delivery_d = tx_time;
}
else
{
orderline->amount =
random_float(OrderLine::MIN_AMOUNT, OrderLine::MAX_AMOUNT);
orderline->delivery_d[0] = '\0';
}
create_random_string(
orderline->dist_info,
sizeof(orderline->dist_info) - 1,
sizeof(orderline->dist_info) - 1);
}
void make_warehouse_without_stock(int32_t w_id)
{
Warehouse w;
generate_warehouse(w_id, &w);
auto warehouses = args.tx.rw(tpcc::TpccTables::warehouses);
warehouses->put(w.get_key(), w);
for (int32_t d_id = 1; d_id <= districts_per_warehouse; ++d_id)
{
District d;
generate_district(d_id, w_id, &d);
auto districts = args.tx.rw(tpcc::TpccTables::districts);
districts->put(d.get_key(), d);
// Select 10% of the customers to have bad credit
std::unordered_set<uint32_t> selected_rows = select_unique_ids(
customers_per_district / 10, customers_per_district);
for (int32_t c_id = 1; c_id <= customers_per_district; ++c_id)
{
Customer c;
bool bad_credit = selected_rows.find(c_id) != selected_rows.end();
generate_customer(c_id, d_id, w_id, bad_credit, &c);
tpcc::TpccTables::DistributeKey table_key;
table_key.v.w_id = w_id;
table_key.v.d_id = d_id;
auto it = tpcc::TpccTables::customers.find(table_key.k);
if (it == tpcc::TpccTables::customers.end())
{
std::string tbl_name = fmt::format("customer_{}_{}", w_id, d_id);
auto r = tpcc::TpccTables::customers.insert(
{table_key.k,
TpccMap<Customer::Key, Customer>(tbl_name.c_str())});
it = r.first;
}
auto customers = args.tx.rw(it->second);
customers->put(c.get_key(), c);
History h;
generate_history(c_id, d_id, w_id, &h);
auto history = args.tx.rw(tpcc::TpccTables::histories);
history->put(h.get_key(), h);
}
// TPC-C 4.3.3.1. says that this should be a permutation of [1,
// 3000]. But since it is for a c_id field, it seems to make sense to
// have it be a permutation of the customers. For the "real" thing this
// will be equivalent
std::vector<int> permutation =
make_permutation(1, customers_per_district);
for (int32_t o_id = 1; o_id <= customers_per_district; ++o_id)
{
// The last new_orders_per_district_ orders are new
bool new_order =
customers_per_district - new_orders_per_district < o_id;
Order o;
generate_order(
o_id, permutation[o_id - 1], d_id, w_id, new_order, &o);
tpcc::TpccTables::DistributeKey table_key;
table_key.v.w_id = w_id;
table_key.v.d_id = d_id;
auto it = tpcc::TpccTables::orders.find(table_key.k);
if (it == tpcc::TpccTables::orders.end())
{
std::string tbl_name = fmt::format("orders_{}_{}", w_id, d_id);
auto r = tpcc::TpccTables::orders.insert(
{table_key.k, TpccMap<Order::Key, Order>(tbl_name.c_str())});
it = r.first;
}
auto order = args.tx.rw(it->second);
order->put(o.get_key(), o);
// Generate each OrderLine for the order
for (int32_t ol_number = 1; ol_number <= o.ol_cnt; ++ol_number)
{
OrderLine line;
generate_order_line(ol_number, o_id, d_id, w_id, new_order, &line);
auto order_lines = args.tx.rw(tpcc::TpccTables::order_lines);
order_lines->put(line.get_key(), line);
if (new_order)
{
tpcc::TpccTables::DistributeKey table_key_;
table_key_.v.w_id = w_id;
table_key_.v.d_id = d_id;
auto it_ = tpcc::TpccTables::new_orders.find(table_key_.k);
if (it_ == tpcc::TpccTables::new_orders.end())
{
std::string tbl_name =
fmt::format("new_orders_{}_{}", w_id, d_id);
auto r = tpcc::TpccTables::new_orders.insert(
{table_key_.k,
TpccMap<NewOrder::Key, NewOrder>(tbl_name.c_str())});
it_ = r.first;
}
NewOrder no;
no.w_id = w_id;
no.d_id = d_id;
no.o_id = o_id;
auto new_orders = args.tx.rw(it_->second);
new_orders->put(no.get_key(), no);
}
}
}
}
}
void generate_item(int32_t id, bool original)
{
Item item;
item.id = id;
item.im_id = random_int(Item::MIN_IM, Item::MAX_IM);
item.price = random_float(Item::MIN_PRICE, Item::MAX_PRICE);
create_random_string(item.name, Item::MIN_NAME, Item::MAX_NAME);
create_random_string(item.data, Item::MIN_DATA, Item::MAX_DATA);
if (original)
{
set_original(item.data);
}
auto items_table = args.tx.rw(tpcc::TpccTables::items);
items_table->put(item.get_key(), item);
}
// Generates num_items items and inserts them into tables.
void make_items()
{
// Select 10% of the rows to be marked "original"
auto original_rows = select_unique_ids(num_items, num_items / 10);
for (uint32_t i = 1; i <= num_items; ++i)
{
bool is_original = original_rows.find(i) != original_rows.end();
generate_item(i, is_original);
}
}
public:
SetupDb(
ccf::endpoints::EndpointContext& args_,
int32_t new_orders_per_district_,
uint32_t seed) :
args(args_),
already_run(false),
new_orders_per_district(new_orders_per_district_)
{
rand_generator.seed(seed);
}
void run()
{
LOG_INFO_FMT("Start create");
if (already_run)
{
throw std::logic_error("Can only create the database 1 time");
}
already_run = true;
make_items();
for (uint32_t i = 0; i < num_warehouses; ++i)
{
make_stock(i);
make_warehouse_without_stock(i);
}
LOG_INFO_FMT("end create");
}
};
} | true |
9973588a838fa567b2b3c806e3eb44d14b900459 | C++ | kcwzzz/KCW | /cocos/170727/170727 MolesBackup_1/Classes/CScrollBg.cpp | WINDOWS-1252 | 1,535 | 2.78125 | 3 | [] | no_license | #include "CScrollBg.h"
CScrollBg::CScrollBg()
{
mpScene = NULL;
mpSpriteA = NULL;
mVecA.x = 0.0f;
mVecA.y = 0.0f;
mpSpriteB = NULL;
mVecB.x = 0.0f;
mVecB.y = 0.0f;
mScrollSpeed = 0.0f;
mZOrder = 0.0f;
}//ʱȭ
CScrollBg::~CScrollBg()
{
}
void CScrollBg::Create(float tScrollSpeed, float tZOrder)
{
mScrollSpeed = tScrollSpeed;
mZOrder = tZOrder;
auto tSpriteSrc = Sprite::create("bg.png");
auto tTexture = tSpriteSrc->getTexture();
mpSpriteA = Sprite::createWithTexture(tTexture);
mpSpriteA->retain();
mpSpriteA->setAnchorPoint(Vec2(0.0f, 0.0f));
mpSpriteB = Sprite::createWithTexture(tTexture);
mpSpriteB->retain();
mpSpriteB->setAnchorPoint(Vec2(0.0f, 0.0f));
mVecA.x = 0.0f;
mVecA.y = 0.0f;
mpSpriteA->setPosition(mVecA);
mVecB.x = 0.0f;
mVecB.y = mpSpriteA->getContentSize().height;
mpSpriteB->setPosition(mVecB);
tHeight = mpSpriteA->getContentSize().height;
}
void CScrollBg::Destroy()
{
}
void CScrollBg::SetScene(Node *tpScene)
{
mpScene = tpScene;
}
void CScrollBg::Build()
{
mpScene->addChild(mpSpriteA, mZOrder);
mpScene->addChild(mpSpriteB, mZOrder);
}
void CScrollBg:: UnBuild()
{
mpScene->removeChild(mpSpriteA, mZOrder);
mpScene->removeChild(mpSpriteB, mZOrder);
}
void CScrollBg::UpdateScroll(float dt)
{
mVecA.y = mVecA.y - mScrollSpeed*dt;
mpSpriteA->setPosition(mVecA);
mVecB.y = mVecB.y - mScrollSpeed*dt;
mpSpriteB->setPosition(mVecB);
if (mVecA.y <= -tHeight)
{
mVecA.y = tHeight;
}
if (mVecB.y <= -tHeight)
{
mVecB.y = tHeight;
}
} | true |
522344cc26257283ef074a0b45ebd14da85e1b02 | C++ | Toleishuangfeng/CPlus | /SortingAdvance/Optional-03-ShellSort-MergeSort-and-QuickSort comparision/MergeSort2.h | GB18030 | 967 | 3.3125 | 3 | [] | no_license | #include<iostream>
using namespace std;
template <typename T>
void _merge2(T arr[], T aux[],int l, int mid, int r) {
for (int i = l; i <= r; i++) {
aux[i ] = arr[i];
}
int i = l, j = mid + 1;
for (int k = l; k <= r; k++) {
if (i > mid) {
arr[k] = aux[j];
j++;
}
else if (j > r) {
arr[k] = aux[i]; i++;
}
else if (aux[i] < aux[j]) {
arr[k] = aux[i]; i++;
}
else {
arr[k] = aux[j ]; j++;
}
}
}
template<typename T>
void _mergeSort2(T arr[], T aux[],int l, int r) {
if (l >= r)return;
int mid = (r - l) / 2 + l;
_mergeSort2(arr,aux, l, mid);
_mergeSort2(arr,aux, mid + 1, r);
if (arr[mid] > arr[mid + 1])
_merge2(arr, aux,l, mid, r);
}
//ԶµĹ鲢,Ż
//һauxռ,ռԲʽݸɹ鲢ĸӺ
template <typename T>
void mergeSort2(T arr[], int n) {
T* aux = new T[n];
_mergeSort2(arr,aux, 0, n - 1);
delete[] aux;
} | true |
0bc4323752ec08a6aa3384064d1182e2ef91f17c | C++ | Bhawna11agg/Competitive | /Maths/FizzBuzz.cpp | UTF-8 | 575 | 3.234375 | 3 | [] | no_license | vector<string> Solution::fizzBuzz(int A) {
vector<string>vect;
int i=1;
while(i<=A){
string name="";
if(i%3==0 && i%5==0){
vect.push_back("FizzBuzz");
i++;
continue;
}
if(i%3==0){
vect.push_back("Fizz");
i++;
continue;
}
if(i%5==0){
vect.push_back("Buzz");
i++;
continue;
}
int k=i;
while(k>0){
name=(char)((k%10)+48)+name;
k=k/10;
}
vect.push_back(name);
i++;
}
return vect;
}
| true |
fe9b8ac2c8151e4f1e5719bec6645df73693580f | C++ | hannapeters/losing-chess | /Helper.h | UTF-8 | 618 | 3.03125 | 3 | [] | no_license | #ifndef HELPER_H
#define HELPER_H
#include <random>
#include <iterator>
int gen_rand_num(int min, int max);
enum Type{king, queen, bishop, knight, rook, pawn};
template<typename Iter, typename RandomGenerator>
Iter select_random_element(Iter start, Iter end, RandomGenerator& g){
std::uniform_int_distribution<> dist(0,distance(start,end)-1);
advance(start,dist(g));
return start;
}
template<typename Iter>
Iter select_random_element(Iter start, Iter end){
static std::random_device rd;
static std::mt19937 gen(rd());
return select_random_element(start,end,gen);
}
#endif | true |
c014e471ecd5b6dedd88044478b74bee3b37aaf0 | C++ | edenreich/console-component | /src/include/console/input.h | UTF-8 | 2,128 | 3.078125 | 3 | [
"MIT"
] | permissive | #ifndef INPUT_H
#define INPUT_H
#include "interfaces/input_interface.h"
#include "interfaces/application_interface.h"
namespace Console
{
/**
* The Input Class
*/
class Input : public Interfaces::InputInterface
{
public:
/**
* Initialize the application interface.
*
* @param Interfaces::ApplicationInterface * app
*/
Input(Interfaces::ApplicationInterface* app);
/**
* Retrieve an input from the user.
*
* @param const std::string & question
* @return std::string
*/
std::string ask(const std::string& question) override;
/**
* Retrieve the parsed options.
*
* @return Options
*/
Types::Options getOptions() override;
/**
* Setter for the parsed options.
*
* @return Console::Types::Options options
* @return void
*/
void setOptions(Console::Types::Options options) override;
/**
* Determine if the -h or --help flag
* was supplied.
*
* @return bool
*/
bool wantsHelp() override;
/**
* Retrieve the option value
* by given option.
*
* @param const std::string & option
* @return std::string
*/
std::string getOption(const std::string& option) override;
/**
* Retrieve the option value
* by given option and alias.
*
* @param const std::string & option
* @param const std::string & alias
* @return std::string
*/
std::string getOption(const std::string& option, const std::string& alias) override;
private:
/**
* Store the options.
*
* @var Options options
*/
Types::Options m_options;
/**
* Store the application interface.
*
* @var Interfaces::ApplicationInterface * m_app
*/
Interfaces::ApplicationInterface* m_app;
};
}
#endif // INPUT_H
| true |
8dbc6533cbf70f0ce3216a58ef2cc6a1284d839c | C++ | zhoujf620/LeetCode-Practice | /C++/1319.number-of-operations-to-make-network-connected.cpp | UTF-8 | 2,770 | 3.453125 | 3 | [] | no_license | /*
* @lc app=leetcode id=1319 lang=cpp
*
* [1319] Number of Operations to Make Network Connected
*
* https://leetcode.com/problems/number-of-operations-to-make-network-connected/description/
*
* algorithms
* Medium (53.47%)
* Likes: 476
* Dislikes: 7
* Total Accepted: 19.9K
* Total Submissions: 37.1K
* Testcase Example: '4\n[[0,1],[0,2],[1,2]]'
*
* There are n computers numbered from 0 to n-1 connected by ethernet cables
* connections forming a network where connections[i] = [a, b] represents a
* connection between computers a and b. Any computer can reach any other
* computer directly or indirectly through the network.
*
* Given an initial computer network connections. You can extract certain
* cables between two directly connected computers, and place them between any
* pair of disconnected computers to make them directly connected. Return the
* minimum number of times you need to do this in order to make all the
* computers connected. If it's not possible, return -1.
*
*
* Example 1:
*
*
*
*
* Input: n = 4, connections = [[0,1],[0,2],[1,2]]
* Output: 1
* Explanation: Remove cable between computer 1 and 2 and place between
* computers 1 and 3.
*
*
* Example 2:
*
*
*
*
* Input: n = 6, connections = [[0,1],[0,2],[0,3],[1,2],[1,3]]
* Output: 2
*
*
* Example 3:
*
*
* Input: n = 6, connections = [[0,1],[0,2],[0,3],[1,2]]
* Output: -1
* Explanation: There are not enough cables.
*
*
* Example 4:
*
*
* Input: n = 5, connections = [[0,1],[0,2],[3,4],[2,3]]
* Output: 0
*
*
*
* Constraints:
*
*
* 1 <= n <= 10^5
* 1 <= connections.length <= min(n*(n-1)/2, 10^5)
* connections[i].length == 2
* 0 <= connections[i][0], connections[i][1] < n
* connections[i][0] != connections[i][1]
* There are no repeated connections.
* No two computers are connected by more than one cable.
*
*/
#include<vector>
using namespace std;
// @lc code=start
class Solution {
public:
int makeConnected(int n, vector<vector<int>>& connections) {
vector<int> root(n);
for (int i=0; i<n; ++i) root[i] = i;
int extra = 0;
for (vector<int>& edge: connections) {
int p1 = findRoot(root, edge[0]);
int p2 = findRoot(root, edge[1]);
if (p1 != p2) root[p1] = p2;
else extra += 1;
}
int group = 0;
for (int i=0; i<n; ++i) if (root[i] == i) group += 1;
if (extra >= group-1) return group - 1;
else return -1;
}
int findRoot(vector<int>& root, int i) {
while (root[i] != i) {
root[i] = root[root[i]];
i = root[i];
}
return i;
}
};
// @lc code=end
| true |
1feb5ee7bc5ce4f71ae8c0caef69e5698392f20b | C++ | UAMiky/tetrisino | /include/melody_player/IMelodyPlayer.hpp | UTF-8 | 1,213 | 3.234375 | 3 | [
"Apache-2.0"
] | permissive | /**
* A melody player for Arduino
* by Miguel Company (UAMike)
*/
#ifndef UAMIKE_MELODY_PLAYER_IMELODYPLAYER_HPP
#define UAMIKE_MELODY_PLAYER_IMELODYPLAYER_HPP
#include "../interfaces/IStoppable.hpp"
namespace uamike {
namespace melody_player {
// Forward declaration of Note
struct Note;
/// An interface for a melody player
struct IMelodyPlayer : public IStoppable
{
/**
* Set a new tempo.
*
* @param qpm New tempo in quarter notes per minute.
*
* @note If a melody is currently playing, the new tempo will be applied on the next note played.
*/
inline virtual void tempo(unsigned int qpm) = 0;
/**
* Stop playing current melody and play a new one.
*
* @param melody Pointer to the beginning of the note array representing the melody.
* @param num_notes Number of notes in the melody.
* @param loop Whether the melody should be repeated or not.
*/
inline virtual void play(const Note* melody, unsigned int num_notes, bool loop) = 0;
/**
* @return Wheter a melody is being played or not
*/
inline virtual bool is_playing() const = 0;
};
} // namespace melody_player
} // namespace uamike
#endif // UAMIKE_MELODY_PLAYER_IMELODYPLAYER_HPP
| true |
d3ec8b33be9d0e132d540a21febd86c8ac50dd74 | C++ | spectre-team/native-algorithms | /src/Spectre.libGenetic.Tests/ParentSelectionStrategyTest.cpp | UTF-8 | 3,959 | 2.546875 | 3 | [
"Apache-2.0"
] | permissive | /*
* ParentSelectionStrategyTest.cpp
* Tests generation.
*
Copyright 2017 Grzegorz Mrukwa, Wojciech Wilgierz
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include <gtest/gtest.h>
#include <numeric>
#include "Spectre.libException/ArgumentOutOfRangeException.h"
#include "Spectre.libGenetic/ParentSelectionStrategy.h"
#include "Spectre.libGenetic/InconsistentGenerationAndScoresLengthException.h"
namespace
{
using namespace spectre::algorithm::genetic;
using namespace spectre::core::exception;
TEST(ParentSelectionStrategyInitialization, initializes)
{
ParentSelectionStrategy parent_selection(0);
}
class ParentSelectionStrategyTest : public ::testing::Test
{
public:
ParentSelectionStrategyTest():
individual1(std::vector<bool> { true, false, true, false }),
individual2(std::vector<bool> { false, true, false, true }),
generation({ individual1, individual2 }) {}
protected:
const unsigned NUMBER_OF_TRIALS = 1000;
const double ALLOWED_MISS_RATE = 0.05;
const Seed SEED = 0;
const Individual individual1;
const Individual individual2;
ParentSelectionStrategy parent_selection;
Generation generation;
void SetUp() override
{
parent_selection = ParentSelectionStrategy(SEED);
}
};
TEST_F(ParentSelectionStrategyTest, all_zero_scores_do_not_cause_error)
{
const std::vector<ScoreType> score { 0, 0 };
EXPECT_NO_THROW(parent_selection.next(generation, score));
}
TEST_F(ParentSelectionStrategyTest, throws_for_negative_weights)
{
const std::vector<ScoreType> score { -1, 0 };
EXPECT_THROW(parent_selection.next(generation, score), ArgumentOutOfRangeException<ScoreType>);
}
TEST_F(ParentSelectionStrategyTest, throws_on_inconsistent_inputs_size)
{
std::vector<ScoreType> tooShortScores({ 0 });
EXPECT_THROW(parent_selection.next(generation, tooShortScores), InconsistentGenerationAndScoresLengthException);
}
TEST_F(ParentSelectionStrategyTest, some_zero_scores_never_draw_corresponding_individuals)
{
const std::vector<ScoreType> score { 1, 0 };
for (auto i = 0u; i < NUMBER_OF_TRIALS; ++i)
{
const auto parents = parent_selection.next(generation, score);
EXPECT_NE(individual2, parents.first);
EXPECT_NE(individual2, parents.second);
}
}
TEST_F(ParentSelectionStrategyTest, scores_influence_draw_probability_proportionally)
{
const std::vector<ScoreType> score { 1, 2 };
auto count1 = 0u;
auto count2 = 0u;
for (auto i = 0u; i < NUMBER_OF_TRIALS; ++i)
{
const auto parents = parent_selection.next(generation, score);
const auto &firstParent = parents.first.get();
const auto &secondParent = parents.second.get();
if (firstParent == generation[0])
{
++count1;
}
else
{
++count2;
}
if (secondParent == generation[0])
{
++count1;
}
else
{
++count2;
}
}
const auto expectedCount1 = score[0] * NUMBER_OF_TRIALS * 2. / (score[0] + score[1]);
const auto expectedCount2 = score[1] * NUMBER_OF_TRIALS * 2. / (score[0] + score[1]);
EXPECT_GT(count1, expectedCount1 - NUMBER_OF_TRIALS * ALLOWED_MISS_RATE);
EXPECT_LT(count1, expectedCount1 + NUMBER_OF_TRIALS * ALLOWED_MISS_RATE);
EXPECT_GT(count2, expectedCount2 - NUMBER_OF_TRIALS * ALLOWED_MISS_RATE);
EXPECT_LT(count2, expectedCount2 + NUMBER_OF_TRIALS * ALLOWED_MISS_RATE);
}
}
| true |
3180d282b5280f432fb368a9bdb4dc04dacd6a6d | C++ | BiralTuya/Contests | /contest 11/g.cpp | UTF-8 | 657 | 2.796875 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
#include <vector>
#include<cstdio>
using namespace std;
int main () {
int t;
scanf("%d",&t);
while(t--){
int first[10000];
int second[10000];
vector<int> v(10000);
vector<int>::iterator it;
int m,n;
cin>>m>>n;
int i;
for(i=0;i<m;i++) cin>>first[i];
int j;
for(j=0;j<n;j++) cin>>second[j];
sort(first,first+m);
sort(second,second+n);
it=set_intersection (first, first+m, second, second+n, v.begin());
v.resize(it-v.begin());
cout<<(m+n)-2*(v.size())<<endl;
}
return 0;
}
| true |
00e5a37c565c7c9d54dbd114d1e77f79ca98371b | C++ | Remi-Coulom/joedb | /test/compiler/generate_translation_header.cpp | UTF-8 | 1,498 | 2.578125 | 3 | [
"MIT"
] | permissive | #include "db/test_readonly.h"
#include "joedb/io/main_exception_catcher.h"
#include <iostream>
/////////////////////////////////////////////////////////////////////////////
static int generate_translation_header(int argc, char **argv)
/////////////////////////////////////////////////////////////////////////////
{
my_namespace::is_nested::test::Readonly_Database db("test.joedb");
std::cout << "#ifndef translation_declared\n";
std::cout << "#define translation_declared\n\n";
std::cout << "namespace translation\n";
std::cout << "{\n";
std::cout << " enum\n";
std::cout << " {\n";
for (const auto string_id: db.get_string_id_table())
{
std::cout << " " << db.get_name(string_id) << " = " << string_id.get_id();
std::cout << ",\n";
}
std::cout << " string_ids\n";
std::cout << " };\n\n";
std::cout << " namespace language\n";
std::cout << " {\n";
std::cout << " enum\n";
std::cout << " {\n";
for (const auto language: db.get_language_table())
{
std::cout << " " << db.get_id(language) << " = " << language.get_id();
std::cout << ",\n";
}
std::cout << " languages\n";
std::cout << " };\n";
std::cout << " }\n";
std::cout << "}\n\n";
std::cout << "#endif\n";
return 0;
}
/////////////////////////////////////////////////////////////////////////////
int main(int argc, char **argv)
/////////////////////////////////////////////////////////////////////////////
{
return joedb::main_exception_catcher(generate_translation_header, argc, argv);
}
| true |
da5fead85aff12ff631e704244df0da6fd48e95a | C++ | Relics/ACM_Coding | /Poj/2299/11889636_RE.cc | UTF-8 | 546 | 3.015625 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
#include <cstdio>
using namespace std;
int a[50100];
int swapnum;
void bubble_sort(int size)
{
swapnum=0;
bool flag=false;
int i,j;
for(i=0;i<size-1;i++)
{
flag=false;
for(j=0;j<size-1-i;j++)
{
if(a[j]>a[j+1])
{
swap(a[j],a[j+1]);
flag=true;
swapnum++;
}
}
if(!flag)
break;
}
}
int main()
{
for(;;)
{
int n;
scanf("%d",&n);
if(n==0)
break;
for(int i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
bubble_sort(n);
printf("%d\n",swapnum);
}
return 0;
} | true |
9b5fb941c389356afbbdc7f8cc69182e6d37b11e | C++ | kunmukh/CS-470 | /CS-470/thread_synchronization/thread.cpp | UTF-8 | 5,553 | 3.375 | 3 | [] | no_license | //File: thread.cpp
//THis project is to implement a senario where there may be multiple
//producers and consumers accessing a bounded buffer as a circular
//queue, each of which is running in a thread.
//-----------------------------------------------------------------
// Class: CS 470 Instructor: Dr. Deborah Hwang
// Assignment: Thread Synchronization Project
// Date assigned: 1/24/2018
// Programmer: Kunal Mukherjee Date completed: 2/7/2018
#include "buffer.h"
#include <cstdlib>
#include <iostream>
#include <unistd.h>
#include <time.h>
#include <semaphore.h>
int sleep_time; //the sleep_time shared between the processes
//declaring semaphores and pthread_mutex
sem_t empty;
sem_t full;
pthread_mutex_t mutex;
pthread_mutex_t mutex_cout;
#define MAX_ITEM 5000
using namespace std;
void *Producer (void* param);
void *Consumer (void* param);
//main gets the command line argument
//initialize buffer
//creates producer threads
//creates consumer threads
//sleep
//exit
int main(int argc, char* argv[]){
//check to see if all the arguments are corrrectly entered
if (argc != 4){
cout << "usage: " << argv[0] << " sleep_time num_producer_thread num_comsumer_thread " << endl;
return 0;
}
//storing variable from input
int num_producer_thread;
int num_consumer_thread;
//variables intitialized
sleep_time = atoi(argv[1]);
num_producer_thread = atoi(argv[2]);
num_consumer_thread = atoi(argv[3]);
//semaphores intiialized
sem_init(&empty, 0, BUFFER_SIZE);
sem_init(&full, 0, 0);
//inititalize the buffer
for (int i = 0; i < BUFFER_SIZE; i++){
buffer[i] = -1;
}
//initialize random number generator
srand(time(0));
//creating pthread arrays for producer and consumer
pthread_t producer_thread [100];
pthread_t consumer_thread [100];
//creating the producer threads
for (int i = 0; i < num_producer_thread; i++){
if (pthread_create(&producer_thread[i], NULL, Producer, (void *)(intptr_t) i)){
cout << "Producer thread cannot be created" << endl;
return 1;
}
else
cout << "Created Producer # " << i << endl;
}
//creating the consumer threads
for (int i = 0; i < num_consumer_thread; i++){
if (pthread_create(&consumer_thread[i], NULL, Consumer, (void *)(intptr_t) i)){
cout << "consumer thread cannot be created" << endl;
return 1;
}
else
cout << "Created consumer # " << i << endl;
}
printBuffer();
sleep(sleep_time);
return 0;
//return 0;
}
void *Producer (void* param){
buffer_item item;
int pid = (intptr_t)param;
do{
//sleep at a random time in between the main sleeps
sleep (rand() % (sleep_time + 1));
//get a random number
item = rand() % (MAX_ITEM + 1);
//get cout mutex lock
pthread_mutex_lock(&mutex_cout);
cout << "Producer # " << pid << " waiting on empty semaphore" << endl;
//get cout mutex lock
pthread_mutex_unlock(&mutex_cout);
//wait for empty semaphore
sem_wait(&empty);
//get cout mutex lock
pthread_mutex_lock(&mutex_cout);
cout << "Producer # " << pid << " getting mutex lock" << endl;
//get cout mutex lock
pthread_mutex_unlock(&mutex_cout);
//getting mutex lock for start entering items
pthread_mutex_lock(&mutex);
insert_item(item);
//get cout mutex lock
pthread_mutex_lock(&mutex_cout);
cout << "Producer # " << pid << " produced " << item << endl;
printBuffer();
//get cout mutex lock
pthread_mutex_unlock(&mutex_cout);
//get cout mutex lock
pthread_mutex_lock(&mutex_cout);
cout << "Producer # " << pid << " releasing mutex lock" << endl;
//set cout mutex unlock
pthread_mutex_unlock(&mutex_cout);
pthread_mutex_unlock(&mutex);
cout << "Producer # " << pid << " signalling full" << endl;
cout << "\n\n\n\n" << endl;
//get cout mutex lock
pthread_mutex_unlock(&mutex_cout);
//unlock full
sem_post (&full);
}while(1);
}
void *Consumer (void* param){
buffer_item item;
int pid = (intptr_t)param;
do{
//sleep at a random time in between the main sleeps
sleep (rand() % (sleep_time));
//get cout mutex lock
pthread_mutex_lock(&mutex_cout);
cout << "Consumer # " << pid << " waiting on full semaphore" << endl;
//get cout mutex lock
pthread_mutex_unlock(&mutex_cout);
//wait for full semaphore
sem_wait(&full);
//get cout mutex lock
pthread_mutex_lock(&mutex_cout);
cout << "Consumer # " << pid << " getting mutex lock" << endl;
//get cout mutex lock
pthread_mutex_unlock(&mutex_cout);
//getting mutex lock for start entering items
pthread_mutex_lock(&mutex);
remove_item(&item);
//get cout mutex lock
pthread_mutex_lock(&mutex_cout);
cout << "Consumer # " << pid << " consumed " << item << endl;
printBuffer();
//get cout mutex lock
pthread_mutex_unlock(&mutex_cout);
//get cout mutex lock
pthread_mutex_lock(&mutex_cout);
cout << "Consumer # " << pid << " releasing mutex lock" << endl;
//get cout mutex lock
pthread_mutex_unlock(&mutex_cout);
//releasing mutex lock
pthread_mutex_unlock(&mutex);
//get cout mutex lock
pthread_mutex_lock(&mutex_cout);
cout << "Consumer # " << pid << " signalling empty" << endl;
cout << "\n\n\n\n" << endl;
//get cout mutex lock
pthread_mutex_unlock(&mutex_cout);
//unlock the semaphore refrence
sem_post (&empty);
}while(1);
}
| true |
7dff134f06debc26556c4f099f34224dfa9543b3 | C++ | CaoMingAAA/PTA | /pta_work/2018/L2-1.cpp | UTF-8 | 937 | 2.921875 | 3 | [] | no_license | #include "pch.h"
#include <iostream>
#include <vector>
using namespace std;
const int MAX = 10005;
int N, M, K;
bool isVaild(vector<int>Adj[], vector<int> V)
{
int Np;
cin >> Np;
for (int i = 0; i < Np; i++)
{
int a;
cin >> a;
V[a] = 0;
int len = Adj[a].size();
for (int j = 0; j < len; j++)
if(V[Adj[a][j]] != 0)
V[Adj[a][j]] --;
}
for (int i = 1; i <= N; i++)
{
if (V[i] != 0)
return false;
}
return true;
}
/*
int main()
{
cin >> N >> M;
if (N == 1)
{
int a;
cin >> K;
for (int i = 0; i < K; i++)
{
cin >> a;
if (a == 1)
cout << "YES" << endl;
}
return 0;
}
vector<int>V(N+2,0);
vector<int>Adj[MAX];
for (int i = 0; i < M; i++)
{
int a; cin >> a;
int b; cin >> b;
Adj[a].push_back(b);
Adj[b].push_back(a);
V[a]++;
V[b]++;
}
cin >> K;
while (K!=0)
{
if (isVaild(Adj, V))
cout << "YES" << endl;
else
cout << "NO" << endl;
K--;
}
return 0;
}
*/ | true |
ec3ed7a1e309b5ba10a306da4e78559bef8685ea | C++ | jjwmezun/boskeopolis-land-2 | /src/input.cpp | UTF-8 | 1,366 | 2.59375 | 3 | [] | no_license | #include "input.hpp"
namespace Input
{
static constexpr int MAX_INPUT_TYPES = ( int )( Type::__NULL );
static bool held_[ MAX_INPUT_TYPES ] = { false };
static bool pressed_[ MAX_INPUT_TYPES ] = { false };
static bool released_since_reset_[ MAX_INPUT_TYPES ] = { true };
static bool held_for_frame_[ MAX_INPUT_TYPES ] = { false };
bool isHeld( Type input )
{
return held_[ ( int )( input ) ];
};
bool isPressed( Type input )
{
return pressed_[ ( int )( input ) ];
};
void setHeld( Type input )
{
if ( input != Type::__NULL )
{
if ( !held_[ ( int )( input ) ] )
{
pressed_[ ( int )( input ) ] = true;
}
held_for_frame_[ ( int )( input ) ] = true;
held_[ ( int )( input ) ] = released_since_reset_[ ( int )( input ) ];
}
};
void setReleased( Type input )
{
if ( input != Type::__NULL )
{
held_[ ( int )( input ) ] = false;
pressed_[ ( int )( input ) ] = false;
released_since_reset_[ ( int )( input ) ] = true;
}
};
void update()
{
for ( int i = 0; i < MAX_INPUT_TYPES; ++i )
{
pressed_[ i ] = false;
if ( !held_for_frame_[ i ] )
{
released_since_reset_[ i ] = true;
}
held_for_frame_[ i ] = false;
}
}
void reset()
{
for ( int i = 0; i < MAX_INPUT_TYPES; ++i )
{
held_[ i ] = pressed_[ i ] = released_since_reset_[ i ] = held_for_frame_[ i ] = false;
}
};
}
| true |
66ac5e41b566b97becbd8b0bb892e85c16c49ac0 | C++ | zxjcarrot/iris | /include/formatter.h | UTF-8 | 1,028 | 2.65625 | 3 | [
"MIT"
] | permissive | #ifndef IRIS_FORMATTER_H_
#define IRIS_FORMATTER_H_
#include "define.h"
#include "buffered_writer.h"
#include "utils.h"
namespace iris {
// fomatter do the real formatting logic, output into @obuf
// return false if there is not enough space in @obuf.
typedef void (*formatter_type)(const loglet_t & l, buffered_writer & w);
template<typename Formatter, typename...Args, std::size_t...Indexes>
static void call_format(buffered_writer & w, const std::tuple<Args...> & args, seq<Indexes...>) {
return Formatter::format(&w, std::move(std::get<Indexes>(args))...);
}
template<typename Formatter, typename... Args>
static void formatter_caller(const loglet_t & l, buffered_writer & w) {
const size_t args_offset = sizeof(formatter_type);
typedef std::tuple<Args...> Args_t;
Args_t & args = *reinterpret_cast<Args_t*>(l.rbuf_ptr + args_offset);
typename make_sequence<sizeof...(Args)>::type indexes;
call_format<Formatter>(w, args, indexes);
//deconstruct parameter pack
args.~Args_t();
}
}
#endif | true |
21fcf5c3eef74e28f51c2dec1d4e82fd61eb1439 | C++ | Pingli/SoloProjects | /pacman/src/Game/Character.cpp | UTF-8 | 2,296 | 3.203125 | 3 | [] | no_license | #include "Character.hpp"
#include "../Settings.hpp"
#include "Structs.hpp"
#include <cassert>
Character::Character()
{
positionOffset.x = TILE_WIDTH / 2.0f;
positionOffset.y = TILE_HEIGHT / 2.0f;
}
void Character::MoveToDirection(GameInfo & info, const sf::Vector2i &direction)
{
assert(abs(direction.x) + abs(direction.y) <= 1);
sf::Vector2i tile = GetCurrentTilePosition();
tile += direction;
SetPositionToTile(tile);
}
bool Character::CanMoveToTile(const GameInfo& info, const sf::Vector2i& tile)
{
int a;
return CanMoveToTile(info, tile, a);
}
bool Character::CanMoveToTile(const GameInfo& info, const sf::Vector2i& tile, int& outTile)
{
sf::Vector2i tileCopy(tile);
if (tile.y < 0 || tile.y > info.level.size() - 1)
{
assert(false);
return false;
}
WrapTileX(tileCopy);
outTile = info.level[tileCopy.y][tileCopy.x];
Tile t = (Tile)outTile;
switch (t)
{
case Tile::EMPTY:
case Tile::PICKUP:
case Tile::PICKUP_BIG:
return true;
default:
return false;
}
}
bool Character::CanMoveToTile(const GameInfo& info, const Direction& direction, int& outTile) const
{
sf::Vector2i dir = DirectionEnumToVector2i(direction);
return CanMoveToTile(info, GetCurrentTilePosition() + dir, outTile);
}
bool Character::CanMoveToTile(const GameInfo& info, const Direction& direction) const
{
int outTile;
sf::Vector2i dir = DirectionEnumToVector2i(direction);
return CanMoveToTile(info, GetCurrentTilePosition() + dir, outTile);
}
bool Character::IsInIntersection(const GameInfo& info) const
{
const unsigned char numberOfDirections = 3;
unsigned char count = 0;
count += CanMoveToTile(info, Direction::Down);
count += CanMoveToTile(info, Direction::Left);
count += CanMoveToTile(info, Direction::Up);
count += CanMoveToTile(info, Direction::Right);
if (count >= numberOfDirections)
{
return true;
}
return false;
}
void Character::Update(GameInfo& info)
{
}
sf::Vector2i Character::DirectionEnumToVector2i(const Direction& direction)
{
switch (direction)
{
case Direction::Up:
return sf::Vector2i(0, -1);
case Direction::Left:
return sf::Vector2i(-1, 0);
case Direction::Right:
return sf::Vector2i(1, 0);
case Direction::Down:
return sf::Vector2i(0, 1);
case Direction::None:
default:
return sf::Vector2i(0, 0);
}
} | true |
4b23083ba9852630b55f9f08a073b3bad5372cc2 | C++ | IgnacioMorillas/Informatica_Grafica_2019-2020 | /Practica1_IG_IgnacioMorillas/objetos_B.cc | UTF-8 | 7,284 | 2.671875 | 3 | [] | no_license | //**************************************************************************
// Práctica 1 usando objetos
//**************************************************************************
#include "objetos_B.h"
//*************************************************************************
// _puntos3D
//*************************************************************************
_puntos3D::_puntos3D()
{
}
//*************************************************************************
// dibujar puntos
//*************************************************************************
void _puntos3D::draw_puntos(float r, float g, float b, int grosor)
{
int i;
glPointSize(grosor);
glColor3f(r,g,b);
glBegin(GL_POINTS);
for (i=0;i<vertices.size();i++){
glVertex3fv((GLfloat *) &vertices[i]);
}
glEnd();
}
//*************************************************************************
// _triangulos3D
//*************************************************************************
_triangulos3D::_triangulos3D()
{
}
//*************************************************************************
// dibujar en modo arista
//*************************************************************************
void _triangulos3D::draw_aristas(float r, float g, float b, int grosor)
{
int i;
glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
glLineWidth(grosor);
glColor3f(r,g,b);
glBegin(GL_TRIANGLES);
for (i=0;i<caras.size();i++){
glVertex3fv((GLfloat *) &vertices[caras[i]._0]);
glVertex3fv((GLfloat *) &vertices[caras[i]._1]);
glVertex3fv((GLfloat *) &vertices[caras[i]._2]);
}
glEnd();
}
//*************************************************************************
// dibujar en modo sólido
//*************************************************************************
void _triangulos3D::draw_solido(float r, float g, float b)
{
int i;
glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
glColor3f(r,g,b);
glBegin(GL_TRIANGLES);
for (i=0;i<caras.size();i++){
glVertex3fv((GLfloat *) &vertices[caras[i]._0]);
glVertex3fv((GLfloat *) &vertices[caras[i]._1]);
glVertex3fv((GLfloat *) &vertices[caras[i]._2]);
}
glEnd();
}
//*************************************************************************
// dibujar en modo sólido con apariencia de ajedrez
//*************************************************************************
void _triangulos3D::draw_solido_ajedrez(float r1, float g1, float b1, float r2, float g2, float b2)
{
int i;
glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
glBegin(GL_TRIANGLES);
for (i=0;i<caras.size();i++){
if(i%2==0){
glColor3f(r1,g1,b1);
}
else{
glColor3f(r2,g2,b2);
}
glVertex3fv((GLfloat *) &vertices[caras[i]._0]);
glVertex3fv((GLfloat *) &vertices[caras[i]._1]);
glVertex3fv((GLfloat *) &vertices[caras[i]._2]);
}
glEnd();
}
//*************************************************************************
// clase cubo
//*************************************************************************
_cubo::_cubo(float tam)
{
//vertices
vertices.resize(8);
///-vertices cara de abajo
vertices[0].x=0;vertices[0].y=0;vertices[0].z=-tam;
vertices[1].x=tam;vertices[1].y=0;vertices[1].z=-tam;
vertices[2].x=tam;vertices[2].y=0;vertices[2].z=0;
vertices[3].x=0;vertices[3].y=0;vertices[3].z=0;
///-vertices cara de arriba
vertices[4].x=0;vertices[4].y=tam;vertices[4].z=0;
vertices[5].x=0;vertices[5].y=tam;vertices[5].z=-tam;
vertices[6].x=tam;vertices[6].y=tam;vertices[6].z=-tam;
vertices[7].x=tam;vertices[7].y=tam;vertices[7].z=0;
//caracteristicas
caras.resize(12);
//Cara base
caras[0]._0=0;caras[0]._1=3;caras[0]._2=1;
caras[1]._0=3;caras[1]._1=2;caras[1]._2=1;
//caratrasera
caras[2]._0=7;caras[2]._1=2;caras[2]._2=3;
caras[3]._0=4;caras[3]._1=7;caras[3]._2=3;
//cara izq
caras[4]._0=4;caras[4]._1=3;caras[4]._2=0;
caras[5]._0=0;caras[5]._1=5;caras[5]._2=4;
//cara frontal
caras[6]._0=0;caras[6]._1=5;caras[6]._2=1;
caras[7]._0=1;caras[7]._1=5;caras[7]._2=6;
//cara derecha
caras[8]._0=6;caras[8]._1=2;caras[8]._2=1;
caras[9]._0=2;caras[9]._1=6;caras[9]._2=7;
//cara superior
caras[10]._0=7;caras[10]._1=6;caras[10]._2=4;
caras[11]._0=4;caras[11]._1=6;caras[11]._2=5;
}
//*************************************************************************
// clase piramide
//*************************************************************************
_piramide::_piramide(float tam, float al)
{
//vertices
vertices.resize(5);
vertices[0].x=-tam;vertices[0].y=0;vertices[0].z=tam;
vertices[1].x=tam;vertices[1].y=0;vertices[1].z=tam;
vertices[2].x=tam;vertices[2].y=0;vertices[2].z=-tam;
vertices[3].x=-tam;vertices[3].y=0;vertices[3].z=-tam;
vertices[4].x=0;vertices[4].y=al;vertices[4].z=0;
caras.resize(6);
caras[0]._0=0;caras[0]._1=1;caras[0]._2=4;
caras[1]._0=1;caras[1]._1=2;caras[1]._2=4;
caras[2]._0=2;caras[2]._1=3;caras[2]._2=4;
caras[3]._0=3;caras[3]._1=0;caras[3]._2=4;
caras[4]._0=3;caras[4]._1=1;caras[4]._2=0;
caras[5]._0=3;caras[5]._1=2;caras[5]._2=1;
}
//*************************************************************************
// clase rombo
//*************************************************************************
_rombo::_rombo(float tam, float al)
{
//vertices
vertices.resize(6);
vertices[0].x=-tam;vertices[0].y=0;vertices[0].z=tam;
vertices[1].x=tam;vertices[1].y=0;vertices[1].z=tam;
vertices[2].x=tam;vertices[2].y=0;vertices[2].z=-tam;
vertices[3].x=-tam;vertices[3].y=0;vertices[3].z=-tam;
vertices[4].x=0;vertices[4].y=al;vertices[4].z=0;
vertices[5].x=0;vertices[5].y=-al;vertices[5].z=0;
caras.resize(8);
//cara superior delantera
caras[0]._0=0;caras[0]._1=1;caras[0]._2=4;
//cara superior derecha
caras[1]._0=1;caras[1]._1=2;caras[1]._2=4;
//cara superior trasera
caras[2]._0=2;caras[2]._1=3;caras[2]._2=4;
//cara superior izquierda
caras[3]._0=3;caras[3]._1=0;caras[3]._2=4;
//cara inferior izquierda
caras[4]._0=3;caras[4]._1=5;caras[4]._2=0;
//cara inferior delantera
caras[5]._0=0;caras[5]._1=5;caras[5]._2=1;
//cara inferior derecha
caras[6]._0=1;caras[6]._1=5;caras[6]._2=2;
//cara inferiro trasera
caras[7]._0=2;caras[7]._1=5;caras[7]._2=3;
//caras[4]._0=3;caras[4]._1=1;caras[4]._2=0;
//caras[5]._0=3;caras[5]._1=2;caras[5]._2=1;
}
//*************************************************************************
// clase piramidecorta
//*************************************************************************
_piramidecorta::_piramidecorta(float tam, float al)
{
//vertices
vertices.resize(7);
vertices[0].x=-tam;vertices[0].y=0;vertices[0].z=0;
vertices[1].x=0;vertices[1].y=0;vertices[1].z=0;
vertices[2].x=0;vertices[2].y=0;vertices[2].z=tam;
vertices[3].x=tam;vertices[3].y=0;vertices[3].z=tam;
vertices[4].x=tam;vertices[4].y=0;vertices[4].z=-tam;
vertices[5].x=-tam;vertices[5].y=0;vertices[5].z=-tam;
vertices[6].x=0;vertices[6].y=al;vertices[6].z=0;
caras.resize(10);
//caras de las bases
caras[0]._0=0;caras[0]._1=5;caras[0]._2=1;
caras[1]._0=1;caras[1]._1=5;caras[1]._2=4;
caras[2]._0=1;caras[2]._1=4;caras[2]._2=3;
caras[3]._0=1;caras[3]._1=3;caras[3]._2=2;
//caras verticales
caras[4]._0=6;caras[4]._1=2;caras[4]._2=3;
caras[5]._0=6;caras[5]._1=3;caras[5]._2=4;
caras[6]._0=6;caras[6]._1=4;caras[6]._2=5;
caras[7]._0=6;caras[7]._1=5;caras[7]._2=0;
caras[8]._0=6;caras[8]._1=0;caras[8]._2=1;
caras[9]._0=6;caras[9]._1=1;caras[9]._2=2;
}
| true |
8a737a0019437cf7bed99d222eb81d8bdbdb89b9 | C++ | shivang-saxena/IB | /DataStructure/Math & Array/Merge_Intervals.cpp | UTF-8 | 1,859 | 3.609375 | 4 | [] | no_license | /*
Merge Intervals
Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary). You may assume that the
intervals were initially sorted according to their start times. Example 1: Given intervals [1,3],[6,9] insert and merge [2,5] would
result in [1,5],[6,9]. Example 2: Given [1,2],[3,5],[6,7],[8,10],[12,16], insert and merge [4,9] would result in [1,2],[3,10],[12,16].
This is because the new interval [4,9] overlaps with [3,5],[6,7],[8,10]. Make sure the returned intervals are also sorted.
*/
/* Solution Approach
Have you covered the following corner cases : 1) Size of interval array as 0. 2) newInterval being an interval preceding all intervals in the array.
Given interval (3,6),(8,10), insert and merge (1,2)
3) newInterval being an interval succeeding all intervals in the array.
Given interval (1,2), (3,6), insert and merge (8,10)
4) newInterval not overlapping with any interval and falling in between 2 intervals in the array.
Given interval (1,2), (8,10) insert and merge (3,6)
5) newInterval covering all given intervals.
Given interval (3, 5), (7, 9) insert and merge (1, 10)
*/
#include<bits/stdc++.h>
using namespace std;
class Solution{
bool mycomp(Interval a,Interval b){
return a.start<b.start;
}
vector<Interval> Solution::insert(vector<Interval> &intervals, Interval newInterval) {
intervals.push_back(newInterval);
sort(intervals.begin(),intervals.end(),mycomp);
vector<Interval> res;
int n=intervals.size();
res.push_back(intervals[0]);
for(int i=1;i<n;i++){
if(intervals[i].start<=res[res.size()-1].end)
res[res.size()-1].end=max(res[res.size()-1].end,intervals[i].end);
else
res.push_back(intervals[i]);
}
return res;
}
int main(){
//input-output code
return 0;
}
}; | true |
c4911fa03affacf6591e1f530c62b86ecf1c9312 | C++ | moonbl3da/bev_prog | /week_07/Drill08/drill08_2.cpp | UTF-8 | 757 | 3.203125 | 3 | [] | no_license | #include "std_lib_facilities.h"
using namespace std;
void swap_v(int a,int b){
int temp;
temp = a;
a = b;
b = temp;
}
void swap_r(int& a,int& b){
int temp;
temp = a;
a = b;
b = temp;
}
/*void swap_cr(const int& a,const int& b){
int temp;
temp = a;
a = b;
b = temp;
} --------------------------Nem müködik----------------------------! */
int main() {
int x = 7;
int y = 9;
swap_r(x,y); /* kicseréli */
swap_v(7,9);
const int cx = 7;
const int cy = 9;
swap_v(cx,cy);
swap_v(7.7,9.9); /* nem cseréli */
double dx = 7.7;
double dy = 9.9;
swap_v(dx,dy);
swap_v(7.7,9.9); /* nem cseréli */
/* Ellenőrzés: */
cout<<x<<' '<<y<<endl;
cout<<cx<<' '<<cy<<endl;
cout<<dx<<' '<<dy<<endl;
return 0;
}
| true |
7bd3536fcf410336e493feb60ccdc347f547aeff | C++ | PoojaRani24/Leetcode_Monthly_Challenge | /Diameter of a Binary Tree.cpp | UTF-8 | 437 | 3.078125 | 3 | [
"MIT"
] | permissive | pair<int,int> dfs(Node* root){
if(root==NULL)
return {0,0};
pair<int,int> left=dfs(root->left);
pair<int,int> right=dfs(root->right);
int dia=max(left.first,right.first);
dia=max(dia,(left.second+right.second));
return {dia,max(left.second+1,right.second+1)};
}
/* Computes the diameter of binary tree with given root. */
int diameter(Node* node) {
// Your code here
return dfs(node).first+1;
}
| true |
3a253e0f64aceedd92b41c949db2745b0ee35490 | C++ | dedoser/cpp_modules | /cpp_03/ex00/main.cpp | UTF-8 | 2,096 | 2.734375 | 3 | [] | no_license | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* main.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: fignigno <fignigno@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/04/22 00:52:53 by fignigno #+# #+# */
/* Updated: 2021/04/22 01:15:25 by fignigno ### ########.fr */
/* */
/* ************************************************************************** */
#include <cstdlib>
#include <fstream>
#include <iostream>
#include "FragTrap.hpp"
int main(void)
{
std::cout << "---------TESTING CREATION FRAGTRAPS---------" << std::endl;
FragTrap frag1("Bot");
FragTrap frag2(frag1);
FragTrap frag3 = frag1;
FragTrap frag4("Bomb");
std::cout << "---------TESTING MELEEATTACK---------" << std::endl;
frag1.meleeAttack("ClapTrap");
frag2.meleeAttack("FRGTRP");
frag3.meleeAttack("Echo");
frag4.meleeAttack("ICANON");
std::cout << "---------TESTING RANGEDATTACK---------" << std::endl;
frag1.rangedAttack("ClapTrap");
frag2.rangedAttack("FRGTRP");
frag3.rangedAttack("Echo");
frag4.rangedAttack("ICANON");
std::cout << "---------TESTING TAKING DAMAGE---------" << std::endl;
frag1.takeDamage(32);
frag2.takeDamage(232323);
frag3.takeDamage(23);
frag4.takeDamage(1);
std::cout << "---------TESTING REPAIR---------" << std::endl;
frag1.beRepaired(50);
frag2.beRepaired(75);
frag3.beRepaired(100);
frag4.beRepaired(0);
std::cout << "---------TESTING VAULTHUNTERDOT_EXE---------" << std::endl;
frag1.vaulthunter_dot_exe("Enemy");
frag2.vaulthunter_dot_exe("Blight Bot");
frag3.vaulthunter_dot_exe("Funzerking");
frag4.vaulthunter_dot_exe("Mechromagician");
}
| true |
9dfe1d11dc2f7b71decb5a8d33b1301779296cb3 | C++ | markmakemate/Statistic-Learning-Theory | /Algorithms_Layer/kNN/BiNode.h | UTF-8 | 558 | 2.9375 | 3 | [] | no_license | #include<iostream>
#include<cstdlib>
using namespace std;
template<class table>
struct BiNode {
table data; //data, a table object with one row and k columns
table split_point; //split point, a table object with single element
Biode<table>* left; //left child pointer
BSTreeNode<table>* right; //right child pointer
BSTreeNode<table>* father; //father pointer
int depth; //node's depth
BSTreeNode(table x,table point,int d) :data(x), split_point(point),depth(d),left(NULL), right(NULL){}
}; //Declaration of Binary search tree node
| true |
a68fde54c1e13c2e24e4ec3e85e8e0a03dd248d0 | C++ | invy/qmlcycling | /riderdata.h | UTF-8 | 2,416 | 2.65625 | 3 | [] | no_license | #ifndef RIDERDATA_H
#define RIDERDATA_H
#include <QObject>
class RiderData : public QObject
{
Q_OBJECT
Q_PROPERTY(qint32 weight READ weight WRITE setWeight NOTIFY weightChanged)
Q_PROPERTY(qint32 bikeWeight READ bikeWeight WRITE setBikeWeight NOTIFY bikeWeightChanged)
Q_PROPERTY(qint32 tireWidth READ tireWidth WRITE setTireWidth NOTIFY tireWidthChanged)
Q_PROPERTY(qint32 largeChainRing READ largeChainRing WRITE setLargeChainRing NOTIFY largeChainRingChanged)
Q_PROPERTY(qint32 smallChainRing READ smallChainRing WRITE setSmallChainRing NOTIFY smallChainRingChanged)
Q_PROPERTY(qint32 smallestCog READ smallestCog WRITE setSmallestCog NOTIFY smallestCogChanged)
Q_PROPERTY(qint32 biggestCog READ biggestCog WRITE setBiggestCogh NOTIFY biggestCogChanged)
public:
void setWeight(qint32 w) {
this->m_weight = w;
emit weightChanged();
}
void setBikeWeight(qint32 w) {
this->m_bikeWeight = w;
emit weightChanged();
}
void setTireWidth(qint32 w) {
this->m_tireWidth = w;
emit tireWidthChanged();
}
void setLargeChainRing(qint32 v) {
this->m_largeChainRing = v;
emit largeChainRingChanged();
}
void setSmallChainRing(qint32 v) {
this->m_smallChainRing = v;
emit smallChainRingChanged();
}
void setSmallestCog(qint32 v) {
this->m_smallestCog = v;
emit smallestCogChanged();
}
void setBiggestCogh(qint32 v) {
this->m_biggestCog = v;
emit biggestCogChanged();
}
qint32 weight() { return m_weight; }
qint32 bikeWeight() { return m_bikeWeight; }
qint32 tireWidth() { return m_tireWidth; }
qint32 largeChainRing() { return m_largeChainRing; }
qint32 smallChainRing() { return m_smallChainRing; }
qint32 smallestCog() { return m_smallestCog; }
qint32 biggestCog() { return m_biggestCog; }
public:
explicit RiderData(QObject *parent = 0);
signals:
void weightChanged();
void bikeWeightChanged();
void tireWidthChanged();
void largeChainRingChanged();
void smallChainRingChanged();
void smallestCogChanged();
void biggestCogChanged();
public slots:
private:
qint32 m_weight;
qint32 m_bikeWeight;
qint32 m_tireWidth;
qint32 m_largeChainRing;
qint32 m_smallChainRing;
qint32 m_smallestCog;
qint32 m_biggestCog;
};
#endif // RIDERDATA_H
| true |