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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
f9bb9281d2c7099c1c2dfa2af1ac9742fae83b10 | C++ | rskryptik61636/DirectXLearning | /include/SimpleQuad.h | UTF-8 | 979 | 2.671875 | 3 | [] | no_license | // header file for the SimpleQuad class
#ifndef SIMPLE_QUAD_H
#define SIMPLE_QUAD_H
#include "ObjectV2.h"
class SimpleQuad : public ObjectV2<SimpleVertex>
{
public:
// param ctor 1, takes in the 4 quad points in CW order as well as the color of each point
SimpleQuad(const std::vector<SimpleVertex> pts);
// define vertex buffer
void initVertexBuffer();
// define index buffer
void initIndexBuffer();
// override the init method to make the vertex buffer dynamic
void init(ID3D11Device *device, float scale);
// updates the color of all the points with the given color
void updateColor(const DXColor color);
// @TODO: define public methods here
protected:
// @TODO: define protected methods here
public:
// @TODO: define public members here
protected:
// quad vertices
std::vector<SimpleVertex> m_pts;
// @TODO: define protected members here
}; // end of class SimpleQuad
typedef std::unique_ptr<SimpleQuad> SimpleQuadPtr;
#endif // SIMPLE_QUAD_H | true |
91595e63023d73541caa91dd75beed509c1ea62b | C++ | tz924/cs38 | /Homework6/ps6_p1_test.cpp | UTF-8 | 2,354 | 3.671875 | 4 | [] | no_license | //
// Assignment name: Problem Set 6
// File name: ps6_p1_test.cpp
// Author: Jing Zhang
//
#include "ps6.h"
using namespace std;
void part1Test()
{
int dollar12 = 12;
int cents3 = 3;
int cents30 = 30;
int cents300 = 300;
double goodCash = 12.3;
double badCash = 1.234;
double crazyCash = 123.456;
// Test default constructor
Money m;
m.show(); // Should be $0.00
// Test 2-arg int constructor
Money m21(dollar12, cents3);
m21.show(); // Should be $12.03
Money m22(dollar12, cents30);
m22.show(); // Should be $12.30
Money m23(dollar12, cents300);
m23.show(); // Should be $15.00
Money m24(dollar12);
m24.show(); // Should be $12.00
// Test 1-arg double constructor
Money m11(goodCash); // Should be $12.30
m11.show();
Money m12(badCash); // Should be $1.23
m12.show();
Money m13(crazyCash); // Should be $123.45
m13.show();
// Test copy constructor
Money mCopy = m13;
mCopy.show(); // Should be $123.45
// Test destructor
Money *cash = new Money(mCopy);
mCopy.show(); // Should be $123.45
delete cash;
// Test 2-arg int set
mCopy.set(dollar12, cents3); // Should be $12.3
mCopy.show();
try
{
mCopy.set(dollar12, cents300); // Won't allow
}
catch (const char* e)
{
cout << e << endl;
}
// Test 1-arg double set
mCopy.set(goodCash);
mCopy.show(); // Should be $12.30
// Test increase
mCopy.increase(dollar12, cents30);
mCopy.show(); // Should be $24.60
mCopy.increase(dollar12, cents300);
mCopy.show(); // Should be $39.60
// Test decrease
mCopy.decrease(dollar12, cents30);
mCopy.show(); // Should be $27.30
mCopy.decrease(dollar12, cents300);
mCopy.show(); // Should be $12.30 (Back)
// Test += with another object
Money myWallet;
myWallet.show();
myWallet += mCopy;
myWallet.show(); // Should be $12.30
// Test += with a double
myWallet += 12.3; // double literal
myWallet += goodCash; // double variable
myWallet.show(); // Should be $36.90
// Test << and >>
cin >> m; // 11 22 will be $11.22
cout << m; // Display the above
// Test comparison (Should show all 4)
Money treasure(1);
Money bank(2);
if (treasure < bank)
cout << "I'm richer" << endl;
if (bank > treasure)
cout << "I'm poorer" << endl;
treasure += 1;
if (treasure == bank)
cout << "I am lucky" << endl;
bank += 1;
if (treasure != bank)
cout << "I don't care" << endl;
}
| true |
d8d3beca43bc3091ebf55403360ab574d348c8af | C++ | wuxingyu1983/Algorithm | /LightOJ/PalindromicNumbers/main.cc | UTF-8 | 3,090 | 2.75 | 3 | [
"Apache-2.0"
] | permissive | #include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <fstream>
#include <stdlib.h>
using namespace std;
#define DEBUG 0
// 最大位数 18 位
const int max_bits = 18;
// bit 位 回文数 的个数
unsigned long long cnt[max_bits];
unsigned long long fnCount(vector<int> &digits, int idx, int lo, int hi)
{
unsigned long long ret = 0;
int n = digits.size();
if (idx == 1 + ceil(((float)n) / 2.0))
{
if (lo <= hi)
{
return 1;
}
else
{
return 0;
}
}
int start = 0;
if (1 == idx)
{
start = 1;
// 0
for (size_t i = 1; i < n; i++)
{
ret += cnt[i];
}
}
if (0 <= digits[idx - 1] - 1)
{
int j = n - 2 * idx;
if (0 > j)
{
ret += digits[idx - 1] - start;
}
else
{
for (; j >= 0; j -= 2)
{
ret += (digits[idx - 1] - start) * cnt[j];
}
}
}
// for (size_t i = start; i <= 9; i++)
{
int i = digits[idx - 1];
int tmp_lo = lo;
int tmp_hi = hi;
if (i < digits[idx - 1] && idx < tmp_lo) tmp_lo = idx;
if (i < digits[n - idx] && n - idx + 1 < tmp_lo) tmp_lo = n - idx + 1;
if (i > digits[idx - 1] && idx < tmp_hi) tmp_hi = idx;
if (i > digits[n - idx] && n - idx + 1 < tmp_hi) tmp_hi = n - idx + 1;
ret += fnCount(digits, idx + 1, tmp_lo, tmp_hi);
}
return ret;
}
unsigned long long getCount(long long num)
{
unsigned long long ret = 0;
if (num < 10)
{
return num + 1;
}
unsigned long long tmp = num;
vector<int> nums;
for (unsigned long long i = 100000000000000000; i > 0; i /= 10)
{
unsigned long long n = tmp / i;
if (0 == n)
{
if (0 < nums.size())
{
nums.push_back(n);
}
}
else
{
nums.push_back(n);
}
tmp %= i;
}
ret += fnCount(nums, 1, nums.size() + 1, nums.size() + 1);
return ret;
}
int main()
{
#if DEBUG
ifstream inFile;
inFile.open("input.txt");
#endif
// init cnt[max_bits]
cnt[0] = 1;
cnt[1] = 10; // 0 - 9
cnt[2] = 9; // 11 - 99
for (int i = 3; i < max_bits; i++)
{
for (int j = i - 2; j >= 0; j -= 2)
{
cnt[i] += 9 * cnt[j];
}
}
unsigned int t;
#if DEBUG
inFile >> t;
#else
cin >> t;
#endif
for (size_t i = 0; i < t; i++)
{
unsigned long long x, y;
#if DEBUG
inFile >> x >> y;
#else
cin >> x >> y;
#endif
if (x > y)
{
unsigned long long tmp = x;
x = y;
y = tmp;
}
cout << "Case " << i + 1 << ": " << getCount(y) - getCount(x - 1) << endl;
}
#if DEBUG
inFile.close();
#endif
return 0;
}
| true |
a7f130411598d1a8618e579bf01dede875aa5b48 | C++ | Jiltseb/Leetcode-Solutions | /solutions/1275.find-winner-on-a-tic-tac-toe-game.325698245.ac.cpp | UTF-8 | 1,255 | 3.03125 | 3 | [
"MIT"
] | permissive | class Solution {
public:
string tictactoe(vector<vector<int>> &moves) {
vector<string> game(3, string(3, ' '));
char c;
for (int i = 0; i < moves.size(); i++) {
move(game, moves, i);
// c = check(game);
// if(c == 'A')return "A";
// else if(c == 'B')return "B";
}
c = check(game);
if (c == 'D') {
if (moves.size() == 9)
return "Draw";
return "Pending";
} else if (c == 'A')
return "A";
else if (c == 'B')
return "B";
return "";
}
void move(vector<string> &game, vector<vector<int>> &moves, int i) {
char c = i % 2 ? 'B' : 'A';
game[moves[i][0]][moves[i][1]] = c;
}
char check(vector<string> &game) {
for (int i = 0; i < 3; i++) {
if (game[i][0] != ' ' && game[i][0] == game[i][1] &&
game[i][1] == game[i][2])
return game[i][0];
if (game[0][i] != ' ' && game[0][i] == game[1][i] &&
game[1][i] == game[2][i])
return game[0][i];
}
if (game[0][0] != ' ' && game[0][0] == game[1][1] &&
game[1][1] == game[2][2])
return game[0][0];
if (game[2][0] != ' ' && game[2][0] == game[1][1] &&
game[1][1] == game[0][2])
return game[2][0];
return 'D';
}
};
| true |
7d0df57bd34bdf03e30c6b4ca9a53f6b7f79609b | C++ | stillwater-sc/universal | /static/posit/math/hyperbolic.cpp | UTF-8 | 13,284 | 2.75 | 3 | [
"MIT",
"LicenseRef-scancode-free-unknown",
"LGPL-3.0-only",
"LicenseRef-scancode-public-domain"
] | permissive | // function_hyperbolic.cpp: test suite runner for hyperbolic functions (sinh/cosh/tanh/atanh/acosh/asinh)
//
// Copyright (C) 2017-2022 Stillwater Supercomputing, Inc.
//
// This file is part of the universal numbers project, which is released under an MIT Open Source license.
#include <universal/utility/directives.hpp>
// when you define ALGORITHM_VERBOSE_OUTPUT the code will print intermediate results for selected arithmetic operations
//#define ALGORITHM_VERBOSE_OUTPUT
#define ALGORITHM_TRACE_SQRT
// use default number system library configuration
#include <universal/number/posit/posit.hpp>
#include <universal/verification/posit_math_test_suite.hpp>
// generate specific test case that you can trace with the trace conditions in posit.hpp
// for most bugs they are traceable with _trace_conversion and _trace_add
template<size_t nbits, size_t es, typename Ty>
void GenerateTestCaseSinh(Ty a) {
Ty ref;
sw::universal::posit<nbits, es> pa, pref, psinh;
pa = a;
ref = std::sinh(a);
pref = ref;
psinh = sw::universal::sinh(pa);
std::cout << std::setprecision(nbits - 2);
std::cout << std::setw(nbits) << a << " -> sinh(" << a << ") = " << std::setw(nbits) << ref << std::endl;
std::cout << pa.get() << " -> sinh( " << pa << ") = " << psinh.get() << " (reference: " << pref.get() << ") " ;
std::cout << (pref == psinh ? "PASS" : "FAIL") << std::endl << std::endl;
std::cout << std::setprecision(5);
}
template<size_t nbits, size_t es, typename Ty>
void GenerateTestCaseCosh(Ty a) {
Ty ref;
sw::universal::posit<nbits, es> pa, pref, pcosh;
pa = a;
ref = std::cosh(a);
pref = ref;
pcosh = sw::universal::cosh(pa);
std::cout << std::setprecision(nbits - 2);
std::cout << std::setw(nbits) << a << " -> cosh(" << a << ") = " << std::setw(nbits) << ref << std::endl;
std::cout << pa.get() << " -> cosh( " << pa << ") = " << pcosh.get() << " (reference: " << pref.get() << ") ";
std::cout << (pref == pcosh ? "PASS" : "FAIL") << std::endl << std::endl;
std::cout << std::setprecision(5);
}
template<size_t nbits, size_t es, typename Ty>
void GenerateTestCaseTanh(Ty a) {
Ty ref;
sw::universal::posit<nbits, es> pa, pref, ptanh;
pa = a;
ref = std::tanh(a);
pref = ref;
ptanh = sw::universal::tanh(pa);
std::cout << std::setprecision(nbits - 2);
std::cout << std::setw(nbits) << a << " -> tanh(" << a << ") = " << std::setw(nbits) << ref << std::endl;
std::cout << pa.get() << " -> tanh( " << pa << ") = " << ptanh.get() << " (reference: " << pref.get() << ") ";
std::cout << (pref == ptanh ? "PASS" : "FAIL") << std::endl << std::endl;
std::cout << std::setprecision(5);
}
template<size_t nbits, size_t es, typename Ty>
void GenerateTestCaseAsinh(Ty a) {
Ty ref;
sw::universal::posit<nbits, es> pa, pref, pasinh;
pa = a;
ref = std::asinh(a);
pref = ref;
pasinh = sw::universal::asinh(pa);
std::cout << std::setprecision(nbits - 2);
std::cout << std::setw(nbits) << a << " -> asinh(" << a << ") = " << std::setw(nbits) << ref << std::endl;
std::cout << pa.get() << " -> asinh( " << pa << ") = " << pasinh.get() << " (reference: " << pref.get() << ") ";
std::cout << (pref == pasinh ? "PASS" : "FAIL") << std::endl << std::endl;
std::cout << std::setprecision(5);
}
template<size_t nbits, size_t es, typename Ty>
void GenerateTestCaseAcosh(Ty a) {
Ty ref;
sw::universal::posit<nbits, es> pa, pref, pacosh;
pa = a;
ref = std::acosh(a);
pref = ref;
pacosh = sw::universal::acosh(pa);
std::cout << std::setprecision(nbits - 2);
std::cout << std::setw(nbits) << a << " -> acosh(" << a << ") = " << std::setw(nbits) << ref << std::endl;
std::cout << pa.get() << " -> acosh( " << pa << ") = " << pacosh.get() << " (reference: " << pref.get() << ") ";
std::cout << (pref == pacosh ? "PASS" : "FAIL") << std::endl << std::endl;
std::cout << std::setprecision(5);
}
template<size_t nbits, size_t es, typename Ty>
void GenerateTestCaseAtanh(Ty a) {
Ty ref;
sw::universal::posit<nbits, es> pa, pref, patanh;
pa = a;
ref = std::atanh(a);
pref = ref;
patanh = sw::universal::atanh(pa);
std::cout << std::setprecision(nbits - 2);
std::cout << std::setw(nbits) << a << " -> atanh(" << a << ") = " << std::setw(nbits) << ref << std::endl;
std::cout << pa.get() << " -> atanh( " << pa << ") = " << patanh.get() << " (reference: " << pref.get() << ") ";
std::cout << (pref == patanh ? "PASS" : "FAIL") << std::endl << std::endl;
std::cout << std::setprecision(5);
}
// Regression testing guards: typically set by the cmake configuration, but MANUAL_TESTING is an override
#define MANUAL_TESTING 0
// REGRESSION_LEVEL_OVERRIDE is set by the cmake file to drive a specific regression intensity
// It is the responsibility of the regression test to organize the tests in a quartile progression.
//#undef REGRESSION_LEVEL_OVERRIDE
#ifndef REGRESSION_LEVEL_OVERRIDE
#undef REGRESSION_LEVEL_1
#undef REGRESSION_LEVEL_2
#undef REGRESSION_LEVEL_3
#undef REGRESSION_LEVEL_4
#define REGRESSION_LEVEL_1 1
#define REGRESSION_LEVEL_2 1
#define REGRESSION_LEVEL_3 0
#define REGRESSION_LEVEL_4 0
#endif
int main()
try {
using namespace sw::universal;
std::string test_suite = "posit hyperbolic sine/cosine/tangent function validation";
std::string test_tag = "classification failed: ";
bool reportTestCases = false;
int nrOfFailedTestCases = 0;
ReportTestSuiteHeader(test_suite, reportTestCases);
#if MANUAL_TESTING
// generate individual testcases to hand trace/debug
GenerateTestCaseSinh<16, 1, double>(pi / 4.0);
GenerateTestCaseCosh<16, 1, double>(pi / 4.0);
GenerateTestCaseTanh<16, 1, double>(pi / 4.0);
GenerateTestCaseAsinh<16, 1, double>(pi / 2.0);
GenerateTestCaseAcosh<16, 1, double>(pi / 2.0);
GenerateTestCaseAtanh<16, 1, double>(pi / 4.0);
// manual exhaustive test
nrOfFailedTestCases += ReportTestResult(VerifySinh<2, 0>(reportTestCases), "posit<2,0>", "sinh");
nrOfFailedTestCases += ReportTestResult(VerifySinh<3, 0>(true), "posit<3,0>", "sinh");
nrOfFailedTestCases += ReportTestResult(VerifySinh<3, 1>(true), "posit<3,1>", "sinh");
nrOfFailedTestCases += ReportTestResult(VerifySinh<4, 0>(true), "posit<4,0>", "sinh");
nrOfFailedTestCases += ReportTestResult(VerifySinh<4, 1>(true), "posit<4,1>", "sinh");
nrOfFailedTestCases += ReportTestResult(VerifySinh<5, 0>(true), "posit<5,0>", "sinh");
nrOfFailedTestCases += ReportTestResult(VerifySinh<5, 1>(true), "posit<5,1>", "sinh");
nrOfFailedTestCases += ReportTestResult(VerifySinh<5, 2>(true), "posit<5,2>", "sinh");
nrOfFailedTestCases += ReportTestResult(VerifySinh<8, 0>(true), "posit<8,0>", "sinh");
nrOfFailedTestCases += ReportTestResult(VerifyCosh<8, 0>(true), "posit<8,0>", "cosh");
nrOfFailedTestCases += ReportTestResult(VerifyTanh<8, 0>(true), "posit<8,0>", "tanh");
nrOfFailedTestCases += ReportTestResult(VerifyAtanh<8, 0>(true), "posit<8,0>", "atanh");
nrOfFailedTestCases += ReportTestResult(VerifyAcosh<8, 0>(true), "posit<8,0>", "acosh");
nrOfFailedTestCases += ReportTestResult(VerifyAsinh<8, 0>(true), "posit<8,0>", "asinh");
ReportTestSuiteResults(test_suite, nrOfFailedTestCases);
return EXIT_SUCCESS; // ignore errors
#else
#if REGRESSION_LEVEL_1
nrOfFailedTestCases += ReportTestResult(VerifySinh<2, 0>(reportTestCases), "posit<2,0>", "sinh");
nrOfFailedTestCases += ReportTestResult(VerifySinh<3, 0>(reportTestCases), "posit<3,0>", "sinh");
nrOfFailedTestCases += ReportTestResult(VerifySinh<3, 1>(reportTestCases), "posit<3,1>", "sinh");
nrOfFailedTestCases += ReportTestResult(VerifySinh<4, 0>(reportTestCases), "posit<4,0>", "sinh");
nrOfFailedTestCases += ReportTestResult(VerifySinh<4, 1>(reportTestCases), "posit<4,1>", "sinh");
nrOfFailedTestCases += ReportTestResult(VerifySinh<5, 0>(reportTestCases), "posit<5,0>", "sinh");
nrOfFailedTestCases += ReportTestResult(VerifySinh<5, 1>(reportTestCases), "posit<5,1>", "sinh");
nrOfFailedTestCases += ReportTestResult(VerifySinh<5, 2>(reportTestCases), "posit<5,2>", "sinh");
nrOfFailedTestCases += ReportTestResult(VerifySinh<6, 0>(reportTestCases), "posit<6,0>", "sinh");
nrOfFailedTestCases += ReportTestResult(VerifySinh<6, 1>(reportTestCases), "posit<6,1>", "sinh");
nrOfFailedTestCases += ReportTestResult(VerifySinh<6, 2>(reportTestCases), "posit<6,2>", "sinh");
nrOfFailedTestCases += ReportTestResult(VerifySinh<6, 3>(reportTestCases), "posit<6,3>", "sinh");
nrOfFailedTestCases += ReportTestResult(VerifySinh<7, 0>(reportTestCases), "posit<7,0>", "sinh");
nrOfFailedTestCases += ReportTestResult(VerifySinh<7, 1>(reportTestCases), "posit<7,1>", "sinh");
nrOfFailedTestCases += ReportTestResult(VerifySinh<7, 2>(reportTestCases), "posit<7,2>", "sinh");
nrOfFailedTestCases += ReportTestResult(VerifySinh<7, 3>(reportTestCases), "posit<7,3>", "sinh");
nrOfFailedTestCases += ReportTestResult(VerifySinh<7, 4>(reportTestCases), "posit<7,4>", "sinh");
// nrOfFailedTestCases += ReportTestResult(VerifySinh<8, 0>(reportTestCases), "posit<8,0>", "sinh");
nrOfFailedTestCases += ReportTestResult(VerifySinh<8, 1>(reportTestCases), "posit<8,1>", "sinh");
nrOfFailedTestCases += ReportTestResult(VerifySinh<8, 2>(reportTestCases), "posit<8,2>", "sinh");
nrOfFailedTestCases += ReportTestResult(VerifySinh<8, 3>(reportTestCases), "posit<8,3>", "sinh");
nrOfFailedTestCases += ReportTestResult(VerifySinh<8, 4>(reportTestCases), "posit<8,4>", "sinh");
nrOfFailedTestCases += ReportTestResult(VerifySinh<8, 5>(reportTestCases), "posit<8,5>", "sinh");
nrOfFailedTestCases += ReportTestResult(VerifySinh<8, 0>(reportTestCases), "posit<8,0>", "sinh");
nrOfFailedTestCases += ReportTestResult(VerifyCosh<8, 0>(reportTestCases), "posit<8,0>", "cosh");
nrOfFailedTestCases += ReportTestResult(VerifyTanh<8, 0>(reportTestCases), "posit<8,0>", "tanh");
nrOfFailedTestCases += ReportTestResult(VerifyAtanh<8, 0>(reportTestCases), "posit<8,0>", "atanh");
nrOfFailedTestCases += ReportTestResult(VerifyAcosh<8, 0>(reportTestCases), "posit<8,0>", "acosh");
nrOfFailedTestCases += ReportTestResult(VerifyAsinh<8, 0>(reportTestCases), "posit<8,0>", "asinh");
#endif
#if REGRESSION_LEVEL_2
nrOfFailedTestCases += ReportTestResult(VerifySinh<9, 0>(reportTestCases), "posit<9,0>", "sinh");
nrOfFailedTestCases += ReportTestResult(VerifySinh<9, 1>(reportTestCases), "posit<9,1>", "sinh");
nrOfFailedTestCases += ReportTestResult(VerifySinh<9, 2>(reportTestCases), "posit<9,2>", "sinh");
nrOfFailedTestCases += ReportTestResult(VerifySinh<9, 3>(reportTestCases), "posit<9,3>", "sinh");
nrOfFailedTestCases += ReportTestResult(VerifySinh<9, 4>(reportTestCases), "posit<9,4>", "sinh");
nrOfFailedTestCases += ReportTestResult(VerifySinh<9, 5>(reportTestCases), "posit<9,5>", "sinh");
nrOfFailedTestCases += ReportTestResult(VerifySinh<9, 6>(reportTestCases), "posit<9,6>", "sinh");
nrOfFailedTestCases += ReportTestResult(VerifySinh<10, 0>(reportTestCases), "posit<10,0>", "sinh");
nrOfFailedTestCases += ReportTestResult(VerifySinh<10, 1>(reportTestCases), "posit<10,1>", "sinh");
nrOfFailedTestCases += ReportTestResult(VerifySinh<10, 2>(reportTestCases), "posit<10,2>", "sinh");
nrOfFailedTestCases += ReportTestResult(VerifySinh<10, 7>(reportTestCases), "posit<10,7>", "sinh");
#endif
#if REGRESSION_LEVEL_3
nrOfFailedTestCases += ReportTestResult(VerifySinh<12, 0>(reportTestCases), "posit<12,0>", "sinh");
nrOfFailedTestCases += ReportTestResult(VerifySinh<12, 1>(reportTestCases), "posit<12,1>", "sinh");
nrOfFailedTestCases += ReportTestResult(VerifySinh<12, 2>(reportTestCases), "posit<12,2>", "sinh");
nrOfFailedTestCases += ReportTestResult(VerifySinh<16, 0>(reportTestCases), "posit<16,0>", "sinh");
nrOfFailedTestCases += ReportTestResult(VerifySinh<16, 1>(reportTestCases), "posit<16,1>", "sinh");
nrOfFailedTestCases += ReportTestResult(VerifySinh<16, 2>(reportTestCases), "posit<16,2>", "sinh");
#endif
#if REGRESSION_LEVEL_4
// nbits=64 requires long double compiler support
// nrOfFailedTestCases += ReportTestResult(VerifyThroughRandoms<64, 2>(reportTestCases, OPCODE_SQRT, 1000), "posit<64,2>", "sinh");
nrOfFailedTestCases += ReportTestResult(VerifySinh<10, 1>(reportTestCases), "posit<10,1>", "sinh");
nrOfFailedTestCases += ReportTestResult(VerifySinh<12, 1>(reportTestCases), "posit<12,1>", "sinh");
nrOfFailedTestCases += ReportTestResult(VerifySinh<14, 1>(reportTestCases), "posit<14,1>", "sinh");
nrOfFailedTestCases += ReportTestResult(VerifySinh<16, 1>(reportTestCases), "posit<16,1>", "sinh");
#endif
ReportTestSuiteResults(test_suite, nrOfFailedTestCases);
return (nrOfFailedTestCases > 0 ? EXIT_FAILURE : EXIT_SUCCESS);
#endif // MANUAL_TESTING
}
catch (char const* msg) {
std::cerr << "Caught ad-hoc exception: " << msg << std::endl;
return EXIT_FAILURE;
}
catch (const sw::universal::universal_arithmetic_exception& err) {
std::cerr << "Caught unexpected universal arithmetic exception : " << err.what() << std::endl;
return EXIT_FAILURE;
}
catch (const sw::universal::universal_internal_exception& err) {
std::cerr << "Caught unexpected universal internal exception: " << err.what() << std::endl;
return EXIT_FAILURE;
}
catch (const std::runtime_error& err) {
std::cerr << "Caught runtime exception: " << err.what() << std::endl;
return EXIT_FAILURE;
}
catch (...) {
std::cerr << "Caught unknown exception" << std::endl;
return EXIT_FAILURE;
}
| true |
2c5123ecde5f26c8cf7b217f12569a2e0f4076f2 | C++ | mrngunuong1/Project_KTMT_HN_1 | /KTMT_HN_Project1/QFloat.cpp | UTF-8 | 6,471 | 2.921875 | 3 | [] | no_license | #include"QFloat.h"
#include"QInt.h"
QFloat::QFloat()
{
data[0] = data[1] = data[2] = data[3] = 0;
}
QFloat::QFloat(string s)
{
data[0] = data[1] = data[2] = data[3] = 0;
string pre_comma;
string post_comma;
int l = s.length();
int i = 0;
if (s[0] == '-')
{
SetBit(0, 1);
i++;
}
for (i; i < l; i++)
{
if (s[i] != '.') pre_comma += s[i];
else break;
}
for (i = i + 1; i < l; i++)
{
post_comma += s[i];
}
string pre_bin = PreComma_to_Binary(pre_comma), post_bin = PostComma_to_Binary(pre_comma, post_comma);
int exp = CalcExponent(pre_bin, post_bin);
WriteToExponent(exp);
WriteToFraction(exp, pre_bin, post_bin);
}
void QFloat::ScanQFloat()
{
string s;
fflush(stdin);
getline(cin, s);
*this = QFloat(s);
}
void QFloat::ScanBinQFloat(string s)
{
int l = s.length();
int i = 0;
for (i; i < l; i++)
{
this->SetBit(i, s[i] - '0');
}
for (i; i < l; i++)
{
this->SetBit(i, 0);
}
}
void QFloat::SetBit(char pos, bool bit)
{
if (bit)
{
data[pos / 32] = data[pos / 32] | (1 << (32 - pos % 32 - 1));
}
}
bool QFloat::GetBit(char pos)
{
return (data[pos / 32] >> (32 - pos % 32 - 1)) & 1;
}
string QFloat::MultiStringForTwo(string s)
{
int temp = false;
string result;
for (int i = s.length() - 1; i >= 0; i--)
{
if (temp != 0)
{
temp = 2 * (s[i] - '0') + 1;
result = char((temp % 10) + '0') + result;
if (temp / 10 != 0)
{
if (i > 0) temp = 1;
else result = '1' + result;
}
else temp = 0;
}
else
{
temp = 2 * (s[i] - '0');
result = char((temp % 10) + '0') + result;
if (temp > 9)
{
if (i > 0) temp = 1;
else result = '1' + result;
}
else temp = 0;
}
}
// while (result[0] == '0' && result.length() > 1) result.erase(0, 1);
return result;
}
string QFloat::DivideStringForTwo(string s)
{
//s là chuỗi số được nhập vào
//result là chuỗi kết quả của phép chia cho 2
string result = "";
//temp lưu số bị chia
int temp = 0;
int l = s.length(); // l: chiều dài chuỗi số
for (int i = 0; i < l; i++)
{
//Nếu phép chia đang có dư
if (temp != 0)
{
temp = 10 + s[i] - '0';
result += temp / 2 + '0';
// R = temp % 2;
temp = temp % 2;
}
//Nếu s[i] nhỏ hơn 2
else
if (s[i] - '0' < 2)
{
result += '0';
temp = s[i] - '0';
}
//Trường hợp s[i] là số lớn hơn 2
else
if (s[i] - '0' >= 2)
{
result += (s[i] - '0') / 2 + '0';
temp = (s[i] - '0') % 2;
}
}
while (result[0] == '0' && result.length() > 1) result.erase(0, 1);
return result;
}
string QFloat::PreComma_to_Binary(string s)
{
string bin;
while (s != "0")
{
if ((s[s.length() - 1] - '0') % 2 == 0) bin = '0' + bin;
else bin = '1' + bin;
s = this->DivideStringForTwo(s);
}
if (bin == "") bin = "0";
return bin;
}
bool isOne(string s)
{
if (s.length() == 1) return false;
if (s[0] == '1')
{
for (int i = 1; i< s.length(); i++)
if (s[i] != '0') return false;
}
else return false;
return true;
}
string QFloat::PostComma_to_Binary(string pre, string s)
{
string bin;
int i = 0;
int exp = 0;
exp = CalcExponent(pre) - 127;
if (exp == 0)
{
while (true)
{
if (s[0] - '0' >=5) {
s = MultiStringForTwo(s);
s.erase(0, 1);
break;
}
else s = MultiStringForTwo(s);
}
}
int ll= 0;
while (i < number_bits_of_fraction - exp)
{
if (isOne(s) && ll < s.length()) {
bin += '1';
break;
}
else
{
ll = s.length();
if (s[0] - '0' >= 5) {
bin += '1';
s = MultiStringForTwo(s);
s.erase(0, 1);
}
else {
bin += '0';
s = MultiStringForTwo(s);
}
}
i++;
}
return bin;
}
int QFloat::CalcExponent(string pre, string post)
{
int l1 = pre.length(), l2 = post.length();
for (int i = 0; i < l1; i++)
{
if (pre[i] == '1') return 127 + (l1 - i - 1);
}
for (int i = 0; i < l2; i++)
{
if (post[i] == '1') return 127 - i -1;
}
return 0;
}
int QFloat::CalcExponent(string pre)
{
int l1 = pre.length();
for (int i = 0; i < l1; i++)
{
if (pre[i] == '1') return 127 + (l1 - i - 1);
}
return 0;
}
void QFloat::WriteToExponent(int exp)
{
int i = number_bits_of_sign_exponent - 1;
while (i>=0)
{
this->SetBit(i, exp % 2);
exp = exp / 2;
i--;
}
}
void QFloat::WriteToFraction(int exp, string pre, string post)
{
int k = exp - 127, i = number_bits_of_sign_exponent;
int l1 = pre.length(), l2 = post.length();
if (k<0)
{
k = -k;
for (i; i < 128; i++)
{
this->SetBit(i , post[k++] - '0');
}
}
else
{
while (k > 0)
{
this->SetBit(i, pre[l1 - k] - '0');
i++;
k--;
}
k = 0;
for (i; i < 128; i++)
{
this->SetBit(i, post[k++] - '0');
}
}
}
void QFloat::PrintQFloat()
{
for (int i = 0; i < 128; i++)
{
cout << GetBit(i);
if (i == 15) cout << " ";
}
}
bool QFloat::isZero()
{
for (int i = 0; i < 128; i++)
{
if (GetBit(i) == 1) return false;
}
return true;
}
string QFloat::Decimal()
{
if (this->isZero()) return "0.0";
string result;
if (GetBit(0) == 1) result += '-';
int exp = 0;
for (int i = 1; i < number_bits_of_sign_exponent; i++)
{
exp += GetBit(i) << (number_bits_of_sign_exponent - i - 1);
}
exp = exp - 127;
string pre_comma;
string post_comma;
if (exp >0) pre_comma = "1";
if (exp < 0)
{
post_comma.insert(0, 1, '1');
post_comma.insert(0, -exp - 1, '0');
}
int i = number_bits_of_sign_exponent;
for (i; i < number_bits_of_sign_exponent + exp; i++)
{
pre_comma += GetBit(i) + '0';
}
for (i; i < 128; i++)
{
post_comma += GetBit(i) + '0';
}
QInt pre_num, post_num;
ScanBinQInt(pre_num, pre_comma);
string pre = GetDecimal(pre_num);
int nonsense_bits = 0;
for (int i = post_comma.length() - 1; i >= 0; i--)
{
if (post_comma[i] == '1') break;
else nonsense_bits++;
}
int k = 1;
int max;
ScanQInt(post_num, "1");
QInt num5, num10;
ScanQInt(num5, "5");
ScanQInt(num10, "10");
if (number_bits_of_fraction - nonsense_bits - exp> 25)
{
max = 25;
}
else max = number_bits_of_fraction - nonsense_bits - exp;
for (int i = 0; i < max; i++)
{
post_num = post_num * num10;
if (post_comma[i] == '1')
{
QInt temp;
ScanQInt(temp, "1");
for (int j = 1; j <= k; j++)
temp = temp *num5;
post_num = post_num + temp;
string s = GetDecimal(post_num);
}
k++;
}
string s = GetDecimal(post_num);
result += pre + "." + GetDecimal(post_num).erase(0,1);
return result;
}
QFloat QFloat::BinToDec(bool *bit)
{
for (int i = 0; i < 128; i++)
this->SetBit(i, bit[i]);
return *this;
} | true |
0080aa380fda3150eb0244ccb8fb05db90693a76 | C++ | Creinman/TestProjectCpp | /main.cpp | UTF-8 | 1,656 | 2.78125 | 3 | [] | no_license |
*//*0A (15., 18., 15), B (33, -87, -99), C (69, 27, -151), D (10.9, 55, -38). */
#include <stdio.h>
#include "myvector3d.h"
int main()
{
MyVector3D A (15,18,15), B (33,-87,-99), C (69,27,-151), D (10.9,55,-38);
printf("\n\n\tProgram started\n");
MyVector3D AB=B-A,
AC=C-A,
AD=D-A,
BC=C-B,
BD=D-B,
CD=D-C;
/* printf("\n\tAB "); PrintMyVector3D(AB);
printf("\n\tAC "); PrintMyVector3D(AC);
printf("\n\tAD "); PrintMyVector3D(AD);
printf("\n\tBC "); PrintMyVector3D(BC);
printf("\n\tBD "); PrintMyVector3D(BD);
printf("\n\tCD "); PrintMyVector3D(CD);*/
MyVector3D n=AB*AC,
n1=AD*AC,
n2=BD*BC,
n3=AD*AB;
printf("\n\n\tAB*AC= "); PrintMyVector3D(n);
printf("\n\tAD*AC= "); PrintMyVector3D(n1);
printf("\n\tBD*BC= "); PrintMyVector3D(n2);
printf("\n\tAD*AD= "); PrintMyVector3D(n3);
double *S=new double[4];
S[0]=(n.norm())/2.;
S[1]=(n1.norm())/2.;
S[2]=(n2.norm())/2.;
S[3]=(n3.norm())/2.;
printf("\n\n\tSabc=%lg",S[0]);
printf("\n\tSadc=%lg",S[1]);
printf("\n\tSabd=%lg",S[2]);
printf("\n\tSbdc=%lg",S[3]);
for (int i = 0; i < 4 - 1; i++) {
for (int j = 0; j < 4 - i - 1; j++) {
if (S[j] < S[j + 1]) {
double temp = S[j];
S[j] = S[j + 1];
S[j + 1] = temp;
}
}
}
printf("\n\n\tSmax=%g",S[0]);
printf("\n\n\tPress ENTER\n");
getchar();
return 0;
}
| true |
92707634bfb20dd7c1bf9c7d7550b6cbbee46adf | C++ | lyyhui1314/51nod | /done-2529-移动长度.cpp | UTF-8 | 692 | 3.078125 | 3 | [] | no_license | // 有n个点,第i号点在一维数轴的i坐标位置。
// 你现在在1号点,你需要移动k次,每次可以移动到1−n的任何一个点,不能够不动,最终移动的总长度为S
// 问这样的方案是否存在。
// 输入
// 第一行三个数n,k,s(2<=n<=10^9,1<=k<=2*10^5,1<=s<=10^18)。
// 输出
// 如果存在方案,输出YES,否则输出NO。
// 输入样例
// 10 2 15
// 输出样例
// YES
#include <stdio.h>
int main(int argc, char const *argv[])
{
double n, k, s;
scanf("%lf%lf%lf", &n, &k, &s);
int flg = s * 1.0 / (n - 1) <= k ? 1 : 0;
if (flg && k <= s)
printf("YES\n");
else
printf("NO\n");
return 0;
}
| true |
f2238f6a74f2a2d5aef89f108a51f8cc0111dc4a | C++ | PVIII/stream | /libstream/transform.hpp | UTF-8 | 5,307 | 2.640625 | 3 | [
"MIT"
] | permissive | /*!
* @author Patrick Wang-Freninger <github@freninger.at>
* @copyright MIT
* @date 2019
* @link github.com/PVIII/stream
*/
#ifndef LIBSTREAM_TRANSFORM_HPP_
#define LIBSTREAM_TRANSFORM_HPP_
#include <liboutput_view/transform.hpp>
#include <libstream/callback.hpp>
#include <libstream/concepts/pipe.hpp>
#include <libstream/detail/context.hpp>
#include <experimental/ranges/range>
namespace stream
{
namespace detail
{
template<class C, class S> class read_context : public base_read_context<C>
{
using typename base_read_context<C>::value_type;
using base_read_context<C>::child_;
S& stream_;
read_done_token<value_type> done_token_;
void done_handler(value_type v) { done_token_(stream_.func_(v)); }
public:
read_context(C&& c, S& s)
: base_read_context<C>{std::forward<C>(c)}, stream_(s)
{
}
auto submit() { return stream_.func_(child_.submit()); }
void submit(read_token<value_type>&& t)
{
done_token_ = t.done;
using this_t = read_context<C, S>;
child_.submit(
read_token<value_type>{t.error, t.cancelled,
read_done_token<value_type>::template create<
this_t, &this_t::done_handler>(this)});
}
};
template<class C, class S> read_context(C&& c, S& s)->read_context<C, S>;
} // namespace detail
template<WriteStreamable S, class F> class transform_write_fn
{
S stream_;
F func_;
public:
transform_write_fn(S&& stream, F&& f)
: stream_(std::forward<S>(stream)), func_(std::forward<F>(f))
{
}
template<class V> auto write(V&& v) const
{
return detail::base_write_context{
stream_.write(func_(std::forward<V>(v)))};
}
template<std::experimental::ranges::InputRange R> auto write(R&& r) const
{
return detail::base_range_context{
stream_.write(std::experimental::ranges::view::transform(
std::forward<R>(r), func_))};
}
template<class V>
auto readwrite(V&& v) const requires ReadWriteStreamable<S>
{
return detail::base_read_context{stream_.readwrite(func_(v))};
}
template<std::experimental::ranges::InputRange Rin,
std::experimental::ranges::Range Rout>
auto readwrite(Rin&& rin, Rout&& rout) const requires ReadWriteStreamable<S>
{
return detail::base_range_context{
stream_.readwrite(std::experimental::ranges::view::transform(
std::forward<Rin>(rin), func_),
std::forward<Rout>(rout))};
}
};
template<ReadStreamable S, class F> class transform_read_fn
{
private:
S stream_;
F func_;
public:
transform_read_fn(S&& stream, F&& f)
: stream_(std::forward<S>(stream)), func_(std::forward<F>(f))
{
}
auto read() const requires PureReadStreamable<S>
{
return detail::read_context{stream_.read(), *this};
}
auto read(std::experimental::ranges::Range&& r) const
requires PureReadStreamable<S>
{
return detail::base_range_context{
stream_.read(output_view::transform(r, func_))};
}
template<class V>
auto readwrite(V&& v) const requires ReadWriteStreamable<S>
{
return detail::read_context{stream_.readwrite(std::forward<V>(v)),
*this};
}
template<std::experimental::ranges::InputRange Rin,
std::experimental::ranges::Range Rout>
auto readwrite(Rin&& rin, Rout&& rout) const requires ReadWriteStreamable<S>
{
return detail::base_range_context{stream_.readwrite(
std::forward<Rin>(rin), output_view::transform(rout, func_))};
}
};
template<WriteStreamable S, class F>
transform_write_fn(S&, F &&)->transform_write_fn<S&, F>;
template<WriteStreamable S, class F>
transform_write_fn(S&&, F &&)->transform_write_fn<S, F>;
template<ReadStreamable S, class F>
transform_read_fn(S&, F &&)->transform_read_fn<S&, F>;
template<ReadStreamable S, class F>
transform_read_fn(S&&, F &&)->transform_read_fn<S, F>;
template<class F> class transform_write_pipe
{
F f_;
public:
transform_write_pipe(F&& f) : f_(f) {}
template<WriteStreamable S> WriteStreamable pipe(S&& s) const
{
return transform_write_fn<S, F>{std::forward<S>(s), F(f_)};
}
};
template<class F> class transform_read_pipe
{
F f_;
public:
transform_read_pipe(F&& f) : f_(f) {}
template<ReadStreamable S> ReadStreamable pipe(S&& s) const
{
return transform_read_fn<S, F>{std::forward<S>(s), F(f_)};
}
};
template<class F> Pipeable transform_write(F&& f)
{
return transform_write_pipe{std::forward<F>(f)};
}
template<class F> Pipeable transform_read(F&& f)
{
return transform_read_pipe{std::forward<F>(f)};
}
template<WriteStreamable S, class F>
WriteStreamable transform_write(S&& stream, F&& f)
{
return transform_write_fn<S, F>{std::forward<S>(stream),
std::forward<F>(f)};
}
template<ReadStreamable S, class F>
ReadStreamable transform_read(S&& stream, F&& f)
{
return transform_read_fn<S, F>{std::forward<S>(stream), std::forward<F>(f)};
}
} // namespace stream
#endif // LIBSTREAM_TRANSFORM_HPP_
| true |
6c9e3c267450396f7d5c5991400bb1a095b45c62 | C++ | jmkim/algorithm_and_practice-pknu-2016 | /excercise15/include/adjacency_matrix.hpp | UTF-8 | 5,395 | 3.6875 | 4 | [
"MIT"
] | permissive | /**
*
* Adjacency Matrix
*
* Weighted graph,
* implementation with adjacency matrix
*
* https://github.com/kdzlvaids/algorithm_and_practice-pknu-2016
*
*/
#ifndef ALGORITHM_ADJACENCYMATRIX_HPP_
#define ALGORITHM_ADJACENCYMATRIX_HPP_ 1
/** Includes */
#include <cstddef> /** size_t definition */
#include <climits> /** UINT_MAX definition */
#include <algorithm> /** fill_n definition */
#include <vector> /** Containers */
namespace algorithm
{
/** Graph implementation with adjacency matrix
\note Vertex deletion is not implemented
\note Edge deletion is not implemented
\note Cannot use double as WeightType
*/
template<
class ValueType, /**< Vertex value type; operator== should be defined */
class WeightType = unsigned int, /**< Weight type */
class KeyType = unsigned int, /**< Key type, used to access an array */
class KeyArrayType = std::vector<KeyType> /**< Array of Key type */
>
class AdjacencyMatrix
{
public:
typedef size_t SizeType;
protected:
const SizeType size_;
const WeightType init_value_; /**< Initial value for weight (should not use this value as data) */
WeightType ** edges_; /**< Edges */
ValueType * vertices_; /**< Vertices */
public:
/** Constructor */
AdjacencyMatrix(const SizeType & size_of_matrix, const WeightType & init_value)
: size_(size_of_matrix)
, init_value_(init_value)
{
edges_ = new WeightType *[size_];
for(KeyType i = 0; i < size_; ++i)
{
edges_[i] = new WeightType[size_];
for(KeyType j = 0; j < size_; ++j)
edges_[i][j] = init_value;
}
}
/** Destructor */
~AdjacencyMatrix(void)
{
for(KeyType i = 0; i < size_; ++i)
delete[] edges_[i];
delete edges_;
}
/** Test whether there is an edge from the vertices src to dest
\return Return true if the edge exists; otherwise return false
\param[in] key_src Key of source (src)
\param[in] key_dest Key of destination (dest)
*/
inline
bool
IsEdgeExist(const KeyType & key_src, const KeyType & key_dest)
const
{ return edges_[key_src][key_dest] != init_value_; }
/** Get a key of the vertex with specific value
If failed to add, return the size of matrix which is an invalid key (maximum key + 1).
\return Return the key of vertex if added successfully; otherwise return the size of matrix
\param[in] value_of_vertex Value of vertex
*/
KeyType
GetVertexKey(const ValueType & value_of_vertex)
{
for(KeyType key = 0; key < size_; ++key)
{
if(vertices_[key] == value_of_vertex)
return key;
}
return size_;
}
/** Get a value of the vertex with specific key
\return Value of vertex
\param[in] key_of_vertex Key of vertex
*/
inline
ValueType
GetVertexValue(const KeyType & key_of_vertex)
const
{ return vertices_[key_of_vertex]; }
/** Set a value of the vertex with specific key
\param[in] key_of_vertex Key of vertex
\param[in] value_of_vertex Value of vertex
*/
inline
void
SetVertexValue(const KeyType & key_of_vertex, const ValueType & value_of_vertex)
{ vertices_[key_of_vertex] = value_of_vertex; }
/** Get a weight of the edge
\return Weight of edge
\param[in] key_src Key of source (src)
\param[in] key_dest Key of destination (dest)
*/
inline
WeightType
GetEdgeWeight(const KeyType & key_src, const KeyType & key_dest)
const
{ return edges_[key_src][key_dest]; }
/** Set a weight of the edge
\param[in] key_src Key of source (src)
\param[in] key_dest Key of destination (dest)
\param[in] weight Weight of edge
*/
inline
void
SetEdgeWeight(const KeyType & key_src, const KeyType & key_dest, const WeightType & weight)
{ edges_[key_src][key_dest] = weight; }
/** Get a count of vertices
\return Count of vertices
*/
inline
SizeType
CountOfVertices(void)
const
{ return size_; }
/** Get a count of edges
\return Count of edges
\param[in] key_of_vertex Key of vertex
*/
inline
SizeType
CountOfEdges(const KeyType & key_of_vertex)
{
KeyArrayType dummy;
return ListOfEdges(dummy, key_of_vertex);
}
/** Get the list of edges
\return Size of list
\param[out] out_edges List of edges
\param[in] key_of_vertex Key of vertex
*/
SizeType
ListOfEdges(KeyArrayType & out_edges, const KeyType & key_of_vertex)
{
out_edges.clear();
WeightType weight;
for(KeyType key = 0; key < size_; ++key)
{
weight = edges_[key_of_vertex][key];
if(weight != init_value_)
out_edges.push_back(weight);
}
return out_edges.size();
}
};
} /** ns: algorithm */
#endif /** ! ALGORITHM_ADJACENCYMATRIX_HPP_ */
| true |
5d522744bb368ca1e74c34e54045e16ec3cf7b93 | C++ | viko3019/LeetCode | /Valid-Parentheses.cpp | UTF-8 | 818 | 3.296875 | 3 | [] | no_license | class Solution {
public:
bool isValid(string s) {
int len = s.length();
stack<int>stc;
for(int i = 0; i< len; i++){
if(s[i] == '(' || s[i] == '{' || s[i] == '['){
stc.push(s[i]);
}
else if(stc.size() == 0){
return false;
}
else if(s[i] == ')' && stc.top() != '('){
return false;
}
else if(s[i] == '}' && stc.top() != '{'){
return false;
}
else if(s[i] == ']' && stc.top() != '['){
return false;
}
else {
stc.pop();
}
}
if(stc.size() == 0){
return true;
}
else {
return false;
}
}
}; | true |
a2dfa37ffcedea0f943dcb7cc48a1bee7a3ba922 | C++ | sammyc304/Word-Search-Project | /main.cpp | UTF-8 | 5,399 | 3.796875 | 4 | [] | no_license | //
// main.cpp
// EECE2560 3b
//
//
#include <iostream>
#include "dictionary.hpp"
#include "grid.hpp"
/*Directional_get locates all of the characters in a single direction with a starting place on the grid (a,b) and stores them in a character vector. This function takes an operation (1-8, for each direction), a starting location (a,b) and a grid object. Based on the operation, offsets 1 and 2 are set to increment in a specific direction. In each iteration, a new letter is acquired from the grid and stored in the character vector ‘word’. Once the starting place is reached again, word is returned.*/
vector<char> Directional_get(Grid g, int op, int a, int b)
{
vector<char> word; // this vector contains all possible words found while navigating
int offset1 = 0, offset2 = 0; // offset 1 corresponds to the y direction, offset 2 corresponds to the x direction
switch (op) // op is a parameter of the function that indicates the direction to search
{
case 1: offset1 = 1;
break;
case 2: offset1 = -1;
break;
case 3: offset2 = 1;
break;
case 4: offset2 = -1;
break;
case 5: offset1 = 1; offset2 = 1;
break;
case 6: offset1 = 1; offset2 = -1;
break;
case 7: offset1 = -1; offset2 = 1;
break;
case 8: offset1 = -1; offset2 = -1;
break;
} // end switch case
int x = a;
int y = b;
do
{
word.push_back(g.get_char(x, y));
x = x + offset1;
y = y + offset2;
// the following four if statements are necessary to catch the instance while navigating the word search when we hit a wall of the search
if (x == g.get_size()) // if the x value exceeds the last letter on the right
{
x = 0;
}
if (y == g.get_size()) // if y value exceeds bottom letter
{
y = 0;
}
if (x == -1) // if the x value exceeds the last letter on the left
{
x = g.get_size() - 1;
}
if (y == -1) // if y value exceeds top letter
{
y = g.get_size() - 1;
}
} while (x != a || y != b); // this is the terminating condition, reached when we return to the starting letter
return word;
} // end Directional_get
/*convertChar_String takes a character vector and passes a string vector by reference. Starting at a length of 5, strings are created by concatenating the elements(char) of the vector. These strings are then stored in the string vector ‘candidates’*/
void convertChar_String(vector<char> word, vector<string>& candidates)
{
size_t x = 5; // size_t is effectively an integer, used for navigating a vector
while (x <= word.size())
{
string strC(word.begin(), word.end() - (word.size() - x)); // converts the array of characters to a string
candidates.push_back(strC); // adds to end of vector
x++;
} // end while
} // end convertChar_String
/*Generate_Candidates takes a grid object as a parameter and returns a string vector. Starting at location (0,0), Directional_get and convertChar_String are called 8 times(for each direction). Then the location gets incremented.*/
vector<string> Generate_Candidates(Grid g)
{
vector<string> all_candidates; // This vector will contain all possible words
int size = g.get_size();
for (int i = 0; i < size; i++) // corresponds to the row number
{
int j = 0;
for (j = 0; j < size; j++) // corresponds to column number
{
int k = 1;
for (k = 1; k <= 8; k++) // corresponds to each direction of a possible word
{
vector<char> word = Directional_get(g, k, i, j);
convertChar_String(word, all_candidates);
} // end for
} // end for
} //end for
return all_candidates;
} //end generate_Candidates
/*findMatches takes a dictionary object and a grid object as parameters and outputs the located words. Generate_Candidates is called to create a string vector with all of the possible words found in the grid. Each element of this vector is then passed to the dictionary object function binarySearch. This returns an integer that, if not equal to -1(invalid word), is passed to the dictionary function get_vector to retrieve the word from the dictionary.*/
void findMatches(Dictionary d, Grid g)
{
vector<string> string = Generate_Candidates(g);
for (size_t i = 0; i < string.size(); i++)
{
int element = d.binarySearch(string[i]);
if (element != -1) // if the key string is found in the dictionary
{
cout << "Found: " << d.get_vector().at(element) << endl;
} // end if
} // end for
} // end findMatches
/*void search() initializes a string called filename to be the user input for the grip txt file. A dictionary object is initialized using the dictionary txt file. DictionarySort() is then called to sort the words in the dictionary. User is asked to input a filename for grid. A grid object is initialized with filename from user input. Finally findMatches is called to output the words in the grid that are found in the dictionary.*/
void search(int sort) // same as search()
{
string filename;
Dictionary d("dictionary3.txt");
switch (sort)
{
case 0: d.dictionarySort();
break;
case 1: d.quickSort(0, (d.get_Dictlength() - 1));
break;
case 2: d.heapSort();
break;
}
cout << "Input your grid filename: ";
cin >> filename;
Grid g(filename);
findMatches(d, g);
} // end search
int main()
{
search(2); //Choose between 0-2 for type of sorting algorithm used
return 0;
} | true |
3fc74e080bf63b0b899e3f9d3a48b3d0caae2ba3 | C++ | danilaml/DZ | /144/HW14_4/HashTable/myhashtable.cpp | UTF-8 | 2,529 | 3.046875 | 3 | [] | no_license | #include "myhashtable.h"
#include <iostream>
MyHashTable::MyHashTable() : hsf(new HashFunction(1013)), ar(new QStringList[1]), size(1)
{
}
MyHashTable::MyHashTable(int initSize) : hsf(new HashFunction(1013)), ar(new QStringList[initSize]), size(initSize)
{
}
MyHashTable::MyHashTable(int initSize, HashFunction *inithsf) : hsf(inithsf), ar(new QStringList[initSize]), size(initSize)
{
}
MyHashTable::~MyHashTable()
{
delete hsf;
delete[] ar;
}
void MyHashTable::add(QString &str)
{
if(contains(str)) return;
ar[hsf->hash(str, size)].append(str);
}
void MyHashTable::del(QString &str)
{
if(!contains(str))
{
std::cout << "No such element" << std::endl;
return;
}
ar[hsf->hash(str, size)].removeOne(str);
}
bool MyHashTable::contains(QString &str) const
{
return ar[hsf->hash(str, size)].contains(str);
}
int MyHashTable::tableSize() const
{
return size;
}
double MyHashTable::loadFactor() const
{
double res = 0;
for(int i = 0; i < size; i++)
{
res += ar[i].size();
}
return (res / size);
}
int MyHashTable::numberOfConflicts() const
{
int res = 0;
for(int i = 0; i < size; i++)
{
if(ar[i].size() > 1)
res += ar[i].size();
}
return res;
}
int MyHashTable::biggestConflitSize() const
{
int res = 1;
for(int i = 0; i < size; i++)
{
if(ar[i].size() > res)
res = ar[i].size();
}
return res;
}
void MyHashTable::changeHashFunc(HashFunction *newhsf)
{
delete hsf;
hsf = newhsf;
QStringList *tmp = new QStringList[size];
for(int i = 0; i < size; i++)
{
while(!ar[i].isEmpty())
{
tmp[hsf->hash(ar[i].first(), size)].append(ar[i].first());
ar[i].removeFirst();
}
}
delete[] ar;
ar = tmp;
}
void MyHashTable::changeHashSize(int newSize)
{
int sizetmp = size;
size = newSize;
QStringList *tmp = new QStringList[newSize];
for(int i = 0; i < sizetmp; i++)
{
while(!ar[i].isEmpty())
{
tmp[hsf->hash(ar[i].first(), size)].append(ar[i].first());
ar[i].removeFirst();
}
}
delete[] ar;
ar = tmp;
}
void MyHashTable::print() const
{
for(int i = 0; i < size; i++)
{
if(!ar[i].isEmpty())
{
for(QString &str : ar[i])
{
std::cout << "( " << str.toStdString() << " , " << i << " ) ";
}
std::cout << std::endl;
}
}
}
| true |
0732cc30c068702f76aed9f16d067a88ee730ed6 | C++ | DoubleSinoptic/GameEngine | /GameEngine/Core/StringFormat.cpp | UTF-8 | 2,361 | 2.75 | 3 | [] | no_license | #include "StringFormat.h"
namespace ge
{
template<typename T>
void staticPut(ExceptPutProvider* provider, T value, const char* qual)
{
char temp[60];
temp[0] = '\0';
int result = snprintf(temp, 60, qual, value);
geAssert(result >= 0);
const char* p = temp;
for (; *p != '\0'; p++)
provider->put(char16_t(*p));
}
void genericPut(ExceptPutProvider* provider, float value)
{
staticPut(provider, value, "%f");
}
void genericPut(ExceptPutProvider* provider, double value)
{
staticPut(provider, value, "%lf");
}
void genericPut(ExceptPutProvider* provider, long value)
{
staticPut(provider, value, "%ld");
}
void genericPut(ExceptPutProvider* provider, long long value)
{
staticPut(provider, value, "%lld");
}
void genericPut(ExceptPutProvider* provider, unsigned long value)
{
staticPut(provider, value, "%lu");
}
void genericPut(ExceptPutProvider* provider, unsigned long long value)
{
staticPut(provider, value, "%llu");
}
void genericPut(ExceptPutProvider* provider, int value)
{
staticPut(provider, value, "%d");
}
void genericPut(ExceptPutProvider* provider, unsigned int value)
{
staticPut(provider, value, "%u");
}
void genericPut(ExceptPutProvider* provider, short value)
{
staticPut(provider, value, "%hd");
}
void genericPut(ExceptPutProvider* provider, unsigned short value)
{
staticPut(provider, value, "%hu");
}
void genericPut(ExceptPutProvider* provider, char value)
{
staticPut(provider, value, "%hhd");
}
void genericPut(ExceptPutProvider* provider, unsigned char value)
{
staticPut(provider, value, "%hhu");
}
void genericPut(ExceptPutProvider* provider, const char* p)
{
const byte* iter = reinterpret_cast<const byte*>(p);
uint32 c = 0;
while (c = ImplUtf8::utf8CharIterator(iter)) {
provider->put(char16_t(c));
}
}
void genericPut(ExceptPutProvider* provider, const wchar_t* p)
{
for (; *p != '\0'; p++)
provider->put(char16_t(*p));
}
void genericPut(ExceptPutProvider* provider, const char16_t* p)
{
for (; *p != '\0'; p++)
provider->put(char16_t(*p));
}
void genericPut(ExceptPutProvider* provider, const String& s)
{
const char16_t* p = s.data();
for (; *p != '\0'; p++)
provider->put(char16_t(*p));
}
void genericPut(ExceptPutProvider* provider, const void* p)
{
staticPut(provider, p, "%px");
}
} | true |
3b6ca1370182fa551347828e1ec6647dcc06b0ba | C++ | AkshayKumar22A/Data-Structures-Algorithms | /Array/Q3_level_1.cpp | UTF-8 | 850 | 4.25 | 4 | [] | no_license | /* Given an array (or string), the task is to reverse the array/string. */
#include<iostream>
#include<cstdlib>
using namespace std;
void revarr(int arr[], int len)
{
int i=0,j=len-1,temp=0;
while(i<j)
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
j--;
}
}
void display(int arr[], int len)
{
int y=0;
cout << "Array After reversing :";
for(y=0; y<len ;y++)
{
cout << arr[y];
}
}
int main()
{
int arr[] = {1, 2, 3, 4, 5, 6};
int len = sizeof(arr)/sizeof(arr[0]);
cout << "Array Before reversing :";
for(int x=0; x<len ;x++)
{
cout << arr[x];
}
cout <<endl;
revarr(arr,len);
display(arr,len);
return 0;
}
/* Time Complexity : O(n) */ | true |
7f2d33012814f9c37ac20c1d6aaec3a774e6cd32 | C++ | Thairam/URI | /Códigos - URI/2017/Ida à Feira/URI 1281.cpp | UTF-8 | 558 | 2.53125 | 3 | [
"Apache-2.0"
] | permissive | #include <bits/stdc++.h>
#include <map>
#include <string>
using namespace std;
int main(){
map<string, double> mapa;
map<string, double> mapa1;
int n;
scanf("%d", &n);
while(n--){
int m;
string s;
double valor;
scanf("%d", &m);
for(int i = 0; i < m; i++){
cin >> s;
scanf("%lf", &valor);
mapa[s] = valor;
}
int p;
int v;
double soma = 0;
scanf("%d", &p);
for(int i = 0; i < p; i++){
cin >> s;
scanf("%d", &v);
mapa1[s] = mapa[s] * v;
soma+= mapa1[s];
}
printf("R$ %.2lf\n", soma);
}
return 0;
}
| true |
1ee5f19beb1e9737e3654653d9e3aa937639d5b1 | C++ | green-fox-academy/Bola00 | /week-03/day-04/08 Strings again/main.cpp | UTF-8 | 760 | 3.734375 | 4 | [] | no_license | #include <iostream>
// Given a string, compute recursively a new string where all the 'x' chars have been removed..
std::string stringManipulator (std::string a){
if (a.size() == 1){// if the last letter is 'x', delete it
if (a[0] == 'x'){
a.clear();
}
return a;
}else {
std::string first_letter = a.substr(0,1); // delete the first letter if it's an 'x'
if (first_letter[0] == 'x'){
first_letter.clear();
}
return (first_letter + stringManipulator( a.substr(1, a.size() ) ) );
}
}
int main() {
std::string userInput;
std::cout << "Write something nice: ";
std::getline(std::cin, userInput);
std::cout << stringManipulator(userInput);
return 0;
} | true |
cd5bb781dcc6d43bf83f6e8d74baaf37e0d03cbb | C++ | VincentChen0110/Data-Structure | /DS0/DS0/main.cpp | UTF-8 | 857 | 3.046875 | 3 | [] | no_license | //
// main.cpp
// DS0
//
// Created by Vincent on 3/12/20.
// Copyright © 2020 Vincent. All rights reserved.
//
// Sample code to perform I/O:
#include<iostream>
using namespace std;
int max(int a, int b) { return (a > b)? a : b; }
int knapSack(int w, int wt[], int cost[], int n)
{
if (n == 0 || w == 0)
return 0;
//if (wt[n-1] > w)
if(wt[n]>w)
return knapSack(w, wt, cost, n-1);
//else return max( cost[n-1] + knapSack(w-wt[n-1], wt, cost, n-1),knapSack(w, wt, cost, n-1) );
else return max( knapSack( w-wt[n],wt,cost,n-1 ) + cost[n], knapSack(w,wt,cost,n-1));
}
int main()
{
int n = 0;
int cost[n] ;
int wt[n] ;
int w ;
cin >> n >> w;
for(int i = n; i > 0; i--){
cin >> cost[i] >> wt[i];
}
cout<<knapSack(w, wt, cost, n);
return 0;
}
| true |
67cf5d76e85d69d80ffdf531e4dd5a419f868661 | C++ | Banjarini/Arduino | /weather_logger/weather_logger.ino | UTF-8 | 2,397 | 2.90625 | 3 | [] | no_license | /*
SD card datalogger
This example shows how to log data from three analog sensors
to an SD card using the SD library.
The circuit:
* analog sensors on analog ins 0, 1, and 2
* SD card attached to SPI bus as follows:
** MOSI - pin 11
** MISO - pin 12
** CLK - pin 13
** CS - pin 4 (for MKRZero SD: SDCARD_SS_PIN)
created 24 Nov 2010
modified 9 Apr 2012
by Tom Igoe
This example code is in the public domain.
*/
#include <SPI.h>
#include <SD.h>
#include <DHT.h>
#include <Wire.h>
#include <Adafruit_BMP085.h>
#include "RTClib.h"
#define DHTPIN 2 // do not connect to pin 0 or pin 1
#define DHTTYPE DHT11 // Define DHT11 module
#define chipSelect 4
RTC_DS1307 rtc;
DHT dht(DHTPIN, DHTTYPE);
Adafruit_BMP085 bmp;
void setup() {
Serial.begin(9600);
dht.begin();
bmp.begin();
Serial.print("Initializing SD card...");
// see if the card is present and can be initialized:
if (!SD.begin(chipSelect)) {
Serial.println("Card failed, or not present");
// don't do anything more:
while (1){analogWrite(3, 50);};
}
Serial.println("card initialized.");
rtc.begin();
if (! rtc.isrunning()) {
Serial.println("RTC is NOT running!");
analogWrite(3, 50);
// following line sets the RTC to the date & time this sketch was compiled
rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
// This line sets the RTC with an explicit date & time, for example to set
// January 21, 2014 at 3am you would call:
// rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0));
}
}
void loop() {
DateTime time = rtc.now();
int t = bmp.readTemperature();
int h = dht.readHumidity();
float p = bmp.readPressure();
String dataString = "";
dataString = time.timestamp(DateTime::TIMESTAMP_FULL);
dataString += ",";
dataString += t;
dataString += ",";
dataString += h;
dataString += ",";
dataString += p;
// open the file. note that only one file can be open at a time,
// so you have to close this one before opening another.
File dataFile = SD.open("datalog.txt", FILE_WRITE);
// if the file is available, write to it:
if (dataFile) {
dataFile.println(dataString);
dataFile.close();
// print to the serial port too:
Serial.println(dataString);
}
// if the file isn't open, pop up an error:
else {
Serial.println("error opening datalog.txt");
analogWrite(3, 50);
}
delay (900000);
}
| true |
ecff4fab90b84e574f341111ffa469adfc64fcb6 | C++ | fauxdiscours/School | /Lab 3 Prime Numbers STL/Prime1:2/Prime1.cpp | UTF-8 | 755 | 4.15625 | 4 | [] | no_license | //Christian Eaves
//Prime1, checks to see if user input number is prime.
#include<iostream>
#include<cmath>
using namespace std;
//Checks if number is prime by dividing the number by up to its square root.
bool isprime(int number) {
int sroot = sqrt(number);
//If number < 2 it is not prime because 2 is the smallest prime number
if(number < 2){
return false;
}
//Checks to see if number is prime, if the remainder is 0 return false, otherwise return true
for(int i = 2; i <= sroot; i++){
if((number%i) == 0){ return false; }
}
return true;
}
int main()
{
int number;
//Outputs " is a prime number" after the number if it is prime
while (cin >> number ) {
if (isprime(number))
cout << number << " is a prime number" << endl;
}
return 0;
}
| true |
8f645c0bf79cb7b38a458cef1eb81ec9a2ce9f65 | C++ | kirkbackus/old-borland-projects | /Bomb/Headers/upgrade.h | UTF-8 | 1,594 | 2.578125 | 3 | [] | no_license | class Upgrade {
public:
int type;
Blackbox::Polygon* collide;
float x,y;
float rotation;
bool visible;
int reload;
Upgrade(float xpos, float ypos, int t1, Blackbox::Polygon* collision_mask);
void Draw();
};
Upgrade::Upgrade(float xpos, float ypos, int t1, Blackbox::Polygon* collision_mask) {
x = xpos;
y = ypos;
type = t1;
collide = collision_mask;
visible = 1;
rotation = 0;
}
void Upgrade::Draw() {
if (!visible) {
if (reload>0) reload--;
else visible = 1;
return;
}
rotation += 1;
glPushMatrix();
glTranslatef(x,y,0);
glRotatef(rotation,0,0,1);
DrawCircle(0,0,16,16,1,1,1,.25,0);
DrawCircle(0,0,16,16,1,1,1,1,1);
switch (type) {
case 0: //Health
DrawRectangle(-8,-4,8,4,0,1,0,1,0);
DrawRectangle(-4,-8,4,8,0,1,0,1,0);
break;
case 1: //Add Ammo
DrawRectangle(-8,-4,8,4,1,0,0,1,0);
DrawRectangle(-4,-8,4,8,1,0,0,1,0);
break;
case 2: //Machine Gun
DrawRectangle(-8,-4,8,0,1,0,1,1,0);
DrawRectangle(-8,0,-4,4,1,0,1,1,0);
break;
case 3: //Rocket Launcher
DrawRectangle(-8,-4,8,0,0,0,1,1,0);
DrawRectangle(-8,0,-4,4,0,0,1,1,0);
break;
case 4: //Lazer
DrawRectangle(-8,-4,8,0,1,1,0,1,0);
DrawRectangle(-8,0,-4,4,1,1,0,1,0);
break;
case 5: //Shotgun
DrawRectangle(-8,-4,8,0,0,1,0,1,0);
DrawRectangle(-8,0,-4,4,0,1,0,1,0);
break;
}
glPopMatrix();
}
| true |
f16a77f4bbf2569f9da2f0f07ac67c4a2534dd28 | C++ | atabakhafeez/SadsHomeworks | /hw6/Cipher/Cipher/main.cpp | UTF-8 | 562 | 2.671875 | 3 | [] | no_license | //
// main.cpp
// Cipher
//
// Created by Atabak Hafeez on 04.05.17.
// Copyright © 2017 Atabak Hafeez. All rights reserved.
//
#include <iostream>
using namespace std;
class EncryptionScheme {
protected:
string IV;
public:
virtual string encrypt(string input) = 0;
virtual string decrypt(string input) = 0;
};
class BlockCipher {
protected:
int s_chunk;
int p_chunk;
string key;
public:
virtual string encrypt(string input) = 0;
virtual string decrypt(string input) = 0;
};
int main(int argc, const char * argv[]) {
return 0;
}
| true |
3383deb89a1769d477b29ce5907313b836f7223a | C++ | takumus/trump | /src/display/texture.cpp | SHIFT_JIS | 3,883 | 2.796875 | 3 | [] | no_license | #include "texture.h"
#include "sprite.h"
#include <stdio.h>
#include <string>
#include <map>
#include <vector>
#include <time.h>
//#include "textfield.h"
using namespace std;
///--------------------------------------------------------//
//eNX`f[^NX
//--------------------------------------------------------//
void TextureData::setup(string _data, int _width, int _height, bool _transparent = false){
data = _data;
width = _width;
height = _height;
transparent = _transparent;
}
//--------------------------------------------------------//
//eNX`NX(Spritep)
//--------------------------------------------------------//
void Texture::setTextureData(TextureData _texture, bool _transparent){
data = _texture.getData();
texture = _texture;
transparent = _transparent;
width = texture.getWidth();
height = texture.getHeight();
/*TextField* t = new TextField;
t->setText("test");
t->x = 9;
t->y = 7;
addChild(t);*/
}
//--------------------------------------------------------//
//eNX`[_[
//--------------------------------------------------------//
bool TextureDataLoader::load(const char* fileName){
if((fp = fopen(fileName, "r,ccs=UTF-8")) == NULL) {
return false;
}
list.clear();
parse();
fclose(fp);
return true;
}
TextureData TextureDataLoader::get(string label){
return list.at(label);
}
void TextureDataLoader::convertToTexture(int width, int height, string name, vector<string> lines){
printf("-------------------------\n");
printf("name : %s\n", name.c_str());
printf("width,height : %d,%d\n", width, height);
int length = lines.size() - 1;
string data = "";
for(int i = 0; i < length; i ++){
while(lines[i].size() < width){
lines[i] += " ";
}
data += lines[i];
}
printf("data : ");
for(int i = 0; i < width*height; i ++){
printf("%c",data.c_str()[i]);
}
printf("\n");
list[name].setup(data, width, height, false);
double interval = 0.05 * CLOCKS_PER_SEC;
clock_t cc = clock();
while(clock() - cc < interval);
}
//ǂݍf[^̃p[X
void TextureDataLoader::parse() {
char c;
int id, twidth, width, height;
string name="";
vector<string> lines;
string phase = "";
while(1) {
c = fgetwc(fp);
//-------------------------------------------------------//
//@VKeNX`̏
//-------------------------------------------------------//
if(c == '@') {
//̃eNX`JnLeNX`o^
if(phase == "data"){
convertToTexture(width, height, name, lines);
}
//̃f[^o^ɔď
id = 0;
name = "";
lines.clear();
lines.push_back("");
height = twidth = width = 0;
//tF[YueNX`̃p[Xv[h
phase = "name";
continue;
}
//-------------------------------------------------------//
//@tF[Y@F@eNX`̃p[X
//-------------------------------------------------------//
if(phase == "name"){
if(c == '\n'){
//sR[hop[XIA
//tF[YueNX`f[^̃p[Xv[h
phase = "data";
continue;
}
name += c;
continue;
}
//-------------------------------------------------------//
//@tF[Y@F@eNX`f[^̃p[X
//-------------------------------------------------------//
if(phase == "data"){
if(c == '\n' || c < 0) {
height++;
if(width < twidth){
width = twidth;
}
twidth = 0;
lines.push_back("");
id++;
//c < 0܂EOFHȂŌ̃f[^o^AIB
if(c < 0){
//eNX`o^
convertToTexture(width, height, name, lines);
break;
}
continue;
}
twidth++;
lines[id] += c;
continue;
}
}
}
| true |
265014e980fa7f399a26dd34e689625bb23a7c2c | C++ | mahbubhimel/Codeforces | /208A/main.cpp | UTF-8 | 734 | 3.25 | 3 | [] | no_license | #include <iostream>
#include <string>
using namespace std;
char array[205];
int main()
{
string song;
cin >> song;
int length = song.length();
for(int i = 0 ; i < length ; i++){
array[i] = song.at(i);
}
array[length+1] = '\0';
for(int i = 0 ; i < length ; i++){
if(array[i] == 'W' && array[i+1] == 'U' && array[i+2] == 'B'){
array[i]=array[i+1]=array[i+2] = '\0';
}
}
int counter = 0;
for(int i = 0 ; i < length ; i++){
if(array[i] != '\0'){
counter++;
cout << array[i];
}else if(counter != 0 && array[i] == '\0' && array[i+1] != '\0'){
cout << " ";
}
}
cout << endl;
return 0;
}
| true |
38c7af992a684a5eab1d57c2bb2780a4ad4dbed9 | C++ | Robbiekorneta11/NIU-School-Work | /CSCI340/Binary-Tree/binarytreeDriver.cc | UTF-8 | 2,992 | 3.53125 | 4 | [] | no_license | /*
Robi Korneta
Z1816167
CSCI 340 - 1
I certify that this is my own work and where appropriate an extension
of the starter code provided for the assignment.
*/
#include <math.h>
#include <algorithm>
#include <iomanip>
#include <iostream>
#include <vector>
using namespace std;
#include "binarytree.h"
#define SEED 1 // seed for RNGs
#define N1 100 // size of 1st vector container
#define LOW1 -999 // low val for rand integer
#define HIGH1 999 // high val for rand integer
#define N2 50 // size of 2nd vector container
#define LOW2 -99999 // low val for rand float
#define HIGH2 99999 // high val for rand float
#define PREC 2 // no of digits after dec pt
#define LSIZE 12 // no of vals printed on line
#define ITEM_W 7 // no of spaces for each item
// prints single val
template <typename T>
void print(const T &);
// prints data vals in tree
template <typename T>
void print_vals(BinaryTree<T> &, const string &);
// class to generate rand ints
class RND1
{
private:
int low, high;
public:
RND1(const int &l = 0, const int &h = 1) : low(l), high(h) {}
int operator()() const { return rand() % (high - low + 1) + low; }
};
// class to generate rand floats
class RND2
{
private:
int low, high, prec;
public:
RND2(const int &l = 0, const int &h = 1, const int &p = 0) : low(l), high(h), prec(p) {}
float operator()() const { return (static_cast<float>(rand() % (high - low + 1) + low)) / pow(10, prec); }
};
// prints val passed as argument
template <typename T>
void print(const T &x)
{
static unsigned cnt = 0;
cout << setw(ITEM_W) << x << ' ';
cnt++;
if (cnt % LSIZE == 0)
cout << endl;
}
// prints size and height of bin tree and data val in
// each node in inorder
template <typename T>
void print_vals(BinaryTree<T> &tree, const string &name)
{
cout << name << ": "; // print name of tree
// print size and height of tree
cout << "size = " << tree.getSize() << ", ";
cout << "height = " << tree.getHeight() << endl
<< endl;
// print data values of tree in inorder
cout << "Data values in '" << name << "' inorder:\n\n";
tree.Inorder(print);
cout << endl;
}
// driver program: to test several member functions of BinaryTree class
int main()
{
srand(SEED); // set seed for RNGs
// create 1st vector and fill it with rand ints
vector<int> A(N1);
generate(A.begin(), A.end(), RND1(LOW1, HIGH1));
// create binary tree with int vals in vector A,
// and print all vals of tree
BinaryTree<int> first;
for (unsigned i = 0; i < A.size(); i++)
first.Insert(A[i]);
print_vals(first, "first");
cout << endl;
// create 2nd vector and fill it with rand floats
vector<float> B(N2);
generate(B.begin(), B.end(), RND2(LOW2, HIGH2, PREC));
// create binary tree with float vals in vector B,
// and print all vals of tree
BinaryTree<float> second;
for (unsigned i = 0; i < B.size(); i++)
second.Insert(B[i]);
print_vals(second, "second");
cout << endl;
return 0;
}
| true |
f41795ae2f9ea96c75472bcd7eaa43737e66ded9 | C++ | katahiromz/BoostWaveExample | /No4_MakeIncludeTree/MakeIncludeTree.hpp | UTF-8 | 1,783 | 2.53125 | 3 | [
"MIT"
] | permissive | #pragma once
#include <boost/wave.hpp>
#include <boost/wave/preprocessing_hooks.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/ref.hpp>
#include <stack>
// A hook class to output the tree
class MakeIncludeTreeHook
:
public boost::wave::context_policies::default_preprocessing_hooks
{
private:
typedef boost::reference_wrapper<boost::property_tree::ptree> ref_ptree;
public:
MakeIncludeTreeHook(boost::property_tree::ptree& target)
:
_target(target),
_current(target),
_parentStack(),
_lastIncFile()
{
}
public:
const boost::property_tree::ptree& getTarget() const
{
return _target;
}
public:
template <typename ContextT>
bool found_include_directive(
ContextT const& ctx,
std::string const& filename,
bool include_next)
{
_lastIncFile = filename;
return false;
}
template<typename ContextT>
void opened_include_file(
ContextT const&,
std::string const&,
std::string const& absname,
bool)
{
using namespace boost::property_tree;
_parentStack.push(_current);
ptree::iterator itr = _current.get().push_back(
ptree::value_type(
_lastIncFile,
boost::property_tree::ptree(absname)));
_current = boost::ref((*itr).second);
}
template<typename ContextT>
void returning_from_include_file(ContextT const&)
{
_current = _parentStack.top();
_parentStack.pop();
}
private:
ref_ptree _target;
ref_ptree _current;
std::stack<ref_ptree> _parentStack;
std::string _lastIncFile;
};
| true |
c97e32275003f2156fc6cf4b400e48ab42b7428d | C++ | kamyu104/ACMFinalsSolutions | /finals2016/stringDK.cc | UTF-8 | 812 | 2.765625 | 3 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
int main() {
int N;
while (cin >> N) {
vector<int> A(N);
for (int i = 0; i < N; i++) cin >> A[i];
int tot = 0;
for (int i = 0; i < N; i++) tot += A[i];
int ret;
for (ret = 100; ret; ret--) {
vector<int> v = A;
if (tot%2) goto fail;
if (ret == 1 && tot != 2) goto fail;
for (int i = ret, p1 = 0, p2 = v.size()-1; i; i--) {
if (v[p1] < i) goto fail;
v[p1] -= i;
while (p1 < p2 && v[p1] == 0) p1++;
if (v[p2] < i) goto fail;
v[p2] -= i;
while (p1 < p2 && v[p2] == 0) p2--;
}
break;
fail: ;
}
if (ret) {
cout << ret << endl;
} else {
cout << "no quotation" << endl;
}
}
}
| true |
ff0fe7929e47f4619e2e1c7bf04b16220df5f8b7 | C++ | mdjellison/Dots-and-Boxes | /Player.h | UTF-8 | 299 | 2.703125 | 3 | [] | no_license | #pragma once
#include <iostream>
class Player
{
public:
Player();
~Player();
int placeLine(const int &numColumns, const int &numRows, int &lineType);
void addPoint();
int giveScore();
private:
int score;
int findLineType(const int &rowInput, const int &columnInput);
};
| true |
abcdee5ba5c9ac38d340aae6cf0afc69038e46f3 | C++ | wowverywell/TriangleRayIntersection | /Контрольная работа №1/belong.cpp | UTF-8 | 952 | 2.796875 | 3 | [] | no_license | #include <iostream>
#include <cmath>
#include "structures.h"
double findSquare(Point A, Point B, Point P) {
Point AB, AP, vectMult;
double square;
AB = { B.coor_x - A.coor_x, B.coor_y - A.coor_y, B.coor_z - A.coor_z };
AP = { P.coor_x - A.coor_x, P.coor_y - A.coor_y, P.coor_z - A.coor_z };
vectMult = { AB.coor_y * AP.coor_z - AB.coor_z * AP.coor_y, AB.coor_z * AP.coor_x - AB.coor_x * AP.coor_z, AB.coor_x * AP.coor_y - AB.coor_y * AP.coor_x };
square = sqrt(pow(vectMult.coor_x, 2) + pow(vectMult.coor_y, 2) + pow(vectMult.coor_z, 2));
return square;
}
int belong(Point first, Point second, Point third, Point fourth) {
double squareAll = findSquare(first, second, third),
square1 = findSquare(first, second, fourth),
square2 = findSquare(third, second, fourth),
square3 = findSquare(first, fourth, third);
if ((square1 + square2 + square3) == squareAll) {
return 1;
}
else {
return 0;
}
} | true |
f1f264b705bb721095aee0e82e1fde7d6b9cd255 | C++ | WhiZTiM/coliru | /Archive2/ec/a4700e759af6a2/main.cpp | UTF-8 | 1,001 | 3.203125 | 3 | [] | no_license | #include <map>
#include <functional>
namespace sf {
struct Keyboard {
enum Key {
Left, Right
};
};
struct Vector2f {
float x,y;
Vector2f(float x,float y) : x(x), y(y) { }
};
}
class InputMap
{
public:
template<typename Function>
void setHotkey(sf::Keyboard::Key hotkey, Function onClick)
{
map[hotkey] = onClick;
}
void triggerHotkey(sf::Keyboard::Key hotkey)
{
if(map.find(hotkey) != map.end())
map[hotkey]();
}
protected:
std::map <sf::Keyboard::Key, std::function<void()>> map;
};
struct Actor {
void move(sf::Vector2f) { }
};
static void setHotkey(sf::Keyboard::Key,std::function<void()>)
{
}
int main(int,char**)
{
Actor TestActorObject;
Actor *TestActor = &TestActorObject;
setHotkey(sf::Keyboard::Left, [=](){TestActor->move(sf::Vector2f(-20, 0));});
setHotkey(sf::Keyboard::Right, [=](){TestActor->move(sf::Vector2f(20, 0));});
}
| true |
22a7be1241705173f29d5cecc08eacc904d9da52 | C++ | XMaxPlatform/support-chain | /foundation/basetypes/include/shortcode.hpp | UTF-8 | 2,357 | 2.875 | 3 | [
"MIT"
] | permissive | /**
* @file
* @copyright defined in xmax/LICENSE
*/
#pragma once
#include <string>
#if WIN32
# if _MSC_VER < 1914
# define _CONST_EXPR_
# else
# define _CONST_EXPR_ constexpr
# endif
#else
# define _CONST_EXPR_ constexpr
#endif
namespace ShortCode {
typedef char sglyph;
typedef uint32_t ssymbol;
typedef uint32_t sregion;
struct scode_rs
{
sregion region;
ssymbol symbol;
constexpr scode_rs(sregion r, ssymbol s)
: region(r)
, symbol(s)
{
}
};
static constexpr sglyph SCODE_REGION_0[] = "#abcdefghijklmnopqrstuvwxyz.1234";
static constexpr sglyph SCODE_REGION_1[] = "#@567890";
static constexpr ssymbol SCODE_SYMBOL_EXPEND = 0;
static constexpr ssymbol SR0_SYMBOL_A = 1;
static constexpr ssymbol SR0_SYMBOL_Z = 26;
static constexpr ssymbol SR0_SYMBOL_POINT = 27;
static constexpr ssymbol SR0_SYMBOL_1 = 28;
static constexpr ssymbol SR0_SYMBOL_4 = 31;
static constexpr ssymbol SR1_SYMBOL_AT = 1;
static constexpr ssymbol SR1_SYMBOL_5 = 2;
static constexpr ssymbol SR1_SYMBOL_9 = 6;
static constexpr ssymbol SR1_SYMBOL_0 = 7;
static constexpr sregion SR0_NUM = 0;
static constexpr sregion SR1_NUM = 1;
static constexpr sregion SRERROR_NUM = -1;
static constexpr uint16_t SCODE_REGION_0_SIZE = sizeof(SCODE_REGION_0) - 1;
static constexpr uint16_t SCODE_REGION_1_SIZE = sizeof(SCODE_REGION_1) - 1;
static _CONST_EXPR_ sglyph get_sglyph(sregion region, ssymbol sym)
{
switch (region)
{
case 0:
{
if (0 < sym && sym < SCODE_REGION_0_SIZE)
{
return SCODE_REGION_0[sym];
}
break;
}
case 1:
{
if (0 < sym && sym < SCODE_REGION_1_SIZE)
{
return SCODE_REGION_1[sym];
}
break;
}
default:
break;
}
return (sglyph)0;
}
static _CONST_EXPR_ scode_rs get_scode_rs(sglyph ch)
{
if ('a' <= ch && ch <= 'z')
{
return scode_rs(SR0_NUM, (ssymbol)(ch - 'a' + SR0_SYMBOL_A));
}
if ('.' == ch)
{
return scode_rs(SR0_NUM, SR0_SYMBOL_POINT);
}
if ('1' <= ch && ch <= '4')
{
return scode_rs(SR0_NUM, (ssymbol)(ch - '1' + SR0_SYMBOL_1));
}
if ('@' == ch)
{
return scode_rs(SR1_NUM, SR1_SYMBOL_AT);
}
if ('5' <= ch && ch <= '9')
{
return scode_rs(SR1_NUM, (ssymbol)(ch - '5' + SR1_SYMBOL_5));
}
if ('0' == ch)
{
return scode_rs(SR1_NUM, SR1_SYMBOL_0);
}
return scode_rs((sregion)SRERROR_NUM, 0);
}
} | true |
bc25278a8e21c9faba9a60ae36b9a9e94aea38e4 | C++ | SammyEnigma/C-11-Concurrency | /timed_mutex/timed_mutex.cpp | UTF-8 | 1,252 | 3.203125 | 3 | [] | no_license | // timed_mutex.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <thread>
#include <mutex>
#include <chrono>
#include <ctime>
std::timed_mutex tmt;
void fireworks()
{
while (!tmt.try_lock_for(std::chrono::milliseconds(200)))
{
std::cout << "-";
}
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
std::cout << "*\n";
tmt.unlock();
}
std::chrono::time_point<std::chrono::system_clock> midnight()
{
using std::chrono::system_clock;
std::time_t tt = system_clock::to_time_t(system_clock::now());
std::tm* ptm = std::localtime(&tt);
++ptm->tm_mday;
ptm->tm_hour = 0;
ptm->tm_min = 0;
ptm->tm_sec = 0;
return system_clock::from_time_t(mktime(ptm));
}
void carriage()
{
if (tmt.try_lock_until(midnight()))
{
std::cout << "ride back home on carrage\n";
tmt.unlock();
}
else
std::cout << "carriage reverts to pumpkin\n";
}
void ball()
{
tmt.lock();
std::cout << "at the ball..\n";
tmt.unlock();
}
int main()
{
/*std::thread task[10];
for (int i = 0; i < 10; ++i)
{
task[i] = std::thread(fireworks);
}
for (auto& x : task)
{
x.join();
}*/
std::thread th1(carriage);
std::thread th2(ball);
th1.join();
th2.join();
return 0;
}
| true |
522e38c320041d4ce9a964dd470ab2da5d0cc09c | C++ | guglielmino/s6-fresnel-firmware-mos | /src/hardware/devices/MCP39F511/uart/MCP39F511UARTProto.hpp | UTF-8 | 4,192 | 2.609375 | 3 | [] | no_license | #ifndef __MCP39F511PUARTPROTO_H
#define __MCP39F511PUARTPROTO_H
#include <vector>
#include <functional>
#include "IMCP39F511UARTProto.h"
#include "../commands/ICommandFrame.hpp"
#include "../../../io/IUART.h"
/**
* MCP39F511 UART protocol. Manage UART communication with MCP39F511 chip
*/
class MCP39F511UARTProto : public IMCP39F511UARTProto {
private:
readCallback_t _finish_cb;
enum FillState {
Idle = 0,
Reading
};
static const uint8_t ACK = 0x06;
static const uint8_t NACK = 0x15;
static const uint8_t CSFAIL = 0x51;
void fillInternalAccumulator(const uint8_t *buffer, size_t size) {
for (int i = 0; i < size; ++i) {
accumulator.push_back(buffer[i]);
bytesLeft--;
}
}
FillState fillState = FillState::Idle;
std::vector <uint8_t> accumulator;
uint8_t bytesLeft; // bytes left to the end of the receiving buffer
ICommandFrame::WaitForType waitFor;
IUART *_uart;
void process(uint8_t *buffer, size_t size) {
LOG(LL_DEBUG, ("McpUARTProtoReader::process 0x%x", (uint8_t) buffer[0]));
switch (fillState) {
case FillState::Idle: {
// Command interpreter
if (buffer[0] == ACK) {
if(waitFor == ICommandFrame::WaitForType::ACK_DATA_CHECKSUM) {
bytesLeft = buffer[1];
LOG(LL_DEBUG, ("ACK (%d - %d)", bytesLeft, size));
// Sometime size > byteLeft (it's due to serial communications, more data than the declared size
// at protocol level). In that case the byteLeft is the total number of bytes to get
fillInternalAccumulator(buffer, MIN(size, bytesLeft));
LOG(LL_DEBUG, ("ACK LEFT (%d)", bytesLeft));
}
else {
bytesLeft = 0;
}
fillState = Reading;
} else if (buffer[0] == NACK) {
LOG(LL_DEBUG, ("NACK\n"));
_finish_cb(RespType::Nack, nullptr, 0);
} else if (buffer[0] == CSFAIL) {
LOG(LL_DEBUG, ("CSFAIL\n"));
accumulator.clear();
fillState = Idle;
bytesLeft = 0;
_finish_cb(RespType::ChecksumErr, nullptr, 0);
} else {
LOG(LL_DEBUG, ("*** Packet - UNKNOW 0x%x", (uint8_t) buffer[0]));
}
}
break;
case FillState::Reading: {
fillInternalAccumulator(buffer, size);
}
break;
}
if (bytesLeft == 0 && fillState == Reading) {
_uart->flush();
fillState = Idle;
_finish_cb(RespType::Ack, reinterpret_cast<uint8_t *>(accumulator.data()), accumulator.size());
accumulator.clear();
}
}
void writeFrame(std::vector <uint8_t> frame) {
int frameSize = frame.size();
for (unsigned int i = 0; i < frameSize; ++i) {
_uart->write(&frame[i], 1);
_uart->flush();
mgos_usleep(1000);
}
}
public:
MCP39F511UARTProto(IUART *uart) : _uart(uart) {
bytesLeft = 0;
fillState = FillState::Idle;
}
bool sendCommand(ICommandFrame& command) {
if(fillState != Idle) {
LOG(LL_DEBUG, ("UART operation in progress"));
return false;
}
std::vector <uint8_t> frame = command.frame();
// Set the waitFot type for the processing command
waitFor = command.waitFor();
writeFrame(frame);
return true;
}
void readAsync(readCallback_t cb) {
_finish_cb = cb;
_uart->readAsync([&, this]() {
size_t rx_av = _uart->readAvail();
if (rx_av > 0) {
uint8_t locbuffer[rx_av];
memset(locbuffer, 0, rx_av);
_uart->read(locbuffer, rx_av);
this->process(locbuffer, rx_av);
}
});
}
};
#endif | true |
5a8bd6bc0e207c2dc60b905e948c908f8de229e9 | C++ | wkindling/SkinnedMesh-Animation | /2D/src/main.cpp | UTF-8 | 2,659 | 2.671875 | 3 | [] | no_license | #include "skinnedmesh.h"
Bone* root = new Bone(Vector2d(0,350),Vector2d(0,0));
Bone* bone1 = new Bone(root, 200, 0);
Bone* bone2 = new Bone(bone1, 200, 0);
Bone* bone3 = new Bone(bone2, 200, 0);
SkinnedMesh mesh(root);
double target_x = bone3->position.x(), target_y = bone3->position.y();
void changePoint(int x, int y)
{
target_x = x;
target_y = 700-y;
glutPostRedisplay();
}
void display()
{
glClear(GL_COLOR_BUFFER_BIT);
mesh.ccd(bone3, Vector2d(target_x, target_y));
mesh.updateMeshPosition();
mesh.draw();
glColor3f(1, 0, 1);
glPointSize(10.0);
glBegin(GL_POINTS);
glVertex2d(target_x, target_y);
glEnd();
glutPostRedisplay();
glutSwapBuffers();
}
int main(int argc, char ** argv)
{
Vertex* vertex0 = new Vertex(Vector2d(0, 50), Vector2d(0, 50)); mesh.addVertex(vertex0);
Vertex* vertex1 = new Vertex(Vector2d(0, -50), Vector2d(0, -50)); mesh.addVertex(vertex1);
Vertex* vertex2 = new Vertex(Vector2d(200, -50), Vector2d(200, -50)); mesh.addVertex(vertex2);
Vertex* vertex3 = new Vertex(Vector2d(200, 50), Vector2d(200, 50)); mesh.addVertex(vertex3);
Vertex* vertex4 = new Vertex(Vector2d(400, 50), Vector2d(400, 50)); mesh.addVertex(vertex4);
Vertex* vertex5 = new Vertex(Vector2d(400, -50), Vector2d(400, -50)); mesh.addVertex(vertex5);
Vertex* vertex6 = new Vertex(Vector2d(600, -50), Vector2d(600, -50)); mesh.addVertex(vertex6);
Vertex* vertex7 = new Vertex(Vector2d(600, 50), Vector2d(600, 50)); mesh.addVertex(vertex7);
vertex0->addRelatedBone(root, 0.5); vertex0->addRelatedBone(bone1, 0.25); vertex0->addRelatedBone(bone2, 0.25);
vertex1->addRelatedBone(root, 0.5); vertex1->addRelatedBone(bone1, 0.25); vertex1->addRelatedBone(bone2, 0.25);
vertex2->addRelatedBone(bone1, 0.5); vertex2->addRelatedBone(root, 0.25); vertex2->addRelatedBone(bone2, 0.25);
vertex3->addRelatedBone(bone1, 0.5); vertex3->addRelatedBone(root, 0.25); vertex3->addRelatedBone(bone2, 0.25);
vertex4->addRelatedBone(bone2, 0.5); vertex4->addRelatedBone(bone1, 0.25); vertex4->addRelatedBone(bone3, 0.25);
vertex5->addRelatedBone(bone2, 0.5); vertex5->addRelatedBone(bone1, 0.25); vertex5->addRelatedBone(bone3, 0.25);
vertex6->addRelatedBone(bone3, 1.0);
vertex7->addRelatedBone(bone3, 1.0);
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
glutInitWindowPosition(0, 0);
glutInitWindowSize(700, 700);
glutCreateWindow("SkinnedMesh_IK");
glutMotionFunc(changePoint);
glClearColor(1.0, 1.0, 1.0, 1.0);
glMatrixMode(GL_PROJECTION);
gluOrtho2D(0.0, 700.0, 0.0, 700.0);
glutDisplayFunc(display);
glutMainLoop();
return 0;
} | true |
b849752442c9739bc4ed76297d7b1838ad9d2bcb | C++ | ja-ho/baekjoon_algorithm | /joon_assignment/2580(sudoku).cpp | UTF-8 | 1,332 | 2.859375 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
#include <vector>
#include <utility>
using namespace std;
int map[10][10];
bool c_1[10][10];
bool c_2[10][10];
bool c_3[10][10];
bool check(int r, int c, int value)
{
if (c_1[r][value]) return false;
if (c_2[c][value]) return false;
if (c_3[(r / 3) * 3 + (c / 3)][value]) return false;
return true;
}
void go(int index)
{
int cnt = 0;
if (index == 81) {
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
cout << map[i][j] << ' ';
}
cout << '\n';
}
return;
}
int r = index / 9;
int c = index % 9;
if (map[r][c] != 0) {
go(index + 1);
}
else {
for (int i = 1; i <= 9; i++) {
if (check(r, c, i)) {
c_1[r][i] = true;
c_2[c][i] = true;
c_3[(r / 3) * 3 + (c / 3)][i] = true;
map[r][c] = i;
go(index + 1);
map[r][c] = 0;
c_1[r][i] = false;
c_2[c][i] = false;
c_3[(r / 3) * 3 + (c / 3)][i] = false;
}
}
}
return;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
cin >> map[i][j];
if (map[i][j] != 0) {
c_1[i][map[i][j]] = true;
c_2[j][map[i][j]] = true;
c_3[(i / 3) * 3 + (j / 3)][map[i][j]] = true;
}
}
}
go(0);
return 0;
} | true |
2a00da8afd7fac6f8444ec4ec3cff6fc1c522b1b | C++ | ckennelly/advent-of-code-2020 | /cpp/21/21b.cc | UTF-8 | 3,272 | 2.515625 | 3 | [
"Apache-2.0"
] | permissive | #include <algorithm>
#include <cmath>
#include <cstdio>
#include <iostream>
#include <map>
#include <regex>
#include <set>
#include <string>
#include <vector>
#include "absl/container/flat_hash_map.h"
#include "absl/container/flat_hash_set.h"
#include "absl/strings/ascii.h"
#include "absl/strings/numbers.h"
#include "absl/strings/match.h"
#include "absl/strings/str_format.h"
#include "absl/strings/str_join.h"
#include "absl/strings/str_split.h"
#include "absl/types/optional.h"
std::string readAll() {
std::stringstream buffer;
buffer << std::cin.rdbuf();
return buffer.str();
}
struct Records {
int seen;
std::map<std::string, int> allergies;
};
struct Parsed {
absl::flat_hash_set<std::string> ingredients;
absl::flat_hash_set<std::string> allergies;
};
int main(int argc, char **argv) {
std::vector<std::string> lines =
absl::StrSplit(readAll(), "\n", absl::SkipEmpty());
std::vector<Parsed> parsed;
absl::flat_hash_set<std::string> ingredients, allergies;
absl::flat_hash_map<std::string, int> seen;
for (const auto& line : lines) {
const size_t pos = line.find('(');
std::string raw_ingredients, raw_allergies;
if (pos == std::string::npos) {
raw_ingredients = line;
} else {
raw_ingredients = line.substr(0, pos);
const size_t offset = pos + strlen("(contains ");
raw_allergies = line.substr(offset, line.size() - offset - 1);
}
Parsed p;
p.ingredients = absl::StrSplit(raw_ingredients, ' ', absl::SkipEmpty());
p.allergies = absl::StrSplit(raw_allergies, ", ", absl::SkipEmpty());
ingredients.insert(p.ingredients.begin(), p.ingredients.end());
allergies.insert(p.allergies.begin(), p.allergies.end());
for (const auto& ingredient : p.ingredients) {
seen[ingredient]++;
}
parsed.push_back(std::move(p));
}
absl::flat_hash_map<std::string, absl::flat_hash_set<std::string>> possible;
for (const auto& allergy : allergies) {
possible[allergy] = ingredients;
}
for (const auto& parse : parsed) {
for (const auto& allergy : parse.allergies) {
for (const auto& ingredient : ingredients) {
if (!parse.ingredients.contains(ingredient)) {
possible[allergy].erase(ingredient);
}
}
}
}
std::set<std::string> known_allergies;
while (known_allergies.size() < allergies.size()) {
for (const auto& allergy : allergies) {
const auto& candidate_ingredients = possible[allergy];
if (candidate_ingredients.size() == 1 &&
known_allergies.insert(allergy).second) {
for (auto& [lhs, rhs] : possible) {
if (lhs == allergy) {
continue;
}
rhs.erase(*candidate_ingredients.begin());
}
}
}
}
std::vector<std::string> known_ingredients;
for (const auto& allergy : known_allergies) {
known_ingredients.push_back(*possible[allergy].begin());
}
absl::PrintF("%s", absl::StrJoin(known_ingredients, ","));
}
| true |
c03855f107091880b51aa00af7c0101ded7f4a4f | C++ | momar95136/process_manager | /src/process.cpp | UTF-8 | 2,346 | 2.90625 | 3 | [
"MIT"
] | permissive | #include "process.h"
#include <sys/time.h>
#include <unistd.h>
#include <cctype>
#include <sstream>
#include <string>
#include <vector>
#include "linux_parser.h"
using std::string;
using std::to_string;
using std::vector;
using std::stof;
// DONE: Return this process's ID
int Process::Pid() { return pid; }
// DONE: Return this process's CPU utilization
float Process::CpuUtilization() {
auto stat = GetProcessUpTimeInfo();
auto upTime = LinuxParser::UpTime();
auto utime = stof(stat[13].c_str());
auto stime = stof(stat[14].c_str());
auto cuttime = stof(stat[15].c_str());
auto ctime = stof(stat[16].c_str());
auto starttime = stof(stat[21].c_str());
auto total_time = utime + stime + cuttime + ctime;
auto seconds = upTime -(starttime / sysconf(_SC_CLK_TCK));
this->cpuUsage = (total_time / sysconf(_SC_CLK_TCK))/seconds;
return this->cpuUsage;
}
// DONE: Return the command that generated this process
string Process::Command() { return LinuxParser::Command(pid); }
// DONE: Return this process's memory utilization
string Process::Ram() {
this->ram = LinuxParser::Ram(pid);
return this->ram;
}
// DONE: Return the user (name) that generated this process
string Process::User() {
this->user = LinuxParser::User(pid);
return user;
}
void Process::init() {
User();
Ram();
Command();
CpuUtilization();
UpTime();
}
vector<string> Process::GetProcessUpTimeInfo() {
string command;
vector<string> stat;
std::istringstream ss;
string processLocation = LinuxParser::kProcDirectory + std::to_string(pid) +
LinuxParser::kStatFilename;
std::ifstream stream(processLocation.c_str());
if (stream.is_open()) {
getline(stream, command);
stream.close();
ss.str(command);
string token;
while (ss >> token) {
stat.push_back(token);
}
}
return stat;
}
// TODO: Return the age of this process (in seconds)
long int Process::UpTime() {
auto stat = GetProcessUpTimeInfo();
auto value = atol(stat[21].c_str());
auto uptime = value / sysconf(_SC_CLK_TCK);
this->upTime = uptime;
return uptime;
}
// TODO: Overload the "less than" comparison operator for Process objects
// REMOVE: [[maybe_unused]] once you define the function
bool Process::operator<(Process const& a) const {
return this->cpuUsage < a.cpuUsage;
} | true |
763dde812affa07c5d9950f77ced6392f8be7473 | C++ | Rinkeeee96/FoxTrot_SA_Engine | /engineFoxtrot/Engine/Physics/PhysicsEngine.cpp | UTF-8 | 5,068 | 2.703125 | 3 | [] | no_license | #include "stdafx.h"
#include "PhysicsFacade.h"
#include "PhysicsEngine.h"
#include "Events\Action\ObjectStopEvent.h"
#include "Events\Action\ObjectMoveToEvent.h"
#include "Events/Key/KeyPressed.h"
#include "Events/Action/TogglePause.h"
/// @brief Constructor
/// @param _frameData
/// A reference to the frameData class owned by Engine, used for accessing deltaTime
PhysicsEngine::PhysicsEngine(unique_ptr<FrameData>& _frameData) : frameData{ _frameData }
{
}
/// @brief Connects the dispatcher, set the listeners for event callbacks
/// @param dispatcher
void PhysicsEngine::start(EventDispatcher& dispatcher) {
this->dispatcher = &dispatcher;
physicsFacade = make_unique<PhysicsFacade>(dispatcher,frameData);
dispatcher.setEventCallback<ActionEvent>(BIND_EVENT_FN(PhysicsEngine::handleAction));
dispatcher.setEventCallback<ObjectStopEvent>(BIND_EVENT_FN(PhysicsEngine::stopObject));
dispatcher.setEventCallback<ObjectMoveToEvent>(BIND_EVENT_FN(PhysicsEngine::moveObjectTo));
dispatcher.setEventCallback<TogglePauseEvent>(BIND_EVENT_FN(PhysicsEngine::onPauseEvent));
dispatcher.setEventCallback<UpdatePhysicsBodyEvent>(BIND_EVENT_FN(PhysicsEngine::handleUpdateBodyEvent));
};
/// @brief Updates the physics world via the physicsFacade.
/// If the currentScene changes the physics facade will be cleaned.
void PhysicsEngine::update() {
if (isPaused()) return;
if (currentSceneID != (*pointerToCurrentScene)->getSceneID())
{
if (DEBUG_PHYSICS_ENGINE)cout << "Cleaning map and reinserting Objects" << endl;
physicsFacade->cleanMap();
registerObjectInCurrentVectorWithPhysicsEngine();
currentSceneID = (*pointerToCurrentScene)->getSceneID();
}
physicsFacade->update();
};
/// @brief Is called on physicsEngine shutdown.
/// Cleans the physicsEngine en deletes the physicsFacade.
void PhysicsEngine::shutdown() {
clean();
paused = false;
}
/// @brief Reloads the physicsFacade objects map.
void PhysicsEngine::reloadPhysicsObjects() {
physicsFacade->cleanMap();
registerObjectInCurrentVectorWithPhysicsEngine();
}
/// @brief Cleans the physicsFacade map
void PhysicsEngine::clean()
{
if (physicsFacade)
physicsFacade->cleanMap();
}
/// @brief
/// Handles a ActionEvent and according to the given direction moves the object
bool PhysicsEngine::handleAction(const Event& event) {
auto actionEvent = static_cast<const ActionEvent&>(event);
auto direction = actionEvent.getDirection();
auto objectId = actionEvent.getObjectId();
switch (direction)
{
case Direction::UP:
this->physicsFacade->Jump(objectId);
return true;
case Direction::LEFT:
this->physicsFacade->MoveLeft(objectId);
return true;
case Direction::RIGHT:
this->physicsFacade->MoveRight(objectId);
return true;
case Direction::DOWN:
this->physicsFacade->Fall(objectId);
return true;
default:
return false;
}
}
/// @brief
/// Handles the UpdatePhysicsEvent and updates the physics body belonging to the object
/// @param event
/// The given UpdatePhysicsBodyEvent
/// @return bool
bool PhysicsEngine::handleUpdateBodyEvent(const Event& event) {
auto actionEvent = static_cast<const UpdatePhysicsBodyEvent&>(event);
physicsFacade->updatePhysicsBody(actionEvent.getObject());
return true;
}
/// @brief Stops the vertical movement of an object.
/// @param event
/// @return bool
bool PhysicsEngine::stopObject(const Event& event) {
auto& e = static_cast<const ObjectStopEvent&>(event);
physicsFacade->stopObject(e.getObjectId(), e.getStopVertical(), e.getStopHorizontal());
return true;
}
/// @brief Sets the velocity of the given object towards the given position
/// @param event
/// The ObjectMoveToEvent
/// @return bool
bool PhysicsEngine::moveObjectTo(const Event& event)
{
auto& e = static_cast<const ObjectMoveToEvent&>(event);
physicsFacade->moveObjectTo(e.getObject(), e.getMoveToX(), e.getMoveToY());
return true;
}
/// @brief Executes on pause event for physics engine
bool PhysicsEngine::onPauseEvent(const Event& event)
{
auto pauseEvent = (TogglePauseEvent&)event;
paused = pauseEvent.isPaused();
return false;
}
/// @brief Destructor
/// @brief Destructor calls the shutdown function
PhysicsEngine::~PhysicsEngine()
{
shutdown();
}
/// @brief
/// A function to create all objects in the facade
void PhysicsEngine::registerObjectInCurrentVectorWithPhysicsEngine()
{
if (DEBUG_PHYSICS_ENGINE)cout << "Size pointertoObj: " << (*pointerToCurrentScene)->getAllObjectsInSceneRenderPhysics().size() << endl;
for (auto object : (*pointerToCurrentScene)->getAllObjectsInSceneRenderPhysics())
{
auto phyObj = shared_ptr<PhysicsBody>(new PhysicsBody(object));
if (DEBUG_PHYSICS_ENGINE)cout << "Registering object : " << phyObj->getObjectId() << endl;
if (object->getIsParticle()) continue;
if (object->getIsRemoved()) continue;
if (object->getStatic())
{
physicsFacade->addStaticObject(phyObj);
}
else
{
if(object->getBodyType() == BodyType::KINEMATIC) {
physicsFacade->addKinamaticObject(phyObj);
}
else{
physicsFacade->addDynamicObject(phyObj);
}
}
}
}
| true |
1181d9f1b40baa48f4b4837c57682f6050254d4d | C++ | guille31794/AAED | /Practica 4/polinom/e_s_polinom.cpp | UTF-8 | 2,726 | 3.140625 | 3 | [] | no_license | #include <iostream>
#include "e_s_polinom.h"
//#include "polinom.h"
#include "polinomio.hpp"
int introducirGrado()
{
int grado = 0;
while(grado > gradoMax || grado < 1)
{
cout << "Introduzca el grado <= " << gradoMax << endl;
cin >> grado;
}
return grado;
}
void introducirCoeficientes(polinomio &p, int g)
{
double coeficiente;
int i = 0;
while (i <= g)
{
cout << "\rIntroduzca el coeficiente " << i << ": " << endl;
cin >> coeficiente;
p.coeficiente(i, coeficiente);
++i;
}
}
void introducirPolinomio(polinomio &p1, polinomio &p2)
{
// Una llamada a cada funcion pora cada polinomio en los parametros
int grado = introducirGrado();
introducirCoeficientes(p1, grado);
grado = introducirGrado();
introducirCoeficientes(p2, grado);
}
void suma(const polinomio &polinomio1, const polinomio &polinomio2)
{
polinomio p(gradoMax);
int i = 0;
while(i <= gradoMax)
{
p.coeficiente(i, (polinomio1.coeficiente(i) + polinomio2.coeficiente(i)));
cout << p.coeficiente(i) << " x^" << i;
if(i < gradoMax)
cout << " + " ;
++i;
}
cout << endl;
}
void resta(polinomio const &p1, polinomio const &p2)
{
polinomio p(gradoMax);
int i = 0;
while(i <= gradoMax)
{
p.coeficiente(i, (p1.coeficiente(i) - p2.coeficiente(i)));
cout << p.coeficiente(i) << " x^" << i;
if(i < gradoMax)
cout << " + " ;
++i;
}
cout << endl;
}
void producto(polinomio const &p1, polinomio const &p2)
{
polinomio p(gradoMax + gradoMax);
int i, j;
double prodCoef, coef1, coef2;
for (i = 0; i <= gradoMax; ++i)
{
for ( j = 0; j <= gradoMax; ++j)
{
coef1 = p1.coeficiente(i);
coef2 = p2.coeficiente(j);
prodCoef = coef1 * coef2;
p.coeficiente(i+j, p.coeficiente(i+j) + prodCoef);
}
}
i = 0;
while (i <= gradoMax + gradoMax)
{
cout << p.coeficiente(i) << " x^" << i;
if(i < gradoMax + gradoMax)
cout << " + ";
++i;
}
cout << endl;
}
void derivada(polinomio const &p1, polinomio const &p2)
{
polinomio p(gradoMax);
int i;
for( i = 0; i <= gradoMax; ++i)
{
p.coeficiente(i, p1.coeficiente(i) * i);
}
i = 0;
while (i <= gradoMax)
{
if(i > 0)
{
cout << p.coeficiente(i) << " x^" << i-1;
if(i < gradoMax)
cout << " + ";
}
++i;
}
cout << endl;
}
| true |
63d8e3fa6ab3ef28718bcfc6e570d9c2199632a5 | C++ | naderabdalghani/paint-for-kids | /Figures/CCircle.h | UTF-8 | 892 | 2.75 | 3 | [
"Apache-2.0"
] | permissive | #pragma once
#ifndef CCIRC_H
#define CCIRC_H
#include "CFigure.h"
class CCircle : public CFigure
{
private:
Point Center;
Point Circumference;
int CalcRadius() const //Utility Function to Calculate radius
{
int radius = sqrt(pow((Center.x - Circumference.x), 2) + pow((Center.y - Circumference.y), 2));
return radius;
}
public:
CCircle(Point, Point, GfxInfo FigureGfxInfo);
CCircle(); //Default Constractor
virtual void Draw(Output* pOut) const;
virtual bool Get(int x,int y) const;
virtual void printinfo(Output* pOut) const;
virtual void Resize(double Scale);
virtual void Rotate(int Angle);
virtual void Save(ofstream & file);
virtual void Load(ifstream & file);
virtual void Paste(Point p,Point Mid);
virtual CFigure* Copy();
virtual string GetF()const;
virtual Point GetMid();
virtual bool OutsideInterface();
};
#endif | true |
9392e8bf74860d98238eab8e393024a1a37d5983 | C++ | sadiuk/naiCRAFTyi | /src/GLAbstraction/ArrayTexture.cpp | UTF-8 | 2,385 | 2.9375 | 3 | [] | no_license | #include "ArrayTexture.h"
namespace GL
{
/* In this constructor you mast pass all
* the paths to images that will be used as textures.
* The sizes, format, depth and resolutions must be the same.
*/
ArrayTexture::ArrayTexture(std::initializer_list<std::string> images)
{
if (images.size() == 0) throw std::runtime_error{"The initializer list must contain at least one member"};
GLCall(glGenTextures(1, &rendererID));
GLCall(glActiveTexture(GL_TEXTURE0));
GLCall(glBindTexture(GL_TEXTURE_2D_ARRAY, rendererID));
GLCall(glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MIN_FILTER, GL_NEAREST));
GLCall(glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MAG_FILTER, GL_NEAREST));
GLCall(glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE));
GLCall(glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE));
stbi_set_flip_vertically_on_load(true);
pixelData = stbi_load(images.begin()->c_str(), &width, &height, &BPP, 4);
if (pixelData == nullptr) throw std::runtime_error("Can not load the image by the path " + *images.begin());
GLCall(glTexStorage3D(GL_TEXTURE_2D_ARRAY, 1, GL_RGBA8, width, height, 256));
GLCall(glTexSubImage3D(GL_TEXTURE_2D_ARRAY, 0, 0, 0, nextSpot++,
width, height, 1, GL_RGBA, GL_UNSIGNED_BYTE, pixelData));
stbi_image_free(pixelData);
for(auto i = images.begin() + 1; i < images.end(); i++)
{
pixelData = stbi_load(i->c_str(), &width, &height, &BPP, 4);
if (pixelData == nullptr) throw std::runtime_error("Can not load the image by the path " + *i);
GLCall(glBindTexture(GL_TEXTURE_2D_ARRAY, rendererID));
GLCall(glTexSubImage3D(GL_TEXTURE_2D_ARRAY, 0, 0, 0, nextSpot++,
width, height, 1, GL_RGBA, GL_UNSIGNED_BYTE, pixelData));
stbi_image_free(pixelData);
}
}
ArrayTexture::~ArrayTexture()
{
GLCall(glDeleteTextures(1, &rendererID));
}
void ArrayTexture::Bind(GLuint slot) const
{
GLCall(glActiveTexture(GL_TEXTURE0 + slot));
GLCall(glBindTexture(GL_TEXTURE_2D_ARRAY, rendererID));
}
void ArrayTexture::UnBind() const
{
GLCall(glBindTexture(GL_TEXTURE_2D_ARRAY, 0));
}
}
| true |
efa7458058d74a7bdd19adb5cef0e8d11908dd55 | C++ | stamaniorec/UP_IS_2017-2018 | /UP_2017_10_05/UP_2017_10_05/UP_2017_10_05.cpp | UTF-8 | 5,905 | 3.609375 | 4 | [] | no_license | // UP_2017_10_05.cpp : Defines the entry point for the console application.
// jkasdjfjalksdf
#include "stdafx.h"
#include <iostream>
#include <cmath>
using namespace std;
// This is a comment. It starts with // and everything after that until
// the end of the line is not executed.
// Programs are executed sequentially, i.e. line after line from top to bottom.
// This program is just a text file. You can open it with Notepad
// if you find it in the file explorer
// (the project usually sits in My Documents/Visual studio 2015 or some place similar).
int main()
{
int x; // This is a variable
// In math, a variable is something we don't know and look to solve for.
// In programming, you can think of it as a box where you can store things.
// Variables have types (int in this case).
// Different types have different sizes - just like boxes.
// Sometimes you can put a smaller item in a bigger box,
// but the other way around is never possible without losing data.
// We'll look into those details later on in the course.
// By the way, we say that the variable x is *declared*,
// i.e. it exists, but we haven't given it a value.
// You can think of computer memory (RAM, but not only) as a massive storage house
// consisting of cells.
// Every cell has a size of 1 byte.
// Different variables take up a different number of cells in memory.
// Byte = 8 bits
// Bit - boolean value - true/false (1/0)
// You've heard about 0s and 1s and all that stuff from movies :)
// 1 byte = 8 bits = 8 times (0 or 1) = 2^8 = 256 possible values
// If you're wondering why a bool variable takes 1 byte (256 possible values)
// when we can only store a 0 or 1 in it...
// Very good!
// That's how computers work, unfortunately. :)
// It's not efficient and there are ways around it but usually we just don't care.
int y = 5;
// We say that y is *initialized*, i.e. we have declared it AND given it a value.
int z;
z = 123; // Don't do that. If you can put it on one line, do so.
// int zz;
// int zz = 123;
// This doesn't work because we declare zz twice.
// We can only declare a variable *once*.
// Every variable has a name.
// You should get in the habit of giving variable meaningful names.
// In a simple program like this one, we can more or less get by with x, y and z.
// However, when we work on an actual project with other people
// we should give our best to make our code easy to understand.
cout << "Hello world" << endl; // This is how we print something on the standard output.
cin >> x; // This is how we read a variable from the standard input.
// endl stands for "end of line"
// Standard input = keyboard
// Standard output = the black scary-looking window
// Things enclosed in double quotes ("") such as "Hello world" we call strings.
// We actually call them string literals, but that's not important for now.
// Roughly speaking, string = text
float piFloat = 3.14f; // Note the f at the end - 3.14 by default is a double
double piDouble = 3.14; // the f tells the computer we want a float
// Floats take up less memory (4 bytes), but are less precise.
// Use double unless you have a reason to use a float.
// Either way should work for the purposes of this course.
// You might be thinking, if 3.14 is a double, then why does
float imprecisePi = 3.14;
// work correctly? Are we not assigning a double value to a float variable?
// Yes, we are. That's one of those cases where you can put a bigger item in a smaller box.
// However, you lose data. In this case, you lose precision.
int i = 3.14; // This is also legal.
// Legal, meaning that the program will run and work.
// However, it won't work like we probably expect it to. :)
cout << i << endl; // Prints 3. We lose data - we lose the floating point part of the number.
cout << "Note that every statement must end with a semicolon (;)!" << endl;
// Statement ~ Line of code ~ Single instruction
// To use cout and cin, we must include the iostream library
// We do so by writing #include <iostream> usually at the top of our file.
// Library = code not written by us which we use because it's handy and we don't want to write our own
// Another library is cmath. It gives us useful mathematical functions such as sqrt.
// Can you write your own program to calculate a square root without using sqrt and cmath?
// Probably not and that's more than fine. :)
// That's why we use libraries.
// Like every library we want to use, we need to #include it at the top.
// cin and cout lie in something called "the standard namespace"
// in order to use them, we need to have access to it
// one way is to do it directly by writing std::cin, std::cout
// but this gets tiring quite fast
// that's why we also add a using namespace std; under our includes
// It literally does what it says.
// (This program will be) using (the) namespace (called) std;
// std is short for standard (namespace)
// We'll get to what exactly namespaces are and why they exist later on in the course.
// For now, you can either think of them as folders where we store things
// or not worry about them at all and just remember to always use the standard namespace. :)
// We won't be using any more namespaces other than std.
// Variables are also very useful for avoiding repetition.
// Remember how I had to change the number twice every time?
// Once when declaring the variable and once when printing?
// That's why we *extract* the 15 into a variable.
int number = 15;
double result = sqrt(number);
cout << "The square root of " << number << " is : " << x << endl;
// On a side note,
// numbers just randomly floating around the code are called "magic numbers"
// Programmers don't like magic numbers. :)
// Time goes on, people change jobs, people forget what that number meant
// and where it came from and why...
return 0;
}
| true |
651d64ffc4057a980962c981c281ca1b86762f16 | C++ | bzhou830/Orz3D | /Orz3D/Camera.cpp | GB18030 | 1,070 | 2.609375 | 3 | [
"MIT"
] | permissive | #include "Camera.h"
#include "imgui/imgui.h"
namespace dx = DirectX;
dx::XMMATRIX Camera::GetMatrix() const noexcept
{
const auto pos = dx::XMVector3Transform(dx::XMVectorSet(0.0f, 0.0f, -r, 0.0f),
dx::XMMatrixRotationRollPitchYaw(phi, -theta, 0.0f));
return dx::XMMatrixLookAtLH(pos, dx::XMVectorZero(), dx::XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f)) *
dx::XMMatrixRotationRollPitchYaw(pitch, -yaw, roll);
}
void Camera::SpawnControlWindow() noexcept
{
if (ImGui::Begin(u8"Camera"))
{
ImGui::Text(u8"λ");
ImGui::SliderFloat("R", &r, 0.0f, 80.0f, "%.1f");
ImGui::SliderAngle("Theta", &theta, -180.0f, 180.0f);
ImGui::SliderAngle("Phi", &phi, -89.0f, 89.0f);
ImGui::Text(u8"");
ImGui::SliderAngle("Roll", &roll, -180.0f, 180.0f);
ImGui::SliderAngle("Pitch", &pitch, -180.0f, 180.0f);
ImGui::SliderAngle("Yaw", &yaw, -180.0f, 180.0f);
if (ImGui::Button("Reset"))
{
Reset();
}
}
ImGui::End();
}
void Camera::Reset() noexcept
{
r = 20.0f;
theta = 0.0f;
phi = 0.0f;
pitch = 0.0f;
yaw = 0.0f;
roll = 0.0f;
} | true |
694715512a31e2398b7d71420f505972cbae271a | C++ | Tom-Li-Lee/learning_notes | /language/c++/language details/C++98/C++对象模型/main_3.cpp | UTF-8 | 1,082 | 3.484375 | 3 | [] | no_license | /*
* main.cpp
*
* Created on: 2011-2-21
* Author: tli
*/
#include <iostream>
#include <stdio.h>
using std::cout;
class Point2d
{
public:
Point2d ():_x(0),_y(0) { cout << "Point2d ctor is called\n";}
Point2d(int x, int y):_x(x),_y(y) {cout << "The Point2d ctor with 2 parameter is called\n";}
Point2d(const Point2d& p) : _x(p._x),_y(p._y) {cout << "Point2d copy ctor is called\n";}
Point2d& operator = (const Point2d& p) { _x = p._x; _y = p._y; cout << "Point2d copy assignment is called\n"; return *this; }
~Point2d() {cout<<"Point2d dtor is called\n";}
protected:
int _x, _y;
};
class Point3d : public Point2d
{
public:
Point3d():_z(0) { cout << "Point3d ctor is called\n";}
Point3d(int x, int y, int z):Point2d(x,y),_z(z) {cout << "The Point3d ctor with 3 parameter is called\n";}
virtual ~Point3d() {cout<<"Point3d dtor is called\n";}
protected:
int _z;
};
int main()
{
Point2d *ptr1 = new Point3d();
Point3d *ptr2 = (Point3d*)ptr1;
printf("%p, %p\n", ptr1, ptr2);
delete ptr1;
}
| true |
eb79105adf81d036024067edcb8fa8ed33de7e25 | C++ | NandhiniManian/my-face-programs | /FACE -C/sorting ascend & descend .cpp | UTF-8 | 471 | 2.90625 | 3 | [] | no_license | #include<iostream>
#include<bits/stdc++.h>
using namespace std;
class s
{
public:int i,a[100];
void sor(int a[],int n)
{
sort(a,a+n);
cout<<"ascending order:";
for(i=0;i<n;i++)
{
cout<<" "<<a[i];
}
cout<<"\n";
cout<<"descending order:";
sort(a,a+n,greater<int>());
for(i=0;i<n;i++)
{
cout<<" "<<a[i];
}
}
};
int main()
{
int n,a[100],i;
s o;
cin>>n;
for(i=0;i<n;i++)
{
cin>>a[i];
}
o.sor(a,n);
}
| true |
ae6d6dbb7242d953ec2127481bcb09b64b5125fc | C++ | hustpython/websocketpp | /socketprogram/src/server.cpp | UTF-8 | 1,950 | 2.515625 | 3 | [] | no_license | #include <sys/socket.h>
#include <memory.h>
#include <stdio.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#define MAX_SOCKET_BUFFER (1024 * 1024 * 4)
#define PORT 8000
int main()
{
int server_sockfd;
int client_sockfd;
int len;
struct sockaddr_in my_addr;
struct sockaddr_in remote_addr;
socklen_t sin_size;
char buf[MAX_SOCKET_BUFFER];
memset(&my_addr,0,sizeof(my_addr));
//bzero(&(my_addr.sin_zero), 8); /* 将整个结构剩余*/
/* 部分数据设为 0 */
my_addr.sin_family = AF_INET;
my_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
//my_addr.sin_addr.s_addr=htonl(INADDR_ANY)//("127.0.0.1");//服务器IP地址--允许连接到所有本地地址上
my_addr.sin_port = htons(PORT);
if((server_sockfd=socket(PF_INET,SOCK_STREAM,0))<0)
{
perror("socket error");
return 1;
}
int opt = 1;
// sockfd为需要端口复用的套接字
setsockopt(server_sockfd, SOL_SOCKET, SO_REUSEADDR, (const char *)&opt, sizeof(opt));
if(bind(server_sockfd,(struct sockaddr *)&my_addr,sizeof(struct sockaddr))<0)
{
perror("bind error");
return 1;
}
if(listen(server_sockfd,5)<0)
{
perror("listen error");
return 1;
}
sin_size = sizeof(struct sockaddr);
if((client_sockfd = accept(server_sockfd,(struct sockaddr *)&remote_addr,&sin_size))<0)
{
perror("accept error");
return 1;
}
printf("accept client %s\n",inet_ntoa(remote_addr.sin_addr));
len = send(client_sockfd,"Welcome to my server\n",21,0);
while((len = recv(client_sockfd,buf,BUFSIZ,0))>0)
{
buf[len] = '\0';
printf("%s\n",buf);
if(send(client_sockfd,buf,len,0)<0)
{
perror("write error");
return 1;
}
}
close (client_sockfd);
close (server_sockfd);
return 0;
} | true |
e76d0ca981023a87036a1d450619a4af8e845042 | C++ | naganath/SPOJ | /ABSURD.cpp | UTF-8 | 938 | 2.875 | 3 | [] | no_license | #include<iostream>
#include<math.h>
#include<stdio.h>
using namespace std;
inline int absurd1( int n)
{
while(n%10==0)
n=n/10;
int cpy =n;
int count=0;
while(cpy)
{
count++;
cpy/=10;
}
if(n%10==5)
return 2*count-1;
return 2*count;
}
inline int absurd2(int n)
{
int rev=0;
while(n)
rev= rev*10 + n%10, n/=10;
return rev;
}
int main()
{
int t,c,i,j,count;
scanf("%d",&t);
int l,u;
int g,o,f=0;
char s[10],t[10];
while(t--)
{
scanf("%d",&c);
f=0;
l = ceil(0.95*c);
u = floor(1.05*c);
g=absurd1(c);
s=itoa(l);
t=itoa(u);
i=absurd2(l);
j= absurd2(u);
int d=0,e=0;
do
{
e=j%10;
d=i%10;f++;
if(d==e)
j/=10,i/=10;
}while(d==e);
//cout<<d << " "<< e <<" ";
if(l<u)
if(i%10==5)
count=2*f-1;
else
count=2*f;
else
if(j%10==5)
count=2*f-1;
else
count=2*f;
if(count<g)
printf("absurd\n");
else
printf("not absurd\n");
}
return 0;
}
| true |
d81fd6d5a1e7016eeacbd5d49674f3c0d7bb5b15 | C++ | mathisloge/dt-dataflow-plugin-protocols | /ublox/src/protocol_ublox.cpp | UTF-8 | 766 | 2.53125 | 3 | [] | no_license | #include "protocol_ublox.hpp"
#include <comms/util/detect.h>
namespace protocol
{
Ublox::Ublox()
: state_{State::activated}
{}
std::string_view Ublox::name() const
{
return "ublox";
}
std::pair<ProtoReadIter, ProtoReadIter> Ublox::consumeOneMessage(ProtoReadIter begin, ProtoReadIter end)
{
if (!isActive())
return std::make_pair(begin, begin);
std::pair<ProtoReadIter, ProtoReadIter> read_range;
const auto status = ubx_instance_.processSingle(begin, end, read_range, ubx_handler_);
return status == comms::ErrorStatus::Success ? read_range : std::make_pair(begin, begin);
}
void Ublox::setState(State state)
{
state_ = state;
}
bool Ublox::isActive() const
{
return state_ == State::activated;
}
} // namespace protocol
| true |
54100144e17cd90c555638a4f1ca25e6ffa045f2 | C++ | VseMiRaki/OOP_3_term | /Contest1_2a/main.cpp | UTF-8 | 4,404 | 3 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <string>
std::vector<int> Z_function(std::string s) {
std::vector<int> z_value(s.size(), 0);
int left = 0, right = 0;
for (int i = 1; i < s.size(); i++) {
if (i > right) {
while (i + z_value[i] < s.size() && s[i + z_value[i]] == s[z_value[i]]) {
z_value[i]++;
}
}
else {
if (z_value[i - left] + i > right) {
z_value[i] = right - i;
while (i + z_value[i] < s.size() && s[i + z_value[i]] == s[z_value[i]]) {
z_value[i]++;
}
}
else {
z_value[i] = z_value[i - left];
}
}
if (i + z_value[i] - 1 > right) {
right = z_value[i] + i - 1;
left = i;
}
}
return z_value;
}
class string_refactoring {
public:
std::vector<int> z_function(const std::string &s) const;
std::string z_to_string(const std::vector<int> &z_values) const;
std::vector<int> prefix_function(const std::string &s) const;
std::string prefix_to_string(const std::vector<int> &p_values) const;
std::vector<int> z_to_prefix(const std::vector<int> &z_values) const;
std::vector<int> prefix_to_z(const std::vector<int> &p_values) const;
};
std::vector<int> string_refactoring::z_function(const std::string &s) const {
std::vector<int> z_value(s.size(), 0);
int left = 0, right = 0;
for (int i = 1; i < s.size(); i++) {
if (i > right) {
while (i + z_value[i] < s.size() && s[i + z_value[i]] == s[z_value[i]]) {
z_value[i]++;
}
}
else {
if (z_value[i - left] + i > right) {
z_value[i] = right - i;
while (i + z_value[i] < s.size() && s[i + z_value[i]] == s[z_value[i]]) {
z_value[i]++;
}
}
else {
z_value[i] = z_value[i - left];
}
}
if (i + z_value[i] - 1 > right) {
right = z_value[i] + i - 1;
left = i;
}
}
return z_value;
}
std::vector<int> string_refactoring::prefix_function(const std::string &s) const {
return z_to_prefix(z_function(s));
}
std::vector<int> string_refactoring::z_to_prefix(const std::vector<int> &z_values) const {
std::vector<int> p_values(z_values.size(), 0);
for (int i = 1; i < z_values.size(); i++) {
for (int j = z_values[i] - 1; j >= 0; j--) {
if (p_values[i + j] > 0) {
break;
}
p_values[i + j] = j + 1;
}
}
return p_values;
}
std::string string_refactoring::prefix_to_string(const std::vector<int> &p_values) const {
std::string str;
str += 'a';
for (int i = 1; i < p_values.size(); i++) {
if (p_values[i] == 0) {
std::vector<bool> used(26, 0);
for (int j = p_values[i - 1]; j > 0; j = p_values[j - 1]) {
used[str[j] - 'a'] = 1;
}
int j = 1;
while (used[j]) {
j++;
}
char c = static_cast<char>('a' + j);
str += c;
}
else {
str += str[p_values[i] - 1];
}
}
return str;
}
std::string fromPiToStr(const std::vector<size_t> &pi) {
std::string str = "a";
for (size_t i = 1; i < pi.size(); i++) {
if (pi[i] == 0) {
std::vector<bool> used(26, false);
size_t k = pi[i - 1];
while (k > 0) {
used[str[k] - 'a'] = true;
k = pi[k - 1];
}
char c = 'b';
while (used[c - 'a']) {
c++;
};
str += c;
} else {
str += str[pi[i] - 1];
}
}
return str;
}
std::string string_refactoring::z_to_string(const std::vector<int> &z_values) const {
return prefix_to_string(z_to_prefix(z_values));
}
std::vector<int> string_refactoring::prefix_to_z(const std::vector<int> &p_values) const {
return z_function(prefix_to_string(p_values));
}
int main() {
std::vector<int> p_values;
int value;
while (std::cin >> value) {
p_values.push_back(value);
}
std::cout << string_refactoring().prefix_to_string(p_values);
return 0;
}
| true |
485842ce1336e0e63b73bf766324aded66e2e6ea | C++ | Vipyr/cppdigraph | /test/test_gvtablerow.cpp | UTF-8 | 1,921 | 2.9375 | 3 | [
"MIT"
] | permissive | /*
* Unit Tests for cdg::GvTableRow
*/
#include "graphviz/gvtablerow.h"
#include "gtest/gtest.h"
using namespace cdg;
// Use an namespace to isolate the tests.
namespace test_gvtablerow {
TEST(TestGvTableRow, setCell_string) {
GvTableRow row = GvTableRow();
std::string expected = "rawr";
row.setCell(1, expected);
EXPECT_EQ(expected, row.getCell(1).getContent());
EXPECT_EQ("", row.getCell(0).getContent());
}
TEST(TestGvTableRow, setCell_GvTableCell) {
GvTableRow row = GvTableRow();
std::string expected = "rawr";
GvTableCell cell = GvTableCell();
cell.setContent(expected);
row.setCell(1, cell);
EXPECT_EQ(expected, row.getCell(1).getContent());
EXPECT_EQ("", row.getCell(0).getContent());
}
TEST(TestGvTableRow, to_string_no_cell_no_attribute) {
GvTableRow row = GvTableRow();
std::string expected = "<TR></TR>";
EXPECT_EQ(expected, row.to_string());
}
TEST(TestGvTableRow, to_string_with_cell_no_attribute) {
GvTableRow row = GvTableRow();
GvTableCell cell = GvTableCell();
cell.setContent("rawr");
row.addCell(cell);
std::string expected = "<TR><TD>rawr</TD></TR>";
EXPECT_EQ(expected, row.to_string());
}
TEST(TestGvTableRow, to_string_no_cell_with_attribute) {
GvTableRow row = GvTableRow();
row.setAttribute("attr", "test");
std::string expected = "<TR attr=\"test\"></TR>";
EXPECT_EQ(expected, row.to_string());
}
TEST(TestGvTableRow, to_string_with_cell_with_attribute) {
GvTableRow row = GvTableRow();
row.setAttribute("attr", "test");
GvTableCell cell = GvTableCell();
cell.setContent("rawr");
row.addCell(cell);
std::string expected = "<TR attr=\"test\"><TD>rawr</TD></TR>";
EXPECT_EQ(expected, row.to_string());
}
TEST(TestGvTableRow, size) {
GvTableRow row = GvTableRow();
GvTableCell cell = GvTableCell();
cell.setContent("rawr");
row.addCell(cell);
int expected = 1;
EXPECT_EQ(expected, row.size());
}
}
| true |
28d4dd948834fb99a1eec3ccb5b445f6868d1f72 | C++ | RVSZ-jiangfangfei/cslibs_navigation_utilities | /src/LaserTo3DTransformation.cpp | UTF-8 | 2,249 | 2.71875 | 3 | [] | no_license | /*
* LaserTo3DTransformation.cpp
*
* Created on: Nov 15, 2010
* Author: Michael Kaulig
*/
#include <cslibs_navigation_utilities/LaserTo3DTransformation.h>
#include <iostream>
#include <tf/tf.h>
LaserTo3DTransformation::LaserTo3DTransformation(Eigen::Vector3d trans): mTrans(trans){
}
LaserTo3DTransformation::~LaserTo3DTransformation() {
// TODO Auto-generated destructor stub
}
/*
* @param angle: anlge of laser beam
* @param dist: measured range
* @param rpy: Orientation of Laserscanner
* @param trans: Translation from middle of Laser to middle of PanTilt Unit
* @param[out] res: transformed 3dpoint
*/
void LaserTo3DTransformation::transform(double angle, double dist, const Eigen::Quaterniond& quat,
const Eigen::Vector3d& laserPos, Eigen::Vector3d& res){
// Transforms a LaserscanPoint (angle, dist) to 3d Point in a frame in the Laser
// PNI Koordinationsystem: x nach vorne (gegenüber Kabelaustritt) (Norden), y rechts (Osten) , z unten
// berechne Karthesische Koordinaten im Laserscannerframe
res = Eigen::Vector3d(dist * cos(angle),dist * sin(angle),0);
// Translatiere in den Ursprung des Pan-Tilt-Frames
res += mTrans;
// rotiere um 180 deg um die x-Achse um ins Pni-Frame zu transformieren
res[1] = -res[1];
res[2] = -res[2];
// rotiere um die Roll- und Tiltwinkel des PNI
tf::Vector3 resBt;
resBt[0] = res[0];
resBt[1] = res[1];
resBt[2] = res[2];
tfScalar roll, pitch, yaw;
tf::Quaternion quatBt;
quatBt.setX(quat.x());
quatBt.setY(quat.y());
quatBt.setZ(quat.z());
quatBt.setW(quat.w());
tf::Matrix3x3(quatBt).getRPY(roll, pitch, yaw);
tf::Matrix3x3 rotMatrix;
rotMatrix.setRPY(roll, pitch, 0);
resBt = rotMatrix * resBt;
// Rotiere zurück ins Pan-Tilt-Koordinatenframe
resBt[1] = -resBt[1];
resBt[2] = -resBt[2];
res[0] = resBt[0];
res[1] = resBt[1];
res[2] = resBt[2];
// Translatiere zurück ins Laserkoordinatensystem
res -= mTrans;
// Translatiere ins Roboterkoordinatenframe
res = res + laserPos;
}
| true |
0c8ebb9de532eb9e0e483390cd99b0d7875aaf5a | C++ | peartail/DirectXPractice2 | /ModelScaling/main.cpp | UTF-8 | 2,899 | 3.0625 | 3 | [] | no_license | #include <ostream>
#include <fstream>
#include <iostream>
#include <math.h>
using namespace std;
void GetModelFilename(char* filename, std::string& outfilename);
bool LoadTextStructure(char* savename,std::string filename);
int maxsize = 1;
struct ModelType
{
float x, y, z;
float tu, tv;
float nx, ny, nz;
float tx, ty, tz;
float bx, by, bz;
};
int main()
{
char filename[256];
string out;
GetModelFilename(filename, out);
cout << "MAX Size : ";
int size;
cin >> size;
if (size > 0)
maxsize = size;
LoadTextStructure(filename,out);
return 0;
}
void GetModelFilename(char* filename,std::string& outfilename)
{
bool done;
ifstream fin;
done = false;
while (!done)
{
cout << "Enter model filename : ";
cin >> filename;
string currentDirectory = ".\\Model\\";
string outputFilename = currentDirectory + filename+".txt";
fin.open(outputFilename);
if (fin.good())
{
done = true;
outfilename = outputFilename;
}
else
{
outfilename = "";
fin.clear();
cout << endl;
cout << "File " << filename << " could not be opened. " << endl << endl;
}
}
}
bool LoadTextStructure(char* savename, std::string filename)
{
int count;
float absmax = 0;
ifstream fin;
char input;
int i;
fin.open(filename);
if (fin.fail())
{
return false;
}
fin.get(input);
while (input != ':')
{
fin.get(input);
}
fin >> count;
ModelType* models = new ModelType[count];
if (!models)
{
return false;
}
fin.get(input);
while (input != ':')
{
fin.get(input);
}
fin.get(input);
fin.get(input);
for (i = 0; i<count; i++)
{
fin >> models[i].x >> models[i].y >> models[i].z;
fin >> models[i].tu >> models[i].tv;
fin >> models[i].nx >> models[i].ny >> models[i].nz;
if (absmax < abs(models[i].x))
{
absmax = abs(models[i].x);
}
if (absmax < abs(models[i].y))
{
absmax = abs(models[i].y);
}
if (absmax < abs(models[i].z))
{
absmax = abs(models[i].z);
}
//cout << models[i].x << models[i].y << models[i].z;
}
absmax = absmax / maxsize;
for (i = 0; i<count; i++)
{
models[i].x = models[i].x / absmax;
models[i].y = models[i].y / absmax;
models[i].z = models[i].z / absmax;
cout << models[i].x << ' ' << models[i].y << ' ' << models[i].z << endl;
}
fin.close();
ofstream fout;
string filestring = savename;
string currentDirectory = ".\\Model\\";
string outputFilename = currentDirectory + (filestring + "_normal.txt").c_str();
//printf(outputFilename);
fout.open(outputFilename);
fout << "Vertex Count: " << count << endl;
fout << endl;
fout << "Data:" << endl;
fout << endl;
for (int i = 0; i < count; ++i)
{
fout << models[i].x << ' ' << models[i].y << ' ' << models[i].z << ' ' << models[i].tu << ' ' << models[i].tv << ' ' << models[i].nx << ' ' << models[i].ny
<< ' ' << models[i].nz << endl;
}
fout.close();
return true;
} | true |
5bac82ac87a59fa3a898844d56bebde1f8f36887 | C++ | daikisuyama/AtCoder_Programs | /ARC_124/C.cc | UTF-8 | 2,371 | 2.53125 | 3 | [] | no_license | //嘘解法です、参考にしないでください
//Codeforcesで128bit整数を使いたいとき
//→__int128_tを使う&GNU C++17 (64)で提出する
//インクルードなど
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
//イテレーション
#define REP(i,n) for(ll i=0;i<ll(n);i++)
#define REPD(i,n) for(ll i=n-1;i>=0;i--)
#define FOR(i,a,b) for(ll i=a;i<=ll(b);i++)
#define FORD(i,a,b) for(ll i=a;i>=ll(b);i--)
#define FORA(i,I) for(const auto& i:I)
//x:コンテナ
#define ALL(x) x.begin(),x.end()
#define SIZE(x) ll(x.size())
//定数
#define INF32 2147483647 //2.147483647×10^{9}:32bit整数のinf
#define INF64 9223372036854775807 //9.223372036854775807×10^{18}:64bit整数のinf
#define MOD 1000000007 //問題による
//略記
#define F first
#define S second
//出力(空白区切りで昇順に)
#define coutALL(x) for(auto i=x.begin();i!=--x.end();i++)cout<<*i<<" ";cout<<*--x.end()<<endl;
//aをbで割る時の繰上げ,繰り下げ
ll myceil(ll a,ll b){return (a+(b-1))/b;}
ll myfloor(ll a,ll b){return a/b;}
signed main(){
//小数の桁数の出力指定
//cout<<fixed<<setprecision(10);
//入力の高速化用のコード
//ios::sync_with_stdio(false);
//cin.tie(nullptr);
ll n;cin>>n;
ll x,y;cin>>x>>y;
deque<pair<ll,ll>> now;
now.push_back({x,y});
REP(i,n-1){
ll a,b;cin>>a>>b;
REP(i,SIZE(now)){
ll x=now.front().F;
ll y=now.front().S;
now.pop_front();
ll l1=lcm(gcd(x,a),gcd(y,b));
ll l2=lcm(gcd(x,b),gcd(y,a));
if(l1>l2){
x=gcd(x,a);
y=gcd(y,b);
now.push_back({x,y});
}else if(l1<l2){
x=gcd(x,b);
y=gcd(y,a);
now.push_back({x,y});
}else{
ll x1,x2,y1,y2;
x1=gcd(x,a);
y1=gcd(y,b);
x2=gcd(x,b);
y2=gcd(y,a);
if(x1==x2 && y1==y2){
now.push_back({x1,y1});
}else{
now.push_back({x1,y1});
now.push_back({x2,y2});
}
}
}
}
ll ans=0;
FORA(i,now){
if(lcm(i.F,i.S)>ans){
ans=lcm(i.F,i.S);
}
}
cout<<ans<<endl;
} | true |
2ef8292d62731e957896c520717c777084955ed9 | C++ | singhsanket143/CppCompetitiveRepository | /CB/OnlineCourseCodes/QueuesC++/FirstNonRepeatingCharacterInAStream.cpp | UTF-8 | 433 | 2.71875 | 3 | [] | no_license | #include <iostream>
#include <queue>
#include <unordered_map>
using namespace std;
int main(int argc, char const *argv[])
{
queue<char> qu;
unordered_map<char, int> mp;
char ch;
cin>>ch;
while(ch != '.') {
qu.push(ch);
mp[ch]++;
while(!qu.empty()) {
if(mp[qu.front()] > 1) {
qu.pop();
} else {
cout<<qu.front()<<endl;
break;
}
}
if(qu.empty()) {
cout<<"-1"<<endl;
}
cin>>ch;
}
return 0;
} | true |
a36f6ebe1d3836ad824607f69bb42bb1c67514b7 | C++ | mxpule/pMol0174 | /src/pMolMpsv/pMolMpsvMask.h | UTF-8 | 3,837 | 2.5625 | 3 | [] | no_license | /***************************************************************************
* Copyright (C) 2006 by Martin Pule *
* martin@pulecyte.com *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* 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, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#ifndef PMOLMPSVMASK_H
#define PMOLMPSVMASK_H
#include <QRectF>
///this class provides a representation of the outline of a glob. It allows other globs
///to be fitted onto it and is designed to work in linear time no matter what the complexity
///of the glob is. Having said that it only represents and outline - not holes by representing
///the space as a series of strips, storing if the strip is used, what the highest point and
///what the lowest point in it is. This may seem like an overly simple way of doing it, but
///when each strip represents one dna base, it makes the whole system very efficient.
class pMolMpsvMask
{
public:
///constructor, needs universal constant
pMolMpsvMask(float p_uc);
///destructor
~pMolMpsvMask();
///is this strip used?
bool getUse(int x);
///what's the highest point on this strip?
int getTop(int x);
///what's the lowest point on this strip
int getBot(int x);
///how wide is the whole mask?
float getWidth();
///how high is the whole mask?
float getHeight();
///fills rect with bounding details
void setRect(QRectF &rect);
///reset - all cleared
void reset();
///translates to (0,0) top
float normalize();
///merge in a rectangular mask
void addMask(float p_x, float p_y, float p_w, float p_h);
///merge in another mask in the same orientation offset to p_x and p_y
void addMaskPos(float p_x, float p_y, pMolMpsvMask* mask);
///merge in another mask 180 degrees rotated offset to p_x and p_y
void addMaskNeg(float p_x, float p_y, pMolMpsvMask* mask);
///fit a mask as snuggly as possible returning the minimum offset upwards
float fitPos(int x, pMolMpsvMask* mask);
///fit mask 180degrees as snuggly as possible returning offset downwards
float fitNeg(int x, pMolMpsvMask* mask);
///copy into a new object
pMolMpsvMask* copy();
///copy into an existing object
pMolMpsvMask* copy(pMolMpsvMask* to);
private:
float uc; //universal constant
int x0,x1,y0,y1; //top left and bottom right corners
static const int max = 1024; //max number of strips (max*uc pixels)
bool use[max]; //array to store if strip used
short int top[max]; //array to store top of strips
short int bot[max]; //array to store bottom of strips
bool virgin; //flag so we know if this is the first entry
void setMask(int x, int p_top, int p_bot);
};
#endif
| true |
9c333c47e3117fa66ce23b5ae802f3f13886c607 | C++ | HuangStomach/Cpp-primer-plus | /16.String&Library/Exercises/10.cpp | UTF-8 | 2,312 | 3.5625 | 4 | [
"MIT"
] | permissive | #include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
struct Review {
string title;
int rating;
double price;
};
bool operator<(const shared_ptr<Review> & r1, const shared_ptr<Review> & r2);
bool worseThan(const shared_ptr<Review> & r1, const shared_ptr<Review> & r2);
bool FillReview(Review & rr);
void ShowReview(const shared_ptr<Review> & rr);
int main(int argc, char const *argv[]) {
vector< shared_ptr<Review> > books;
Review temp;
shared_ptr<Review> review(new Review(temp));
while (FillReview(temp)) books.push_back(review);
if (books.size() > 0) {
cout << "Enter:\n";
for_each(books.begin(), books.end(), ShowReview);
sort(books.begin(), books.end());
for_each(books.begin(), books.end(), ShowReview);
sort(books.begin(), books.end(), worseThan);
for_each(books.begin(), books.end(), ShowReview);
shuffle(books.begin(), books.end(), random());
for_each(books.begin(), books.end(), ShowReview);
}
else cout << "Nothing.\n";
return 0;
}
bool operator<(const shared_ptr<Review> & r1, const shared_ptr<Review> & r2) {
if (r1->title < r2->title) return true;
else if (r1->title == r2->title && r1->rating < r2->rating) return true;
else if (r1->title == r2->title && r1->rating == r2->rating && r1->price < r2->price) return true;
else return false;
}
bool worseThan(const shared_ptr<Review> & r1, const shared_ptr<Review> & r2) {
if (r1->title < r2->title) return true;
else if (r1->title == r2->title && r1->rating < r2->rating) return true;
else if (r1->title == r2->title && r1->rating == r2->rating && r1->price < r2->price) return true;
else return false;
}
bool FillReview(Review & rr) {
cout << "Enter title (quit to quit): ";
getline(cin, rr.title);
if (rr.title == "quit") return false;
cout << "Enter book rating: ";
cin >> rr.rating;
if (!cin) return false;
while (cin.get() != '\n') continue;
cout << "Enter book price: ";
cin >> rr.price;
if (!cin) return false;
while (cin.get() != '\n') continue;
return true;
}
void ShowReview(const shared_ptr<Review> & rr) {
cout << rr->rating << "\t" << rr->title << "\t" << rr->price << endl;
}
| true |
cca556781d968751609ca44cc987973b828fcc59 | C++ | ayush-krishna/koss-task1 | /test.cpp | UTF-8 | 6,008 | 3.734375 | 4 | [] | no_license | #include<iostream>
#include<string>
using namespace std;
class Account
{
float balance;
char type;
string name;
int accno;
public:
Account()
{
balance=0;
}
void create()
{
cout<<"Enter account holder's name:\t";
cin>>name;
cout<<"\n"<<"Enter type of account Savings(S) or Current(C):\t ";
cin>>type;
cout<<"\n"<<"Account number:\t";
cin>>accno;
cout<<"\n"<<"Enter opening balance:\t";
cin>>balance;
cout<<"\n"<<"Account created..\n\n";
}
void show()
{
cout<<"\nAccount holder's name:"<<name<<endl;
cout<<"\nType of account :"<<type<<endl;
cout<<"\nAccount number:"<<accno<<endl;
cout<<"\nInitial Balance:"<<balance<<endl;
}
int returnaccountnumber()
{
return accno;
}
float returnbalance()
{
return balance;
}
void deposit(int deposit)
{
if(deposit>0)
{
balance=balance+deposit;
}
else
{
cout<<"Enter valid amount to be deposited"<<endl;
}
cout<<"\n Updated balance:"<<balance<<endl;
}
void draw(int wdraw)
{
if(wdraw>0 && wdraw<=balance)
{
balance=balance-wdraw;
}
else
{
cout<<"Enter valid amount to be withdrawn"<<endl;
}
cout<<"\n Updated balance:"<<balance<<endl;
}
char return_type()
{
return type;
}
void modify()
{
cout<<"\nEnter new details of account"<<endl;
cout<<"\nAccount Number:"<<accno<<endl;
cout<<"\nEnter modified name:";
cin>>name;
cout<<"\nEnter modified type of account (S/C):";
cin>>type;
cout<<"\nEnter modified balance:";
cin>>balance;
}
void report()
{
cout<<accno<<"\t\t"<<name<<"\t\t"<<type<<"\t\t"<<balance<<endl;
}
};
int main()
{
int ch;
int anum,i=0;int flag=0;
Account obj[100];
do
{
cout<<"\t\t\t\tBANK MANAGEMENT SYSTEM";
cout<<"\n\t\t\t\t1.NEW ACCOUNT";
cout<<"\n\t\t\t\t2. DEPOSIT AMOUNT";
cout<<"\n\t\t\t\t3. WITHDRAW AMOUNT";
cout<<"\n\t\t\t\t4. BALANCE ENQUIRY";
cout<<"\n\t\t\t\t5. ALL ACCOUNT HOLDER LIST";
cout<<"\n\t\t\t\t6. MODIFY AN ACCOUNT";
cout<<"\n\t\t\t\t7. EXIT";
cout<<"\n\n\t\t\t\tSelect Your Option (1-7): ";
cin>>ch;
switch(ch)
{
case 1:
obj[i].create();i++;break;
case 2:
cout<<"\n\n\t\t\tEnter The account No. : ";
cin>>anum; flag=0;
for(int a=0;a<i;a++)
{
if(anum==obj[a].returnaccountnumber())
{
flag=1;
obj[a].show();
int deposit=0;
cout<<"Enter deposit amount"<<endl;
cin>>deposit;
obj[a].deposit(deposit);
break;
}
}
if(flag==0)
{
cout<<"Please enter valid account number"<<endl;
}
break;
case 3:
cout<<"\n\n\t\t\tEnter The account No. : ";
cin>>anum; flag=0;
for(int a=0;a<i;a++)
{
if(anum==obj[a].returnaccountnumber())
{
flag=1;
obj[a].show();
int wdraw=0;
cout<<"\n Enter amount to be withdrawn"<<endl;
cin>>wdraw;
obj[a].draw(wdraw);
break;
}
}
if(flag==0)
{
cout<<"Please enter valid account number"<<endl;
}
break;
case 4: cout<<"\n\n\t\t\tEnter The account No. : ";
cin>>anum; flag=0;
for(int a=0;a<i;a++)
{
if(anum==obj[a].returnaccountnumber())
{
flag=1;obj[a].show();
cout<<"Available Balance:"<<obj[a].returnbalance();
break;
}
}
if(flag==0)
{
cout<<"Please enter valid account number"<<endl;
}
break;
case 5: cout<<"\n\n\t\tACCOUNT HOLDER LIST\n\n";
cout<<"****************************************************\n";
cout<<"A/c no. NAME Type Balance\n";
cout<<"----------------------------------------------------\n";
if(i==0)
{
cout<<"There are no accounts in this bank"<<endl;
}
else
{
for(int a=0;a<i;a++)
{
obj[a].report();
}
}
break;
case 6:cout<<"\n\n\t\t\tEnter The account No. : ";
cin>>anum;flag=0;
for(int a=0;a<i;a++)
{
if(anum==obj[a].returnaccountnumber())
{
flag=1;
obj[a].show();
obj[a].modify();
break;
}
}
if(flag==0)
{
cout<<"\nPlease enter valid account number"<<endl;
}
break;
case 7:cout<<"\nThank You!..\n"<<endl ;
break;
}
}while(ch!=7);
return 0;
}
| true |
f239b9930ee1863ee47c5235ef0fe195c952303b | C++ | ChesterHu/cs32 | /proj4/SymbolTable.bst.cpp | UTF-8 | 5,794 | 3.421875 | 3 | [] | no_license | // SymbolTable.cpp
// This is a correct but inefficient implementation of
// the SymbolTable functionality.
#include "SymbolTable.h"
#include <string>
#include <iostream>
#include <cassert>
#include <vector>
using namespace std;
const int TABLE_SIZE = 20000;
// struct to store lineNum and scope
struct Pair
{
int lineNum;
int scope;
Pair(int newLine, int newScope) : lineNum(newLine), scope(newScope) {}
};
// a hashTable for string
class hashTable
{
public:
hashTable();
~hashTable();
void deleteScope(string id);
bool declare(string id, int lineNum, int scopeNum);
int find(string id) const;
private:
struct Node
{
string id;
vector<Pair> m_Scopes;
Node* next;
Node(string new_id, int new_line, int new_Scope)
: id(new_id), next(nullptr)
{
m_Scopes.push_back(Pair(new_line, new_Scope));
}
~Node() { delete next; }
};
Node* bucket[TABLE_SIZE];
};
// This class does the real work of the implementation.
class SymbolTableImpl
{
public:
SymbolTableImpl() { idVector.push_back(vector<string>()); }
void enterScope();
bool exitScope();
bool declare(const string& id, int lineNum);
int find(const string& id) const;
private:
vector<vector<string> > idVector;
hashTable table;
};
// function implementation
///////////////////////////////////////////////////////////
// constructor
hashTable::hashTable()
{
for (int i = 0; i < TABLE_SIZE; ++i)
bucket[i] = nullptr;
}
// destructor
hashTable::~hashTable()
{
for (int i = 0; i < TABLE_SIZE; ++i)
delete bucket[i];
}
// return the hash value of a key
inline int hashF(const string& key)
{
unsigned int hashVal = 0;
for (int i = 0; i < key.size(); ++i)
hashVal = hashVal * 101 + key[i] + 1;
return hashVal % TABLE_SIZE;
}
void hashTable::deleteScope(string id)
{
Node* ptr = bucket[hashF(id)];
while (ptr != nullptr && ptr->id != id)
ptr = ptr->next;
ptr->m_Scopes.pop_back();
}
bool hashTable::declare(string id, int lineNum, int scopeNum)
{
Node** ptr = &bucket[hashF(id)]; // get pointer points to the pointer of the hash values bucket
while (*ptr != nullptr)
{
if ((*ptr)->id == id) // if find the node with the same id
{
if ((*ptr)->m_Scopes.empty() || (*ptr)->m_Scopes.back().scope != scopeNum)
{
(*ptr)->m_Scopes.push_back(Pair(lineNum, scopeNum));
return true;
}
return false;
}
ptr = &((*ptr)->next);
}
*ptr = new Node(id, lineNum, scopeNum);
return true;
}
int hashTable::find(string id) const
{
Node* ptr = bucket[hashF(id)];
while (ptr != nullptr)
{
if (ptr->id == id)
return (ptr->m_Scopes.empty()) ? -1 : ptr->m_Scopes.back().lineNum;
ptr = ptr->next;
}
return -1;
}
inline void SymbolTableImpl::enterScope()
{
idVector.push_back(vector<string>());
}
inline bool SymbolTableImpl::exitScope()
{
if (idVector.size() > 1)
{
vector<string>& currId = idVector.back();
for (int i = 0; i < currId.size(); ++i)
table.deleteScope(currId[i]);
idVector.pop_back();
return true;
}
return false;
}
inline bool SymbolTableImpl::declare(const string& id, int lineNum)
{
if (table.declare(id, lineNum, idVector.size()))
{
idVector.back().push_back(id);
return true;
}
return false;
}
inline int SymbolTableImpl::find(const string& id) const
{
return table.find(id);
}
/*
int main()
{
hashTable ht;
assert(ht.declare("abc", 1, 0));
assert(ht.declare("abc", 2, 2));
assert(!ht.declare("abc", 3, 2));
assert(ht.find("abc") == 2);
SymbolTable st;
assert(st.declare("alpha", 1));
assert(st.declare("beta", 2));
assert(st.declare("p1", 3));
assert(st.find("alpha") == 1); // the alpha declared in line 1
assert(st.declare("p2", 4));
assert(st.find("beta") == 2); // the beta declared in line 2
assert(st.declare("p3", 5));
assert(st.find("gamma") == -1); // Error! gamma hasn't been declared
assert(st.declare("f", 6));
st.enterScope();
assert(st.declare("beta", 7));
assert(st.declare("gamma", 8));
assert(st.find("alpha") == 1); // the alpha declared in line 1
assert(st.find("beta") == 7); // the beta declared in line 7
assert(st.find("gamma") == 8); // the gamma declared in line 8
st.enterScope();
assert(st.declare("alpha", 13));
assert(st.declare("beta", 14));
assert(!st.declare("beta", 15)); // Error! beta already declared
assert(st.find("alpha") == 13); // the alpha declared in line 13
assert(st.exitScope());
assert(st.find("alpha") == 1); // the alpha declared in line 1
assert(st.find("beta") == 7); // the beta declared in line 7
st.enterScope();
assert(st.declare("beta", 21));
assert(st.find("beta") == 21); // the beta declared in line 21
assert(st.exitScope());
assert(st.exitScope());
assert(st.declare("p4", 25));
assert(st.find("alpha") == 1); // the alpha declared in line 1
assert(st.declare("p5", 26));
assert(st.find("beta") == 2); // the beta declared in line 2
assert(st.declare("p6", 27));
assert(st.find("gamma") == -1); // Error! gamma is not in scope
assert(st.declare("main", 28));
st.enterScope();
assert(st.declare("beta", 29));
assert(st.find("beta") == 29); // the beta declared in line 29
assert(st.find("f") == 6); // the f declared in line 6
assert(st.exitScope());
}
*/
//*********** SymbolTable functions **************
// For the most part, these functions simply delegate to SymbolTableImpl's
// functions.
SymbolTable::SymbolTable()
{
m_impl = new SymbolTableImpl;
}
SymbolTable::~SymbolTable()
{
delete m_impl;
}
void SymbolTable::enterScope()
{
m_impl->enterScope();
}
bool SymbolTable::exitScope()
{
return m_impl->exitScope();
}
bool SymbolTable::declare(const string& id, int lineNum)
{
return m_impl->declare(id, lineNum);
}
int SymbolTable::find(const string& id) const
{
return m_impl->find(id);
}
| true |
3937653e4169303fe20c4a1b63eca8d2e8dcdd35 | C++ | bruno99/Programacion-I | /actividades/sesion5/MarcosGago/sesion5ej7.cpp | UTF-8 | 492 | 3.375 | 3 | [
"MIT"
] | permissive | #include <iostream>
using namespace std;
void Media(int a){
float media{0};
int i{0};
float b{0};
while (i<a){
cout<<"Escribe un numero"<<endl;
cin>>b;
media=(media+b);
i++;
}
media=media/(i);
cout<<"La media es "<<media<<endl;
}
int main()
{
int a;
cout<<"Escribe la cantidad de numeros que deseas introducir"<<endl;
cout<<"y despues te mostrare la media de todos ellos"<<endl;
cin>>a;
Media(a);
return 0;
}
| true |
558e20584a2ecdbe8ba76af70b0a6259f0a1c99f | C++ | cwru-robotics/cwru-eecs-275 | /minimal_turtlebot/src/turtlebot_controller.cpp | UTF-8 | 817 | 2.53125 | 3 | [] | no_license | #include "minimal_turtlebot/turtlebot_controller.h"
void turtlebot_controller(turtlebotInputs turtlebot_inputs, uint8_t *soundValue, float *vel, float *ang_vel)
{
//Place your code here! you can access the left / right wheel
//dropped variables declared above, as well as information about
//bumper status.
//outputs have been set to some default values. Feel free
//to change these constants to see how they impact the robot.
*vel = 0.0; // Robot forward velocity in m/s
//0.7 is max and is a lot
*ang_vel = 0.2; // Robot angular velocity in rad/s
//0.7 is max and is a lot
*soundValue = 0;
//here are the various sound value enumeration options
//soundValue.OFF
//soundValue.RECHARGE
//soundValue.BUTTON
//soundValue.ERROR
//soundValue.CLEANINGSTART
//soundValue.CLEANINGEND
}
| true |
b494be3a658e8fb76538b4f961e2538891156d91 | C++ | mollnels/Interpreter | /environment.cpp | UTF-8 | 4,922 | 3.15625 | 3 | [] | no_license | #include "expression.cpp"
template <class VALUE1, class VALUE2, class VALUE3>
class Environment{
public:
VALUE1* values1[100];
char* variables1[100];
VALUE2* values2[100];
char* variables2[100];
VALUE3* values3[100];
char* variables3[100];
Environment();
Environment* extendenv(char var, VALUE1 val, Environment<VALUE1, VALUE2, VALUE3>* env);
Environment* extendenv(char var, VALUE2 val, Environment<VALUE1, VALUE2, VALUE3>* env);
Environment* extendenv(char var, VALUE3 val, Environment<VALUE1, VALUE2, VALUE3>* env);
//Environment* extendenvrec(char var1, char var2, Expression* exp, Environment* env);
bool i;
bool b;
bool p;
VALUE1 applyenvi(char var, Environment<VALUE1, VALUE2, VALUE3>* env);
VALUE2 applyenvb(char var, Environment<VALUE1, VALUE2, VALUE3>* env);
VALUE3 applyenvp(char var, Environment<VALUE1, VALUE2, VALUE3>* env);
bool varin(char var, Environment<VALUE1, VALUE2, VALUE3>* env);
VALUE1 findvari(char var, Environment<VALUE1, VALUE2, VALUE3>* env);
VALUE2 findvarb(char var, Environment<VALUE1, VALUE2, VALUE3>* env);
VALUE3 findvarp(char var, Environment<VALUE1, VALUE2, VALUE3>* env);
int findlength(char* vars);
};
template <class VALUE1, class VALUE2, class VALUE3>
Environment<VALUE1, VALUE2, VALUE3>::Environment(){
for (int i = 0; i < 100; ++i)
{
values1[i] = '\0';
variables1[i] = '\0';
values2[i] = '\0';
variables2[i] = '\0';
values3[i] = '\0';
variables3[i] = '\0';
}
}
template <class VALUE1, class VALUE2, class VALUE3>
int Environment<VALUE1, VALUE2, VALUE3>::findlength(char* vars){
int len = 0;
while(vars[i] != '\0'){
len++;
}
return len;
}
template <class VALUE1, class VALUE2, class VALUE3>
Environment<VALUE1, VALUE2, VALUE3>* Environment<VALUE1, VALUE2, VALUE3>::extendenv(char var, VALUE1 val, Environment* env){
int len = findlength(env->values1);
env->values1[len] = val;
env->variables1[len] = var;
return env;
}
template <class VALUE1, class VALUE2, class VALUE3>
Environment<VALUE1, VALUE2, VALUE3>* Environment<VALUE1, VALUE2, VALUE3>::extendenv(char var, VALUE2 val, Environment* env){
int len = findlength(env->values2);
env->values2[len] = val;
env->variables2[len] = var;
return env;
}
template <class VALUE1, class VALUE2, class VALUE3>
Environment<VALUE1, VALUE2, VALUE3>* Environment<VALUE1, VALUE2, VALUE3>::extendenv(char var, VALUE3 val, Environment* env){
int len = findlength(env->values3);
env->values3[len] = val;
env->variables3[len] = var;
return env;
}
// Environment* Environment::extendenvrec(char var1, char var2, Expression* exp, Environment* env){
// return env;
// }
template <class VALUE1, class VALUE2, class VALUE3>
bool Environment<VALUE1, VALUE2, VALUE3>::varin(char var, Environment<VALUE1, VALUE2, VALUE3>* env){
for (int i = 0; i < 100; ++i) {
if(env->variables1[i] == var) return true;
if(env->variables2[i] == var) return true;
if(env->variables3[i] == var) return true;
}
return false;
}
template <class VALUE1, class VALUE2, class VALUE3>
VALUE1 Environment<VALUE1, VALUE2, VALUE3>::findvari(char var, Environment<VALUE1, VALUE2, VALUE3>* env){
for (int i = 0; i < 100; ++i) {
if(env->variables1[i] == var){
return env->values1[i];
}
}
}
template <class VALUE1, class VALUE2, class VALUE3>
VALUE2 Environment<VALUE1, VALUE2, VALUE3>::findvarb(char var, Environment<VALUE1, VALUE2, VALUE3>* env){
for (int i = 0; i < 100; ++i) {
if(env->variables2[i] == var){
return env->values2[i];
}
}
}
template <class VALUE1, class VALUE2, class VALUE3>
VALUE3 Environment<VALUE1, VALUE2, VALUE3>::findvarp(char var, Environment<VALUE1, VALUE2, VALUE3>* env){
for (int i = 0; i < 100; ++i) {
if(env->variables3[i] == var){
return env->values3[i];
}
}
}
template <class VALUE1, class VALUE2, class VALUE3>
VALUE1 Environment<VALUE1, VALUE2, VALUE3>::applyenvi(char var, Environment<VALUE1, VALUE2, VALUE3>* env){
if(varin(var, env)){
VALUE1 val = findvari(var, env);
i = true;
b = false;
p = false;
return val;
}
else{
cout << "ERROR. No binding for " << var << endl;
}
}
template <class VALUE1, class VALUE2, class VALUE3>
VALUE2 Environment<VALUE1, VALUE2, VALUE3>::applyenvb(char var, Environment<VALUE1, VALUE2, VALUE3>* env){
if(varin(var, env)){
VALUE2 val = findvarb(var, env);
b = true;
i = false;
p = false;
return val;
}
else{
cout << "ERROR. No binding for " << var << endl;
}
}
template <class VALUE1, class VALUE2, class VALUE3>
VALUE3 Environment<VALUE1, VALUE2, VALUE3>::applyenvp(char var, Environment<VALUE1, VALUE2, VALUE3>* env){
if(varin(var, env)){
VALUE3 val = findvarp(var, env);
p = true;
i = false;
b = false;
return val;
}
else{
cout << "ERROR. No binding for " << var << endl;
}
}
//findlength function
//varin function - returns true if variable is in environment
//findvar fundtion - returns value of variable
| true |
12510d72045fd543b94f1eb09642afc19eb94a9a | C++ | tacaswell/pyraft | /raft/raft_radon_bresenham.cpp | UTF-8 | 3,333 | 2.984375 | 3 | [] | no_license | #include "raft_radon_bresenham.h"
#include "raft_ddaiterator.h"
#include <vector>
#include <thread>
extern "C" {
// BLAS daxpy:
void daxpy_( int const *, double const *, double const *, int const *, double *, int const * );
// BLAS dcopy:
void dcopy_( int const *, double const *, int const *, double *, int const * );
}
void raft_radon_bresenham_worker( raft_image image,
raft_image sino,
int start_angle, int end_angle
)
{
// Counters:
int i, j;
// Zero out output storage:
const double dzero = 0.0;
const int izero = 0;
for ( j = start_angle; j < end_angle; ++j )
dcopy_( &( sino.data.lines ),
&dzero,
&izero,
&( raft_image_sample( sino, 0, j ) ),
&( sino.data.column_stride )
);
// Iterator:
raft_ddaiterator it;
raft_ddaiterator_set_image( &it, image );
// Sampling factors:
double delta_theta = raft_image_hsamplingdistance( sino );
double delta_t = raft_image_vsamplingdistance( sino );
// Run through views:
for ( j = start_angle; j < end_angle; ++j )
{
// Set view in iterator:
raft_ddaiterator_set_theta( &it, sino.tl_x + ( j * delta_theta ) );
// Run through rays in view:
for ( i = 0; i < sino.data.lines; ++i )
{
// Set ray in iterator:
raft_ddaiterator_set_t( &it, sino.tl_y + ( i * delta_t ) );
// Trace the ray!
while ( !raft_ddaiterator_end( &it ) )
{
raft_image_sample( sino, i, j ) += raft_image_sample( image, it.i, it.j ) * it.sigma;
raft_ddaiterator_update( &it );
}
}
}
}
void raft_radon_bresenham( raft_image image,
raft_image sino,
int nthreads
)
{
// Actual number of threads:
int actual_nthreads;
// Make sure we do not have too many or too little threads:
actual_nthreads = ( nthreads <= sino.data.columns ) ? nthreads : sino.data.columns;
actual_nthreads = ( nthreads > 0 ) ? nthreads : 1;
// Base number of angles per thread:
int base_nangles = sino.data.columns / actual_nthreads;
// Remainder, i.e., number of threads with an extra angle:
int remainder_nangles = sino.data.columns % actual_nthreads;
// Current starting view for working thread:
int cur_starting_angle = 0;
// Number of angles to be processed by current thread:
int cur_nangles;
// Create working threads:
std::vector< std::thread > threads;
threads.reserve( actual_nthreads );
for ( int cur_thread = 0; cur_thread < actual_nthreads; ++cur_thread )
{
cur_nangles = base_nangles + ( cur_thread < remainder_nangles );
threads.push_back( std::thread( raft_radon_bresenham_worker,
image,
sino,
cur_starting_angle,
cur_starting_angle + cur_nangles
)
);
cur_starting_angle += cur_nangles;
}
// Wait for threads to finish the job:
for ( auto& thread : threads )
if ( thread.joinable() )
thread.join();
}
| true |
01df5a4af9bc7e2ed228bc355eb51459deb8f4b4 | C++ | ngvozdiev/ctr-base | /src/prob_model/dist_model.h | UTF-8 | 9,563 | 2.53125 | 3 | [
"MIT"
] | permissive | #ifndef CTR_DIST_MODEL_H
#define CTR_DIST_MODEL_H
#include <fftw3.h>
#include <stddef.h>
#include <chrono>
#include <complex>
#include <cstdint>
#include <map>
#include <memory>
#include <random>
#include <string>
#include <utility>
#include <vector>
#include "ncode/common.h"
#include "ncode/strutil.h"
#include "ncode/net/net_common.h"
#include "ncode/thread_runner.h"
#include "../common.h"
namespace ctr {
class AggregateHistory;
} /* namespace ctr */
namespace ctr {
struct ConvolutionTimingData {
// Time to bin data before doing an FFT.
std::chrono::microseconds binning;
// Time to do all FFTs, one per aggregate.
std::chrono::microseconds fft;
// Time to do a single inverse FFT.
std::chrono::microseconds ifft;
std::string ToString() const;
};
using Complex = std::complex<double>;
class FFTRunner {
public:
FFTRunner(size_t fft_size);
~FFTRunner();
const std::vector<Complex>& ComputeForward(const std::vector<double>& input);
std::vector<double> ComputeBackward(const std::vector<Complex>& input);
private:
void InitPlans();
size_t fft_size_;
// This is where the computation is performed.
std::vector<Complex> out_;
// The plans.
fftw_plan plan_fw_;
fftw_plan plan_bw_;
// Initializing the plans is relatively expensive, so they are not initalized
// until a call to Compute* is made.
bool init_;
DISALLOW_COPY_AND_ASSIGN(FFTRunner);
};
// A discrete distribution.
class Distribution {
public:
// Convolves a number of distributions and returns their sum. The resulting
// distribution will have 'resolution' levels. If the last argument is not
// null will populate it with timing data.
static std::unique_ptr<Distribution> Sum(
const std::vector<Distribution*>& distributions, size_t resolution,
FFTRunner* fft_runner, ConvolutionTimingData* timing_data);
Distribution(const std::vector<double>& probabilities, uint64_t base);
Distribution(const std::vector<uint64_t>& values);
uint64_t max_element() const { return max_element_; }
uint64_t min_element() const { return base_; }
uint64_t bin_size() const { return bin_size_; }
// Bins this distribution. Only valid if the current bin size is 1. Should
// have cumulative probabilities cached.
std::unique_ptr<Distribution> Bin(size_t new_bin_size);
// Returns the probabilities as a map.
std::map<uint64_t, double> GetProbabilities() const;
// Returns a series or x,y points that can be used in a histogram or a CDF
// plot (if cumulative is true).
std::vector<std::pair<double, double>> GetDataSeries(bool cumulative) const;
// Returns the p-th percentile of this distribution. The percentile value will
// be linearly interpolated between the values of the closest cumulative
// probabilities.
double Percentile(double p) const;
// Samples 'count' values from this distribution.
std::vector<uint64_t> Sample(size_t count, std::mt19937* rnd) const;
// The probabilities array --- the value of element i is the probability of
// min_element + i.
const std::vector<double>& probabilities_raw() const {
return probabilities_;
}
private:
// Caches cumulative probabilities. Should be called before attempting to bin.
void CacheCumulativeProbabilities();
Distribution(uint64_t base, uint64_t bin_size, uint64_t max_element);
std::vector<double> probabilities_;
uint64_t base_;
uint64_t bin_size_;
uint64_t max_element_;
// A cumulative sum of probabilities.
std::vector<double> probabilities_cumulative_;
// Protects the cumulative probabilities.
std::mutex cumulative_probs_mu_;
DISALLOW_COPY_AND_ASSIGN(Distribution);
};
// A single query --- when summing up a set of aggregates, can they fit within a
// given rate?
struct ProbModelQuery {
// How to process the query.
enum QueryType {
// Combines all bins from aggregates and runs them through a simulated
// queue.
QUEUE_SIMULATION = 1,
// Treats each aggrgate's bins as independent random variables, convolves
// them to get a distribution of their sum and checks if the rate from the
// query is statistically likely to cause queues.
CONVOLUTION = 2,
// Does both.
BOTH = 3,
};
QueryType type;
// A list aggregates and fractions. All the aggregate's bins will be
// multiplied by the fraction.
std::vector<std::pair<AggregateId, double>> aggregates;
// Rate to test.
nc::net::Bandwidth rate;
std::string ToString() const {
std::vector<std::string> pieces;
for (const auto& aggregate : aggregates) {
pieces.emplace_back(nc::StrCat(std::to_string(aggregate.first.src()), " ",
std::to_string(aggregate.first.dst()), " ",
std::to_string(aggregate.second)));
}
return nc::Join(pieces, ",");
}
};
struct ProbModelReply {
// True if the aggregates from the query fit the rate from the query.
bool fit;
// Max simulated queue size. If this is above the threshold in ProbModelConfig
// fit will be false.
std::chrono::milliseconds max_simulated_queue_size;
// The min rate that will fit the traffic with low probability for queues.
nc::net::Bandwidth optimal_rate;
};
struct ProbModelConfig {
// Initial quantization to apply to values. Each value will be equal to
// floor(bin_size / initial_quantization).
size_t initial_quantization = 1000;
// How many levels a distribution should have.
size_t distribution_levels = 2048;
// Probability the convolved distribution to exceed the queried rate.
double exceed_probability = 0.005;
// In order to detect mutually-dependent spikes in multiple aggregates will
// also run a simple queue simulation and check if the queue is ever above
// this threshold.
std::chrono::milliseconds simulated_queue_threshold =
std::chrono::milliseconds(10);
};
// Per-query timing data.
struct ProbModelTimingData {
// Time to perform queue simulation.
std::chrono::microseconds queue_simulation;
// Total processing time for the query.
std::chrono::microseconds total;
// Fractional aggregates will need to be split and rebinned. This is the total
// time it took to do that.
std::chrono::microseconds split_aggregates;
// Timing to do the convolution.
ConvolutionTimingData convolution_timing;
std::string ToString() const;
};
// The model associates with each aggregate an AggregateHistory instance. It can
// be queried about whether or not a set of aggregates, when combined, will fit
// in a given rate.
class ProbModel {
public:
ProbModel(const ProbModelConfig& config)
: config_(config), batch_processor_(kParallelThreads) {
for (size_t i = 0; i < kParallelThreads; ++i) {
runners_.emplace_back(
nc::make_unique<FFTRunner>(config.distribution_levels));
}
}
void AddAggregate(const AggregateId& aggregate_id,
const AggregateHistory* history);
void ClearAggregates();
// Answers to multiple queries. Item i in the return vector corresponds to
// query i in 'queries'. If the last argument is not null, will populate it
// with timing data for each query.
std::vector<ProbModelReply> Query(
const std::vector<ProbModelQuery>& queries,
std::vector<ProbModelTimingData>* timing_data = nullptr);
private:
// Number of threads to process queries on.
static constexpr size_t kParallelThreads = 4;
// Returns the max and the min bins.
std::pair<double, double> MaxMinBins(const ProbModelQuery& query) const;
// Sums up the bins from the query. Also populates the last argument with the
// total of all max values of all histories of aggregates in the query.
std::vector<uint64_t> SumUpBins(const ProbModelQuery& query) const;
// Returns the common bin size for all aggregates in the query.
std::chrono::milliseconds GetBinSize(const ProbModelQuery& query) const;
// Runs the sum of the aggregates in the query through a simulated queue of
// the same service rate as the one in the query. Each bin is a single
// simulated 'packet'. Returns the max queue size in milliseconds.
std::chrono::milliseconds SimulateQueue(
const ProbModelQuery& query, const std::vector<uint64_t>& bins_summed,
double bytes_per_bin) const;
// The rate that should (most of the time) fit the traffic.
nc::net::Bandwidth OptimalRate(const ProbModelQuery& query,
FFTRunner* fft_runner,
ProbModelTimingData* timing_data);
// Performs a single query.
ProbModelReply SingleQuery(const ProbModelQuery& query, FFTRunner* fft_runner,
ProbModelTimingData* timing_data);
class AggregateState {
public:
AggregateState(const AggregateHistory* history, size_t quantization);
Distribution* distribution();
const AggregateHistory* history() const { return history_; }
private:
// The history.
const AggregateHistory* history_;
// The distribution, created on demand.
std::unique_ptr<Distribution> distribution_;
// Quantization for the distribution.
size_t quantization_;
// Protects the distribution.
std::mutex distribution_mu_;
};
// Configuration
const ProbModelConfig config_;
std::map<AggregateId, AggregateState> aggregate_states_;
// Processes batches of queries.
nc::ThreadBatchProcessor<ProbModelQuery> batch_processor_;
// Per-thread FFT runner.
std::vector<std::unique_ptr<FFTRunner>> runners_;
};
} // namespace fubar
#endif
| true |
ccdaf141a5f1f2fda24c16cddaae24375695d895 | C++ | ishiikurisu/CodingDojo | /2016/160618/session2.cpp | UTF-8 | 4,355 | 3.1875 | 3 | [
"Beerware"
] | permissive | #include <vector>
#include <iostream>
#include <stdio.h>
using namespace std;
/* Maratona 18\06\16
Guitar Queer-O
Autor: Matheus Pimenta
Apos comprarem o novo Guitar Hero III: Legends of Rock, Stan e Kyle tem
treinado incessantemente para se tornarem astros do rock.
Acontece que a copia do jogo dos garotos veio cheia de bugs! Agora eles
precisam da sua ajuda para continuarem o treinamento!
Dada a sequencia de combinacoes de teclas da musica e as duas sequencias de
teclas pressionados por Stan e Kyle, determine a pontuacao total dos garotos.
Cada combinacao tem no maximo 5 teclas e pode dar no minimo -5 e no maximo 5
pontos para cada garoto. Dadas duas combinacoes de teclas, a combinacao
correta e a combinacao pressionada, cada tecla fixa que aparece
simultaneamente em ambas as combinacoes acrescenta um ponto para o garoto que
a pressionou. Alem disso, para cada tecla que foi pressionada quando nao
deveria, ou que nao foi pressionada quando deveria, um ponto e subtraido.
Entrada
A primeira linha da entrada contem um unico inteiro N, o numero de combinacoes
de teclas da musica.
As proximas N linhas representam as combinacoes de teclas que devem ser
pressionadas para tocar a musica corretamente.
As proximas N linhas representam as combinacoes pressionadas por Stan.
As proximas N linhas representam as combinacoes pressionadas por Kyle.
Uma combinacao de teclas e uma string no formato G-R-Y-B-O. Variacoes deste
formato onde algumas letras sao substituidas por - (hifen) tambem sao
combinacoes validas. Cada letra representa uma tecla.
Saida
Imprima uma linha com a pontuacao total dos garotos.
Caso a pontuacao total seja a maior possivel, imprima outra linha com a
mensagem CONGRATULATIONS, YOU ARE FAGS!.
Caso a pontuacao total seja a menor possivel, imprima outra linha com a
mensagem GAME OVER, YOU SUCK!.
Restricoes
1 ≤ N ≤ 10^5
Exemplos
Entrada
1
--R-Y-B--
--R-Y---O
--R-Y-B-O
Saida
2
Entrada
1
--R-Y-B--
--R-Y-B--
--R-Y-B-O
Saida
5
Entrada
1
--R-Y-B--
--R-Y-B--
--R-Y-B--
Saida
6
CONGRATULATIONS, YOU ARE FAGS!
Entrada
1
--R-Y-B--
G-------O
G-------O
Saida
-10
GAME OVER, YOU SUCK!
A) Sobre a entrada
1. A entrada de seu programa deve ser lida da entrada padrao.
2. Quando uma linha da entrada contem varios valores, estes sao separados por
um unico espaco em branco; a entrada nao contem nenhum outro espaco em branco.
3. Cada linha, incluindo a ultima, contem o caractere final-de-linha.
4. O final da entrada coincide com o final do arquivo.
B) Sobre a saida
1. A saida de seu programa deve ser escrita na saida padrao.
2. Quando uma linha da saida contem varios valores, estes devem ser separados
por um unico espaco em branco; a saida nao deve conter nenhum outro espaco
em branco.
3. Cada linha, incluindo a ultima, deve conter o caractere final-de-linha.
*/
int main(int argc, char const *argv[]) {
int N, score;
bool noErrors = true;
std::string line;
vector<string> gameOutput;
vector<string> kyleInput;
vector<string> stanInput;
// LEITURA DAS VARIÁVEIS
getline(cin, line);
sscanf(line.c_str(), "%d", &N);
for (int l = 0; l < N; l++)
getline(cin, line),
gameOutput.push_back(line);
for (int l = 0; l < N; l++)
getline(cin, line),
kyleInput.push_back(line);
for (int l = 0; l < N; l++)
getline(cin, line),
stanInput.push_back(line);
// LÓGICA DO PROGRAMA
score = 0;
for (int n = 0; n < N; n++)
{
string inlet = gameOutput.at(n);
string kyle = kyleInput.at(n);
string stan = stanInput.at(n);
for (int i = 0; i < 9; i += 2)
{
if (inlet[i] == kyle[i]) { // checar se é igual
if(inlet[i]!='-') { // checar se pode pontuar
score++;
}
}
else {
score--;
noErrors = false;
}
if (inlet[i] == stan[i]) {
if(inlet[i]!='-') {
score++;
}
}
else {
score--;
noErrors = false;
}
}
}
std::cout << score << std::endl;
if (score == -10*N)
cout << "GAME OVER, YOU SUCK!" << endl;
if (noErrors)
cout << "CONGRATULATIONS, YOU ARE FAGS!" << endl;
return 0;
}
| true |
4fb4e03e635e197f5927ccee988e581fb45858d1 | C++ | lriki/Lumino.Core | /include/Lumino/Math/Version.h | SHIFT_JIS | 1,667 | 2.90625 | 3 | [
"Zlib",
"MIT"
] | permissive |
#ifndef LUMINO_MATH_VERSION_H
#define LUMINO_MATH_VERSION_H
#include "Common.h"
#define LUMINO_MATH_VERSION_MAJOR 1 ///< W[o[W
#define LUMINO_MATH_VERSION_MINOR 0 ///< }Ci[o[W
#define LUMINO_MATH_VERSION_PATCH 0 ///< pb`ԍ
#define LUMINO_MATH_VERSION_STRING "1.0.0" ///< o[W
LN_NAMESPACE_BEGIN
namespace Version
{
/**
@brief wCũo[WłB
@details ̃NX擾łl̓CũoCit@C̃o[WԍłB
wb_t@C̃o[WvvZXŎgpꍇ
LUMINO_MATH_VERSION_MAJOR LUMINO_MATH_VERSION_MINOR gpĂB
*/
class LUMINO_EXPORT Math
{
public:
/**
@brief W[o[W擾܂B
*/
static int GetMajor();
/**
@brief }Ci[o[W擾܂B
*/
static int GetMinor();
/**
@brief pb`ԍ擾܂B
*/
static int GetPatch();
/**
@brief o[W̎擾擾܂B
*/
static const char* GetVersionString();
/**
@brief w肵o[WԍƁACut@C̃RpCo[Wԍr܂B
@return wo[W >= RpCo[W łꍇAtrue Ԃ܂B
*/
static bool IsAtLeast(int major = LUMINO_MATH_VERSION_MAJOR, int minor = LUMINO_MATH_VERSION_MINOR, int patch = LUMINO_MATH_VERSION_PATCH);
};
} // namespace Version
LN_NAMESPACE_END
#endif // LUMINO_MATH_VERSION_H
| true |
6f76ebe21d66451e2266a319bbb11a025af20535 | C++ | bostikforever/adv2020 | /src/day11.0.cpp | UTF-8 | 3,802 | 3.25 | 3 | [] | no_license | #include <algorithm>
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <fstream>
#include <iostream>
namespace {
class Solution {
static constexpr char occupied = '#';
static constexpr char floor = '.';
static constexpr char empty = 'L';
static constexpr int8_t dirs[] = {-1, 0, 1};
uint64_t solution = 0;
std::size_t calls = 0;
bool checkOccupy(std::string& tmp,
std::string& values,
std::size_t rowSize,
std::size_t colSize) const
{
// for (auto i = 0; i < values.size(); ++i) {
// if (i % rowSize == 0) {
// std::cout << '\n';
// }
// std::cout << values[i];
// }
// std::cout << '\n';
tmp.swap(values);
bool changed = false;
for (std::size_t i = 0; i < values.size(); ++i) {
if (tmp[i] == floor) {
continue;
}
const std::size_t col = i % rowSize;
std::size_t occupiedCount = 0;
for (auto dir_x : dirs) {
if (col == 0 && dir_x == -1 ||
col == rowSize - 1 && dir_x == 1) {
continue;
}
const std::size_t row = i / rowSize;
for (auto dir_y : dirs) {
if (row == 0 && dir_y == -1 ||
row == colSize - 1 && dir_y == 1) {
continue;
}
if (dir_y == dir_x && dir_x == 0) {
continue;
}
occupiedCount += tmp[i + dir_x + dir_y * rowSize]
== occupied;
}
}
// if (i % rowSize == 0) {
// std::cout << '\n';
// }
// std::cout << occupiedCount;
if (tmp[i] == occupied && occupiedCount >= 4) {
values[i] = empty;
changed = true;
continue;
}
if (tmp[i] == empty && occupiedCount == 0) {
values[i] = occupied;
changed = true;
continue;
}
// unchanged
values[i] = tmp[i];
}
return changed;
}
std::size_t countOccupied(const std::string& values) const
{
return std::count(values.begin(), values.end(), occupied);
}
template <typename CALLABLE>
bool solve(CALLABLE&& loop)
{
++calls;
std::string values;
int cols = 0;
const auto ret = loop([&](const std::string& line) {
++cols;
values += line;
return true;
});
std::string valuesTemp(values);
while (checkOccupy(valuesTemp, values, values.size()/cols, cols));
solution = countOccupied(values);
return ret;
}
public:
template <typename ...Args>
bool operator()(Args... args)
{
return solve(args...);
}
auto output() const
{
std::cout << "calls: " << calls << '\n';
return solution;
}
};
template <typename CALLABLE>
void readBatches(const std::string& filename, CALLABLE&& callable)
{
std::ifstream inputFile(filename);
std::string line;
const auto ret = callable([&](auto&& body) {
bool res;
while (inputFile >> line && (res = body(line)))
;
return res;
});
}
} // close unnamed namespace
int main(int argc, const char* argv[])
{
assert(argc > 1);
std::string filename = argv[1];
Solution solution;
readBatches(filename, solution);
std::cout << solution.output() << '\n';
return 0;
}
| true |
3b5fd3d24aec73120cccb8ce7ae7ac6efd3bad44 | C++ | bingo456/functions | /calculateNormals/demo_gpu/main_demo_normals_gpu.cpp | UTF-8 | 3,030 | 2.921875 | 3 | [] | no_license | /**********************************************************************//**
[GPU Version]
Demo about using calculateNormalsOnGpu.h(cpp)
@file main_demo_normals_gpu.cpp
@author WD
@date 2020/03/02
@brief using function calNormalsOnGpu()
**************************************************************************/
// C++
#include <iostream>
#include <string>
// PCL
#include <pcl/point_types.h>
#include <pcl/io/pcd_io.h>
// OpenCV
#include <opencv2/opencv.hpp>
#include "../calculateNormalsOnGpu.h"
// main
int main(int argc, char* argv[])
{
// ---------------------------------------------------------------------------------------------------------
/*
calNormalsOnGpu() 测试
*/
if (argc < 4)
{
std::cout << "usage: " << argv[0] << " inputFile scale(5.0) max_elements(256)" << std::endl;
return EXIT_FAILURE;
}
float scale;
unsigned int max_elements;
std::string infile = std::string(argv[1]);// the file to read from
std::istringstream (argv[2]) >> scale;
std::istringstream (argv[3]) >> max_elements;
// test-1: 输入是pcl格式点云,输出是pcl格式法线的 法线估计函数
#if 0
// Load cloud (.pcd file)
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZ>);
pcl::io::loadPCDFile(infile.c_str(), *cloud);
std::cout << "Done: Load pointCloud data of " << infile.c_str() << std::endl;
// calculate normals on gpu
pcl::PointCloud<pcl::PointNormal>::Ptr normals(new pcl::PointCloud<pcl::PointNormal>);
calNormalsOnGpu(cloud, scale, max_elements, normals);
std::cout << "Done: calNormalsOnGpu(). " << std::endl;
#endif
// test-2: 输入是Mat矩阵点云,输出是Mat矩阵法线的 法线估计函数
#if 1
// Load cloud (.xml file)
cv::Mat matCloud = {};
cv::FileStorage fsRead(infile.c_str(), cv::FileStorage::READ);
fsRead["imageDepth"] >> matCloud;// 这和我写出xml文件时使用的名字有关
// fsRead["pointCloud"] >> matCloud;
fsRead.release();
std::cout << "Done: Load pointCloud data of " << infile.c_str() << std::endl;
// calculate normals on gpu
cv::Mat matNormals = {};
calNormalsOnGpu(matCloud, scale, max_elements, matNormals);
std::cout << "matNormals: \n"
<< " - type: " << matNormals.type() << "\n"
<< " - channel: " << matNormals.channels() << "\n"
<< " - size: " << matNormals.size
<< std::endl;
std::cout << "Done: calNormalsOnGpu(). " << std::endl;
#endif
// ---------------------------------------------------------------------------------------------------------
/*
End - 等待输入,方便显示上述运行结果
*/
std::cout << "--------------------------------------------" << std::endl;
std::cout << "Waiting for inputting an integer: ";
int wd_wait;
std::cin >> wd_wait;
std::cout << "----------------------------------" << std::endl;
std::cout << "------------- closed -------------" << std::endl;
std::cout << "----------------------------------" << std::endl;
return EXIT_SUCCESS;
} | true |
e432a92c035602e3f718efc2f9a529faa75e7745 | C++ | YYang30/LintcodeSol | /MinDepth_in_Binary_Tree.cpp | UTF-8 | 633 | 3.375 | 3 | [] | no_license | #include <vector>
using namespace std;
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
/*
* Minimum Depth of Binary Tree
*/
class Solution{
public:
int minDepth(TreeNode *root){
if(root == NULL) return 0;
int lMin = 0x7fffffff, rMin = 0x7fffffff;
if(root->left == NULL && root->right == NULL) return 1;
if(root->left) lMin = minDepth(root->left);
if(root->right) rMin = minDepth(root->right);
return min(lMin, rMin) + 1;
}
};
| true |
c37e76f03e202d4f71519ca1e14dee11cda0dfb9 | C++ | XOKAGE95/AaDS | /laba3/main.cpp | UTF-8 | 1,785 | 3.59375 | 4 | [] | no_license | #include <iostream>
#include <exception>
#include<math.h>
#include <ctime>
#include <iomanip>
#include <fstream>
using namespace std;
template <typename A>
void Display (A *arr, int n, ostream &file)
{
file << "Your array: " << endl;
for (int i = 0; i < n; i++)
file << setw(7) << left << setprecision(5) <<arr[i];
file << endl;
}
template<typename A>
void ShellSort(int n, A *arr)
{
int d, i, j, count = 0;;
A tmp;
for (d = n / 2; d > 0; d /= 2)
{
count ++;
cout << "Iteration " << count << " d = " << d << endl;
for (i = d; i < n; i++)
for (j = i - d; j >= 0 && arr[j] > arr[j + d]; j -= d)
{
cout << "Swap " << arr[j] << " " << arr[j+d] << endl;
tmp = arr[j];
arr[j] = arr[j + d];
arr[j + d] = tmp;
}
Display(arr, n, cout);
}
}
template <typename T>
T *RandomArray(int n)
{
srand( time(NULL) );
T *arr = new T[n];
for (int i = 0; i < n; i++)
arr[i] = T((rand() % 100 )/(float)(rand() % 9 + 1.0));
return arr;
}
template <typename T>
bool CreateArray(int n)
{
T *array1 = RandomArray<T>(n);
Display(array1, n, cout);
ShellSort(n, array1);
Display(array1, n, cout);
for (int i = 0; i < n; i++)
delete [] array1;
return true;
}
int main()
{
cout << "Enter n: ";
int n;
cin >> n;
cout << "Enter array type: ";
string ArrayType;
cin >> ArrayType;
bool condition;
if (ArrayType == "double")
condition = CreateArray<double>(n);
else if(ArrayType == "float")
condition = CreateArray<float>(n);
else if(ArrayType == "int")
condition = CreateArray<int>(n);
if (condition) return 0;
else return -1;
}
| true |
cba52f73d6c5d3910b766eca2edeb26083f6d146 | C++ | seakers/daphne-robot | /arduino/tracking.ino/tracking.ino.ino | UTF-8 | 702 | 3.171875 | 3 | [] | no_license | #include <Servo.h>
Servo servo;
int pos = 90;
void setup() {
Serial.begin(9600);
servo.attach(9);
}
void loop() {
char input_char;
int int_from_char;
if(Serial.available()>0){
input_char = char(Serial.read());
while(input_char == 'u' && pos<180 ) { // goes from 0 degrees to 180 degrees
// in steps of 1 degree
servo.write(pos); // tell servo to go to position in variable 'pos'
pos+=1;
// waits 15ms for the servo to reach the position
}
while(input_char == 'd' && pos >30){
servo.write(pos); // tell servo to go to position in variable 'pos'
pos-=1;
}
}
// put your main code here, to run repeatedly:
}
| true |
ab0ead5b738ac4e5f8ae8157eebde09f46726867 | C++ | lquinlan/c- | /零碎/template用法.cpp | GB18030 | 445 | 2.765625 | 3 | [] | no_license | /*
йTemplate÷,֪ʲô,ǰ¼һ
ͨıӦһ,ָ,һģ
*/
#include<iostream>
using namespace std;
template <class T>
class A
{
template <class U>
class B
{
typedef A<U> other;
};
};
template<class T1,class T2>
class test
{
typedef typename T1:: template B<T2>::other t1_type;
};
int main ()
{
}
| true |
074acd0865a5f6d72c31589f7fa139b2f54ec680 | C++ | sacckey/atcoder | /minpro2019/minpro2019.cpp | UTF-8 | 824 | 2.59375 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
void solveA(){
int n,k;
cin >> n >> k;
if (k <= (n+1)/2){
cout << "YES" << endl;
}
else {
cout << "NO" << endl;
}
}
void solveB(){
int a[3],b[3];
int cnt[4] = {0};
bool flg = true;
for(int i=0;i<3;i++){
cin >> a[i] >> b[i];
cnt[a[i]-1] ++;
cnt[b[i]-1] ++;
}
for(int i=0;i<4;i++){
if (cnt[i] >= 3) flg = false;
}
if (flg) cout << "YES" << endl;
else cout << "NO" << endl;
}
void solveC(){
long long k,a,b;
cin >> k >> a >> b;
bool flg = true;
long long bis = 1;
long long del = b-a;
if (del<=2) flg = false;
for(long long i=1;i<=k;i++){
if (bis>=a && (k-i>=1 && flg)){
bis+=del;
i ++;
}
else {
bis ++;
}
}
cout << bis << endl;
}
void solveD(){
}
int main(){
solveC();
}
| true |
9b4d096ad2b456dc25eb1c4d4c94a8f2f870bbdd | C++ | fredfeng/compass | /dex-parser/Int2Str.cpp | UTF-8 | 1,317 | 3.09375 | 3 | [] | no_license | #include "Int2Str.h"
string Int2Str(int value)
{
stringstream ss;
ss << value;
return ss.str();
}
string Long2Str(long value){
stringstream ss;
ss << value;
return ss.str();
}
string Float2Str(float value)
{
stringstream ss;
ss << value;
return ss.str();
}
string Double2Str(double value)
{
stringstream ss;
ss << value;
return ss.str();
}
int Str2Int(string str)
{
return atoi(str.c_str());
}
unsigned int zeroExtendedto4Bytes(unsigned int value, unsigned int readbytes)
{
unsigned int retvalue;
if(readbytes == 1){
retvalue = value & 0x000000ff;
}else if(readbytes == 2){
retvalue = value & 0x0000ffff;
}else if(readbytes == 3){
retvalue = value & 0x00ffffff;
}else{
assert(readbytes == 4);
retvalue = value && 0xffffffff;
}
return retvalue;
}
double Str2Double(string what){
istringstream instr(what);
double val;
instr >> val;
return val;
}
string splitFieldStr_getFieldClass(string str){
int pos1 = str.find("->");
return str.substr(0, pos1);
}
string splitFieldStr_getFieldName(string str){
int pos1 = str.find("->");
int pos2 = pos1 + 2;
int pos3 = str.find(":");
return str.substr(pos2, pos3 - pos1 - 2);
}
string splitFieldStr_getFieldType(string str){
int pos4 = str.find(" ");
return str.substr(pos4 + 1, str.length() - pos4 - 1);
}
| true |
ae50e90b6ef74558be4982dab5d32ec64e705bc3 | C++ | SCS2017/Leetcode-Solution | /二叉树/111_二叉树的最小深度.cpp | UTF-8 | 2,975 | 4.1875 | 4 | [] | no_license | /*
给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回它的最小深度 2.
*/
#include <iostream>
#include <stdio.h>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
//TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
struct Node {
int val;
Node *root;
Node *left;
Node *right;
Node(int x) : val(x), left(NULL), right(NULL) {}
};
Node* CreateTree(Node *root)//创建一棵二叉树
{
Node *p1 = new Node(1);
Node *p2 = new Node(2);
Node *p3 = new Node(3);
Node *p4 = new Node(4);
Node *p5 = new Node(5);
Node *p6 = new Node(6);
Node *p7 = new Node(7);
Node *p8 = new Node(8);
Node *p9 = new Node(9);
p1->left = p2;
p1->right = p3;
p2->left = p4;
p2->right = p5;
p5->left = p6;
p3->left = p7;
p3->right = p8;
p8->right = p9;
root = p1;
return p1;
}
void CreateTree(TreeNode* &root, int a[], int len, int index)
{
if(index >= len){
return;
}
root = new TreeNode;
root->val = a[index];
root->left = NULL;
root->right = NULL;
CreateTree(root->left, a, len, 2 * index + 1);
CreateTree(root->right, a, len, 2 *index + 2);
}
void CreateBiTree(TreeNode* &T){
//按先序输入二叉树中结点的值(一个字符),空格字符代表空树,
//构造二叉树表表示二叉树T。
char ch;
if((ch = getchar()) == '#') T = NULL;//其中getchar()为逐个读入标准库函数
else{
T = new TreeNode;//产生新的子树
T->val = ch;//由getchar()逐个读入来
CreateBiTree(T->left);//递归创建左子树
CreateBiTree(T->right);//递归创建右子树
}
}//CreateTree
void PreOrder(TreeNode *node)
{
if(node)
{
cout << node->val << " ";
PreOrder(node->left);
PreOrder(node->right);
}
}
class Solution {
public:
int minDepth(TreeNode* root) {
if(root == 0){
return 0;
}
if(root->left){
if(root->right){
return min(minDepth(root->left), minDepth(root->right)) + 1;
}
else{
return minDepth(root->left) + 1;
}
}
else if(root->right){
return minDepth(root->right) + 1;
}
else{
return 1;
}
}
};
int main()
{
TreeNode* root;
int arr[7] = {3, 9, 20, 30, 2, 15, 7};
CreateTree(root, arr, 7, 0);
PreOrder(root);
cout << endl;
Solution first;
int result;
result = first.minDepth(root);
cout << result << endl;
TreeNode* node;
CreateBiTree(node);
PreOrder(node);
cout << endl;
return 0;
} | true |
b374f3bb46e240b4a4f132a6a409abb24cc83361 | C++ | adriancarriger/experiments | /udacity/self-driving-intro/5/3/optimized/blur.cpp | UTF-8 | 1,128 | 3.078125 | 3 | [
"MIT"
] | permissive | #include "headers/blur.h"
#include "headers/zeros.h"
using namespace std;
vector<vector<float>> blur(vector<vector<float>> &grid, float blurring) {
vector<float> row;
vector<float> newRow;
unsigned long height;
unsigned long width;
float center, corner, adjacent;
height = grid.size();
width = grid[0].size();
center = 1.0 - blurring;
corner = blurring / 12.0;
adjacent = blurring / 6.0;
static vector<vector<float>> window{
{corner, adjacent, corner}, {adjacent, center, adjacent}, {corner, adjacent, corner}};
static vector<int> DX{-1, 0, 1};
static vector<int> DY{-1, 0, 1};
unsigned long new_i;
unsigned long new_j;
vector<vector<float>> newGrid = zeros(height, width);
for (unsigned long i = 0; i < height; i++) {
for (unsigned long j = 0; j < width; j++) {
for (unsigned long ii = 0; ii < 3; ii++) {
for (unsigned long jj = 0; jj < 3; jj++) {
new_i = (i + DY[ii] + height) % height;
new_j = (j + DX[jj] + width) % width;
newGrid[new_i][new_j] += grid[i][j] * window[ii][jj];
}
}
}
}
return newGrid;
}
| true |
c7d7180f0f4489614023b5578952ccc06170553c | C++ | hse-spb-2020-cpp/practice-alferov | /pract16/visitor.cpp | UTF-8 | 1,385 | 3.78125 | 4 | [] | no_license | #include <string>
#include <memory>
#include <iostream>
struct EmployeeVisitor;
struct Employee {
std::string name;
virtual ~Employee() = default;
virtual void accept(EmployeeVisitor* visitor) = 0;
};
struct Developer;
struct Manager;
struct EmployeeVisitor {
virtual ~EmployeeVisitor() = default;
virtual void visitDeveloper(Developer* dev) = 0;
virtual void visitManager(Manager* man) = 0;
};
struct Developer: public Employee {
std::string language = "C++";
~Developer() override = default;
void accept(EmployeeVisitor* visitor) override {
visitor->visitDeveloper(this);
}
};
struct Manager: public Employee {
std::string region;
~Manager() override = default;
void accept(EmployeeVisitor* visitor) override {
visitor->visitManager(this);
}
};
struct PrintingEmployeeVisitor: public EmployeeVisitor {
~PrintingEmployeeVisitor() override = default;
void visitDeveloper(Developer* dev) override {
std::cout << "Developer " << dev->language << std::endl;
}
void visitManager(Manager* man) override {
std::cout << "Manager " << std::endl;
}
};
int main() {
std::unique_ptr<Employee> dev{new Developer()};
std::unique_ptr<Employee> manager{new Manager()};
PrintingEmployeeVisitor visitor;
dev->accept(&visitor);
manager->accept(&visitor);
}
| true |
19a5a4fb0e11bf483a516bdce2b646fec26e2f4c | C++ | anthonydaig/The_Collab | /ANN/ann.cpp | UTF-8 | 6,664 | 2.765625 | 3 | [] | no_license | #include <math.h>
#include "Eigen/Dense"
#include <random>
#include <stdio.h>
#include <iostream>
#include <stdlib.h>
using namespace Eigen;
class ann {
private:
void sigmoid(MatrixXd, MatrixXd*);
void sigmoidDeriv(MatrixXd*,int);
void initializeTheta(int, int, MatrixXd*);
void add_bias(MatrixXd*);
void set_ones_sigd(int nodes, int *num_nodes, int x_col, int y_col);
void multiply_two(MatrixXd x1, MatrixXd *x2, int);
MatrixXd *z_s;
MatrixXd *a_s;
MatrixXd *ones;
MatrixXd *assoc_err;
MatrixXd *gradients;
MatrixXd *momenta;
MatrixXd *temp_mom;
int layers;
void find_grad(MatrixXd X, MatrixXd Y, int m, int nodes, double *cost);
public:
double eta = 0.1;
double lambda = .015;
double momentum = .5;
int iter = 1000;
MatrixXd *hidden_layers;
ann() { }
MatrixXd normalize(MatrixXd);
void set_learning_param(double eta1){eta = eta1;}
void set_regularizer(double regular){lambda = regular;}
void set_iterations(int num){iter = num;}
void set_iterations(double momentum1){momentum = momentum1;}
void clean();
// MatrixXd* gradientStep(MatrixXd, MatrixXd, int, std::vector<int>, bool);
void learn(MatrixXd, MatrixXd, int, int*, bool prelearn =1/*whether or not we want stacked autoencoders (default 1)*/);
MatrixXd predict(MatrixXd);
};
void ann::clean()
{
delete[] z_s;
delete[] a_s;
delete[] ones;
delete[] assoc_err;
delete[] gradients;
delete[] momenta;
delete[] temp_mom;
}
MatrixXd ann::normalize(MatrixXd x)
{
double mean, sd;
for(int i = 0; i < x.cols(); ++i)
{
mean = x.col(i).mean();
sd = sqrt((((x.col(i).array() - mean)/(x.rows()-1)).matrix().transpose())*(((x.col(i).array() - mean)/(x.rows()-1)).matrix()));
x.col(i) = ((x.col(i).array() - mean)/sd).matrix();
}
return x;
}
void ann::sigmoid(MatrixXd x, MatrixXd *x1)
{
*x1 = (1./(1. + exp(-1.*x.array()))).matrix();
}
void ann::sigmoidDeriv(MatrixXd *x1, int m)
{
double temp;
for (int i = 0; i < m; ++i)
{
temp = (1./(1. + exp(-1. * ((*x1)(0,i)))));
(*x1)(0,i) = (1 - temp)*temp;
}
}
void ann::multiply_two(MatrixXd x1, MatrixXd *x2, int m)
{
for (int i = 0; i < m; ++i)
{
(*x2)(0,i) = (*x2)(0,i)*x1(0,i);
}
}
void ann::add_bias(MatrixXd *x)
{
x->conservativeResize(x->rows(), x->cols()+1);
x->col(x->cols()-1).setOnes();
}
void ann::initializeTheta(int inp, int out, MatrixXd *theta)
{
double eps = sqrt(6)/sqrt((double)inp + (double)out);
std::default_random_engine generator;
std::uniform_real_distribution<double> distribution(-eps,eps);
(*theta).conservativeResize(inp, out);
for(int i = 0; i < inp; ++i)
{
for(int j = 0; j < out; ++j)
{
(*theta)(i,j) = distribution(generator);
}
}
}
void ann::set_ones_sigd(int nodes, int *num_nodes, int x_col, int y_col)
{
ones[0] = MatrixXd::Ones(num_nodes[0], x_col+1);
for (int i = 1; i < nodes; ++i)
{
ones[i] = MatrixXd::Ones(num_nodes[i], num_nodes[i-1]+1);
}
ones[nodes] = MatrixXd::Ones(y_col, num_nodes[nodes-1]);
}
void ann::learn(MatrixXd X, MatrixXd Y, int nodes, int *num_nodes, bool prelearn)
{
layers = nodes;
hidden_layers = new MatrixXd[nodes+1];
if (nodes <1)
{
fprintf(stderr, "Number of nodes must be greater than 0\n");
}
if (!prelearn) //randomly initialize weights
{
initializeTheta(num_nodes[0],X.cols()+1, &(hidden_layers[0]));
for (int i = 1; i < nodes; ++i)
{
initializeTheta(num_nodes[i], num_nodes[i-1] + 1, &(hidden_layers[i]));
}
initializeTheta(Y.cols(), num_nodes[nodes-1] + 1, &(hidden_layers[nodes]));
}
else{/* stacked autoencoder plz */}
int i = 0;
MatrixXd x = normalize(X);
add_bias(&x);
int m = x.rows();
z_s = new MatrixXd[nodes+1];
a_s = new MatrixXd[nodes+2];
ones = new MatrixXd[nodes+1];
assoc_err = new MatrixXd[nodes+1];
gradients = new MatrixXd[nodes+1];
momenta = new MatrixXd[nodes+1];
temp_mom = new MatrixXd[nodes+1];
set_iterations(1000);
set_ones_sigd(nodes, num_nodes, X.cols(), Y.cols());
double cost = 0;
while(i < iter)
{
find_grad(x, Y, m, nodes, &cost);
for (int j = 0; j < nodes+1; ++j)
{
if (i)
{
gradients[j] = (gradients[j] + lambda*hidden_layers[j])/m;
temp_mom[j] = -eta*gradients[j] + momentum*momenta[j];
hidden_layers[j] = hidden_layers[j] + temp_mom[j];
momenta[j] = temp_mom[j];
}
else
{
gradients[j] = (gradients[j] + lambda*hidden_layers[j])/m;
momenta[j] = -eta*gradients[j];
hidden_layers[j] = hidden_layers[j] + momenta[j];
}
}
cost = 0;
i++;
}
}
void ann::find_grad(MatrixXd X, MatrixXd Y, int m, int nodes, double *cost)
{
int j;
for (int i = 0; i < m; ++i)
{
a_s[0] = X.row(i);
for (j = 0; j < nodes+1; ++j)
{
z_s[j] = a_s[j]*(hidden_layers[j].transpose());
sigmoid(z_s[j], &(a_s[j+1]));
a_s[j+1].conservativeResize(a_s[j+1].rows(), a_s[j+1].cols()+1);
a_s[j+1].col(a_s[j+1].cols()-1).setOnes();
}
a_s[nodes+1].conservativeResize(a_s[nodes+1].rows(), a_s[nodes+1].cols()-1);
for (j = 0; j < Y.cols(); ++j)
{
*cost += -1 * Y(i,j)*log(a_s[nodes+1](0,j))
- (1. - Y(i,j))*log(1. - a_s[nodes+1](0,j));
}
assoc_err[nodes] = a_s[nodes+1] - Y.row(i);
for (j = nodes; j > 0; --j)
{
assoc_err[j-1] = assoc_err[j]*(hidden_layers[j]);
assoc_err[j-1].conservativeResize(1, assoc_err[j-1].cols()-1);
sigmoidDeriv(&(z_s[j-1]), z_s[j-1].cols());
multiply_two(z_s[j-1], &(assoc_err[j-1]), assoc_err[j-1].cols());
}
for (int j = 0; j < nodes+1; ++j)
{
if (i)
{
gradients[j] = gradients[j] + (assoc_err[j].transpose() * a_s[j]);
}
else
{
gradients[j] = (assoc_err[j].transpose() * a_s[j]);
}
}
}
*cost = *cost / m;
}
MatrixXd ann::predict(MatrixXd unkn)
{
MatrixXd inp = normalize(unkn);
add_bias(&inp);
MatrixXd predictions(unkn.rows(), hidden_layers[layers].rows());
for (int i = 0; i < unkn.rows(); ++i)
{
a_s[0] = inp.row(i);
for (int j = 0; j < layers+1; ++j)
{
z_s[j] = a_s[j]*(hidden_layers[j].transpose());
sigmoid(z_s[j], &(a_s[j+1]));
a_s[j+1].conservativeResize(a_s[j+1].rows(), a_s[j+1].cols()+1);
a_s[j+1].col(a_s[j+1].cols()-1).setOnes();
}
for (int j = 0; j < hidden_layers[layers].rows(); ++j)
{
predictions(i,j) = a_s[layers+1](0,j);
}
}
return predictions;
}
int main(int argv, char** argc){
ann net;
MatrixXd x(4,4);
MatrixXd y(4,2);
x << 0, 0, 3, 6,
1, 1, 3, 4,
1, 0, 1, 2,
0, 1, 1, 1;
y << 0, 1,
0, 1,
1, 0,
1, 0;
int nodes[3];
nodes[0] = 5;
nodes[1] = 6;
nodes[2] = 9;
// net.enc_dec(x, 2);
// net.learn(x, y, 3, nodes, 0);
// std::cout << net.predict(x) << "\nsuppp\n"<< std::endl;
// std::cout << x << std::endl;
return 0;
}
| true |
423be921c87143c555fdfb85fc5839187517dcd9 | C++ | Woutuuur/sorting-visualizer | /include/button.h | UTF-8 | 1,057 | 2.765625 | 3 | [] | no_license | #ifndef BUTTON_H
#define BUTTON_H
#include <SDL2/SDL.h>
#include <SDL2/SDL_ttf.h>
#include <string>
class Button
{
public:
Button(SDL_Renderer* renderer, const int x, const int y, const int w, const int h);
~Button();
void render();
void setBackgroundColor(const int r, const int g, const int b);
void setTextColor(const int r, const int g, const int b);
void setText(std::string text);
void setText(std::string text, const int fontSize);
void setFontSize(const unsigned int fontSize);
void setFont(std::string fontDir);
bool mouseHover() const;
private:
SDL_Rect* buttonRect;
SDL_Renderer *renderer;
SDL_Color backgroundColor = {255, 255, 255, 255};
// Text components
std::string text = "Button";
std::string fontDir = "./res/FreeSans.ttf";
int fontSize = 12;
SDL_Color textColor = {0, 0, 0, 255};
TTF_Font* font;
void setFont();
void renderText() const;
};
#endif
| true |
f3302eca9a92b8211bcef2f2ee6b29e547a6edbf | C++ | civinx/ACM_Code | /Practice/ZUCCACM/Problem : Pills (卡特兰数)/Problem : Pills (卡特兰数)/main.cpp | UTF-8 | 557 | 2.59375 | 3 | [] | no_license | //
// main.cpp
// Problem : Pills (卡特兰数)
//
// Created by czf on 16/4/2.
// Copyright © 2016年 czf. All rights reserved.
//
#include <cstdio>
#include <cstring>
typedef long long ll;
const int maxn = 100;
ll f[maxn][maxn];
int main() {
for(int i = 0; i < maxn; i ++) f[0][i] = 1;
for(int i = 1; i <= 30; i ++) {
for(int j = 0; j <= 30; j ++) {
f[i][j] = f[i-1][j+1] + (j == 0 ? 0 : f[i][j-1]);
}
}
int n;
while(scanf("%d",&n) && n) {
printf("%lld\n",f[n][0]);
}
return 0;
} | true |
e4f3ac8e6f692b17c7d89c0c211bec26d6a02608 | C++ | romanivanov21/web_server | /inc/process/worker_process/worker_process.h | UTF-8 | 666 | 2.703125 | 3 | [] | no_license | /**
* Флайл: worker_process.h
*
* Описание: класс реализющий worker процесс
*/
#ifndef _WORKER_PROCESS_H_
#define _WORKER_PROCESS_H_
#include "process.h"
#include "event_dispatcher.h"
class worker_process : public process, protected event_dispatcher
{
public:
worker_process();
~worker_process();
/**
* @brief точка входа в worker процесс
*/
void start_process() noexcept override;
worker_process( const worker_process © ) = delete;
worker_process& operator=( const worker_process © ) = delete;
private:
delegate<void()> *delegate1_;
};
#endif //_WORKER_H_ | true |
4742953af663ff698aa677c5e6b4aea70e33fe07 | C++ | Gabriele91/Theoretical-and-Computational-Methods-for-The-Molecular-Sciences | /include/kernels.h | UTF-8 | 6,267 | 2.953125 | 3 | [] | no_license | //
// kernels.h
// MPI-Test_01
//
// Created by Gabriele on 27/03/16.
// Copyright © 2016 Gabriele. All rights reserved.
//
#pragma once
#include <vector>
#include <string>
#include <complexmath.h>
#include <polynomial.h>
template<class T>
using kernel = std::complex<T>(*)(const polynomial< T >&, const std::complex<T>&);
namespace kernels
{
/// newton
template< class T >
inline std::complex< T > newton (const polynomial< T >& constants, const std::complex< T >& x)
{
std::complex< T > vn = constants[0];
std::complex< T > wn = vn;
//Horner
for(size_t i=1;i < constants.size()-1;++i)
{
vn = vn*x+constants[i];
wn = wn*x+vn;
}
//last pass
vn = vn*x+constants[constants.size()-1];
//newton
return x-(vn/wn);
};
/// schroeder
template< class T >
inline std::complex< T > schroeder (const polynomial< T >& constants, const std::complex< T >& x)
{
if(constants.size()==0) return 0;
if(constants.size()==1) return constants[0];
std::complex<T> vn=constants[0];
std::complex<T> wn=vn;
std::complex<T> un=wn;
//Horner
for(size_t i=1;i<(size_t)(constants.size())-2;++i)
{
vn = vn*x+constants[i];
wn = wn*x+vn;
un = un*x+wn;
}
vn = vn*x+constants[constants.size()-2];
wn = wn*x+vn;
vn = vn*x+constants[constants.size()-1];
//schroeder pass
auto q=vn/wn;
auto s1=q+q*q*un/wn;
//return schroeder
return x-s1;
};
/// schroeder4
template< class T >
inline std::complex< T > schroeder4(const polynomial< T >& constants, const std::complex< T >& x)
{
//exit condiction
if(constants.size()==0) return 0;
if(constants.size()==1) return constants[0];
std::complex<T> vn=constants[0];
std::complex<T> wn=vn;
std::complex<T> un=wn;
std::complex<T> yn=un;
//Horner
for(size_t i=1;i<(size_t)(constants.size())-3;++i)
{
vn = vn*x+constants[i];
wn = wn*x+vn;
un = un*x+wn;
yn = yn*x+un;
}
//last Schroeder4
vn = vn*x+constants[constants.size()-3];
wn = wn*x+vn;
un = un*x+wn;
vn = vn*x+constants[constants.size()-2];
wn = wn*x+vn;
vn = vn*x+constants[constants.size()-1];
//Schroeder4
auto q=vn/wn;
auto s3=q+(q*q)*(un/wn);
auto s4=s3-(q*q*q)*((yn/wn)-(un/(wn*wn)));
//return
return x-s4;
}
/// halley: ( f(x)*f'(x) ) / ( (f'(x)^2) - ( (f''(x)^2)/4 ) )
template< class T >
inline std::complex< T > halley(const polynomial< T >& constants, const std::complex< T >& x)
{
//exit condiction
if(constants.size()==0) return 0;
if(constants.size()==1) return constants[0];
std::complex<T> vn=constants[0];
std::complex<T> wn=vn;
std::complex<T> un=wn;
//Horner
for(size_t i=1;i<(size_t)(constants.size())-2;++i)
{
vn = vn*x+constants[i];
wn = wn*x+vn;
un = un*x+wn;
}
vn = vn*x+constants[constants.size()-2];
wn = wn*x+vn;
vn = vn*x+constants[constants.size()-1];
//halley
auto s=vn*wn;
auto d=(wn*wn)-vn*un;
//
return x-(s/d);
}
/// halley 4
template< class T >
inline std::complex< T > halley4(const polynomial< T >& constants,const std::complex< T >& x)
{
//exit condiction
if(constants.size()==0) return 0;
if(constants.size()==1) return constants[0];
std::complex<T> vn=constants[0];
std::complex<T> wn=vn;
std::complex<T> un=wn;
std::complex<T> yn=un;
//Horner
for(size_t i=1;i<(size_t)(constants.size())-3;++i)
{
vn = vn*x+constants[i];
wn = wn*x+vn;
un = un*x+wn;
yn = yn*x+un;
}
vn = vn*x+constants[constants.size()-3];
wn = wn*x+vn;
un = un*x+wn;
vn = vn*x+constants[constants.size()-2];
wn = wn*x+vn;
vn = vn*x+constants[constants.size()-1];
//halley4
auto wn2=wn*wn;
auto s=(vn*wn2)-(vn*vn*un);
auto d=((vn*vn)*yn)+(wn2*wn)-((T)(2.0L)*vn*wn*un);
//
return x-(s/d);
}
//get kernel field
template < class T >
struct kernel_field
{
std::string m_name;
kernel<T> m_kernel;
};
template < class T >
using kernels_table = std::vector< kernel_field<T> >;
template < class T >
inline const kernels_table<T>& get_kernels_table()
{
static kernels_table<T> kernels_table=
{
{"newton" ,kernels::newton< T > },
{"schroeder" ,kernels::schroeder< T > },
{"schroeder4",kernels::schroeder4< T >},
{"halley" ,kernels::halley< T > },
{"halley4" ,kernels::halley4< T > }
};
return kernels_table;
}
template < class T >
inline long get_kernel_id_from_name(const std::string& k_name)
{
//id count
long id_count = 0;
//search
for(auto& field : get_kernels_table< T >())
{
if(field.m_name == k_name) return id_count;
//count...
++id_count;
}
return -1;
}
template < class T >
inline kernel<T> get_kernel_from_id(long id)
{
return get_kernels_table< T >()[id].m_kernel;
}
template < class T >
inline kernel<T> get_kernel_from_name(const std::string& k_name)
{
for(auto& field: get_kernels_table< T >())
{
if(field.m_name == k_name) return field.m_kernel;
}
return nullptr;
}
}
| true |
314fb1490532126a739df3c8a7b9bb797e8e25f2 | C++ | ronishz/bootcamp | /cl1p/B3_0-1 Knapsack.cpp | UTF-8 | 4,652 | 3.421875 | 3 | [] | no_license | // A Dynamic Programming based solution for 0-1 Knapsack problem
// Time Complexity: O(nW) where n is the number of items and W is the capacity of knapsack.
// O(b^d)
#include<stdio.h>
#include<iostream>
#define maxi 10
using namespace std;
// A utility function that returns maximum of two integers
int max(int a, int b) { return (a > b)? a : b; }
// Returns the maximum value that can be put in a knapsack of capacity W
int knapSack(int W, int wt[], int val[], int n)
{
int i, w;
int K[n+1][W+1]; // creates that 0-1 knapsack matrix.
// Build table K[][] in bottom up manner
for (i = 0; i <= n; i++)
{
for (w = 0; w <= W; w++)
{
if (i==0 || w==0)
K[i][w] = 0; //making 1st row and col zero.
else if (wt[i-1] <= w) // if weight of array is less then equal to w then
K[i][w] = max(val[i-1] + K[i-1][w-wt[i-1]], K[i-1][w]); // assign max of value to k[i][j].
else
K[i][w] = K[i-1][w]; // else assign this value to k[i][w].
}
}
return K[n][W]; // return last row and col of that matrix as a result of 0-1 knapsack.
}
int main()
{
int val[maxi];
int wt[maxi];
int W,n;
cout<<"Enter the maximum weight of knapsack : ";
cin>>W;
cout<<"\n Enter no of items present : ";
cin>>n;
cout<<"\n Enter the values(profit) of each item : "<<endl;
for(int i=0;i<n;i++)
{
cin>>val[i];
}
cout<<"\n Enter the weight of each item : "<<endl;
for(int i=0;i<n;i++)
{
cin>>wt[i];
}
cout<<"Answer is-"<<knapSack(W, wt, val, n)<<endl;
return 0;
}
/*
OUTPUT:
tony@tony-HP-Pavilion-g6-Notebook-PC:$ g++ b3.cpp
tony@tony-HP-Pavilion-g6-Notebook-PC:$ ./a.out
Enter the maximum weight of knapsack : 50
Enter no of items presents : 3
Enter the values(profit) of each item :
60
100
120
Enter the weight of each item :
10
20
30
Answer is- 220
tony@tony-HP-Pavilion-g6-Notebook-PC:$ g++ B3.cpp
tony@tony-HP-Pavilion-g6-Notebook-PC:$ ./a.out
Enter the maximum weight of knapsack : 10
Enter no of items present : 4
Enter the values(profit) of each item :
10
40
30
50
Enter the weight of each item :
5
4
6
3
Answer is-90
tony@tony-HP-Pavilion-g6-Notebook-PC:$
*/
/*
#include<iostream>
using namespace std;
class knap
{
float pro[20],wt[20];
int mw,n,ub,v[20],k;
int wt1,pt;
public:
knap()
{
k=-1;
wt1=pt=0;
}
int getdata();
int getubound();
int getleastcost();
int knapsack();
int display();
};
int knap::getdata() // get data function.
{
cout<<"\nenter the number of items";
cin>>n;
cout<<"\nenter the values";
for(int i=0;i<n;i++)
{
cout<<"\nenter the weight";
cin>>wt[i];
cout<<"\nenter the profit";
cin>>pro[i];
}
cout<<"\nenter the maximum weight";
cin>>mw;
return 0;
}
int knap::display() // display data function.
{
cout<<"\nThe solution vector is:";
for(int i=0;i<n;i++)
{
cout<<"";
cout<<v[i];
}
cout<<"\nAnd the cost is"<<pt;
return 0;
}
int knap::getubound() // to set the upper bound in each node.
{
for(int i=k+1;i<n;i++)
{
if(wt1+wt[i]<=mw)
{
wt1=wt1+wt[i];
pt=pt+pro[i];
}
}
return pt;
}
int knap::getleastcost() // to get the minimum cost .
{
for(int i=k+1;i<n;i++)
{ wt1=wt1+wt[i];
if(wt1<=mw)
{
pt=pt+pro[i];
}
else
{
return (pt+((1-((wt1-mw)/wt[i]))*pro[i]));
}
}
return pt;
}
int knap::knapsack()
{
int l=0;
int ub1=0,ub2=0,c1=0,c2=0;
int wt3=0,pt3=0;
while(l<n)
{
wt3=wt1;
pt3=pt;
ub1=getubound();
wt1=wt3;
pt=pt3;
c1=getleastcost();
wt1=wt3;
pt=pt3;
k=l;
ub2=getubound();
wt1=wt3;
pt=pt3;
c2=getleastcost();
wt1=wt3;
pt=pt3;
if(ub1>ub2)
{
v[l]=1;
wt1=wt1+wt[l];
pt=pt+pro[l];
}
else
{
v[l]=0;
}
l++;
ub1=ub2=c1=c2=0;
}
display();
return 0;
}
int main()
{
knap p;
p.getdata();
p.knapsack();
return 0;
}
output:
tony@tony-HP-Pavilion-g6-Notebook-PC:~/Music/CL1$ g++ B3_0-1\ Knapsack.cpp
tony@tony-HP-Pavilion-g6-Notebook-PC:~/Music/CL1$ ./a.out
enter the number of items3
enter the values
enter the weight8
enter the profit32
enter the weight12
enter the profit24
enter the weight6
enter the profit6
enter the maximum weight15
The solution vector is:101
And the cost is38
tony@tony-HP-Pavilion-g6-Notebook-PC:~/Music/CL1$
*/
| true |
a35e4d8722702ca633e7bff31d39ec824266e2be | C++ | bochalito/computational-geometry | /VVRFramework/include/GeoLib/C2DHoledPolyBaseSet.h | UTF-8 | 5,448 | 2.59375 | 3 | [] | no_license | /*---------------------------------------------------------------------------
Copyright (C) GeoLib.
This code is used under license from GeoLib (www.geolib.co.uk). This or
any modified versions of this cannot be resold to any other party.
---------------------------------------------------------------------------*/
/**--------------------------------------------------------------------------<BR>
\file 2DHoledPolyBaseSet.h
\brief Declaration file for the C2DHoledPolyBaseSet Class.
Declaration file for C2DHoledPolyBaseSet, a collection of holed polygons.
\class C2DHoledPolyBaseSet.
\brief A collection of holed polygons.
Class which represents a collection of holed polygons.
<P>---------------------------------------------------------------------------*/
#ifndef _GEOLIB_C2DHOLEDPOLYBASESET_H
#define _GEOLIB_C2DHOLEDPOLYBASESET_H
#include "Grid.h"
#include "C2DHoledPolyBase.h"
#include "C2DBaseSet.h"
#include "MemoryPool.h"
#ifdef _POLY_EXPORTING
#define POLY_DECLSPEC __declspec(dllexport)
#else
#ifdef _STATIC
#define POLY_DECLSPEC
#else
#define POLY_DECLSPEC __declspec(dllimport)
#endif
#endif
class POLY_DECLSPEC C2DHoledPolyBaseSet : public C2DBaseSet
{
public:
_MEMORY_POOL_DECLARATION
/// Constructor
C2DHoledPolyBaseSet(void);
/// Destructor
~C2DHoledPolyBaseSet(void);
/// Adds a copy of the other pointer array
void AddCopy(const C2DHoledPolyBaseSet& Other);
/// Makes a copy of the other
void MakeCopy( const C2DHoledPolyBaseSet& Other);
/// Passes ONLY the pointers of this type or inherited types from the Other into this.
void operator<<(C2DBaseSet& Other);
/// Adds a new pointer and takes responsibility for it.
void Add(C2DHoledPolyBase* NewItem) { C2DBaseSet::Add(NewItem);}
/// Adds a copy of the item given
void AddCopy(const C2DHoledPolyBase& NewItem) { C2DBaseSet::Add(new C2DHoledPolyBase( NewItem ) );}
/// Deletes the current item and sets the pointer to be the new one
void DeleteAndSet(int nIndx, C2DHoledPolyBase* NewItem) { C2DBaseSet::DeleteAndSet(nIndx, NewItem );}
/// Extracts the current item and sets the pointer to be the new one
C2DHoledPolyBase* ExtractAndSet(int nIndx, C2DHoledPolyBase* NewItem) { return dynamic_cast<C2DHoledPolyBase*> (C2DBaseSet::ExtractAndSet(nIndx, NewItem ) );}
/// Returns the value at the point given
C2DHoledPolyBase* GetAt(int nIndx) { return dynamic_cast<C2DHoledPolyBase*> (C2DBaseSet::GetAt(nIndx ) ) ;}
/// Returns the value at the point given
const C2DHoledPolyBase* GetAt(int nIndx) const { return dynamic_cast<const C2DHoledPolyBase*> (C2DBaseSet::GetAt(nIndx ) ) ;}
/// Returns a reference to the value at the point given.
C2DHoledPolyBase& operator[] (int nIndx) { return *dynamic_cast<C2DHoledPolyBase*> (C2DBaseSet::GetAt(nIndx ) ) ;}
/// Returns a reference to the value at the point given.
const C2DHoledPolyBase& operator[] (int nIndx) const { return *dynamic_cast<const C2DHoledPolyBase*> (C2DBaseSet::GetAt(nIndx ) ) ;}
/// Returns a pointer to the last item
C2DHoledPolyBase* GetLast(void) { return dynamic_cast<C2DHoledPolyBase*> (C2DBaseSet::GetLast( ) ) ;}
/// Extracts the pointer passing deletion responsibility over.
C2DHoledPolyBase* ExtractAt(unsigned int nIndx) { return dynamic_cast<C2DHoledPolyBase*> (C2DBaseSet::ExtractAt(nIndx ) ) ;}
/// Extracts the pointer passing deletion responsibility over.
C2DHoledPolyBase* ExtractLast(void) { return dynamic_cast<C2DHoledPolyBase*> (C2DBaseSet::ExtractLast( ) ) ;}
/// Insertion
void InsertAt(unsigned int nIndex, C2DHoledPolyBase* NewItem) {C2DBaseSet::InsertAt(nIndex, NewItem);}
/// Insertion of another array
void InsertAt(unsigned int nIndex, C2DHoledPolyBaseSet& Other) {C2DBaseSet::InsertAt(nIndex, Other);}
/// Passes all the pointers from the Other into this
void operator<<(C2DHoledPolyBaseSet& Other) {C2DBaseSet::operator <<(Other);}
/// Adds a new pointer and takes responsibility for it.
void operator<<(C2DHoledPolyBase* NewItem) {C2DBaseSet::operator <<(NewItem);};
/// Basic multiple unification.
void UnifyBasic(void);
/// Unification by growing shapes of fairly equal size (fastest for large groups).
void UnifyProgressive(CGrid::eDegenerateHandling eDegen = CGrid::None);
/// Assumes current set is distinct.
void AddAndUnify(C2DHoledPolyBase* pPoly);
/// Assumes both sets are distinct.
void AddAndUnify(C2DHoledPolyBaseSet& pOther);
/// Assumes current set is distinct.
bool AddIfUnify(C2DHoledPolyBase* pPoly);
/// Adds polygons known to be holes of those currently in the set.
void AddKnownHoles( C2DPolyBaseSet& pOther );
/// Total Line count for all polygons contained.
unsigned int GetLineCount(void);
/// Minimum line count of all polys.
unsigned int GetMinLineCount(void);
// Passes all the pointers from the Other into this
void operator<<(C2DPolyBaseSet& Other);
///// Adds a new pointer and takes responsibility for it.
void operator<<(C2DPolyBase* NewItem);
// Makes all arc valid if not already by adjusting radius to minimum required.
unsigned int MakeValidArcs(void);
// True if there are arcs in the shape.
bool HasArcs(void) const;
// True if all the arcs are valid
bool IsValidArcs(void) const;
// Removes all lines whose end is the same is the start. Returns the number found.
unsigned int RemoveNullLines(void);
void MakeClockwise(void);
void Transform(CTransformation* pProject);
void InverseTransform(CTransformation* pProject);
};
#endif | true |
3fd4540af1930f9b7ee26ac576cbcc0c8583f4e3 | C++ | gwsystems/schedcat | /native/src/edf/ffdbf.cpp | UTF-8 | 7,349 | 2.765625 | 3 | [] | no_license | #include <algorithm> // for min
#include <queue>
#include <vector>
#include "tasks.h"
#include "schedulability.h"
#include "math-helper.h"
#include "edf/ffdbf.h"
#include <iostream>
#include "task_io.h"
using namespace std;
static void get_q_r(const Task &t_i, const fractional_t &time,
integral_t &q_i, fractional_t &r_i)
{
// compute q_i -- floor(time / period)
// r_i -- time % period
r_i = time / t_i.get_period();
q_i = r_i; // truncate, i.e. implicit floor
r_i = time;
r_i -= q_i * t_i.get_period();
}
static void compute_q_r(const TaskSet &ts, const fractional_t &time,
integral_t q[], fractional_t r[])
{
for (unsigned int i = 0; i < ts.get_task_count(); i++)
get_q_r(ts[i], time, q[i], r[i]);
}
static void ffdbf(const Task &t_i,
const fractional_t &time, const fractional_t &speed,
const integral_t &q_i, const fractional_t &r_i,
fractional_t &demand,
fractional_t &tmp)
{
/* this is the cost in all three cases */
demand += q_i * t_i.get_wcet();
/* check for (a) and (b) cases */
tmp = 0;
tmp -= t_i.get_wcet();
tmp /= speed;
tmp += t_i.get_deadline();
if (r_i >= tmp)
{
// add one more cost charge
demand += t_i.get_wcet();
if (r_i <= t_i.get_deadline())
{
/* (b) class */
tmp = t_i.get_deadline();
tmp -= r_i;
tmp *= speed;
demand -= tmp;
}
}
}
static void ffdbf_ts(const TaskSet &ts,
const integral_t q[], const fractional_t r[],
const fractional_t &time, const fractional_t &speed,
fractional_t &demand, fractional_t &tmp)
{
demand = 0;
for (unsigned int i = 0; i < ts.get_task_count(); i++)
ffdbf(ts[i], time, speed, q[i], r[i], demand, tmp);
}
class TestPoints
{
private:
fractional_t time;
fractional_t with_offset;
unsigned long period;
bool first_point;
public:
void init(const Task& t_i,
const fractional_t& speed,
const fractional_t& min_time)
{
period = t_i.get_period();
with_offset = t_i.get_wcet() / speed;
if (with_offset > t_i.get_deadline())
with_offset = t_i.get_deadline();
with_offset *= -1;
time = min_time;
time /= period;
// round down, i.e., floor()
truncate_fraction(time);
time *= period;
time += t_i.get_deadline();
with_offset += time;
first_point = true;
while (get_cur() <= min_time)
next();
}
const fractional_t& get_cur() const
{
if (first_point)
return with_offset;
else
return time;
}
void next()
{
if (first_point)
first_point = false;
else
{
time += period;
with_offset += period;
first_point = true;
}
}
};
class TimeComparator {
public:
bool operator() (TestPoints *a, TestPoints *b)
{
return b->get_cur() < a->get_cur();
}
};
typedef priority_queue<TestPoints*,
vector<TestPoints*>,
TimeComparator> TimeQueue;
class AllTestPoints
{
private:
TestPoints *pts;
TimeQueue queue;
fractional_t last;
TaskSet const &ts;
public:
AllTestPoints(const TaskSet &ts)
: ts(ts)
{
pts = new TestPoints[ts.get_task_count()];
}
void init(const fractional_t &speed,
const fractional_t &min_time)
{
last = -1;
// clean out queue
while (!queue.empty())
queue.pop();
// add all iterators
for (unsigned int i = 0; i < ts.get_task_count(); i++)
{
pts[i].init(ts[i], speed, min_time);
queue.push(pts + i);
}
}
~AllTestPoints()
{
delete[] pts;
}
void get_next(fractional_t &t)
{
TestPoints* pt;
do // avoid duplicates
{
pt = queue.top();
queue.pop();
t = pt->get_cur();
pt->next();
queue.push(pt);
} while (t == last);
last = t;
}
};
bool FFDBFGedf::witness_condition(const TaskSet &ts,
const integral_t q[], const fractional_t r[],
const fractional_t &time,
const fractional_t &speed)
{
fractional_t demand, bound;
ffdbf_ts(ts, q, r, time, speed, demand, bound);
bound = - ((int) (m - 1));
bound *= speed;
bound += m;
bound *= time;
return demand <= bound;
}
bool FFDBFGedf::is_schedulable(const TaskSet &ts,
bool check_preconditions)
{
if (m < 2)
return false;
if (check_preconditions)
{
if (!(ts.has_only_feasible_tasks() &&
ts.is_not_overutilized(m) &&
ts.has_only_constrained_deadlines() &&
ts.has_no_self_suspending_tasks()))
return false;
}
// allocate helpers
AllTestPoints testing_set(ts);
integral_t *q = new integral_t[ts.get_task_count()];
fractional_t *r = new fractional_t[ts.get_task_count()];
fractional_t sigma_bound;
fractional_t time_bound;
fractional_t tmp(1, epsilon_denom);
// compute sigma bound
tmp = 1;
tmp /= epsilon_denom;
ts.get_utilization(sigma_bound);
sigma_bound -= m;
sigma_bound /= - ((int) (m - 1)); // neg. to flip sign
sigma_bound -= tmp; // epsilon
sigma_bound = min(sigma_bound, fractional_t(1));
// compute time bound
time_bound = 0;
for (unsigned int i = 0; i < ts.get_task_count(); i++)
time_bound += ts[i].get_wcet();
time_bound /= tmp; // epsilon
fractional_t t_cur;
fractional_t sigma_cur, sigma_nxt;
bool schedulable;
t_cur = 0;
schedulable = false;
// Start with minimum possible sigma value, then try
// multiples of sigma_step.
ts.get_max_density(sigma_cur);
// setup brute force sigma value range
sigma_nxt = sigma_cur / sigma_step;
truncate_fraction(sigma_nxt);
sigma_nxt += 1;
sigma_nxt *= sigma_step;
while (!schedulable &&
sigma_cur <= sigma_bound &&
t_cur <= time_bound)
{
testing_set.init(sigma_cur, t_cur);
do {
testing_set.get_next(t_cur);
if (t_cur <= time_bound)
{
compute_q_r(ts, t_cur, q, r);
schedulable = witness_condition(ts, q, r, t_cur, sigma_cur);
}
else
// exceeded testing interval
schedulable = true;
} while (t_cur <= time_bound && schedulable);
if (!schedulable && t_cur <= time_bound)
{
// find next sigma variable
do
{
sigma_cur = sigma_nxt;
sigma_nxt += sigma_step;
} while (sigma_cur <= sigma_bound &&
!witness_condition(ts, q, r, t_cur, sigma_cur));
}
}
delete [] q;
delete [] r;
return schedulable;
}
| true |
d37e238bbc994ba844903d071b8e59c0cc647da4 | C++ | avallete/CPPool | /J05/ex01/Form.hpp | UTF-8 | 1,458 | 2.96875 | 3 | [] | no_license | #ifndef FORM_HPP
#define FORM_HPP
#include <iostream>
class Bureaucrat;
class Form
{
public:
Form(void);
Form(std::string name, int sgrade, int xgrade);
~Form(void);
std::string& getName(void) const;
int getSGrade(void) const;
int getXGrade(void) const;
bool getSign(void) const;
void beSigned(Bureaucrat& b);
Form& operator=(Form const & rhs);
class GradeTooHighException: public std::exception
{
private:
GradeTooHighException& operator=(GradeTooHighException const & rhs);
public:
GradeTooHighException(GradeTooHighException const & src): std::exception(src)
{return;};
GradeTooHighException(void){return;};
~GradeTooHighException(void) throw(){return;};
virtual const char* what() const throw(){
return ("Grade Too Hight");
};
};
class GradeTooLowException: public std::exception
{
private:
GradeTooLowException& operator=(GradeTooLowException const & rhs);
public:
GradeTooLowException(GradeTooLowException const & src): std::exception(src)
{return;};
GradeTooLowException(void)
{return;};
~GradeTooLowException(void) throw(){return;};
virtual const char* what() const throw(){
return ("Grade Too Low");
};
};
private:
Form(Form const & src);
std::string const m_name;
int const m_sgrade;
int const m_xgrade;
bool m_sign;
};
std::ostream& operator<<(std::ostream&, Form&);
#include "Bureaucrat.hpp"
#endif | true |
098091f94f71ddd6d72b7b90b309063267b3d417 | C++ | ayushh7/codeforces-solutions-2 | /9A.cpp | UTF-8 | 503 | 2.734375 | 3 | [] | no_license | /*
* Author: Rushi Vachhani
* Platform: Codeforces
* Problem_ID: 9A
* Language: C++
*/
#include<bits/stdc++.h>
using namespace std;
void solve() {
int a, b;
cin >> a >> b;
if(a==1 && b==1) { cout<<"1/1"; return; }
int max_element = max(a,b);
int possibilities = (6-max_element)+1;
int gcd = __gcd(possibilities, 6);
cout<<possibilities/gcd<<"/"<<6/gcd;
return;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
solve();
return 0;
} | true |
aeeee5653938e751341ee32c744eed4467491580 | C++ | oliver-zeng/leetcode | /0200-Number_of_Islands/main-2.cpp | UTF-8 | 1,229 | 2.71875 | 3 | [] | no_license | class Solution {
int d[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
void dfs(vector<vector<char>> &grid, vector<vector<bool>> &used, int x, int y) {
for (int i = 0; i < 4; i++) {
int newx = x + d[i][0];
int newy = y + d[i][1];
if ((newx >= 0 && newx < grid.size()) &&
(newy >= 0 && newy < grid[0].size()) &&
!used[newx][newy] && grid[newx][newy] == '1') {
used[newx][newy] = true;
dfs(grid, used, newx, newy);
}
}
}
public:
int numIslands(vector<vector<char>>& grid) {
// 二维定义sop,要用变量,不能直接带进去
// vector<vector<bool>> used(grid.size(), vector<int>(grid[0].size(), false));
int row = grid.size();
if (row == 0) return 0;
int col = grid[0].size();
vector<vector<bool>> used(row, vector<bool>(col, false));
int res = 0;
for (int i = 0; i < grid.size(); i++)
for (int j = 0; j < grid[0].size(); j++)
if (grid[i][j] == '1' && !used[i][j]) {
res++;
dfs(grid, used, i, j);
}
return res;
}
}; | true |
a1ae2b6e7cf71f9cd122be7708282dfdae214a70 | C++ | Freeman97/PAT-Solve | /Q1007/solve.cpp | UTF-8 | 390 | 2.953125 | 3 | [] | no_license | #include <iostream>
#include <math.h>
using namespace std;
int main()
{
int N = 0;
int counter = 0;
int prev = 2;
bool flag;
cin >> N;
for(int i = 2; i <= N; i++)
{
flag = true;
for(int j = 2; j <= sqrt(i); j++)
{
if(i % j == 0)
{
flag = false;
break;
}
}
if(flag)
{
if(i - prev == 2)
{
counter++;
}
prev = i;
}
}
cout << counter;
}
| true |
0ccc9bf470c0b5deb31d7a2b52a7168072df1055 | C++ | Mikhael777/tiitDeliveryLab1 | /021703/Samchuk_ZHENYA/library.cpp | WINDOWS-1251 | 2,624 | 3.28125 | 3 | [] | no_license | // ( )
#include <iostream>
#include "Library_prot.h"
using namespace std;
node::node(node* Pr, node* Ne) {
previous = Pr;
next = Ne;
dequeue = new int[Max]();
}
void node::print() {
for (int k = 0; k < Max; k++) {
if (dequeue[k] != 0)
cout << dequeue[k] << " | ";
}
cout<< endl;
}
Dequeue::Dequeue() {
node* N = new node(nullptr, nullptr); //
first = N;
last = N;
first_small_deque = Max / 2 - 1;
last_small_deque = Max / 2; //
Size = 0; //
}
void Dequeue::add_first() {
node* N = new node(nullptr, first);
first->previous = N;
first = N;
first_small_deque = Max - 1;
}
void Dequeue::add_last() {
node* N = new node(last, nullptr);
last->next = N;
last = N;
last_small_deque = 0;
}
void Dequeue::delete_first() {
node* N = first->next;
delete first;
first = N;
first->previous = nullptr;
first_small_deque = 0;
}
void Dequeue::delete_last() {
node* N = last->previous;
delete last;
last = N;
last->next = nullptr;
last_small_deque = Max - 1;
}
void Dequeue::push_front(int n) {
(first->dequeue)[first_small_deque] = n;
first_small_deque--;
Size++;
if (first_small_deque == -1) //If -
add_first();
}
void Dequeue::push_back(int n) {
(last->dequeue)[last_small_deque] = n;
last_small_deque++;
Size++;
if (last_small_deque == Max)
add_last();
}
void Dequeue::pop_front() {
Size--;
if (first_small_deque == Max - 1)
delete_first();
else
first_small_deque++;
(first->dequeue)[first_small_deque] = 0;
}
void Dequeue::pop_back() {
Size--;
if (last_small_deque == 0)
delete_last();
else
last_small_deque--;
(last->dequeue)[last_small_deque] = 0;
}
bool Dequeue::empty() { return (Size == 0); }
void Dequeue::clear() {
node* N = first;
while (N) {
node* M = N->next;
delete N->previous;
delete N;
N = M;
}
N = new node(nullptr, nullptr);
first = N;
last = N;
Size = 0;
first_small_deque = Max / 2 - 1;
last_small_deque = Max / 2;
}
void Dequeue::print() {
cout << "RESULT - | ";
node* N = first;
while (N) {
N->print(); //
N = N->next;
}
} | true |
017f7b874e10f239fb46824e6f01426667ab1ec1 | C++ | BeauRogers/train_signaling | /src/simulation.cpp | UTF-8 | 1,685 | 2.75 | 3 | [] | no_license | #include <iostream>
using namespace std;
#include <limits.h>
#include <chrono>
#include <thread>
#include "include/train.h"
#include "include/simulation.h"
void initialize_trains(Train* trains, int num_trains, node_info* global_map, std::string* names,
int num_stops, next_node* train_pos)
{
for(int i=0; i<num_trains; i++)
{
trains[i] = Train(global_map, num_stops, train_pos[2*i],
train_pos[(2*i) + 1], names[i]);
}
}
bool verify_valid_routes(Train* trains, int num_trains, int* destinations, node_info* global_map)
{
for(int i = 0; i<num_trains; i++)
{
if(trains[i].determine_route(destinations[i], global_map) == false)
{
return false;
}
}
return true;
}
bool run_train_simulation(node_info* global_map, Train* trains, int num_trains, int delay_time)
{
bool destination_reached = true;
bool trains_in_gridlock = true;
for(int i = 0; i<num_trains; i++)
{
destination_reached = destination_reached & trains[i].move_train(global_map);
}
if(destination_reached == true)
{
for(int i = 0; i<num_trains; i++)
{
trains[i].display_train_position();
}
return true;
}
for(int i = 0; i<num_trains; i++)
{
trains[i].display_train_position();
}
cout << endl;
for(int i = 0; i<num_trains; i++)
{
trains_in_gridlock = trains_in_gridlock & trains[i].is_train_waiting();
}
if(trains_in_gridlock == true)
{
cout << "Trains in gridlock" << endl;
return true;
}
std::this_thread::sleep_for(std::chrono::milliseconds(delay_time));
return false;
} | true |
47df7bfe7a3ffd1cbec0e73e81bcc8f39c717154 | C++ | derekzhang79/Algorithm-Training | /ACM模板/数学/素数/素数筛选和合数分解.cpp | UTF-8 | 869 | 2.578125 | 3 | [] | no_license | #include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
//素数筛选和合数分解
const int maxn = 1e4;
int prime[maxn+1];
void getPrime()
{
memset(prime,0,sizeof(prime));
for(int i=2;i<=maxn;i++)
{
if(!prime[i]) prime[++prime[0]] = i;
for(int j=1;j<=prime[0] && prime[j]<=maxn/i;j++)
{
prime[prime[j]*i] = 1;
if(i%prime[j]==0) break;
}
}
}
long long factor[100][2];
int fatCnt;
int getFactors(long long x)
{
fatCnt = 0;
long long tmp = x;
for(int i=1;prime[i]<=tmp/prime[i];i++)
{
factor[fatCnt][1] = 0;
if(tmp%prime[i]==0)
{
factor[fatCnt][0] = prime[i];
while(tmp%prime[i]==0)
{
factor[fatCnt][1]++;
tmp /= prime[i];
}
fatCnt++;
}
}
if(tmp!=1)
{
factor[fatCnt][0] = tmp;
factor[fatCnt][1] = 1;
}
return fatCnt;
}
int main()
{
return 0;
} | true |
7cc90fccc37520bc34d22a4b54be1c80f362c254 | C++ | SteinVR/DoublePend | /DoublePGL/DoublePGL/Main.cpp | WINDOWS-1251 | 4,988 | 2.625 | 3 | [] | no_license | #include <stdio.h>
#include "freeglut.h"
#define _USE_MATH_DEFINES
#include <cmath>
#include <iostream>
const double m1 = 1; // 1-
const double m2 = 1; // 2-
const double l1 = 1; // 1-
const double l2 = 1; // 2-
const double g = 9.8;
const double initialfi1 = M_PI / 3; // 1-
const double initialfi2 = M_PI / 6; // 2-
const double initialp1 = 0; // 1-
const double initialp2 = 0; // 2-
const int h = 800; //
const double k = h / 3; //
const double a = (m1 / 3 + m2) * pow(l1, 2);
const double b = m2 * pow(l2, 2) / 3;
const double c = m2 * l1 * l2 / 2;
const double y = (m1 / 2 + m2) * g * l1;
const double e = m2 * g * l2 / 2;
//const int n = 100;
double Fi1(double t, double fi1, double fi2, double p1, double p2) {
return((b * p1 - c * p2 * cos(fi1 - fi2)) / (a * b - pow(c * cos(fi1 - fi2), 2)));
}
double Fi2(double t, double fi1, double fi2, double p1, double p2) {
return((a * p2 - c * p1 * cos(fi1 - fi2)) / (a * b - pow(c * cos(fi1 - fi2), 2)));
}
double P1(double t, double fi1, double fi2, double p1, double p2) {
return(-c * Fi1(t, fi1, fi2, p1, p2) * Fi2(t, fi1, fi2, p1, p2) * sin(fi1 - fi2) - y * sin(fi1));
}
double P2(double t, double fi1, double fi2, double p1, double p2) {
return(c * Fi1(t, fi1, fi2, p1, p2) * Fi2(t, fi1, fi2, p1, p2) * sin(fi1 - fi2) - e * sin(fi2));
}
struct Size
{
float w;
float h;
};
Size size = { 1200, 800 };
struct Coord
{
double x1;
double x2;
double y1;
double y2;
};
Coord pos = { 0, 0, 0, 0 };
void reshape(int w, int h)
{
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0, w, 0, h);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
void display()
{
glClear(GL_COLOR_BUFFER_BIT);
glPointSize(10);
glBegin(GL_POINTS);
glVertex2f(size.w / 2, size.h);
glVertex2f(pos.x1, pos.y1);
glVertex2f(pos.x2, pos.y2);
glEnd();
glLineWidth(5);
glBegin(GL_LINE_STRIP);
glColor3f(1.0, 1.0, 1.0);
glVertex2f(size.w / 2, size.h);
glVertex2f(pos.x1, pos.y1);
glVertex2f(pos.x2, pos.y2);
glEnd();
glutSwapBuffers();
}
double k1, k2, k3, k4, r1, r2, r3, r4, h1, h2, h3, h4, g1, g2, g3, g4, dt;
double t = 0;
double end = 10;
double fi1 = initialfi1;
double fi2 = initialfi2;
double p1 = initialp1;
double p2 = initialp2;
void time(int=0)
{
//
dt = 0.01;
k1 = dt * Fi1(t, fi1, fi2, p1, p2);
r1 = dt * Fi2(t, fi1, fi2, p1, p2);
h1 = dt * P1(t, fi1, fi2, p1, p2);
g1 = dt * P2(t, fi1, fi2, p1, p2);
k2 = dt * Fi1(t + dt / 2, fi1 + k1 / 2, fi2 + r1 / 2, p1 + h1 / 2, p2 + g1 / 2);
r2 = dt * Fi2(t + dt / 2, fi1 + k1 / 2, fi2 + r1 / 2, p1 + h1 / 2, p2 + g1 / 2);
h2 = dt * P1(t + dt / 2, fi1 + k1 / 2, fi2 + r1 / 2, p1 + h1 / 2, p2 + g1 / 2);
g2 = dt * P2(t + dt / 2, fi1 + k1 / 2, fi2 + r1 / 2, p1 + h1 / 2, p2 + g1 / 2);
k3 = dt * Fi1(t + dt / 2, fi1 + k2 / 2, fi2 + r2 / 2, p1 + h2 / 2, p2 + g2 / 2);
r3 = dt * Fi2(t + dt / 2, fi1 + k2 / 2, fi2 + r2 / 2, p1 + h2 / 2, p2 + g2 / 2);
h3 = dt * P1(t + dt / 2, fi1 + k2 / 2, fi2 + r2 / 2, p1 + h2 / 2, p2 + g2 / 2);
g3 = dt * P2(t + dt / 2, fi1 + k2 / 2, fi2 + r2 / 2, p1 + h2 / 2, p2 + g2 / 2);
k4 = dt * Fi1(t + dt, fi1 + k3, fi2 + r3, p1 + h3, p2 + g3);
r4 = dt * Fi2(t + dt, fi1 + k3, fi2 + r3, p1 + h3, p2 + g3);
h4 = dt * P1(t + dt, fi1 + k3, fi2 + r3, p1 + h3, p2 + g3);
g4 = dt * P2(t + dt, fi1 + k3, fi2 + r3, p1 + h3, p2 + g3);
fi1 += (k1 + k2 / 2 + k3 / 2 + k4) / 6;
fi2 += (r1 + r2 / 2 + r3 / 2 + r4) / 6;
p1 += (h1 + h2 / 2 + h3 / 2 + h4) / 6;
p2 += (g1 + g2 / 2 + g3 / 2 + g4) / 6;
t += dt;
pos.x1 = k * l1 * sin(fi1) + size.w / 2;
pos.y1 = -k * l1 * cos(fi1) + size.h;
pos.x2 = k * (l1 * sin(fi1) + l2 * sin(fi2)) + size.w / 2;
pos.y2 = k * (-l1 * cos(fi1) - l2 * cos(fi2)) + size.h;
display();
glutTimerFunc(10, time, 0);
}
int main(int argc, char* argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA);
glutInitWindowSize(size.w, size.h);
glutCreateWindow("DoubleP");
glutReshapeFunc(reshape);
glutDisplayFunc(display);
time();
glutMainLoop();
return 0;
} | true |
6ec483f88c3c254beaa3812ac29fa8e05d05d00c | C++ | liuzhengzhe/leetcode | /26.cpp | UTF-8 | 378 | 2.671875 | 3 | [] | no_license | class Solution {
public:
int removeDuplicates(int A[], int n) {
int len=1;
if(!n){
return NULL;
}
if(n==1){
return 1;
}
for(int i=1;i<n;i++){
if(A[i]!=A[i-1]){
A[len]=A[i];
len++;
}
}
return len;
}
}; | true |
4a1af8657482c170c07395a4515df20e376b0223 | C++ | utcoupe/Coupe2012 | /executables/visio/tests/visio_detector/Perspective.cpp | UTF-8 | 5,011 | 2.84375 | 3 | [] | no_license | #include "Perspective.h"
using namespace cv;
void Perspective::calculateTransformation()
{
// proportions de l'échiquier en pixels
double chess_lengthX_01 = sqrt(
pow(src_vertices[1].x - src_vertices[0].x, 2) +
pow(src_vertices[1].y - src_vertices[0].y, 2) );
double chess_lengthY_02 = chess_lengthX_01 / cellsX * cellsY;
double xmin = 1;
double ymin = 1;
src_vertices[0] = Point2f(src_vertices[0].x + xmin, src_vertices[0].y + ymin);
src_vertices[1] = Point2f(src_vertices[1].x + xmin, src_vertices[1].y + ymin);
src_vertices[2] = Point2f(src_vertices[2].x + xmin, src_vertices[2].y + ymin);
src_vertices[3] = Point2f(src_vertices[3].x + xmin, src_vertices[3].y + ymin);
// plan caméra
int deplace = 200;
dst_vertices[0] = Point2f(src_vertices[0].x + deplace, src_vertices[0].y + deplace);
dst_vertices[1] = Point2f(src_vertices[1].x + deplace, src_vertices[0].y + deplace);
dst_vertices[2] = Point2f(src_vertices[0].x + deplace, src_vertices[0].y - chess_lengthY_02 + deplace);
dst_vertices[3] = Point2f(src_vertices[1].x + deplace, src_vertices[0].y - chess_lengthY_02 + deplace);
// dst_vertices[0] = Point2f(src_vertices[0].x, src_vertices[0].y);
// dst_vertices[1] = Point2f(src_vertices[0].x - chess_lengthX_01, src_vertices[0].y);
// dst_vertices[2] = Point2f(src_vertices[0].x, src_vertices[0].y - chess_lengthY_02);
// dst_vertices[3] = Point2f(src_vertices[0].x - chess_lengthX_01, src_vertices[0].y - chess_lengthY_02);
chess_x_mmBypixels = cellXmm / (chess_lengthX_01 / cellsX);
chess_y_mmBypixels = cellYmm / (chess_lengthY_02 / cellsY);
// on calcule la perspective avec le plan trouvé
chessWarpMatrix = getPerspectiveTransform(src_vertices, dst_vertices);
};
// cellsX >= 2 && cellsY >= 2
Perspective::Perspective(int cellsX, int cellsY, float cellXmm, float cellYmm) {
this->cellsX = cellsX;
this->cellsY = cellsY;
this->chess_board_size = Size(cellsX, cellsY);
this->cellXmm = cellXmm;
this->cellYmm = cellYmm;
// par défaut on fait aucune transformation
reset();
};
// Trouve l'échiquier dans l'image n&b ou couleur
bool Perspective::findChessboard(Mat &img)
{
chess_found = findChessboardCorners(img, chess_board_size, chess_cells_points_found);
if (chess_found) {
src_vertices[0] = chess_cells_points_found[0];
src_vertices[1] = chess_cells_points_found[4];
src_vertices[2] = chess_cells_points_found[15];
src_vertices[3] = chess_cells_points_found[19];
calculateTransformation();
}
// drawChessboardCorners: affiche l'échiquier trouvé
// drawChessboardCorners(pyr, chess_board_size, Mat(chess_cells_points_found), chess_found);
return chess_found;
};
bool Perspective::ready()
{
return chess_found; // ready do to perspective
};
void Perspective::reset()
{
chess_found = false;
// ici on initialise avec les mêmes plans
// donc le changement de perspective de fait rien
this->src_vertices[0] = Point(0, 0);
this->src_vertices[1] = Point(10, 0);
this->src_vertices[2] = Point(10, 10);
this->src_vertices[3] = Point(0, 10);
this->dst_vertices[0] = Point(0, 0);
this->dst_vertices[1] = Point(10, 0);
this->dst_vertices[2] = Point(10, 10);
this->dst_vertices[3] = Point(0, 10);
// on initialise la matrix pour éviter un pointeur null
this->chessWarpMatrix = getPerspectiveTransform(src_vertices, dst_vertices);
};
// Affiche les 4 bords de l'échiquier sur l'image donnée
void Perspective::drawBorders(Mat &img)
{
circle(img, src_vertices[0], 9, Scalar(255, 0, 0), -1, 8, 0 );
circle(img, src_vertices[1], 9, Scalar(0, 255, 0), -1, 8, 0 );
circle(img, src_vertices[2], 9, Scalar(0, 255, 0), -1, 8, 0 );
//circle(img, src_vertices[3], 9, Scalar(0, 0, 0), -1, 8, 0 );
putText(img, "0", src_vertices[0], FONT_HERSHEY_SIMPLEX, 0.3, Scalar(255, 255, 255));
putText(img, "1 X", src_vertices[1], FONT_HERSHEY_SIMPLEX, 0.3, Scalar(255, 255, 255));
putText(img, "2 Y", src_vertices[2], FONT_HERSHEY_SIMPLEX, 0.3, Scalar(255, 255, 255));
//putText(img, "3", src_vertices[3], FONT_HERSHEY_SIMPLEX, 0.3, Scalar(255, 255, 255));
};
// Redresse le plan de l'image donnée à celui de la caméra
void Perspective::wrapPerspective(Mat &in, Mat &out)
{
int multi = 3;
CvPoint p;
p.x = -3;
p.y = -1;
warpPerspective(in, out, chessWarpMatrix, Size(in.cols*multi, in.rows*multi), INTER_LINEAR, BORDER_CONSTANT);
// BORDER_CONSTANT => bordures noires
// BORDER_WRAP => mozaik
// BORDER_REFLECT_101 => mozaik mirroire
// BORDER_TRANSPARENT => touche pas au fond
};
// Calcule la position du pixel donné de l'image redressée par rapport
// à l'origine de l'échiquier, le tout en milimètre.
CvPoint2D32f Perspective::realDistanceToChessOrigin(Point imagePoint)
{
float mmX = abs(imagePoint.x - dst_vertices[0].x) * chess_x_mmBypixels;
float mmY = abs(imagePoint.y - dst_vertices[0].y) * chess_y_mmBypixels;
CvPoint2D32f realPoint;
realPoint.x = mmX;
realPoint.y = mmY;
return realPoint;
};
| true |
f306419d158352b0d6acbc4c1a591b62eb6e2968 | C++ | DaeunOh/ALGORITHM | /AlgorithmJobs/[24] Exam/[BF]놀이공원.cpp | UTF-8 | 3,398 | 3.21875 | 3 | [] | no_license | // 소요시간: 35분
/*
문제
알랩놀이공원 입구에는 10개의 매표소가 있다. 놀이공원에 손님이 많지 않은 탓에 날마다 문을 여는 매표소의 개수는 다르다.
1 개의 매표소에서 손님 1 명을 입장 시키는데 1 분이 걸린다.
경비원 유니는 입구에서 손님들이 올 때마다, 최대한 빠르게 입장할 수 있도록 줄을 적게 서있는 매표소로 안내하고 있다.
단체손님은 같은 매표소로 안내해주며, 단체손님 또한 1명 당 1분의 입장시간이 소요된다.
이 1분의 시간은 줄을 서는데 부터 입장하는데 까지 걸린 총 시간이다.
유니가 줄을 배정하는데에는 시간이 소요되지 않는다고 가정한다.
손님 그룹의 개수, 문을 연 매표소의 수, 각 그룹 손님의 인원이 주어질 때
가장 빠르게 입장시키는 방법의 소요시간을 출력하는 프로그램을 만드시오.
입력
첫째 줄에 손님 그룹의 개수 N 과 문을 연 매표소 K 가 정수로 주어진다.
둘째 줄 부터 N 줄 만큼 각 그룹의 손님수가 유니에게 도착한 순서대로 주어진다. 그룹은 입력된 순서대로 매표소에 줄을 선다.
( 1 ≤ N ≤ 1,000 , 1 ≤ K ≤ 10 , 1 ≤ 각 그룹의 손님 수 ≤ 100 )
출력
입장에 소요되는 최소 시간(분)을 출력 하시오.
예제 입력 1
5 2
4
3
5
2
8
예제 출력 1
14
예제 입력 2
8 4
5
4
2
3
5
7
8
9
예제 출력 2
14
*/
/*
구현 자체는 어렵지 않은데 어떤 방법을 고를지 결정하는 게 오래 걸렸던 문제.
기존에 풀었던 방법처럼 비어있는 상점에 한 그룹씩 입장시키면서 시간을 증가시키고,
특정 시간이 되면 다른 그룹을 들여 보내는 방식을 사용해도 됐지만,
이 문제는 입장 시간이 따로 정해져있지 않기에 조금 더 쉽게 풀 수 있으리라 생각했다.
결과적으로 그 방법보다 훨씬 더 간결하고 쉬운 코드를 짤 수 있게 되었고, 수행 단계는 다음과 같다.
1) K개의 상점을 모두 보면서 비어있는 상점이 있다면 그룹 순서대로 해당 상점에 입장시킨다.
2) 또한, 각 상점에는 그룹의 수가 쓰여있는데, 모든 상점을 봄과 동시에 최솟값도 함께 찾는다.
3) 최솟값이 갱신이 되지 않았다면 상점이 모두 다 비어있고, 대기 손님이 없다는 의미이므로 while문을 빠져 나간다.
4) 최솟값이 갱신 되었다면 현재 시간을 최솟값만큼 증가시키고, 모든 상점에 있는 손님의 수를 최솟값만큼 감소시킨다.
5) 최솟값이 갱신 되지 않을 때까지 1~4를 반복한다.
*/
#include <iostream>
using namespace std;
const int MAX = 10 + 10;
int N, K;
int group[1010];
int store[MAX] = {0, };
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cin >> N >> K;
for(int i=0; i<N; i++) cin >> group[i];
int idx = 0, t = 0;
int myMin;
while(1) {
myMin = 987987987;
for(int i=0; i<K; i++) {
if(!store[i] && idx < N) {
store[i] = group[idx++];
}
if(store[i] && myMin > store[i]) {
myMin = store[i];
}
}
if(myMin == 987987987) break;
t += myMin;
for(int i=0; i<K; i++) {
if(store[i]) store[i] -= myMin;
}
}
cout << t;
return 0;
} | true |
dd710c7fac45002af72dbb620c3b1126f5e4b2c0 | C++ | AgostonSzepessy/battle-of-oxshan | /Game.cpp | UTF-8 | 854 | 2.75 | 3 | [
"MIT"
] | permissive | #include "Game.hpp"
Game::Game()
{
window.create(sf::VideoMode(WIDTH, HEIGHT), "Game", sf::Style::Close);
window.setVerticalSyncEnabled(false);
accumulator = 0;
}
void Game::run()
{
init();
int prevTime = c.getElapsedTime().asMilliseconds();
int currentTime = 0;
while (window.isOpen())
{
currentTime = c.getElapsedTime().asMilliseconds();
accumulator += currentTime - prevTime;
prevTime = currentTime;
while (accumulator >= STEP.asMilliseconds())
{
accumulator -= STEP.asMilliseconds();
update();
}
draw();
}
}
void Game::init()
{
gsm.changeState(MenuState::build(&window, &gsm));
}
void Game::update()
{
// check if window is open or get a segfault
if (window.isOpen())
gsm.update();
}
void Game::draw()
{
// check if window is open or get a segfault
if (window.isOpen())
gsm.draw();
}
Game::~Game()
{
}
| true |
65e56e6ceafae2c0c93fb7239b451045f69379fe | C++ | jedrak/chesspp | /library/include/Field.h | UTF-8 | 390 | 2.640625 | 3 | [] | no_license | #ifndef GAME_FIELD_H
#define GAME_FIELD_H
#include "typedefs.h"
class Field {
private:
int x;
int y;
unitPtr unit;
boardPtr board;
public:
int getX() const;
int getY() const;
const unitPtr &getUnit() const;
void setUnit(const unitPtr &unit);
bool occupied() const;
Field(int x, int y);
std::string toString();
};
#endif //GAME_FIELD_H
| true |
23633e6ec7d9f3baea7a37e97a668a51ed96f488 | C++ | ProfDoof/CompilerComparisonCode | /c++/jacobiSolve/WIP/LinearContiguousStorage.hpp | UTF-8 | 1,207 | 2.984375 | 3 | [] | no_license | #ifndef LINEARCONTIGUOUSSTORAGE_HPP
#define LINEARCONTIGUOUSSTORAGE_HPP
#include "Storage.hpp"
template <typename GridT>
class LinearContiguousStorage: public Storage<GridT> {
protected:
size_t _lda;
public:
LinearContiguousStorage();
virtual ~LinearContiguousStorage();
size_t lda();
virtual void resize(size_t new_Ny, size_t new_Nx) = 0;
virtual GridT & operator()(size_t y, size_t x) const = 0;
};
template <typename GridT>
LinearContiguousStorage<GridT>::LinearContiguousStorage() {
#ifdef __DEBUG__
cout << "LinearContiguousStorage<GridT>::LinearContiguousStorage()" << endl;
#endif
this->_Ny = 0;
this->_Nx = 0;
this->_flatGrid = nullptr;
}
template <typename GridT>
LinearContiguousStorage<GridT>::~LinearContiguousStorage() {
#ifdef __DEBUG__
cout << "LinearContiguousStorage<GridT>::~LinearContiguousStorage()" << endl;
#endif
this->_Ny = 0;
this->_Nx = 0;
this->_flatGrid = nullptr;
}
template <typename GridT>
size_t LinearContiguousStorage<GridT>::lda() {
#ifdef __DEBUG__
cout << "size_t LinearContiguousStorage<GridT>::lda()" << endl;
#endif
return _lda;
}
#endif // LINEARCONTIGUOUSSTORAGE_HPP
| true |
d98e5c013d7e82b542e7fd9467bb21db9d8eefbd | C++ | Tchoks/pricing_option | /pricing_option/Matrix.h | UTF-8 | 671 | 3.140625 | 3 | [] | no_license | #pragma once
#include <vector>
template<class T>
class Matrix
{
public:
//Matrix(); // default constructor
Matrix(const int& rows, const int& cols, const T& value);
Matrix(const Matrix<T>& mat);
Matrix<T>& operator= (const Matrix<T>& mat);
std::vector<std::vector<T>> get_mat() const;
T& value(const int& row, const int& col);
//T& operator() (const int& row, const int& col);
//const T& operator() (const int& row, const int& col) const ;
/*T& operator[] (const std::int row);
const T& operator[] (const std::int row) const;
*/
//virtual ~Matrix();
private:
const int rows;
const int cols;
std::vector<std::vector<T>> data;
};
| true |
b3adc6111a142fd1ccf035b311a1fdc9bec6e007 | C++ | OmarAbdelrahman/solved-problems | /UVA/competitive_programming/chapter_2/Basic Data Structures/11360 - Have Fun With Matrices.cpp | UTF-8 | 2,035 | 3.4375 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
#include <vector>
#include <string>
using namespace std;
int matrix[10][10];
int sizeofMatrix;
bool IsTen(int);
bool IsNegative(int);
void Transpose();
void Increment();
void Decrement();
void ChangeRow(int, int);
void ChangeCol(int, int);
int main() {
char temp;
int numberofCases;
int numberofOrders;
string orders;
scanf("%d", &numberofCases);
for (int _Cases = 1; _Cases <= numberofCases; _Cases++) {
scanf("%d", &sizeofMatrix);
for (int i = 0; i < sizeofMatrix; i++)
for (int j = 0; j < sizeofMatrix; j++) {
cin >> temp;
matrix[i][j] = temp - '0';
}
scanf("%d", &numberofOrders);
for (int i = 0; i < numberofOrders; i++) {
cin >> orders;
if (orders == "transpose") {
Transpose();
} else if (orders == "inc") {
Increment();
} else if (orders == "dec") {
Decrement();
} else if (orders == "row") {
int r, c;
cin >> r >> c;
ChangeRow(r, c);
} else if (orders == "col") {
int r, c;
cin >> r >> c;
ChangeCol(r, c);
}
}
printf("Case #%d\n", _Cases);
for (int i = 0; i < sizeofMatrix; i++) {
for (int j = 0; j < sizeofMatrix; j++)
cout << matrix[i][j];
cout << endl;
}
cout << endl;
}
return 0;
}
bool IsTen(int n) {
return (n == 10);
}
bool IsNegative(int n) {
return (n < 0);
}
void Transpose() {
for (int i = 0; i < sizeofMatrix; i++)
for (int j = 0; j < sizeofMatrix; j++)
if (i != j) swap(matrix[i][j], matrix[j][i]);
}
void Increment() {
for (int i = 0; i < sizeofMatrix; i++)
for (int j = 0; j < sizeofMatrix; j++)
if (IsTen(++matrix[i][j])) matrix[i][j] = 0;
}
void Decrement() {
for (int i = 0; i < sizeofMatrix; i++)
for (int j = 0; j < sizeofMatrix; j++)
if (IsNegative(--matrix[i][j])) matrix[i][j] = 9;
}
void ChangeRow(int r1, int r2) {
for (int i = 0; i < sizeofMatrix; i++)
swap(matrix[r1 - 1][i], matrix[r2 - 1][i]);
}
void ChangeCol(int c1, int c2) {
for (int i = 0; i < sizeofMatrix; i++)
swap(matrix[i][c1 - 1], matrix[i][c2 - 1]);
} | true |