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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
3ede34ce7621d800b1cb279b0f351990d53b99bd | C++ | ruchika-swain/Data-networking-basic-codes | /data_networking/single_parity_check.cpp | UTF-8 | 804 | 3.5 | 4 | [] | no_license | /* to check if the given message has error or not considering last bit as parity bit and for even parity */
#include<bits/stdc++.h>
using namespace std;
int convertBinaryToDecimal(int n)
{
int decimalNumber = 0, i = 0, remainder;
while (n!=0)
{
remainder = n%10;
n /= 10;
decimalNumber += remainder*pow(2,i);
++i;
}
return decimalNumber;
}
bool get_parity(int n)
{
bool parity =0;
while (n)
{
parity=!parity;
n=n&(n-1);
}
return parity;
}
int main()
{
int n;
cin>>n;
int curr_parity=n&1;
n=convertBinaryToDecimal(n-curr_parity);
int actual_parity=get_parity(n);
cout<<"message has "<<(curr_parity==actual_parity?"no error":"error");
return 0;
} | true |
6496c359cc82b20aec3abfad8bbe9755bcac1302 | C++ | VARIACION/Student-Management-System | /Courses.cpp | UTF-8 | 10,134 | 3.375 | 3 | [] | no_license | #include "Courses.h"
Time::Time() {
this->minute = this->hour = -1;
}
int Time::getHour() { return this->hour; }
int Time::getMinute() { return this->minute; }
bool Time::setHour(const int & hourInput) {
if (hourInput < 7 || hourInput > 17)
return false;
this->hour = hourInput;
return true;
}
bool Time::setMinute(const int & minuteInput) {
if (minuteInput < 0 || minuteInput > 59)
return false;
this->minute = minuteInput;
return true;
}
bool Time::operator>(Time & timeCompare)
{
if (this->hour > timeCompare.getHour())
return true;
else if (this->hour < timeCompare.getHour())
return false;
else if (this->hour == timeCompare.getHour())
if (this->minute > timeCompare.getMinute())
return true;
return false;
}
bool Time::operator<(Time & timeCompare)
{
if (this->hour < timeCompare.getHour())
return true;
else if (this->hour > timeCompare.getHour())
return false;
else if (this->hour == timeCompare.getHour())
if (this->minute < timeCompare.getMinute())
return true;
return false;
}
bool Time::operator==(Time & timeCompare)
{
return (this->hour == timeCompare.getHour() && this->minute == timeCompare.getMinute());
}
Date::Date() {
this->day = this->month = this->year = 0;
}
int Date::getDay() { return this->day; }
int Date::getMonth() { return this->month; }
int Date::getYear() { return this->year; }
bool Date::setMonth(const int & monthInput) {
if (monthInput < 1 || monthInput > 12)
return false;
this->month = monthInput;
return true;
}
bool Date::setYear(const int & yearInput) {
struct tm newtime;
time_t now = time(0);
localtime_s(&newtime, &now);
if (yearInput < 2000 || yearInput > 1900 + newtime.tm_year)
return false;
this->year = yearInput;
return true;
}
bool Date::setDate(const int & dayInput) {
if (this->month == 0 || this->year == 0)
return false;
if (dayInput < 1)
return false;
switch (this->month) {
case 1: case 3: case 5: case 7: case 8: case 10: case 12:
if (dayInput <= 31) this->day = dayInput;
break;
case 4: case 6: case 9: case 11:
if (dayInput <= 30) this->day = dayInput;
break;
case 2:
if (this->year % 4 == 0 && this->year % 100 != 0 && dayInput <= 29)
this->day = dayInput;
else if (this->year % 400 == 0 && dayInput <= 29)
this->day = dayInput;
else if (dayInput <= 28)
this->day = dayInput;
else return false;
break;
}
return true;
}
bool Date::operator>(Date & dateCompare)
{
if (this->year > dateCompare.getYear())
return true;
else if (this->year < dateCompare.getYear())
return false;
else if (this->year == dateCompare.getYear())
if (this->month > dateCompare.getMonth())
return true;
else if (this->month < dateCompare.getMonth())
return false;
else if (this->month == dateCompare.getMonth())
if (this->day > dateCompare.getDay())
return true;
return false;
}
bool Date::operator<(Date & dateCompare)
{
if (this->year < dateCompare.getYear())
return true;
else if (this->year > dateCompare.getYear())
return false;
else if (this->year == dateCompare.getYear())
if (this->month < dateCompare.getMonth())
return true;
else if (this->month > dateCompare.getMonth())
return false;
else if (this->month == dateCompare.getMonth())
if (this->day < dateCompare.getDay())
return true;
return false;
}
bool Date::operator==(Date & dateCompare)
{
if (this->day == dateCompare.getDay() && this->month == dateCompare.getMonth() && this->year == dateCompare.getYear())
return true;
return false;
}
Courses::Courses() {
this->code = this->name = this->lecturerUsername = this->year = "";
this->semester = 1;
}
Courses::~Courses(){
}
void Courses::setCode(const string & codeInput) { this->code = codeInput; }
string Courses::getCode() { return this->code; }
void Courses::setName(const string & nameInput) { this->name = nameInput; }
string Courses::getName() { return this->name; }
void Courses::setLecturerUsername(const string & lecturerUsernameInput) { this->lecturerUsername = lecturerUsernameInput; }
string Courses::getLecturerUsername() { return this->lecturerUsername; }
bool Courses::setYear(const string & yearInput) {
struct tm newtime;
time_t now = time(0);
localtime_s(&newtime, &now);
try {
if (yearInput.substr(0, 4) == yearInput.substr(5, 4) ||
stoi(yearInput.substr(0, 4)) < 2000 || stoi(yearInput.substr(5, 4)) > 1900 + newtime.tm_year)
return false;
}
catch (const exception &error) {
ofstream error_message("errors_messages.log", ios::app);
error_message << error.what() << endl;
error_message.close();
return false;
}
this->year = yearInput;
return true;
}
string Courses::getYear() { return this->year; }
int Courses::getSemester() { return this->semester - '0'; }
bool Courses::setSemester(const char & semesterInput) {
if (semesterInput < '1' || semesterInput > '3')
return false;
this->semester = semesterInput;
return true;
}
Date Courses::getStartDate() { return this->start; }
bool Courses::setStartDate(Date & startDateInput) {
if (this->year == "")
return false;
try {
if (startDateInput.getYear() < stoi(this->year.substr(0, 4)) || startDateInput.getYear() > stoi(this->year.substr(0, 4)) + 1)
return false;
}
catch (const exception &error) {
ofstream error_message("errors_messages.log", ios::app);
error_message << error.what() << endl;
error_message.close();
return false;
}
this->start = startDateInput;
return true;
}
Date Courses::getEndDate() { return this->end; }
bool Courses::setEndDate(Date & endDateInput) {
if (this->year == "")
return false;
try {
if (endDateInput.getYear() < stoi(this->year.substr(0, 4)) || endDateInput.getYear() > stoi(this->year.substr(0, 4)) + 1)
return false;
}
catch (const exception &error) {
ofstream error_message("errors_messages.log", ios::app);
error_message << error.what() << endl;
error_message.close();
return false;
}
this->end = endDateInput;
return true;
}
Time Courses::getStartTime() { return this->from; }
bool Courses::setStartTime(string & startTimeInput) {
int hour, minute;
try {
hour = stoi(splitToken(startTimeInput, "h"));
minute = stoi(startTimeInput);
}
catch (exception &error) {
ofstream error_message("errors_messages.log", ios::app);
error_message << error.what() << endl;
error_message.close();
return false;
}
return (this->from.setHour(hour) && this->from.setMinute(minute));
}
Time Courses::getEndTime() { return this->to; }
string Courses::getStartTime_str() {
return to_string(this->from.getHour()) + "h" + to_string(this->from.getMinute());
}
string Courses::getEndTime_str() {
return to_string(this->to.getHour()) + "h" + to_string(this->to.getMinute());
}
bool Courses::setEndTime(string & endTimeInput) {
int hour, minute;
try {
hour = stoi(splitToken(endTimeInput, "h"));
minute = stoi(endTimeInput);
}
catch (const exception &error) {
ofstream error_message("errors_messages.log", ios::app);
error_message << error.what() << endl;
error_message.close();
return false;
}
return (this->to.setHour(hour) && this->to.setMinute(minute));
}
bool Courses::setDateOfWeek(const string &dayStart) {
if (dayStart == "MONDAY")
this->dateOfWeek = MONDAY;
else if (dayStart == "TUESDAY")
this->dateOfWeek = TUESDAY;
else if (dayStart == "WEDNESDAY")
this->dateOfWeek = WEDNESDAY;
else if (dayStart == "THURSDAY")
this->dateOfWeek = THURSDAY;
else if (dayStart == "FRIDAY")
this->dateOfWeek = FRIDAY;
else if (dayStart == "SATURDAY")
this->dateOfWeek = SATURDAY;
else if (dayStart == "SUNDAY")
this->dateOfWeek = SUNDAY;
else return false;
return true;
}
Week Courses::getDateOfWeek() { return this->dateOfWeek; }
ListCourses::~ListCourses() {
this->list.clear();
}
string Courses::getStartDate_str() {
return to_string(this->start.getDay()) + "/" + to_string(this->start.getMonth()) + "/" + to_string(this->start.getYear());
}
string Courses::getEndDate_str() {
return to_string(this->end.getDay()) + "/" + to_string(this->end.getMonth()) + "/" + to_string(this->end.getYear());
}
string Courses::getDateOfWeek_str() {
switch (this->dateOfWeek) {
case MONDAY:
return "MONDAY";
case TUESDAY:
return "TUESDAY";
case WEDNESDAY:
return "WEDNESDAY";
case THURSDAY:
return "THURSDAY";
case FRIDAY:
return "FRIDAY";
case SATURDAY:
return "SATURDAY";
case SUNDAY:
return "SUNDAY";
}
return "";
}
bool Courses::setStartDate_str(string & startDataInput) {
string day = splitToken(startDataInput, "/");
string month = splitToken(startDataInput, "/");
Date checkDate;
try {
checkDate.setYear(stoi(startDataInput));
checkDate.setMonth(stoi(month));
checkDate.setDate(stoi(day));
}
catch (const exception &error) {
ofstream error_message("errors_messages.log", ios::app);
error_message << error.what() << endl;
error_message.close();
return false;
}
return this->setStartDate(checkDate);
}
bool Courses::setEndDate_str(string & endDataInput) {
string day = splitToken(endDataInput, "/");
string month = splitToken(endDataInput, "/");
Date checkDate;
try {
checkDate.setYear(stoi(endDataInput));
checkDate.setMonth(stoi(month));
checkDate.setDate(stoi(day));
}
catch (const exception &error) {
ofstream error_message("errors_messages.log", ios::app);
error_message << error.what() << endl;
error_message.close();
return false;
}
return this->setEndDate(checkDate);
}
bool Courses::compareStartEndDate() {
if (this->start > this->end)
return true;
else
return false;
}
bool Courses::compareStartEndTime()
{
if (this->from > this->to)
return true;
else
return false;
} | true |
01e03e5c7deb696acfe0957d6e123819026fd9e9 | C++ | faterazer/LeetCode | /0592. Fraction Addition and Subtraction/Solution.cpp | UTF-8 | 1,600 | 3.359375 | 3 | [] | no_license | #include <numeric>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
class Solution {
public:
string fractionAddition_MK1(string expression)
{
expression.push_back('+');
int numerator1 = 0, denominator1 = 1, sign = 1, numerator2 = 0, denominator2 = 0, num = 0;
int i = 0, n = expression.size();
if (expression[i] == '+' || expression[i] == '-')
if (expression[i++] == '-')
sign = -1;
while (i < n) {
if (expression[i] == '+' || expression[i] == '-') {
denominator2 = num;
num = 0;
numerator1 = numerator1 * denominator2 + sign * numerator2 * denominator1;
denominator1 *= denominator2;
sign = expression[i] == '+' ? 1 : -1;
} else if (expression[i] == '/') {
numerator2 = num;
num = 0;
} else {
num = num * 10 + expression[i] - '0';
}
++i;
}
if (numerator1 == 0)
return "0/1";
int g = gcd(numerator1, denominator1);
return to_string(numerator1 / g) + "/" + to_string(denominator1 / g);
}
string fractionAddition_MK2(string expression)
{
istringstream in(expression);
int A = 0, B = 1, a, b;
char _;
while (in >> a >> _ >> b) {
A = A * b + a * B;
B *= b;
int g = gcd(A, B);
A /= g;
B /= g;
}
return to_string(A) + '/' + to_string(B);
}
};
| true |
3e1c5ee80f3e0561c416cc3a609552de5e96b0b9 | C++ | brendankeesing/Collision-Detection | /CollisionDetection/CollisionFrustum.cpp | UTF-8 | 3,325 | 2.921875 | 3 | [
"Unlicense"
] | permissive | #include "CollisionFrustum.h"
static void trasformperspective(MthVector3& out, const MthVector3& point, const MthMatrix& mat)
{
MthVector4 temppoint(point.x, point.y, point.z, 1.0f);
MthVector4 tempout;
mat.Transform(tempout, temppoint);
out = (MthVector3&)tempout * (1.0f / tempout.w);
}
void CollisionFrustum::GetCenterPoint(MthVector3& out) const
{
// calculates the average of all vertices
out = MthVector3(0.0f, 0.0f, 0.0f);
for (int i = 0; i < 8; ++i)
out += _vertices[i];
out *= 1.0f / 6.0f;
}
float CollisionFrustum::GetFurthestDistance(const MthVector3& point) const
{
float furthestdist = _vertices[0].LengthSqr();
float temp;
for (int i = 1; i < 6; ++i)
{
temp = _vertices[i].LengthSqr();
if (temp > furthestdist)
furthestdist = temp;
}
return sqrtf(furthestdist);
}
bool CollisionFrustum::IntersectAABB(const MthVector3& p, const MthVector3& dimensions) const
{
for (int i = 0; i < 6; ++i)
{
MthVector3 cp(_planes[i].a > 0.0f ? p.x - dimensions.x : p.x + dimensions.x,
_planes[i].b > 0.0f ? p.y - dimensions.y : p.y + dimensions.y,
_planes[i].c > 0.0f ? p.z - dimensions.z : p.z + dimensions.z);
float distance =_planes[i].a * cp.x + _planes[i].b * cp.y + _planes[i].c * cp.z + _planes[i].d;
if (distance >= 0.0f)
return false;
}
return true;
}
bool CollisionFrustum::IntersectPoint(const MthVector3& p) const
{
for (int i = 0; i < 6; ++i)
{
float distance =_planes[i].a * p.x + _planes[i].b * p.y + _planes[i].c * p.z + _planes[i].d;
if (distance >= 0.0f)
return false;
}
return true;
}
bool CollisionFrustum::IntersectSphere(const MthVector3& p, float radius) const
{
for (int i = 0; i < 6; ++i)
{
float distance =_planes[i].a * p.x + _planes[i].b * p.y + _planes[i].c * p.z + _planes[i].d;
if (distance >= radius)
return false;
}
return true;
}
void CollisionFrustum::Recalculate(const MthMatrix& viewprojection)
{
MthMatrix invviewprojection;
if (!invviewprojection.Inverse(viewprojection))
return;
// front/near verts
trasformperspective(_vertices[0], MthVector3(-1.0f, -1.0f, 0.0f), invviewprojection);
trasformperspective(_vertices[1], MthVector3(-1.0f, 1.0f, 0.0f), invviewprojection);
trasformperspective(_vertices[2], MthVector3( 1.0f, 1.0f, 0.0f), invviewprojection);
trasformperspective(_vertices[3], MthVector3( 1.0f, -1.0f, 0.0f), invviewprojection);
// back/far verts
trasformperspective(_vertices[4], MthVector3(-1.0f, -1.0f, 1.0f), invviewprojection);
trasformperspective(_vertices[5], MthVector3(-1.0f, 1.0f, 1.0f), invviewprojection);
trasformperspective(_vertices[6], MthVector3( 1.0f, 1.0f, 1.0f), invviewprojection);
trasformperspective(_vertices[7], MthVector3( 1.0f, -1.0f, 1.0f), invviewprojection);
_calculatefromvertices();
}
void CollisionFrustum::_calculatefromvertices()
{
_planes[0].FromPoints(_vertices[0], _vertices[1], _vertices[2]); // front
_planes[1].FromPoints(_vertices[4], _vertices[6], _vertices[5]); // back
_planes[2].FromPoints(_vertices[0], _vertices[4], _vertices[1]); // left
_planes[3].FromPoints(_vertices[2], _vertices[6], _vertices[3]); // right
_planes[4].FromPoints(_vertices[1], _vertices[5], _vertices[2]); // top
_planes[5].FromPoints(_vertices[0], _vertices[3], _vertices[4]); // bottom
for (int i = 0; i < 6; ++i)
_planes[i].Normalize();
} | true |
6c910b7e98b8d21fe30f2e2bdc70f4d3c4c38d86 | C++ | petru-d/leetcode-solutions-reboot | /problems/p845.h | UTF-8 | 1,845 | 3.25 | 3 | [] | no_license | #pragma once
#include <vector>
namespace p845
{
class Solution
{
public:
int longestMountain(std::vector<int>& A)
{
auto AA = A.size();
if (AA < 3)
return 0;
enum class State
{
Ascending,
Descending
};
size_t best_mountain = 0;
State s = State::Ascending;
size_t mountain_start = 0;
while (mountain_start < AA - 1 && A[mountain_start] >= A[mountain_start + 1])
++mountain_start;
for (size_t i = mountain_start + 1; i < AA; ++i)
{
if (A[i - 1] < A[i])
{
if (s == State::Descending)
{
best_mountain = std::max(best_mountain, i - mountain_start);
mountain_start = i - 1;
s = State::Ascending;
}
}
else if (A[i - 1] > A[i])
{
if (s == State::Ascending)
s = State::Descending;
}
else
{
if (s == State::Descending)
{
best_mountain = std::max(best_mountain, i - mountain_start);
}
while (i < AA && A[i - 1] >= A[i])
++i;
mountain_start = i - 1;
s = State::Ascending;
}
}
if (s == State::Descending)
best_mountain = std::max(best_mountain, AA - mountain_start);
if (best_mountain < 3)
best_mountain = 0;
return int(best_mountain);
}
};
}
| true |
a196dd49d2a580d90270d5c51e29cf65393236e3 | C++ | BUCTdarkness/JiyiShen-s-Coding | /LeetCode/Unique Binary Search Trees.cpp | UTF-8 | 560 | 2.828125 | 3 | [] | no_license | class Solution
{
public:
int f[1010][1010];
int getv(int begin,int end)
{
if(begin>end)
return 1;
return f[begin][end];
}
int numTrees(int n)
{
for(int i=0;i<n;i++)
{
f[i][i]=1;
}
for(int len=2;len<=n;len++)
{
for(int begin=0;begin<n;begin++)
{
int end=begin+len-1;
if(end>=n)
break;
f[begin][end]=0;
for(int mid=begin;mid<=end;mid++)
{
f[begin][end]+=getv(begin,mid-1)*getv(mid+1,end);
}
}
}
return f[0][n-1];
}
};
| true |
fef6be29cf57631fc69ce15c1e6516d04f897f6b | C++ | katasanirohith/HackerRankCodes | /Stick cutting.cpp | UTF-8 | 474 | 2.6875 | 3 | [] | no_license | #include <iostream>
#include <stdlib.h>
using namespace std;
int main()
{
cout<<INT_MAX;
int n;
cin>>n;
int a[n];
int min=INT_MAX;
for(int i=0;i<n;i++)
{
cin>>a[i];
}
int index=n;
//cout<<n<<endl;
int count=0;
while(index>0)
{
cout<<index<<endl;
min=INT_MAX;
for(int i=0;i<n;i++)
{
if(min>a[i])
{
min=a[i];
}
}
for(int i=0;i<n;i++)
{
if(a[i]==min)
{
index--;
a[i]=INT_MAX;
}
else
{
a[i]=a[i]-min;
}
}
}
}
| true |
6b0741322645d9d886bb354ff7490816d74cbb3d | C++ | newdeal123/BOJ | /Greedy Algorithm(그리디 알고리즘)/1080_행렬.cpp | UTF-8 | 791 | 2.53125 | 3 | [] | no_license | #include <iostream>
using namespace std;
const int MAX_N = 50 + 2;
#pragma warning(disable:4996)
int main()
{
int N, M, cnt = 0;
cin >> N >> M;
int board1[MAX_N][MAX_N], board2[MAX_N][MAX_N];
for (int i = 1; i <= N; i++)
for (int j = 1; j <= M; j++)
scanf("%1d", &board1[i][j]);
for (int i = 1; i <= N; i++)
for (int j = 1; j <= M; j++)
scanf("%1d", &board2[i][j]);
for (int i = 1; i <= N - 2; i++)
for (int j = 1; j <= M - 2; j++)
{
if (board1[i][j] == board2[i][j])
continue;
cnt++;
for (int y = i; y < i + 3; y++)
for (int x = j; x < j + 3; x++)
board1[y][x] = abs(1 - board1[y][x]);
}
for (int i = 1; i <= N; i++)
for (int j = 1; j <= M; j++)
if (board1[i][j] != board2[i][j])
{
cout << "-1";
return 0;
}
cout << cnt;
} | true |
c2803ffb524719704084c6f672ce5a57af76958d | C++ | gfunk0704/FinancialEngineering | /FinancialEngineering/quote.h | UTF-8 | 390 | 2.625 | 3 | [] | no_license | #pragma once
#include <calendar.h>
#include <period.h>
#include <global_variable.h>
namespace FinancialEngineering
{
class Quote
{
public:
Quote(Date, Real, SharedPointer<Calendar>);
Quote(Real, SharedPointer<Calendar>);
Real value();
protected:
SharedPointer<Calendar> _calendar;
Date _value_date;
Real _value;
};
inline Real Quote::value()
{
return _value;
}
}
| true |
678b0117de7b16431efc8e6c6d82abbe129a9c36 | C++ | rrkarim/neerc | /leet/sudoku_solver.cpp | UTF-8 | 1,794 | 3 | 3 | [] | no_license | /*
Sudoku Solver
*/
class Solution {
public:
unordered_map<int, int> mp_c, mp_r, mp_b;
int ind[10][10];
int box(int i, int j) {
int a = i / 3, b = j / 3;
return 3*a+b;
}
bool solve(vector <vector <char>>& board) {
int r = -1, c = -1, cx = 0;
for(int i = 0; i < board.size(); ++i) {
for(int j = 0; j < board.size(); ++j) {
if(board[i][j] == '.') {
r = i, c = j, cx = 1;
break;
}
}
if(cx) break;
}
if(r == -1 && c == -1) return 1;
int t = mp_c[r] | mp_r[c] | mp_b[ind[r][c]];
for(int num = 1; num <= 9; ++num) {
if((t & (1 << (num - 1))) == 0) {
board[r][c] = num + '0';
mp_c[r] |= 1 << (num-1), mp_r[c] |= 1 << (num-1), mp_b[ ind[r][c] ] |= 1 << (num-1);
if(solve(board)) return true;
board[r][c] = '.';
int x = 0;
for(int z = 0; z < 9; ++z) {
if(z == (num - 1)) continue;
x |= (1 << z);
}
mp_c[r] &= x, mp_r[c] &= x, mp_b[ ind[r][c] ] &= x;
}
}
return 0;
}
void solveSudoku(vector<vector<char>>& board) {
int n = board.size();
for(int i = 0; i < n; ++i) for(int j = 0; j < n; ++j) ind[i][j] = box(i, j);
for(int i = 0; i < n; ++i) {
for(int j = 0; j < n; ++j) {
if(board[i][j] != '.') {
int x = (board[i][j]-'0')-1;
mp_c[i] |= 1 << x;
mp_r[j] |= 1 << x;
mp_b[ ind[i][j] ] |= (1 << x);
}
}
}
solve(board);
}
}; | true |
357ec606e910322273d5f9def63a2576c2a16da7 | C++ | st076569/MatMex_MMM_Programming | /Semester_3/03.09.2020/Program_2/source/raidlib.cpp | UTF-8 | 8,319 | 2.703125 | 3 | [] | no_license | ////////// RAID 5 ////////////////////////////////////////////////////////////
// Автор : Баталов Семен //
// Дата : 10.09.2020 //
// Задача : Решить задачу с помощью STL. Эффективно смоделировать RAID 5, //
// для k буферов размера n кБайт. Технология использует //
// контрольные суммы для восстановления данных в случае выхода из //
// строя одного жёсткого диска. Нужно проделать тоже самое, только //
// на буферах (массивах фиксированной длины). В моделировании //
// нужно заполнить несколько буферов данных, по ним построить //
// буфер контрольных сумм. Затем выбрать случайным образом один из //
// буферов, как исчезнувший. После восстановить исчезнувшие данные //
// и сравнить восстановленные данные с настоящими. //
//////////////////////////////////////////////////////////////////////////////
#include "raidlib.h"
////////// struct Buffer /////////////////////////////////////////////////////
// Эта структура представляет из себя буфер, состоящий из битовых //
// блоков и являющийся элементом массива RAID. //
//////////////////////////////////////////////////////////////////////////////
// (1) Конструктор
bat::Buffer::Buffer()
{
blocks.clear();
isCrashed = false;
}
// (2) Конструктор копирования
bat::Buffer::Buffer(const bat::Buffer& buffer)
{
*this = buffer;
}
// (3) Перегрузка оператора присваивания
bat::Buffer& bat::Buffer::operator=(const bat::Buffer& buffer)
{
// Проверка на самоприсваивание
if (this != &buffer)
{
isCrashed = buffer.isCrashed;
blocks = buffer.blocks;
}
return *this;
}
// (4) Вывод в консоль
void bat::Buffer::print()
{
if (isCrashed)
{
std::cout << "// STATUS : 'Crashed'\n";
}
else
{
std::cout << "// STATUS : 'Available'\n";
}
for (int i = 0; i < blocks.size(); ++i)
{
if (i < 10)
{
std::cout << "// [" << i << "] : ";
}
else
{
std::cout << "// [" << i << "] : ";
}
std::cout << blocks[i] << "\n";
}
}
// (5) Изменяет размер буфера
void bat::Buffer::resize(const int& blockNumber)
{
if (blockNumber >= 0)
{
blocks.resize(blockNumber);
}
}
// (6) Задает случайные значения
void bat::Buffer::setRandomValues()
{
reset();
for (int i = 0; i < blocks.size(); ++i)
{
for (int j = 0; j < bat::BLOCK_SIZE; ++j)
{
if (rand() % 2 == 0)
{
blocks[i].flip(j);
}
}
}
}
// (7) Сбрасывает значение статуса
void bat::Buffer::resetStatus()
{
isCrashed = false;
}
// (8) Сбрасывает значения всех битов до нуля
void bat::Buffer::reset()
{
for (int i = 0; i < blocks.size(); ++i)
{
blocks[i].reset();
}
resetStatus();
}
// (9) Очищает элементы буфера
void bat::Buffer::clear()
{
blocks.clear();
isCrashed = false;
}
// (10) Деструктор
bat::Buffer::~Buffer()
{
clear();
}
////////// class Raid5 ///////////////////////////////////////////////////////
// Этот класс представляет модель технологии "Raid 5". Она позволяет //
// быстро востанавливать данные в случае выхода из строя одного из //
// носителей. //
//////////////////////////////////////////////////////////////////////////////
// (1) Конструктор
bat::Raid5::Raid5()
{
buffers_.clear();
bufferNumber_ = 0;
bufferSize_ = 0;
}
// (2) Конструктор копирования
bat::Raid5::Raid5(const Raid5& raid5)
{
*this = raid5;
}
// (3) Перегрузка оператора присваивания
bat::Raid5& bat::Raid5::operator=(const bat::Raid5& raid5)
{
if (this != &raid5)
{
buffers_ = raid5.buffers_;
bufferNumber_ = raid5.bufferNumber_;
bufferSize_ = raid5.bufferSize_;
}
return *this;
}
// (4) Вывод в консоль
void bat::Raid5::print()
{
for (int i = 0; i < bufferNumber_; ++i)
{
std::cout << "////////////////////////////// Buffer (" << i << ")\n";
buffers_[i].print();
}
}
// (5) Изменяет размеры рейда
void bat::Raid5::resize(const int& buffferNumber, const int& bufferSize)
{
if (buffferNumber >= 0 && bufferSize >= 0)
{
buffers_.resize(buffferNumber);
for (int i = 0; i < buffferNumber; ++i)
{
buffers_[i].resize(bufferSize);
}
bufferNumber_ = buffferNumber;
bufferSize_ = bufferSize;
}
}
// (6) Задает случайные значения буферов
void bat::Raid5::setRandomValues()
{
for (int i = 0; i < bufferNumber_; ++i)
{
buffers_[i].setRandomValues();
}
}
// (7) Записать все контрольные суммы
void bat::Raid5::setControlSums()
{
int iBlock = 0;
Block temp;
for (int i = 0; i < bufferNumber_; ++i)
{
iBlock = i;
while (iBlock < bufferSize_)
{
temp.reset();
for (int j = 0; j < bufferNumber_; ++j)
{
if (j != i)
{
temp ^= buffers_[j].blocks[iBlock];
}
}
buffers_[i].blocks[iBlock] = temp;
iBlock += bufferNumber_;
}
}
}
// (8) Разрушить буфер под номером "bufferNumber"
void bat::Raid5::crashBuffer(const int& bufferNumber)
{
bool haveCrashedBuffer = false;
for (int i = 0; i < bufferNumber_ && !haveCrashedBuffer; ++i)
{
haveCrashedBuffer = buffers_[i].isCrashed;
}
if (bufferNumber >= 0 && bufferNumber < bufferNumber_ &&
!haveCrashedBuffer)
{
buffers_[bufferNumber].reset();
buffers_[bufferNumber].isCrashed = true;
}
}
// (9) Восстановить утраченную информацию
void bat::Raid5::recoverInformation()
{
int crashedCount = 0;
int crashedNumber = 0;
Block temp;
for (int i = 0; i < bufferNumber_; ++i)
{
if (buffers_[i].isCrashed)
{
++crashedCount;
crashedNumber = i;
}
}
if (crashedCount == 1)
{
for (int i = 0; i < bufferSize_; ++i)
{
temp.reset();
for (int j = 0; j < bufferNumber_; ++j)
{
if (j != crashedNumber)
{
temp ^= buffers_[j].blocks[i];
}
}
buffers_[crashedNumber].blocks[i] = temp;
}
resetStatuses();
}
}
// (10) Сбрасывает значения всех статусов
void bat::Raid5::resetStatuses()
{
for (int i = 0; i < bufferNumber_; ++i)
{
buffers_[i].resetStatus();
}
}
// (11) Сбрасывает значения всех битов до нуля
void bat::Raid5::reset()
{
for (int i = 0; i < bufferNumber_; ++i)
{
buffers_[i].reset();
}
}
// (12) Очищает элементы буфера
void bat::Raid5::clear()
{
buffers_.clear();
}
// (13) Деструктор
bat::Raid5::~Raid5()
{
clear();
} | true |
9836c73ef84587028b61f290bcfc2ab86b22a786 | C++ | vital228/Algorithm | /Popovich/Popovich/List.h | WINDOWS-1251 | 5,242 | 3.46875 | 3 | [] | no_license | #pragma once
#include <iostream>
#include <string>
#include "Node.h"
using namespace std;
template<class T>
class List
{
friend class Node<T>;
Node<T>* Head;
Node<T>* Tail;
int count;
public:
class Iterator
{
friend class List<T>;
Node<T>* it;
Iterator(Node<T>* ptr)
{
it = ptr;
}
public:
Iterator()
{
it = nullptr;
}
T& operator*()
{
return it->key;
}
bool operator==(const Iterator& iter)
{
return it == iter.it;
}
bool operator!=(const Iterator& iter)
{
return it != iter.it;
}
Iterator& operator--()
{
if (it->prev == nullptr) throw "Out of range";
it = it->prev;
return *this;
}
Iterator& operator--(int notused)
{
if (it->prev == nullptr) throw "Out of range";
Iterator tmp = *this;
it = it->prev;
return tmp;
}
Iterator& operator++()
{
if (it->next == nullptr) throw "Out of range";
it = it->next;
return *this;
}
Iterator& operator+(int n)
{
for (int i = 0; i < n; i++)
{
this->operator++();
}
return *this;
}
Iterator& operator-(int n)
{
for (int i = 0; i < n; i++)
{
this->operator--();
}
return *this;
}
Iterator& operator++(int notused)
{
if (it->next == nullptr) throw "Out of range";
Iterator tmp = *this;
it = it->next;
return tmp;
}
};
friend class Iterator;
List();
~List();
void insert(Iterator i, const T& value);
void pop_back();
void del(Iterator i);
void push_back(const T& value);
void add(const T& value);
bool find(const T& value);
void redactor(Iterator i, const T& value);
void print();
void printEl(Iterator i, bool con);
int size()
{
return count;
}
Iterator begin() const
{
return Iterator(Head);
}
Iterator end() const
{
return Iterator(Tail);
}
T& operator[](int index)
{
Iterator it = begin() + index;
return *it;
}
};
template<class T>
List<T>::List()
{
Head = new Node<T>();
Tail = Head;
count = 0;
}
template<class T>
List<T>::~List()
{
while (Head != Tail)
{
pop_back();
}
delete Head;
Head = Tail = nullptr;
}
template<class T>
void List<T>::pop_back()
{
if (Head == Tail)
{
throw "List is empty";
}
Node<T>* tmp = Tail->prev;
if (tmp->prev == nullptr)
{
Head = Tail;
count--;
}
else
{
tmp->prev->next = Tail;
Tail->prev = tmp->prev;
count--;
}
delete tmp;
};
template<class T>
void List<T>::del(Iterator i)
{
if (Head == Tail)
{
throw "List is empty";
}
Node<T>* tmp = Head;
while (tmp != Tail)
{
if (i == Iterator(tmp))
{
if (tmp == Head)
{
tmp->next->prev = nullptr;
Head = tmp->next;
delete tmp;
count--;
return;
}
else
{
tmp->prev->next = tmp->next;
tmp->next->prev = tmp->prev;
delete tmp;
count--;
return;
}
}
tmp = tmp->next;
}
}
template<class T>
void List<T>::push_back(const T& value)
{
Node<T>* tmp = new Node<T>(value, nullptr, Tail);
if (Head == Tail)
{
Tail->prev = tmp;
Head = tmp;
count++;
}
else
{
tmp->prev = Tail->prev;
Tail->prev->next = tmp;
Tail->prev = tmp;
count++;
}
}
template<class T>
void List<T>::insert(Iterator i, const T& value)
{
if (Head == Tail)
{
Node<T>* tmp = new Node<T>(value, nullptr, Tail);
Tail->prev = tmp;
Head = tmp;
count++;
return;
}
if (i == Iterator(Head))
{
Node<T>* tmp = new Node<T>(value);
Head->prev = tmp;
tmp->next = Head;
Head = tmp;
count++;
return;
}
else if (i == Iterator(Tail))
{
push_back(value);
// count++
return;
}
else if (i == Iterator(Tail->prev))
{
Node<T>* tmp = new Node<T>(value, Tail->prev->prev, Tail->prev);
Tail->prev->prev->next = tmp;
Tail->prev->prev = tmp; //
count++;
return;
}
Node<T>* tp = Head;
while (tp->next != Tail)
{
if (i == Iterator(tp))
{
Node<T>* tmp = new Node<T>(value, tp->prev, tp);
tp->prev->next = tmp;
tp->prev = tmp;
count++;
return;
}
tp = tp->next;
}
}
template<class T>
inline void List<T>::add(const T& value)
{
push_back(value);
Node<T>* tmp = Head;
for (tmp; tmp != Tail; tmp = tmp->next)
{
Node<T>* tmpn = tmp->next;
for (tmpn; tmpn != Tail; tmpn = tmpn->next)
{
if (tmp->key > tmpn->key)
{
if (tmp->prev != nullptr)
{
tmp->prev->next = tmpn;
tmpn->prev->next = tmpn->next;
tmpn->next->prev = tmpn->prev;
tmpn->prev = tmp->prev;
tmp->prev = tmpn;
tmpn->next = tmp;
}
else
{
Tail->prev = tmpn->prev;
tmpn->prev->next = Tail;
tmpn->next = tmp;
tmp->prev = tmpn;
tmp->prev = nullptr;
Head = tmpn;
}
}
}
}
}
template<class T>
void List<T>::redactor(Iterator i, const T& value)
{
Node<T>* tmp = Head;
while (tmp != Tail)
{
if (i == Iterator(tmp))
{
tmp->key = value;
return;
}
tmp = tmp->next;
}
}
template<class T>
bool List<T>::find(const T& value)
{
Node<T>* tmp = Head;
for (tmp; tmp != Tail; tmp = tmp->next)
{
if (value == tmp->key)
{
return true;
}
}
return false;
}
template<class T>
void List<T>::print()
{
Iterator i = begin();
for (; i != end(); ++i)
{
cout << *i << "\n";
}
}
template<class T>
void List<T>::printEl(Iterator i, bool con)
{
if (con)
{
cout << *i << "\n";
}
} | true |
c31b152637646c296e9e2e404d5a11c0a58b55cc | C++ | suzyz/leetcode_practice | /p164/p164.cpp | UTF-8 | 1,424 | 3.3125 | 3 | [
"MIT"
] | permissive | // Part of bucket sort.
#include <iostream>
#include <vector>
#include <set>
#include <cmath>
using namespace std;
class Solution {
public:
int maximumGap(vector<int>& nums) {
int n = nums.size();
if (n < 2)
return 0;
int minv = nums[0], maxv = nums[0];
for (int i = 1; i < n; ++i)
{
minv = min(minv,nums[i]);
maxv = max(maxv,nums[i]);
}
if (minv == maxv)
return 0;
int size_of_buckets = ceil(1.0*(maxv-minv)/(n-1))-1;
if (size_of_buckets == 0)
size_of_buckets = 1;
int num_of_buckets = ceil(1.0*(maxv-minv)/size_of_buckets)+1;
vector<pair<int,int>> buckets(num_of_buckets,make_pair(maxv+1,minv-1));
for (int i = 0; i < n; ++i)
{
int idx = (nums[i]-minv)/size_of_buckets;
buckets[idx].first = min(buckets[idx].first,nums[i]);
buckets[idx].second = max(buckets[idx].second,nums[i]);
}
int max_gap = size_of_buckets, last = -1;
for (int i = 0; i < num_of_buckets; ++i)
if (buckets[i].first <= maxv)
{
if (last != -1)
max_gap = max(max_gap,buckets[i].first - buckets[last].second);
last = i;
}
return max_gap;
}
};
int main()
{
Solution s;
int d[] = {33,923,341,1,234,12};
vector<int> v(d,d+6);
cout << s.maximumGap(v) << endl;
return 0;
}
| true |
7a9ade574b592c76203eba0b4f6a465b755f7cd2 | C++ | asyan4ik/ws2812b_effects_loop | /police/police.ino | UTF-8 | 1,963 | 2.640625 | 3 | [] | no_license | #include <Adafruit_NeoPixel.h>
#ifdef __AVR__
#include <avr/power.h>
#endif
#define PIN 6
const int buttonPin = 2;
int buttonState = 0; // статус кнопки - нажата или отпущена
// All of this stuff below is from the example
// Parameter 1 = number of pixels in strip
// Parameter 2 = Arduino pin number (most are valid)
// Parameter 3 = pixel type flags, add together as needed:
Adafruit_NeoPixel strip = Adafruit_NeoPixel(11, PIN, NEO_GRB + NEO_KHZ800);
void setup() {
strip.begin();
strip.show();
Serial.begin(9600);
pinMode(buttonPin, INPUT_PULLUP);
}
void loop() {
/*
* For strip.Color(R, G, B), use 0-255 to set intensity
* for each color (R)ed, (G)reen, (B)lue
*
* The last number is a delay 0-255 range.
*/
buttonState = digitalRead(buttonPin);
if (buttonState == LOW) {
// включаем светодиод
WigWag2(strip.Color(0, 0, 255), strip.Color(255, 0, 0), 100); // Blue and Red
ClearLights();
} else {
// иначе выключаем светодиод
}
}
// WigWag2(strip.Color(0, 0, 255), strip.Color(255, 0, 0), 100); // Blue and Red
// ClearLights();
// delay(1000);
void WigWag2(uint32_t c, uint32_t c2, uint8_t wait) {
for (int j = 0; j < 5; j++) { // The j<# determines how many cycles
for (int i = 0; i < strip.numPixels(); i = i + 1) {
strip.setPixelColor(i, c);
}
for (int i = (strip.numPixels() / 2); i < strip.numPixels(); i = i + 1) {
strip.setPixelColor(i, 0);
}
strip.show();
delay(wait);
for (int i = 0; i < strip.numPixels(); i = i + 1) {
strip.setPixelColor(i, 0);
}
for (int i = (strip.numPixels() / 2); i < strip.numPixels(); i = i + 1) {
strip.setPixelColor(i, c2);
}
strip.show();
delay(wait);
}
}
void ClearLights() {
for (int i = 0; i < strip.numPixels(); i = i + 1) {
strip.setPixelColor(i, 0); //turn every pixel off
}
strip.show();
}
| true |
aa3893d262c8298257333300662256191e1fb64d | C++ | jpc014/Phile_Scanner | /Phile_Scanner source code/Hydra.h | UTF-8 | 395 | 2.609375 | 3 | [] | no_license | #pragma once
#include "pathItem.h"
class Hydra {
public:
struct node_thing {
node_thing* next;
node_thing* previous;
pathItem content;
};
Hydra(int preffered_comb_size, const int num_drives);
pathItem remove_node();
int add_node(int drive, pathItem fileLoc);
bool is_empty();
int iterate();
private:
int comb_size, num_heads, size;
node_thing current_node;
node_thing *heads;
}; | true |
0a0d19e5e94cb1985a9abe376fe6eb95ad863802 | C++ | baiyucraft/DS_study | /2.线性表/LinkList_17.cpp | GB18030 | 677 | 3.375 | 3 | [] | no_license | #include <stdio.h>
#include "DLinkList.h"
// бѭ˫ǷԳ
bool SymmertryCirDLinkList(DLinkList L) {
// ͷָp
DNode* p = L->next;
// βָq
DNode* q = L->prior;
// ʱp=qżʱq->next=p(p->next=qΪûбȽֱֹͣ)
while (p != q && q->next != p) {
if (p->data == q->data) {
p = p->next;
q = q->prior;
}
else
return false;
}
return true;
}
void SolveDLinkList17() {
DLinkList L;
TailInsertCirDLinkList(L);
printf("ѭ˫Ϊ");
PrintCirDLinkList(L);
if (SymmertryCirDLinkList(L))
printf("Գ");
else
printf("Գ");
} | true |
2d394fba871dc8acd63567f2e479e464b005fcb6 | C++ | Z-maple/CodeInterviewGuide | /CH9/9.19/main.cc | UTF-8 | 862 | 3.9375 | 4 | [] | no_license | ///在有序旋转数组中找到最小值
#include <iostream>
#include <vector>
using namespace std;
int getMin(vector<int> &input){
int left = 0, right = input.size() - 1;
while(left < right){
int middle = (right - left)/2 + left;
if(left == right - 1){
return min(input[left], input[right]);
}
// if(input[left] > input[middle]){
// right = middle;
// }
// else if(input[middle] > input[right]){
// left = middle;
// }
// else{
// right = middle;
// }
if(input[middle] > input[right]){
left = middle;
}
else{
right = middle;
}
}
return input[left];
}
int main(){
vector<int> input({4, 5, 6, 7, 1, 2, 3});
int ret = getMin(input);
cout<<ret<<endl;
} | true |
c09dfac82122adf3997cf845967ddd09e86b5900 | C++ | subatomicdev/binancebeast | /binancebeast/examples/rest.cpp | UTF-8 | 2,384 | 2.578125 | 3 | [
"Apache-2.0"
] | permissive | #include <binancebeast/BinanceBeast.h>
#include <mutex>
#include <functional>
#include <condition_variable>
using namespace bblib;
int main (int argc, char ** argv)
{
if (argc != 2 && argc != 3)
{
std::cout << "Usage, requires key file or keys:\n"
<< "For key file: " << argv[0] << " <full path to keyfile>\n"
<< "For keys: " << argv[0] << " <api key> <secret key>\n";
return 1;
}
ConnectionConfig config;
if (argc == 2)
config = ConnectionConfig::MakeTestNetConfig(Market::USDM, std::filesystem::path{argv[1]});
else if (argc == 3)
config = ConnectionConfig::MakeTestNetConfig(Market::USDM, argv[1], argv[2]);
// to notify main thread when we have a reply
std::condition_variable cvHaveReply;
BinanceBeast bb;
// start the network processing
bb.start(config);
// send the request, the lamda is called when a reply is received
bb.sendRestRequest([&](RestResponse result)
{
if (result.hasErrorCode())
std::cout << "\nFAIL: " << result.failMessage << "\n";
else
std::cout << "\n" << result.json << "\n";
cvHaveReply.notify_one();
},
"/fapi/v1/allOrders", // the stream path
RestSign::HMAC_SHA256, // this call requires a signature
RestParams{{{"symbol", "BTCUSDT"}}}, // rest parameters
RequestType::Get); // this is a GET request
{
std::mutex mux;
std::unique_lock lck(mux);
cvHaveReply.wait(lck);
}
// invalid path
// send the request, the path does not exist
bb.sendRestRequest([&](RestResponse result)
{
if (result.failMessage == "path not found")
std::cout << "\nPASS:\n";
else
std::cout << "\nFAIL: should be invalid path\n";
cvHaveReply.notify_one();
},
"/fapi/v1/thispathDoesnotExist123",
RestSign::HMAC_SHA256,
RestParams{{{"symbol", "BTCUSDT"}}},
RequestType::Get);
{
std::mutex mux;
std::unique_lock lck(mux);
cvHaveReply.wait(lck);
}
return 0;
}
| true |
afdec30a6679c48499193d8b3063700302146da5 | C++ | JackMalone1/RPG | /TileMapLoader.h | UTF-8 | 995 | 2.859375 | 3 | [] | no_license | #pragma once
#include <SFML/System/Vector2.hpp>
#include <vector>
#include <sstream>
#include <fstream>
#include <iostream>
#include "yaml-cpp\yaml.h"
#include <SFML/Graphics.hpp>
#include <unordered_map>
enum class LayerType
{
Renderable = 0,
Collision,
Triggers
};
struct Tile
{
sf::Vector2f position;
sf::Sprite sprite;
sf::Texture texture;
sf::IntRect subTexture;
int layer;
void render(sf::RenderWindow& window)
{
sprite.setTexture(texture);
sprite.setTextureRect(subTexture);
window.draw(sprite);
}
};
struct Layer
{
std::string name;
LayerType type;
std::string tileSetName;
std::vector<Tile> tiles;
void render(sf::RenderWindow& window)
{
for (Tile& t : tiles)
{
t.render(window);
}
}
};
struct TileMap
{
std::vector<Layer> layers;
void render(sf::RenderWindow& window)
{
for (Layer l : layers)
{
l.render(window);
}
}
};
class TileMapLoader
{
public:
TileMapLoader() = default;
static void load(std::string file, TileMap& map);
};
| true |
d7017c77e9a7b2853f9b617a0acde6d5147e8a0b | C++ | harry1213812138/water-problem-code | /Cpp1 star.cpp | UTF-8 | 358 | 2.90625 | 3 | [] | no_license | #include <stdio.h>
int main()
{
int i,j;
for(i = 0;i < 4;i++)
{
for(j = 0;j <= 2-i;j++)
{
printf(" ");
}
for(j = 0;j <= i*2;j++)
{
printf("*");
}
printf("\n");
}
for(i = 3;i > 0;i--)
{
for(j = 0;j <= 3-i;j++)
{
printf(" ");
}
for(j = 0;j <= i*2-2;j++)
{
printf("*");
}
printf("\n");
}
return 0;
} | true |
e0866295844adbdd6462882f3fd63217de64aa64 | C++ | Rice-Farmer/Cpts-122 | /Homework/Homework 1/Exersice 7/timeOutput.cpp | UTF-8 | 257 | 3.078125 | 3 | [] | no_license | #include <iostream>
void formatOutputTime(int hours, int minutes)
{
using namespace std;
if(minutes>=10)
cout << "Time: " << hours << ":" << minutes << endl;
else
cout << "Time: " << hours << ":0" << minutes << endl;
} | true |
d2fd3c0eb2dad4fbce0b2253e4894bb581fb3bd2 | C++ | chuanyedadiao/dataStructure | /第一周/1-2(2).cpp | GB18030 | 1,223 | 3.234375 | 3 | [] | no_license | #include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
typedef struct list
{
int data;
struct list *next;
}LNode,*LinkList;
LinkList InitList()
{
LinkList L;
L=(LinkList)malloc(sizeof(LNode));
L->next=NULL;
return L;
}
void createList(LinkList list,int n)
{
LNode *p,*q;
p=list;
int i;
for(i=0;i<n;i++)
{
q=(LNode *)malloc(sizeof(LNode));
p->next=q;
printf("\n");
scanf("%d",&q->data);
p=q;
}
p->next=NULL;
}
void reserve(LinkList list)
{
LNode *p,*q,*s;
q=list->next;
if(q==NULL) printf("ñΪձ");
else{
list->next=NULL;
p=NULL;
s=q->next;
while(s)
{
s=q->next;
list->next=q;
q->next=p;
p=q;
q=s;
}
}
}
void output(LinkList list)
{
LNode *p,*q;
p=list;
q=p->next;
while(q)
{
printf("%d\t",q->data);
p=q;
q=p->next;
}
}
int main()
{
LinkList L;
int n;
system("date/t");
system("time/t");
printf("ѧ:031720106\n:˳\n");
L=InitList();
printf("ݵĸ\n");
scanf("%d",&n);
if(n==0) printf("Ϊձ\n");
else{
createList(L,n);
printf("֮ǰ\n");
output(L);
reserve(L);
printf("\n֮\n");
output(L);
}
return 0;
}
| true |
a0edb6635e995c317c84c656edf80166900e2a81 | C++ | mrouillard/Arduino-PC-Gameport-HID | /Analog_Joystick/PC_Gameport_Analog_Joystick.ino | UTF-8 | 3,752 | 2.765625 | 3 | [] | no_license |
// Settings
#define ENABLE_DEBUG;
// Pins
const int button0 = 7;
const int button1 = 6;
const int button2 = 5;
const int button3 = 4;
const int axis0 = A0;
const int axis1 = A1;
const int axis2 = A2;
const int axis3 = A3;
// Analog to digital
const int AXIS_MIN = 550;
const int AXIS_MAX = 1023;
const int AXIS_NUL = 720;
// Joestick
JoyState_t joyStick;
// Ugly vars
int buttonState0= 0;
int buttonState1= 0;
int buttonState2= 0;
int buttonState3= 0;
int buttonState4= 0;
int buttonState5= 0;
int buttonState6= 0;
int buttonState7= 0;
// Setup
void setup() {
Serial.begin(9600);
// pull up
pinMode(button0, INPUT_PULLUP);
pinMode(button1, INPUT_PULLUP);
pinMode(button2, INPUT_PULLUP);
pinMode(button3, INPUT_PULLUP);
}
void loop(){
// read data
buttonState0 = !digitalRead(button0);
buttonState1 = !digitalRead(button1);
buttonState2 = !digitalRead(button2);
buttonState3 = !digitalRead(button3);
buttonState4 = analogRead(axis0);
buttonState5 = analogRead(axis1);
buttonState6 = analogRead(axis2);
buttonState7 = analogRead(axis3);
#ifdef ENABLE_DEBUG
Serial.print(buttonState0);
Serial.print(buttonState1);
Serial.print(buttonState2);
Serial.print(buttonState3);
Serial.print(" ");
Serial.print(buttonState4);
Serial.print(" ");
Serial.print(buttonState5);
Serial.print(" ");
Serial.print(buttonState6);
Serial.print(" ");
Serial.print(buttonState7);
Serial.println("");
#endif
float tempState = 127;
if(buttonState4>AXIS_NUL){
tempState = 127+(AXIS_NUL - buttonState4)/2;
}
else{
tempState =127+ (AXIS_NUL - buttonState4)/1;
}
tempState = tempState<0?0:tempState;
tempState = tempState>255?255:tempState;
joyStick.xAxis = tempState;
tempState = 127;
if(buttonState5>AXIS_NUL){
tempState = 127+(AXIS_NUL - buttonState5)/2;
}
else{
tempState =127+ (AXIS_NUL - buttonState5)/1;
}
tempState = tempState<0?0:tempState;
tempState = tempState>255?255:tempState;
joyStick.yAxis = tempState;
tempState = buttonState6 - AXIS_MIN;
tempState = tempState<0?0:tempState;
tempState = (256 *tempState)/ (float)(AXIS_MAX-AXIS_MIN);
tempState = tempState>255?255:tempState;
joyStick.rudder = tempState;
tempState = buttonState7 - AXIS_MIN;
tempState = tempState<0?0:tempState;
tempState = (256 *tempState)/ (float)(AXIS_MAX-AXIS_MIN);
tempState = abs(tempState - 256);
tempState = tempState<0?0:tempState;
tempState = tempState>255?255:tempState;
joyStick.throttle = tempState;
// all another axis set to zero position
joyStick.zAxis = 127;
joyStick.xRotAxis = 127;
joyStick.yRotAxis = 127;
joyStick.zRotAxis = 127;
//joyStick.throttle = 127;
//joyStick.rudder = 127;
// hat connected to 4 key
if(buttonState0 && buttonState1 && buttonState2 && buttonState3){
joyStick.hatSw1 = 0;
}
else if(buttonState0 && buttonState1 && !buttonState2 && buttonState3){
joyStick.hatSw1 = 4;
}
else if(buttonState0 && buttonState1 && !buttonState2 && !buttonState3){
joyStick.hatSw1 = 6;
}
else if(buttonState0 && buttonState1 && buttonState2 && !buttonState3){
joyStick.hatSw1 = 2;
}
else{
joyStick.hatSw1 = 8;
// buttons connects
joyStick.buttons = 0;
// digital buttons to mask
if(buttonState0){
joyStick.buttons = joyStick.buttons | 1;
}
if(buttonState1){
joyStick.buttons = joyStick.buttons | 2;
}
if(buttonState2){
joyStick.buttons = joyStick.buttons | 4;
}
if(buttonState3){
joyStick.buttons = joyStick.buttons | 8;
}
}
// and hat2 to center
joyStick.hatSw2 = 8;
Joystick.setState(&joyStick);
delay(1);
}
| true |
7bdf4529fad4c2ef7bec090e3b81267ae07294f5 | C++ | purpleKarrot/nccmake | /cmAlgorithms.h | UTF-8 | 1,028 | 2.8125 | 3 | [] | no_license | /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
file Copyright.txt or https://cmake.org/licensing for details. */
#ifndef cmAlgorithms_h
#define cmAlgorithms_h
#include <algorithm>
#include <utility>
namespace ContainerAlgorithms {
template<typename T>
struct cmIsPair
{
enum
{
value = false
};
};
template<typename K, typename V>
struct cmIsPair<std::pair<K, V>>
{
enum
{
value = true
};
};
template<
typename Range,
bool valueTypeIsPair = cmIsPair<typename Range::value_type>::value>
struct DefaultDeleter
{
void operator()(typename Range::value_type value) const { delete value; }
};
template<typename Range>
struct DefaultDeleter<Range, /* valueTypeIsPair = */ true>
{
void operator()(typename Range::value_type value) const
{
delete value.second;
}
};
} // namespace ContainerAlgorithms
template<typename Range>
void cmDeleteAll(Range const& r)
{
std::for_each(
r.begin(), r.end(), ContainerAlgorithms::DefaultDeleter<Range>());
}
#endif
| true |
b5ec06eb4a4af99316919a32396889a295447430 | C++ | Nocturne-hub/IG | /Src/Laser.cpp | UTF-8 | 1,916 | 2.640625 | 3 | [] | no_license | #include "Laser.h"
Laser::Laser() {
tailleX = 0.15f;
tailleY = 0.15f;
tailleZ = 1.0f;
}
Laser::Laser(Vaisseau v, int i) {
tailleX = 0.15f;
tailleY = 0.15f;
tailleZ = 1.0f;
posX = v.coordCanons[i][0];
posY = v.coordCanons[i][1];
if (i == 0) {
posZ = -0.5;
}
else {
posZ = 1.9;
}
}
float Laser::getPosX() {
return posX;
}
float Laser::getPosY() {
return posY;
}
float Laser::getPosZ() {
return posZ;
}
void Laser::setPosX(float x) {
posX = x;
}
void Laser::setPosY(float y) {
posY = y;
}
void Laser::setPosZ(float z) {
posZ = z;
}
void Laser::mySolidCylindre(GLdouble base, GLdouble height, GLint slices, GLint stacks) {
GLUquadricObj* theQuadric;
theQuadric = gluNewQuadric();
gluQuadricDrawStyle(theQuadric, GLU_FILL);
gluQuadricNormals(theQuadric, GLU_SMOOTH);
gluCylinder(theQuadric, base, base, height, slices, stacks);
gluDeleteQuadric(theQuadric);
}
void Laser::mySolidSphere(GLdouble height, GLint slices, GLint stacks) {
GLUquadricObj* sphere = NULL;
sphere = gluNewQuadric();
gluQuadricDrawStyle(sphere, GLU_FILL);
gluQuadricNormals(sphere, GLU_SMOOTH);
gluSphere(sphere, height, slices, stacks);
gluDeleteQuadric(sphere);
}
void Laser::mySolidLaser(){
glPushMatrix();
glRotatef(180.0f, 1.0f, 0.0f, 0.0f);
mySolidSphere(tailleX/2, 50, 50);
mySolidCylindre(tailleX / 2, tailleZ, 50, 50);
glTranslatef(0.0f, 0.0f, tailleZ);
mySolidSphere(tailleX/2, 50, 50);
glPopMatrix();
}
bool Laser::enCollision(Patatoide p) {
if (p.isBoomed()) {
return false;
}
float absX = abs(p.getPosX() - posX);
float absY = abs(p.getPosY() - posY);
float absZ = abs(p.getPosZ() - posZ);
if (absX <= tailleX + 1.0f && absY <= tailleY + 1.0f && absZ <= tailleZ + 1.0f) {
return true;
}
return false;
} | true |
a832fe3b64b3927eac34cfe3c9d29e29803df003 | C++ | LawHsia1/CPU-Simulator | /Memory.h | UTF-8 | 827 | 2.640625 | 3 | [] | no_license | /*
* Memory.h
*
* Created on: Sep 26, 2014
* Author: rayhsia
*/
#ifndef MEMORY_H_
#define MEMORY_H_
#include <fstream>
#include <sstream>
#include <stdexcept>
#include "flags.h"
#include <stdlib.h>
#include <unistd.h>
class Memory
{
public:
enum ErrorNums
{
INVALID_ACCESS = 1,
BOUNDS_ERROR,
};
public:
Memory();
Memory(char* fileName);
int readAddress(int, int);
int readFromCPU(); //function returns two values. The value obtained from CPU and the flag obtained
void writeToCPU(int valueToWrite);
void writeToAddress(int data, int address, int mode);
void setPipeEnds(int r, int w);
~Memory();
private:
int stringToNum(std::string&);
private:
int cells[2000];
int readEnd;
int writeEnd;
bool sysMode;
// 0 - 999 = user programs
// 1000 - 1999 = system code
};
#endif /* MEMORY_H_ */
| true |
6238d679b38ec322729e08902b48f46d00d7aaad | C++ | czqmike/Leetcode | /iqiyi2021秋招提前批Java/split_str.cpp | UTF-8 | 814 | 3.046875 | 3 | [] | no_license | /***
* @Author: czqmike
* @Date: 2021-08-01 17:02:46
* @LastEditTime: 2021-08-02 19:11:30
* @LastEditors: czqmike
* @Description:
* @FilePath: \undefinedd:\git_repos\Leetcode\iqiyi2021秋招提前批Java\split_str.cpp
*/
#include <bits/stdc++.h>
using namespace std;
vector<string> split_str(const string& s, const string& delimiter) {
int pos1 = 0, pos2 = s.find(delimiter);
vector<string> v;
while (pos2 != string::npos) {
v.push_back(s.substr(pos1, pos2 - pos1));
pos1 = pos2 + delimiter.size();
pos2 = s.find(delimiter, pos1);
}
if (pos1 != s.length()) {
v.push_back(s.substr(pos1));
}
return v;
}
int main() {
string s = "1, 2, 3, 4, 5, 6, 7";
vector<string> v = split_str(s, ", ");
for (auto item : v) {
cout << item << " ";
}
return 0;
} | true |
e55c73856a9af53c57350865a33b68717eba91f1 | C++ | bdumitriu/playground | /university-work/utcn/sisteme de operare/linux/so/include/driver/DirectoryListing.h | UTF-8 | 4,999 | 3.40625 | 3 | [] | no_license | /*
* Project: File System Simulator
* Author: Bogdan DUMITRIU
* E-mail: bdumitriu@bdumitriu.ro
* Date: Sun Oct 27 2002
* Description: This is the interface of the DirectoryListing class.
*/
/***************************************************************************
* *
* 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. *
* *
***************************************************************************/
#ifndef _DIRECTORY_LISTING_H
#define _DIRECTORY_LISTING_H
#include <stdlib.h>
#include <iostream.h>
#include <string.h>
#include "DirectoryEntry.h"
#include "../exceptions/ArrayIndexOutOfBoundsException.h"
/**
* This class contains a set of directory entries (i.e. files or (sub)directories)
* which represent a directory's contents. It allows manipulation of this set of
* entries.
*
* @short This class manages a set of directory entries.
* @author Bogdan DUMITRIU
* @version 0.1
*/
class DirectoryListing
{
public:
/**
* Creates an empty directory listing with an initial capacity
* of 50. This capacity represents the number of entries the
* internal array can store. If this capacity is reached a
* new array with a double capacity is allocated and the old
* one is copied into the new one.
*/
DirectoryListing();
/**
* Creates an empty directory listing with <code>initialCapacity</code>
* as its initial capatcity. This capacity represents the number of
* entries the internal array can store. If this capacity is reached a
* new array with a double capacity is allocated and the old
* one is copied into the new one.
*/
DirectoryListing(unsigned long initialCapaicty);
/**
* The destructor of the class. This destructor deletes the
* internal array and all the DirectoryEntry objects as
* well.
*/
~DirectoryListing();
/**
* Returns the number of entries in the directory listing.
*
* @return the number of entries in the directory listing.
*/
unsigned long size();
/**
* Adds the entry received as parameter in the listing.
*
* @param entry the entry too add.
*/
void addEntry(DirectoryEntry* entry);
/**
* Returns the entry in the <code>index</code>th position
* of the directory.
*
* The method throws:
* <ul>
* <li> ArrayIndexOutOfBoundsException* if <code>index</code>
* is less than 0 or greater than or equal to <code>this->size()</code>.
* </li>
* </ul>
*
* @param index the index of the entry to be returned.
* @return the entry in the <code>index</code>th position
* of the directory.
*/
DirectoryEntry* getEntry(unsigned long index) throw(ArrayIndexOutOfBoundsException*);
/**
* Returns the DirectoryEntry whose entry name is equal to
* <code>entryName</code>. If no such entry exists, NULL
* is returned.
*
* @param entryName the entry name of the entry you want. It
* should be a string (i.e., it should end with '\0').
* @return the DirectoryEntry whose entry name is equal to
* <code>entryName</code>.
*/
DirectoryEntry* getEntry(const char* entryName);
/**
* Delete the <code>index</code>th entry in the listing
* and shifts the entries that follow one position to
* the left.
*
* The method throws:
* <ul>
* <li> ArrayIndexOutOfBoundsException* if <code>index</code>
* is less than 0 or greater than or equal to <code>this->size()</code>.
* </li>
* </ul>
*
* @param index the index of the entry to be deleted.
* @return the deleted DirectoryEntry.
*/
DirectoryEntry* deleteEntry(unsigned long index) throw(ArrayIndexOutOfBoundsException*);
/**
* Returns the index of the DirectoryEntry whose entry name is
* equal to <code>entryName</code>. If no such entry exists, this->size()
* is returned.
*
* @param entryName the entry name of the entry whose index you want. It
* should be a string (i.e., it should end with '\0').
* @return the index of the DirectoryEntry whose entry name is
* equal to <code>entryName</code>.
*/
unsigned long indexOf(const char* entryName);
/**
* Returns true if listing contains an entry with <code>entryName</code>
* as its entry name and false otherwise.
*
* @param entryName the entry name of the entry you are looking for It
* should be a string (i.e., it should end with '\0').
* @return true if listing contains an entry with <code>entryName</code>
* as its entry name and false otherwise.
*/
bool contains(const char* entryName);
private:
DirectoryEntry** entries; /* the internal array */
unsigned long length; /* number of valid elements in the array */
unsigned long capacity; /* the number of elements the array can hold */
};
#endif
| true |
726099b646ce17e5cd0388c2d1cca8e8c52e80b3 | C++ | Linueks/Fys4411-Variational-Monte-Carlo | /Hamiltonians/harmonicoscillator.h | UTF-8 | 537 | 2.75 | 3 | [] | no_license | #pragma once
#include "hamiltonian.h"
#include <vector>
class HarmonicOscillatorNum : public Hamiltonian{
public:
HarmonicOscillatorNum(System* system, double omega_ho, double omega_r);
double computePotentialEnergy(std::vector<Particle*> particles);
protected:
double m_omega_ho = 0;
double m_omega_r = 0;
};
class HarmonicOscillator : public HarmonicOscillatorNum{
public:
HarmonicOscillator(System* system, double omega_ho, double omega_r);
double computeKineticEnergy(std::vector<Particle*> particles);
};
| true |
98ab4ec076e7c50f9dbb7bbc14cc99368fa9fda4 | C++ | jobgsk/CppGameEngine | /animation/AnimationFrame.h | UTF-8 | 2,471 | 2.78125 | 3 | [] | no_license | #ifndef ANIMATION_FRAME_H_
#define ANIMATION_FRAME_H_
#include <vector>
#include "AnimationBone.h"
#include "../GameObject.h"
class AnimationFrame
{
public:
std::vector<AnimationBone*> blist;
int current;
int m_id;
GameObject * m_owner;
AnimationFrame(int id, GameObject * owner):
m_id(id), m_owner(owner)
{
};
void create_bone(
int bid, std::string bname, int pid,
float len,
float px, float py, float pz,
float w, float vx, float vy, float vz)
{
current = blist.size();
blist.push_back(new AnimationBone(px, py, pz, w, vx, vy, vz, bid, bname));
}
AnimationBone * get_current()
{
if (blist.size() == 0)
return NULL;
return blist[current];
}
/*void test()
{
for (int i = 0; i < blist.size(); i++)
{
Quaternion orient = blist[i]->m_body->getOrientation();
orient.get_euler();
Vector3 pos = blist[i]->m_body->getPointInWorldSpace(Vector3(0, 0, 0));
//Vector3 dir = blist[i]->m_body->getDirectionInWorldSpace(Vector3(1, 1, 1));
//Matrix3 r_matrix = Matrix3();
//r_matrix.setOrientation(blist[i]->m_body->getOrientation());
//Vector3 dir = r_matrix.transform(Vector3(1, 1, 1));
//Vector3 dir = blist[i]->m_body->
std::cout
<< "id " << blist[i]->m_id
<< "pos " << pos.x << " " << pos.y << " " << pos.z
<< " orient " << orient.alpha << " " << orient.axis.x << " " << orient.axis.y << " " << orient.axis.z
<< std::endl;
}
}
*/
virtual void update(float duration)
{
Vector3 owner_pos = m_owner->get_pos();
//owner_pos.y -= m_owner->half_size.y;
Quaternion owner_orient = m_owner->get_orient();
Matrix4 owner_trans = Matrix4();
owner_trans.setOrientationAndPos(owner_orient, owner_pos);
for (int i = 0; i < blist.size(); i++)
{
//Vector3 bone_pos = blist[i]->get_ini_pos();
//Quaternion bone_orient = blist[i]->get_ini_orient();
//Vector3 bone_dir = blist[i]->get_ini_dir();
//bone_pos += owner_pos;
//owner_orient *= bone_orient;
blist[i]->m_transformation = owner_trans * blist[i]->m_init_transformation;
//blist[i]->m_body->setPosition(bone_pos);
//blist[i]->m_body->setOrientation(bone_orient);
//blist[i]->m_body->calculateDerivedData();
//blist[i]->m_body->integrate(duration);
}
}
void render()
{
for (int i = 0; i < blist.size(); i++)
{
blist[i]->render();
}
};
};
#endif /* ANIMATION_FRAME_H_ */
| true |
1eff0978a3e6229a2dcd6b1bbcac723596da12eb | C++ | 9643kavinder/Algorithms | /PATTERN_3.cpp | UTF-8 | 459 | 2.6875 | 3 | [] | no_license | /* PATTERN
1
0 1
1 0 1
0 1 0 1
1 0 1 0 1
*/
#include<iostream>
using namespace std;
int main(){
int n;
cout<<"ENTER THE NUMBER";
cin>>n;
int val,j;
for(int i=0;i<=n;i++){
if(i%2==0){
val = 0;
for(j=1;j<=i;j++){
cout<<val<<" ";
if(val==0){
val = 1;
}
else{
val = 0;
}
}
}
else{
val = 1;
for(j=1;j<=i;j++){
cout<<val<<" ";
if(val==0){
val = 1;
}
else{
val = 0;
}
}
}
cout<<endl;
}
return 0;
}
| true |
a315859a9ba700a108ad2f2bf7ae18fa8879d6c5 | C++ | anishsingh935/C- | /swap.cpp | UTF-8 | 962 | 3.78125 | 4 | [] | no_license | #include <iostream>
using namespace std;
class aman;
class anish
{
private:
int val1;
friend void exchange(anish &, aman &);
public:
void set_data(int a)
{
val1 = a;
}
void display ()
{
cout<<"The value of class 1 :"<<val1<<endl;
}
};
class aman
{
private:
int val2;
friend void exchange(anish &, aman &);
public:
void det(int a)
{
val2 = a;
}
void display ()
{
cout<<"The value of class 1 :"<<val2<<endl;
}
};
void exchange(anish & a, aman & b)
{
int temp;
temp = a.val1;
a.val1 = b.val2;
b.val2 = temp;
cout<<"value 1:"<<a.val1<<endl;
cout<<"value 2:"<<b.val2<<endl;
}
int main()
{
anish c1;
aman c2;
c1.set_data(2);
c1.display();
c2.det(6);
c2.display();
cout << "Aftr exchangin the values \n"<< endl;
exchange(c1 ,c2 );
return 0;
} | true |
c4542a2967bcd625649511fdb692874678f72ea8 | C++ | jjzhang166/WinNT5_src_20201004 | /NT/inetsrv/iis/svcs/cmp/webdav/inc/ex/autoptr.h | UTF-8 | 9,612 | 2.796875 | 3 | [] | no_license | /*
* E X \ A U T O P T R . H
*
* Implementation of automatic-cleanup pointer template classes.
* This implementation is safe for use in NON-throwing environments
* (save for EXDAV & other store-loaded components).
*
* Copyright 1986-1998 Microsoft Corporation, All Rights Reserved.
*/
//----------------------------------------------------------------------//
//
// Automatic pointers defined here:
//
// auto_ptr<>
// auto_heap_ptr<>
// auto_handle<>
// auto_heap_array<>
// auto_ref_ptr<CRefCountedObject>
//
#ifndef _EX_AUTOPTR_H_
#define _EX_AUTOPTR_H_
#include <caldbg.h>
#include <calrc.h>
#include <ex\exmem.h>
#pragma warning(disable: 4284) // operator-> to a non UDT
// ========================================================================
//
// TEMPLATE CLASS auto_ptr
//
// Stripped down auto_ptr class based on the C++ STL standard one
//
// Calls delete on dtor.
// NO equals operator between these classes, as that hides
// the transfer-of-ownership. Handle those yourself, EXPLICITLY,
// like this:
// auto-ptr1 = auto-ptr2.relinquish();
//
template<class X>
class auto_ptr
{
protected:
X * px;
// NOT IMPLEMENTED
//
auto_ptr(const auto_ptr<X>& p);
auto_ptr& operator=(const auto_ptr<X>& p);
public:
// CONSTRUCTORS
//
explicit auto_ptr(X* p=0) : px(p) {}
~auto_ptr()
{
delete px;
}
// ACCESSORS
//
bool operator!()const { return (px == NULL); }
operator X*() const { return px; }
// X& operator*() const { Assert (px); return *px; }
X* operator->() const { Assert (px); return px; }
X* get() const { return px; }
// MANIPULATORS
//
X* relinquish() { X* p = px; px = 0; return p; }
X** operator&() { Assert (!px); return &px; }
void clear()
{
delete px;
px = NULL;
}
auto_ptr& operator=(X* p)
{
Assert(!px); // Scream on overwrite of good data.
px = p;
return *this;
}
};
// ========================================================================
//
// TEMPLATE CLASS auto_handle
//
// auto_ptr for NT system handles.
//
// Closes the handle on dtor.
// NO equals operator between these classes, as that hides
// the transfer-of-ownership. Handle those yourself, EXPLICITLY,
// like this:
// auto-handle-1 = auto-handle-2.relinquish();
//
template<class X>
class auto_handle
{
private:
X handle;
// NOT IMPLEMENTED
//
auto_handle(const auto_handle<X>& h);
auto_handle& operator=(auto_handle<X>& h);
public:
// CONSTRUCTORS
//
auto_handle(X h=0) : handle(h) {}
~auto_handle()
{
if (handle && INVALID_HANDLE_VALUE != handle)
{
CloseHandle(handle);
}
}
// ACCESSORS
//
operator X() const { return handle; }
X get() const { return handle; }
// MANIPULATORS
//
X relinquish() { X h = handle; handle = 0; return h; }
X* load() { Assert(NULL==handle); return &handle; }
X* operator&() { Assert(NULL==handle); return &handle; }
void clear()
{
if (handle && INVALID_HANDLE_VALUE != handle)
{
CloseHandle(handle);
}
handle = 0;
}
auto_handle& operator=(X h)
{
Assert (handle == 0); // Scream on overwrite of good data
handle = h;
return *this;
}
};
// ========================================================================
//
// TEMPLATE CLASS auto_ref_ptr
//
// Holds a ref on an object. Works with CRefCountedObject.
// Grabs a ref when a pointer is assigned into this object.
// Releases the ref when this object is destroyed.
//
template<class X>
class auto_ref_ptr
{
private:
X * m_px;
void init()
{
if ( m_px )
{
m_px->AddRef();
}
}
void deinit()
{
if ( m_px )
{
m_px->Release();
}
}
// NOT IMPLEMENTED
// We turn off operator new to try to prevent auto_ref_ptrs being
// created via new(). However, storext.h uses a macro to redefine new,
// so this line is only used on non-DBG.
#ifndef DBG
void * operator new(size_t cb);
#endif // !DBG
public:
// CONSTRUCTORS
//
explicit auto_ref_ptr(X* px=0) :
m_px(px)
{
init();
}
auto_ref_ptr(const auto_ref_ptr<X>& rhs) :
m_px(rhs.m_px)
{
init();
}
~auto_ref_ptr()
{
deinit();
}
// ACCESSORS
//
X& operator*() const { return *m_px; }
X* operator->() const { return m_px; }
X* get() const { return m_px; }
// MANIPULATORS
//
X* relinquish() { X* p = m_px; m_px = 0; return p; }
X** load() { Assert(NULL==m_px); return &m_px; }
X* take_ownership(X* p) { Assert(NULL==m_px); return m_px = p; }
void clear()
{
deinit();
m_px = NULL;
}
auto_ref_ptr& operator=(const auto_ref_ptr<X>& rhs)
{
if ( m_px != rhs.m_px )
{
deinit();
m_px = rhs.m_px;
init();
}
return *this;
}
auto_ref_ptr& operator=(X* px)
{
if ( m_px != px )
{
deinit();
m_px = px;
init();
}
return *this;
}
};
// ========================================================================
//
// TEMPLATE CLASS auto_heap_ptr
//
// An auto_ptr class based on the heap instead of new.
//
// Calls ExFree() on dtor.
// NO equals operator between these classes, as that hides
// the transfer-of-ownership. Handle those yourself, EXPLICITLY,
// like this:
// auto-heap-ptr1 = auto-heap-ptr2.relinquish();
//
template<class X>
class auto_heap_ptr
{
private:
X * m_px;
// NOT IMPLEMENTED
//
auto_heap_ptr (const auto_heap_ptr<X>& p);
auto_heap_ptr& operator= (const auto_heap_ptr<X>& p);
//void * operator new(size_t cb);
public:
// CONSTRUCTORS
//
explicit auto_heap_ptr (X* p=0) : m_px(p) {}
~auto_heap_ptr()
{
clear();
}
// ACCESSORS
//
// NOTE: this simple cast operator (operator X*()) allows
// the [] operator to function.
//$REVIEW: Should we add an explicit [] operator?
operator X*() const { return m_px; }
X* operator->() const { Assert (m_px); return m_px; }
X* get() const { return m_px; }
//X& operator[] (UINT index) const { return *(m_px + index); }
//X& operator[] (UINT index) const { return m_px[index]; }
// MANIPULATORS
//
X* relinquish() { X* p = m_px; m_px = 0; return p; }
X** load() { Assert(!m_px); return &m_px; }
//$REVIEW: Can we migrate all users of operator&() to use load() instead???
//$REVIEW: Benefit: it's more explicit. Detriment: need to change existing code.
X** operator&() { Assert (!m_px); return &m_px; }
void clear()
{
if (m_px) // Release any object we're holding now
{
ExFree (m_px);
}
m_px = NULL;
}
// Realloc
//$REVIEW:
// This operator is technically NOT safe for store-side code!
// It makes it easy to ignore memory failures.
// (However, it is currently so ingrained in our vocabulary that
// removing it will touch a very large number of files: )
// For now, to be safe, callers MUST check the value of their
// object (using .get()) after calling this function.
//
void realloc(UINT cb)
{
VOID * pvTemp;
if (m_px)
pvTemp = ExRealloc (m_px, cb);
else
pvTemp = ExAlloc (cb);
Assert (pvTemp);
m_px = reinterpret_cast<X*>(pvTemp);
}
//$REVIEW: end
// Failing Realloc
//
BOOL frealloc(UINT cb)
{
VOID * pvTemp;
if (m_px)
pvTemp = ExRealloc (m_px, cb);
else
pvTemp = ExAlloc (cb);
if (!pvTemp)
return FALSE;
m_px = static_cast<X*>(pvTemp);
return TRUE;
}
// NOTE: This method asserts if the auto-pointer already holds a value.
// Use clear() or relinquish() to clear the old value before
// taking ownership of another value.
//
void take_ownership (X * p)
{
Assert (!m_px); // Scream on overwrite of good data.
m_px = p;
}
// NOTE: This operator= is meant to do exactly the same as take_ownership().
//
auto_heap_ptr& operator= (X * p)
{
Assert (!m_px); // Scream on overwrite of good data.
m_px = p;
return *this;
}
};
// ========================================================================
//
// TEMPLATE CLASS auto_co_task_mem
//
// Stripped down auto_co_task_mem class based on the C++ STL standard one
//
// Calls CoTaskMemFree on dtor.
// NO equals operator between these classes, as that hides
// the transfer-of-ownership. Handle those yourself, EXPLICITLY,
// like this:
// auto-co_task_mem1 = auto-co_task_mem2.relinquish();
//
template<class X>
class auto_co_task_mem
{
protected:
X * m_px;
// NOT IMPLEMENTED
//
auto_co_task_mem(const auto_co_task_mem<X>& p);
auto_co_task_mem& operator=(const auto_co_task_mem<X>& p);
public:
// CONSTRUCTORS
//
explicit auto_co_task_mem(X* p=0) : m_px(p) {}
~auto_co_task_mem()
{
CoTaskMemFree(m_px);
}
// ACCESSORS
//
X* operator->() const { Assert (m_px); return m_px; }
X* get() const { return m_px; }
// MANIPULATORS
//
X* relinquish() { X* p = m_px; m_px = 0; return p; }
X** load() { Assert(!m_px); return &m_px; }
X** operator&() { Assert (!m_px); return &m_px; }
void clear()
{
CoTaskMemFree(m_px);
m_px = NULL;
}
// NOTE: This method asserts if the auto-pointer already holds a value.
// Use clear() or relinquish() to clear the old value before
// taking ownership of another value.
//
void take_ownership (X * p)
{
Assert (!m_px); // Scream on overwrite of good data.
m_px = p;
}
auto_co_task_mem& operator=(X* p)
{
Assert(!m_px); // Scream on overwrite of good data.
m_px = p;
return *this;
}
};
#endif //!_EX_AUTOPTR_H_
| true |
da6546d900a7db6b9aeb93fb6300338537558941 | C++ | kushagraagrawal/codeforces-codechef | /Music/git_project2/codeforces/499B.cpp | UTF-8 | 337 | 2.859375 | 3 | [] | no_license | #include<map>
#include<cmath>
#include<iostream>
using namespace std;
map<string,string> dict;
int main()
{
int N,M,i;
string key,val;
cin>>N>>M;
while(M--)
{
cin>>key>>val;
dict[key] = val;
}
while(N--)
{
cin>>val;
if(dict[val].length() < val.length())
cout<<dict[val]<<" ";
else
cout<<val<<" ";
}
return 0;
}
| true |
9e0ee1b40dc7892f251a8fa23cf9775156ca6c66 | C++ | yoqwerty/trial | /middleElemLL.cpp | UTF-8 | 586 | 3.21875 | 3 | [] | no_license | /*
Please note that it's Function problem i.e.
you need to write your solution in the form Function(s) only.
Driver Code to call/invoke your function would be added by GfG's Online Judge.*/
/* Link list Node
struct Node {
int data;
Node* next;
}; */
/* Should return data of middle node. If linked list is empty, then -1*/
int getMiddle(Node *head)
{
// Your code here
Node *sp=head,*fp=head;
if(head==NULL){
return -1;
}
while(fp && fp->next){
sp=sp->next;
fp=fp->next->next;
}
return sp->data;
}
| true |
9d797a32f32c255bf49924a504df48c8e34c07dc | C++ | adityaXXX/Spoj | /ARMY.cpp | UTF-8 | 480 | 2.671875 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int main(){
int t;
std::cin >> t;
while (t--) {
int n, m;
std::cin >> n >> m;
int N = INT_MIN, M = INT_MIN, temp;
for(int i = 0; i < n; i++){
std::cin >> temp;
if(temp > N)
N = temp;
}
for(int i = 0; i < m; i++){
std::cin >> temp;
if(temp > M)
M = temp;
}
if(N<M)
std::cout << "MechaGodzilla" << '\n';
else
std::cout << "Godzilla" << '\n';
}
}
| true |
5bc6f619f270f6517f3d318d876ffd69f552697b | C++ | MarwenAouiti/competitiveProgrammingAlgorithms | /Backtracking.cpp | UTF-8 | 1,453 | 3.4375 | 3 | [] | no_license | #include <bits/stdc++.h>
/**
backtrakingAlgorithms(Permute a string)
Pseudocode :
fonction permute(s):
if s is an empty string :
nothing to do
else :
foreach character in s :
choose c to be first
permute the rest of s
un-choose c
**/
using namespace std;
void permute(string s);
void combin(string s, int len);
int main()
{
permute("Google");
return 0;
}
void permuteHelper(string s , string chosen,set<string>& alreadyPrinted) {
cout<<"permuteHelper (\""<<s<<"\",\""<<chosen<<"\")"<<endl;
/**
File I/O
**/
if(s.empty()) {
const bool is_in = alreadyPrinted.find(chosen) != alreadyPrinted.end();
if(!(is_in))
{
cout<<chosen<<endl;
alreadyPrinted.insert(chosen);
}
} else {
for(int i=0;i<(int)s.length();i++) {
/** choose */
char c = s[i];
chosen += c;
s.erase(i,1);
/**Explore*/
permuteHelper(s,chosen,alreadyPrinted);
/*** un-choose */
s.insert(i,1,c);
chosen.erase(chosen.length()-1,1);
}
}
}
void permute(string s) {
set<string> chosen;
permuteHelper(s, "",chosen);
}
| true |
35ce62b57a29d25481a5b19b22230b849a787463 | C++ | wangxx2026/universe | /ideas/procpp/mixin_handler/tests/map.cpp | UTF-8 | 786 | 2.640625 | 3 | [] | no_license | #include "ReactHandler.h"
#include <map>
#include <iostream>
using namespace std;
int main()
{
map<string, string> m;
L.debug_log("prepare map");
for (int i = 0; i < 10000000; i++) {
m[Utils::rand_string(50)] = Utils::rand_string(20);
}
L.debug_log("look up map");
auto start = Utils::now();
for (int i = 0; i < 1000; i++) {
auto f = m.find(Utils::rand_string(50));
}
auto end = Utils::now();
auto elapsed_get = end - start;
for (int i = 0; i < 1000; i++) {
m[Utils::rand_string(50)] = Utils::rand_string(20);
}
auto elapsed_set = Utils::now() - end;
cout << "1000 look up tooks " << elapsed_get.count() << "s\r\n";
cout << "1000 set tooks " << elapsed_set.count() << "s\r\n";
return 0;
}
| true |
124ba7e16ed69eb0c6f30407f39649e7950a7e19 | C++ | vladimir-123/Straustrup | /u3_task6.cpp | UTF-8 | 749 | 3.328125 | 3 | [] | no_license | #include <iostream>
// программа получает на вход 3 числа и выводит их в порядке убывания
int main(int argc, char const *argv[])
{
std::cout << "Enter three numbers:\n";
int a, b, c;
std::cin >> a >> b >> c;
if (a >= b && a >= c){
std::cout << a << ", ";
if (b >= c){
std::cout << b << ", " << c << ".\n";
} else {
std::cout << c << ", " << b << ".\n";
}
} else if (b >= c){
std::cout << b << ", ";
if (a >= c){
std::cout << a << ", " << c << ".\n";
} else {
std::cout << c << ", " << a << ".\n";
}
} else {
std::cout << c << ", ";
if (a >= b){
std::cout << a << ", " << b << ".\n";
} else {
std::cout << b << ", " << a << ".\n";
}
}
return 0;
} | true |
a2fc7b232acbbb86d3dd7eb8e2f51d8d4f727397 | C++ | patriquus/PROGRAMOWANIE-TOTAL | /C++/for gwiazdki2.cpp | UTF-8 | 353 | 2.6875 | 3 | [] | no_license | #include <cstdlib>
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
int x;
cin>>x;
for(int i=x; i>1; i--)
{
for(int j=1; j<=i; j++)
{
cout<<"* ";
}
cout<<endl;
}
for(int i=1; i<x+1; i++)
{
for(int j=1; j<=i; j++)
{
cout<<"* ";
}
cout<<endl;
}
system("pause");
return 0;
}
| true |
7ece717c4b628b575b1180d037499b87700e349b | C++ | N1MBER/AlgorithmAndDataStructure | /Second_Part/P3210_MKolesnikov_1322.cpp | UTF-8 | 904 | 2.859375 | 3 | [] | no_license | #include <iostream>
using namespace std;
int first_char;
int m = 100000;
string str;
int *counts = new int[m];
int *analog;
int sum = 0;
char *result_word;
int main() {
cin >> first_char;
cin >> str;
analog = new int[m];
result_word = new char [str.length()];
for (int i = 0; i < m; i++) {
counts[i]=0;
}
for (int j = 0; j < str.length(); j++) {
counts[str[j]]++;
}
for (int l = 0; l < m; l++) {
sum += counts[l];
counts[l] = sum - counts[l];
}
for(int m = 0; m < str.length(); m++){
analog[counts[str[m]]] = m;
counts[str[m]]++;
}
int order = analog[first_char-1];
for (int w = 0; w < str.length() ; w++) {
result_word[w] = str[order];
order = analog[order];
}
for (int i = 0; i < str.length(); i++){
cout << result_word[i];
}
cout << endl;
return 0;
} | true |
69793edfdbb4095b9d15fbe7aac37311c13ce0a4 | C++ | Dongeun1206/SGA | /2017 1228 스택 큐 풀큐 원형 큐/ConsoleApplication1/cPoolingQueue.cpp | UHC | 1,138 | 3.109375 | 3 | [] | no_license | #include "stdafx.h"
#include "cPoolingQueue.h"
#include "cQueue.h"
#include "cNode.h"
cPoolingQueue::cPoolingQueue()
{
m_pQueue = new cQueue;
m_pMemoryPool = new cQueue;
}
cPoolingQueue::~cPoolingQueue()
{
delete m_pQueue;
m_pQueue = NULL;
delete m_pMemoryPool;
m_pMemoryPool = NULL;
}
void cPoolingQueue::Enqueue(int n)
{
if (m_pMemoryPool->IsEmpty())
{
m_pQueue->Enqueue(n);
}
else
{
cNode* temp = m_pMemoryPool->Dequeue();
if (temp != NULL)
{
temp->SetValue(n);
m_pQueue->Enqueue(temp);
}
else
m_pQueue->Enqueue(n);
}
//Ǯ ٸ
//Ǯ ť ִٸ Ǯ ͼ .
}
cNode * cPoolingQueue::Dequeue()
{
cNode* temp = m_pQueue->Dequeue();
m_pMemoryPool->Enqueue(temp);
return temp;
}
void cPoolingQueue::Print()
{
cNode* iter = m_pQueue->m_pFront;
// ÿ÷ο , Ϲ
while (iter != NULL)
{
cout << iter->GetValue() << endl;
iter = iter->GetNext();
}
}
bool cPoolingQueue::IsEmpty()
{
return m_pMemoryPool->IsEmpty();
}
| true |
7d306d857e10c5bb7813ba38d6bd1fd8c25983b5 | C++ | A3mercury/Backus-Naur-Form | /Backus-Naur Form/Backus-Naur Form/Source.cpp | UTF-8 | 1,211 | 2.921875 | 3 | [] | no_license | // Backus-Naur Form
// Austin Andrews
// Visual Studio 2013
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
const string INPUT = "bnf.in";
const string OUTPUT = "bnf.out";
const string HALT = "HALT";
bool isXNumber(string X)
{
if (X == "0") return true;
else if (X == "1") return true;
else if (X == "2") return true;
else if (X == "3") return true;
else if (X == "4") return true;
else if (X == "5") return true;
else if (X == "6") return true;
else if (X == "7") return true;
else if (X == "8") return true;
else if (X == "9") return true;
else return false;
}
bool isXOp(string X)
{
if (X == "+") return true;
else if (X == "-") return true;
else return false;
}
bool isXVariable(string X)
{
if (X == "x") return true;
else if (X == "y") return true;
else if (X == "z") return true;
else return false;
}
string whatIsX(string X)
{
if (isXNumber(X))
return "num";
else if (isXOp(X))
return "op";
else if (isXVariable(X))
return "var";
}
void main()
{
ifstream fin(INPUT);
if (fin)
{
ofstream fout(OUTPUT);
string readX;
fin >> readX;
string X = whatIsX(readX);
fout.close();
fin.close();
}
else
{
cout << "Input file not found." << endl;
}
} | true |
bdc2f55a557ca74da76a1aee2168f1a331d6d8ae | C++ | egeigel/MPI_Scheduling | /Downloads/MPI/MPI/MPI/static_sched.cpp | UTF-8 | 2,440 | 2.828125 | 3 | [] | no_license | #include <iostream>
#include <cmath>
#include <cstdlib>
#include <chrono>
#include <mpi.h>
#ifdef __cplusplus
extern "C" {
#endif
float f1(float x, int intensity);
float f2(float x, int intensity);
float f3(float x, int intensity);
float f4(float x, int intensity);
#ifdef __cplusplus
}
#endif
float (*function) (float,int);
int main (int argc, char* argv[])
{
if (argc < 6)
{
std::cerr<<"usage: "<<argv[0]<<" <functionid> <a> <b> <n> <intensity>"<<std::endl;
return -1;
}
MPI_Comm comm;
int rank, size;
MPI_Init (&argc, &argv);
MPI_Comm_rank (MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &size);
int a = atoi(argv[2]);
int n = atoi(argv[4]);
int intensity = atoi(argv[5]);
int chunkSize = n/size;
int tag = MPI_ANY_TAG;
double globalResult = 0.0;
float multiplier = (atoi(argv[3])-a)/(float)n;
switch(atoi(argv[1])){
case 1:
function = &f1;
break;
case 2:
function = &f2;
break;
case 3:
function = &f3;
break;
case 4:
function = &f4;
break;
default:
std::cerr<<"Invalid function number provided\n";
return -1;
}
std::chrono::time_point<std::chrono::system_clock> start = std::chrono::system_clock::now();
int arrStart = rank*chunkSize;
int arrEnd = (rank+1)*chunkSize;
if (rank==size-1){
arrEnd = n;
}
double result = 0.0;
//compute local result
for (int x=arrStart;x<arrEnd;x++){
result += (double)function(a + (x + 0.5) * multiplier, intensity) * multiplier;
}
//send to master node
if (rank!=0){
MPI_Send(&result,1,MPI_DOUBLE_PRECISION,0,100+rank,MPI_COMM_WORLD);
}
//receive as master node and add together
else{
globalResult = result;
for (int x = 1; x < size; ++x)
{
MPI_Status status;
MPI_Recv(&result,1,MPI_DOUBLE_PRECISION,x,100+x,MPI_COMM_WORLD,&status);
globalResult += result;
}
}
MPI_Finalize();
std::chrono::time_point<std::chrono::system_clock> end = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed_seconds = end-start;
if(rank == 0){
std::cout<<globalResult<<std::endl;
std::cerr<<elapsed_seconds.count()<<std::endl;
}
return 0;
}
| true |
7e053d9d614665505bba9dba6266d3bc4a2e3d25 | C++ | yoogle96/algorithm | /BOJ/알고리즘 분류/다이나믹 프로그래밍/2133.cpp | UTF-8 | 281 | 2.703125 | 3 | [] | no_license | #include <iostream>
using namespace std;
int DP[31];
int N;
int main() {
cin >> N;
DP[0] = 1;
DP[1] = 0;
DP[2] = 3;
for (int i = 4; i <= N; i+=2){
DP[i]=DP[i-2]*3;
for(int j=4;i-j>=0;j+=2)
DP[i]+=DP[i-j]*2;
}
cout << DP[N];
} | true |
a04cde97e0352b0d63014c4b44a23fb943974754 | C++ | Sieunguoimay/GameWandering_Dec2016_Win32_VS_Backup | /Dec2016GameProject/Button.cpp | UTF-8 | 2,597 | 3.125 | 3 | [] | no_license | #include "Button.h"
Button::Button(float x, float y, float w, float h, Texture*texture, Sound*sound, Sound*sound2)
:ButtonDefault(x,y,w,h,texture),sound(sound),sound2(sound2)
{
buttonState = 0;//0123
dead = false;
}
Button::~Button()
{
dead = false;
delete rectangle;
rectangle = NULL;
sound = NULL;
sound2 = NULL;
texture = NULL;
}
void Button::reset()
{
dead = false;
pressed = false;
buttonState = NORMAL;
}
void Button::readMouseState(bool state)
{
if (state) {
buttonState = PUSH;
pressed = true;
}
else {
if (buttonState == NORMAL)
sound2->play();
buttonState = ACTIVE;
}
}
void Button::handleEvent(SDL_Event & mainEvent)
{
if (mainEvent.type == SDL_MOUSEBUTTONDOWN) {
buttonState = PUSH;
pressed = true;
}else if (mainEvent.type == SDL_MOUSEBUTTONUP) {
buttonState = ACTIVE;
pressed = false;
}
else if (mainEvent.type == SDL_MOUSEMOTION) {
if (pressed)
buttonState = PUSH;
else
{
if (buttonState == NORMAL)
sound2->play();
buttonState = ACTIVE;
}
}
}
void Button::setButtonState(int buttonState)
{
this->buttonState = buttonState;
}
void Button::display()
{
texture->render((int)(rectangle->x - rectangle->w / 2),(int)( rectangle->y - rectangle->h / 2),
(int)rectangle->w,(int)rectangle->h,buttonState);
if (pressed) {
if (!dead)
sound->play();
dead = true;
}
}
bool Button::checkInside(float mouseX, float mouseY) const
{
if (mouseX < rectangle->x - rectangle->w/2)
return false;
if (mouseX > rectangle->x+rectangle->w/2)
return false;
if (mouseY < rectangle->y - rectangle->h/2)
return false;
if (mouseY > rectangle->y + rectangle->h/2)
return false;
return true;
}
bool Button::isPressed() const
{
return dead;
}
ButtonDefault::ButtonDefault(float x, float y, float w, float h, Texture * texture)
:texture(texture)
{
rectangle = new Rectangle(x, y, w, h);
}
ButtonDefault::~ButtonDefault()
{
}
void ButtonDefault::handleEvent(SDL_Event & mainEvent)
{
}
void ButtonDefault::setButtonState(int buttonState)
{
}
void ButtonDefault::display()
{
texture->render((int)(rectangle->x - rectangle->w / 2.0f), (int)(rectangle->y - rectangle->h / 2.0f),
(int)rectangle->w, (int)rectangle->h, ButtonState::DISABLED);
}
bool ButtonDefault::checkInside(float x, float y) const
{
return false;
}
bool ButtonDefault::isPressed() const
{
return false;
}
Rectangle * ButtonDefault::getRectangle()
{
return rectangle;
}
void ButtonDefault::setPosition(float x, float y)
{
rectangle->x = x;
rectangle->y = y;
}
Size * ButtonDefault::getTextureSize()
{
return texture->getSize();
}
| true |
67892151a1cb69c880de1bb890cf24d62408221b | C++ | cuom1999/CP | /HashCode_2020/sortfirst.cpp | UTF-8 | 8,752 | 2.625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
string subtasks[6] = {"a_example.txt", "b_read_on.txt",
"c_incunabula.txt", "d_tough_choices.txt",
"e_so_many_books.txt", "f_libraries_of_the_world.txt"};
string output(int index) {
char c = (char) (index + 'a');
string res = "output_";
res += c;
res += ".txt";
return res;
}
//constructor: MinCostFlow<int, int> mcmf(n)
//res : mcmf.minCostMaxFlow(source, sink)
//trace: add one more instance "real" to class Edge to note if it is the original edge
//for (auto e: G[i]) (i, e.to, mcmf.getFlow(e)) = (u, v, cap)
// tested: https://open.kattis.com/problems/mincostmaxflow
template<typename flow_t = int, typename cost_t = int>
struct MinCostFlow {
struct Edge {
cost_t c;
flow_t f;
int to, rev;
Edge(int _to, cost_t _c, flow_t _f, int _rev) : c(_c), f(_f), to(_to), rev(_rev) {}
};
int N;
vector<vector<Edge> > G;
// MinCostFlow(int _N, int _S, int _T) : N(_N), S(_S), T(_T), G(_N), eps(0) {}
MinCostFlow(int _N): N(_N), G(_N), eps(0) {}
void addEdge(int a, int b, flow_t cap, cost_t cost) {
assert(cap >= 0);
assert(a >= 0 && a < N && b >= 0 && b < N);
if (a == b) { assert(cost >= 0); return; }
cost *= N;
eps = max(eps, abs(cost));
G[a].emplace_back(b, cost, cap, G[b].size());
G[b].emplace_back(a, -cost, 0, G[a].size() - 1);
}
flow_t getFlow(Edge const &e) {
return G[e.to][e.rev].f;
}
pair<flow_t, cost_t> minCostMaxFlow(int S, int T) {
cost_t retCost = 0;
for (int i = 0; i<N; ++i) {
for (Edge &e : G[i]) {
retCost += e.c*(e.f);
}
}
//find max-flow
flow_t retFlow = max_flow(S, T);
h.assign(N, 0); ex.assign(N, 0);
isq.assign(N, 0); cur.assign(N, 0);
queue<int> q;
for (; eps; eps >>= scale) {
//refine
fill(cur.begin(), cur.end(), 0);
for (int i = 0; i < N; ++i) {
for (auto &e : G[i]) {
if (h[i] + e.c - h[e.to] < 0 && e.f) push(e, e.f);
}
}
for (int i = 0; i < N; ++i) {
if (ex[i] > 0){
q.push(i);
isq[i] = 1;
}
}
// make flow feasible
while (!q.empty()) {
int u = q.front(); q.pop();
isq[u]=0;
while (ex[u] > 0) {
if (cur[u] == G[u].size()) {
relabel(u);
}
for (unsigned int &i=cur[u], max_i = G[u].size(); i < max_i; ++i) {
Edge &e = G[u][i];
if (h[u] + e.c - h[e.to] < 0) {
push(e, ex[u]);
if (ex[e.to] > 0 && isq[e.to] == 0) {
q.push(e.to);
isq[e.to] = 1;
}
if (ex[u] == 0) break;
}
}
}
}
if (eps > 1 && eps>>scale == 0) {
eps = 1<<scale;
}
}
for (int i = 0; i < N; ++i) {
for (Edge &e : G[i]) {
retCost -= e.c*(e.f);
}
}
return make_pair(retFlow, retCost / 2 / N);
}
private:
static constexpr cost_t INFCOST = numeric_limits<cost_t>::max()/2;
static constexpr int scale = 2;
cost_t eps;
vector<unsigned int> isq, cur;
vector<flow_t> ex;
vector<cost_t> h;
vector<vector<int> > hs;
vector<int> co;
void add_flow(Edge& e, flow_t f) {
Edge &back = G[e.to][e.rev];
if (!ex[e.to] && f) {
hs[h[e.to]].push_back(e.to);
}
e.f -= f; ex[e.to] += f;
back.f += f; ex[back.to] -= f;
}
void push(Edge &e, flow_t amt) {
if (e.f < amt) amt = e.f;
e.f -= amt; ex[e.to] += amt;
G[e.to][e.rev].f += amt; ex[G[e.to][e.rev].to] -= amt;
}
void relabel(int vertex){
cost_t newHeight = -INFCOST;
for (unsigned int i = 0; i < G[vertex].size(); ++i){
Edge const&e = G[vertex][i];
if(e.f && newHeight < h[e.to] - e.c){
newHeight = h[e.to] - e.c;
cur[vertex] = i;
}
}
h[vertex] = newHeight - eps;
}
flow_t max_flow(int S, int T) {
ex.assign(N, 0);
h.assign(N, 0); hs.resize(2*N);
co.assign(2*N, 0); cur.assign(N, 0);
h[S] = N;
ex[T] = 1;
co[0] = N-1;
for (auto &e : G[S]) {
add_flow(e, e.f);
}
if (hs[0].size()) {
for (int hi = 0; hi>=0;) {
int u = hs[hi].back();
hs[hi].pop_back();
while (ex[u] > 0) { // discharge u
if (cur[u] == G[u].size()) {
h[u] = 1e9;
for(unsigned int i = 0; i < G[u].size(); ++i) {
auto &e = G[u][i];
if (e.f && h[u] > h[e.to]+1) {
h[u] = h[e.to]+1, cur[u] = i;
}
}
if (++co[h[u]], !--co[hi] && hi < N) {
for (int i = 0; i < N; ++i) {
if (hi < h[i] && h[i] < N) {
--co[h[i]];
h[i] = N + 1;
}
}
}
hi = h[u];
} else if (G[u][cur[u]].f && h[u] == h[G[u][cur[u]].to]+1) {
add_flow(G[u][cur[u]], min(ex[u], G[u][cur[u]].f));
} else {
++cur[u];
}
}
while (hi>=0 && hs[hi].empty()) {
--hi;
}
}
}
return -ex[S];
}
};
int nBooks, nLibs, nDays;
int score[100005];
struct Lib {
int signupTime;
int booksPerDay;
vector<int> books;
} lib[100005];
// return total score
// using res to print output
int calcScore(vector<int> &libOrder, vector<vector<int>>& res) {
vector<bool> scanned(nBooks), signedUp(nLibs);
res.clear();
int curDay = 0;
int totalScore = 0;
auto verLib = [&](int a) {return a;};
auto verBook = [&](int a) {return nLibs + a;};
int source = nLibs + nBooks;
int sink = source + 1;
MinCostFlow<int, int> mcmf(sink + 1);
for (auto index: libOrder) {
vector<int> toScan;
int remainTime = nDays - curDay;
if (signedUp[index] || lib[index].signupTime >= remainTime) continue;
int booksCanScan = (remainTime - lib[index].signupTime)
* lib[index].booksPerDay;
mcmf.addEdge(source, verLib(index), booksCanScan, 0);
// may need to use some heuristics here
for (auto i: lib[index].books) {
mcmf.addEdge(verLib(index), verBook(i), 1, -score[i]);
}
}
for (int i = 0; i < nBooks; i++) {
mcmf.addEdge(verBook(i), sink, 1, 0);
}
totalScore = mcmf.minCostMaxFlow(source, sink).second;
vector<int> resBooks[100005];
for (int i = 0; i < nLibs; i++) {
for (auto e: mcmf.G[verLib(i)]) {
if (mcmf.getFlow(e) && e.c < 0) {
resBooks[i].push_back(e.to - nLibs);
}
}
}
for (auto i: libOrder) {
res.push_back(resBooks[i]);
}
return -totalScore;
}
vector<int> sortLib() {
vector<int> res;
for (int i = 0; i < nLibs; i++) {
res.push_back(i);
}
sort(res.begin(), res.end(), [&](int a, int b) {
return lib[a].signupTime < lib[b].signupTime;
});
return res;
}
int main() {
int sub = 2;
freopen(subtasks[sub].c_str(), "r", stdin);
freopen(output(sub).c_str(), "w", stdout);
ios::sync_with_stdio(0);
cin >> nBooks >> nLibs >> nDays;
for (int i = 0; i < nBooks; i++) {
cin >> score[i];
}
for (int i = 0; i < nLibs; i++) {
int numBooks;
cin >> numBooks >> lib[i].signupTime >> lib[i].booksPerDay;
for (int j = 1; j <= numBooks; j++) {
int x;
cin >> x;
lib[i].books.push_back(x);
}
}
vector<vector<int>> res;
vector<int> order = {0, 1};
cout << calcScore(order, res) << endl;
return 0;
} | true |
a21e6973fffd2e9d193639bdd6daf2acedca92b5 | C++ | kartikdutt18/CPP-and-its-Algo-based-Problems | /To-Be-Restructured/Competitive/Count_Sub_Tree_With_Given_sum.cpp | UTF-8 | 1,081 | 3.78125 | 4 | [] | no_license | //https://practice.geeksforgeeks.org/problems/count-number-of-subtrees-having-given-sum/1
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
struct Node
{
int data;
struct Node *left;
struct Node *right;
Node(int x)
{
data = x;
left = right = NULL;
}
};
int ConvertTree(Node *&root)
{
if (root == NULL)
return 0;
int temp = root->data;
int lsum = ConvertTree(root->left);
int rsum = ConvertTree(root->right);
root->data = lsum + rsum;
return temp + root->data;
}
int GetCount(Node *root, int x)
{
if (root == NULL)
return 0;
int ans = 0;
queue<Node *> q;
q.push(root);
while (!q.empty())
{
Node *cur = q.front();
q.pop();
if (cur->data == x)
ans++;
if (cur->right)
q.push(cur->right);
if (cur->left)
q.push(cur->left);
}
return ans;
}
int countSubtreesWithSumX(Node *root, int x)
{
if (!root)
return 0;
ConvertTree(root);
cout << GetCount(root, x) << endl;
}
| true |
1454cb3601674f4cab0ba27e3dc8efef79a39d09 | C++ | alexandraback/datacollection | /solutions_5765824346324992_0/C++/mkocian/b-barbers2.cpp | UTF-8 | 1,430 | 2.5625 | 3 | [] | no_license | #include<cstdio>
#include<vector>
#include<map>
#include<set>
#include<iostream>
#include<iomanip>
#include<time.h>
#include<sstream>
#include<fstream>
#include<string>
#include<string.h>
#include<algorithm>
#include<queue>
#define nl printf("\n")
using namespace std;
int gcd(int a, int b)
{
for (;;)
{
if (a == 0) return b;
b %= a;
if (b == 0) return a;
a %= b;
}
}
int lcm(int a, int b)
{
int temp = gcd(a, b);
return temp ? (a / temp * b) : 0;
}
int main()
{
int T;
scanf("%d", &T);
for (int t = 1; t <= T; t++) {
int B;
scanf("%d", &B);
int N;
scanf("%d", &N);
priority_queue<pair<int, int>> Q;
int LCM = 1;
vector<int> barbers(B, 0);
for (int k = 0; k < B; k++) {
int Mk;
scanf("%d", &Mk);
barbers[k] = Mk;
LCM = lcm(LCM, Mk);
Q.push(make_pair(-0, -k));
}
int sum = 0;
for (int k = 0; k < B; k++) {
sum += LCM / barbers[k];
}
//printf("sum %d LCM %d\n", sum, LCM);
N = 1 + (N-1) % sum;
int barber;
for (int n = 0; n < N; n++) {
auto a = Q.top();
barber = -a.second;
Q.pop();
Q.push(make_pair(a.first - barbers[barber], -barber));
}
printf("Case #%d: %d\n", t, barber+1);
}
}
| true |
a6f382e97669eb0bcccc347fb5fa1cb2911e9d1d | C++ | jbengtsson/jmbgsddb | /src/glps_ops.cpp | UTF-8 | 4,823 | 2.859375 | 3 | [] | no_license |
#include "math.h"
#include <sstream>
#include <limits>
#include <stdexcept>
#include "glps_parser.h"
namespace {
// Numeric operations
int unary_negate(parse_context* ctxt, expr_value_t *R, const expr_t * const *A)
{
*R = -boost::get<double>(A[0]->value);
return 0;
}
int unary_sin(parse_context* ctxt, expr_value_t *R, const expr_t * const *A)
{
*R = sin(boost::get<double>(A[0]->value));
return 0;
}
int unary_cos(parse_context* ctxt, expr_value_t *R, const expr_t * const *A)
{
*R = cos(boost::get<double>(A[0]->value));
return 0;
}
int unary_tan(parse_context* ctxt, expr_value_t *R, const expr_t * const *A)
{
*R = tan(boost::get<double>(A[0]->value));
return 0;
}
int unary_asin(parse_context* ctxt, expr_value_t *R, const expr_t * const *A)
{
*R = asin(boost::get<double>(A[0]->value));
return 0;
}
int unary_acos(parse_context* ctxt, expr_value_t *R, const expr_t * const *A)
{
*R = acos(boost::get<double>(A[0]->value));
return 0;
}
int unary_atan(parse_context* ctxt, expr_value_t *R, const expr_t * const *A)
{
*R = atan(boost::get<double>(A[0]->value));
return 0;
}
int binary_add(parse_context* ctxt, expr_value_t *R, const expr_t * const *A)
{
*R = boost::get<double>(A[0]->value)+boost::get<double>(A[1]->value);
return 0;
}
int binary_sub(parse_context* ctxt, expr_value_t *R, const expr_t * const *A)
{
*R = boost::get<double>(A[0]->value)-boost::get<double>(A[1]->value);
return 0;
}
int binary_mult(parse_context* ctxt, expr_value_t *R, const expr_t * const *A)
{
*R = boost::get<double>(A[0]->value)*boost::get<double>(A[1]->value);
return 0;
}
int binary_div(parse_context* ctxt, expr_value_t *R, const expr_t * const *A)
{
double result = boost::get<double>(A[0]->value)/boost::get<double>(A[1]->value);
if(!isfinite(result)) {
ctxt->last_error = "division results in non-finite value";
return 1;
}
*R = result;
return 0;
}
// beamline operations
int unary_bl_negate(parse_context* ctxt, expr_value_t *R, const expr_t * const *A)
{
// reverse the order of the beamline
const std::vector<std::string>& line = boost::get<std::vector<std::string> >(A[0]->value);
std::vector<std::string> ret(line.size());
std::copy(line.rbegin(),
line.rend(),
ret.begin());
*R = ret;
return 0;
}
template<int MULT, int LINE>
int binary_bl_mult(parse_context* ctxt, expr_value_t *R, const expr_t * const *A)
{
// multiple of scale * beamline repeats the beamline 'scale' times
assert(A[MULT]->etype==glps_expr_number);
assert(A[LINE]->etype==glps_expr_line);
double factor = boost::get<double>(A[MULT]->value);
if(factor<0.0 || factor>std::numeric_limits<unsigned>::max()) {
ctxt->last_error = "beamline scale by negative value or out of range value";
return 1;
}
unsigned factori = (unsigned)factor;
const std::vector<std::string>& line = boost::get<std::vector<std::string> >(A[LINE]->value);
std::vector<std::string> ret(line.size()*factori);
if(factori>0)
{
std::vector<std::string>::iterator outi = ret.begin();
while(factori--)
outi = std::copy(line.begin(),
line.end(),
outi);
}
*R = ret;
return 0;
}
}
parse_context::parse_context()
:last_line(0), error_scratch(300), scanner(NULL)
{
addop("-", &unary_negate, glps_expr_number, 1, glps_expr_number);
addop("sin", &unary_sin, glps_expr_number, 1, glps_expr_number);
addop("cos", &unary_cos, glps_expr_number, 1, glps_expr_number);
addop("tan", &unary_tan, glps_expr_number, 1, glps_expr_number);
addop("asin",&unary_asin,glps_expr_number, 1, glps_expr_number);
addop("acos",&unary_acos,glps_expr_number, 1, glps_expr_number);
addop("atan",&unary_atan,glps_expr_number, 1, glps_expr_number);
// aliases to capture legacy behavour :P
addop("arcsin",&unary_asin,glps_expr_number, 1, glps_expr_number);
addop("arccos",&unary_acos,glps_expr_number, 1, glps_expr_number);
addop("arctan",&unary_atan,glps_expr_number, 1, glps_expr_number);
addop("+", &binary_add, glps_expr_number, 2, glps_expr_number, glps_expr_number);
addop("-", &binary_sub, glps_expr_number, 2, glps_expr_number, glps_expr_number);
addop("*", &binary_mult,glps_expr_number, 2, glps_expr_number, glps_expr_number);
addop("/", &binary_div, glps_expr_number, 2, glps_expr_number, glps_expr_number);
addop("-", &unary_bl_negate, glps_expr_line, 1, glps_expr_line);
addop("*", &binary_bl_mult<0,1>, glps_expr_line, 2, glps_expr_number, glps_expr_line);
addop("*", &binary_bl_mult<1,0>, glps_expr_line, 2, glps_expr_line, glps_expr_number);
}
parse_context::~parse_context()
{
}
| true |
03c7036bbadb6541cf45c3c280c7681a3efad5dd | C++ | Personal-Learnings/CPP_Learning_CodeLite | /Workspace/References/main.cpp | UTF-8 | 894 | 3.734375 | 4 | [] | no_license | #include <iostream>
#include <vector>
#include <string>
using namespace std;
void displayVector(const vector<string> input);
int main() {
vector<string> names {"Madan", "Jayashree", "Yashika"};
for(auto name : names)
name = "New Name";
cout << "Items in the Vector will not be modified : ";
displayVector(names);
for(auto &name : names)
name = "Hello " + name;
cout << "The Modified Items in the Vector : ";
displayVector(names);
return 0;
}
void displayVector(const vector<string> input) {
cout << endl;
//Here It Creates copy of each item in the vector, hence uses more memory
for(const auto i : input)
cout << i << " ";
cout << endl;
//Here It uses Reference and Saves space
for(const auto &i : input)
cout << i << " ";
cout << endl << endl;
} | true |
8d16f3f983d843bf1579e5f9cc1e7c56c8674224 | C++ | liyuan989/blink | /src/blink/TcpClient.cpp | UTF-8 | 3,941 | 2.546875 | 3 | [
"BSD-3-Clause"
] | permissive | #include <blink/TcpClient.h>
#include <blink/SocketBase.h>
#include <blink/EventLoop.h>
#include <blink/Connector.h>
#include <blink/Log.h>
#include <boost/bind.hpp>
#include <assert.h>
#include <stdio.h>
namespace blink
{
namespace detail
{
void removeConnection(EventLoop* loop, const TcpConnectionPtr& connection)
{
loop->queueInLoop(boost::bind(&TcpConnection::connectDestroyed, connection));
}
void removeConnector(const ConnectorPtr& connector)
{
// TODO
}
} // namespace detail
TcpClient::TcpClient(EventLoop* loop, const InetAddress& server_addr, const string& name_arg)
: loop_(CHECK_NOTNULL(loop)),
connector_(new Connector(loop, server_addr)),
name_(name_arg),
connection_callback_(defaultConnectionCallback),
message_callback_(defaultMessageCallback),
retry_(false),
connect_(false),
next_connection_id_(1)
{
connector_->setNewConnectionCallback(boost::bind(&TcpClient::newConnection, this, _1));
LOG_INFO << "TcpClient::TcpClient[" << name_ // FIXME: setConnectFailCallback
<< "] - connector " << boost::get_pointer(connector_);
}
TcpClient::~TcpClient()
{
LOG_INFO << "TcpClient::~TcpClient[" << name_
<< "] - connector " << boost::get_pointer(connector_);
TcpConnectionPtr connection;
bool unique = false;
{
MutexLockGuard guard(mutex_);
unique = connection_.unique();
connection = connection_;
}
if (connection)
{
assert(loop_ = connection->getLoop());
// not 100% safe, if we are in different thread.
CloseCallback cb = boost::bind(detail::removeConnection, loop_, _1);
loop_->runInLoop(boost::bind(&TcpConnection::setCloseCallback, connection, cb));
if (unique)
{
connection->forceClose();
}
}
else
{
connector_->stop();
loop_->runAfter(1, boost::bind(detail::removeConnector, connector_));
}
}
void TcpClient::connect()
{ // FIXME: check state
LOG_INFO << "TcpClient::connect[" << name_ << "] - connecting to "
<< connector_->serverAddress().toIpPort();
connect_ = true;
connector_->start();
}
void TcpClient::disconnect()
{
connect_ = false;
{
MutexLockGuard guard(mutex_);
if (connection_)
{
connection_->shutdown();
}
}
}
void TcpClient::stop()
{
connect_ = false;
connector_->stop();
}
void TcpClient::newConnection(int sockfd)
{
loop_->assertInLoopThread();
InetAddress peer_addr(sockets::getPeerAddr(sockfd));
char buf[32];
snprintf(buf, sizeof(buf), ":%s#%d", peer_addr.toIpPort().c_str(), next_connection_id_);
++next_connection_id_;
string connection_name = name_ + buf;
InetAddress locak_addr(sockets::getLocalAddr(sockfd));
TcpConnectionPtr connection(new TcpConnection(loop_, connection_name, sockfd, locak_addr, peer_addr));
connection->setConnectionCallback(connection_callback_);
connection->setMessageCallback(message_callback_);
connection->setWriteCompleteCallback(write_complete_callback_);
connection->setCloseCallback(boost::bind(&TcpClient::removeConnection, this, _1)); // unsafe
{
MutexLockGuard guard(mutex_);
connection_ = connection;
}
connection->connectEstablished();
}
void TcpClient::removeConnection(const TcpConnectionPtr& connection)
{
loop_->assertInLoopThread();
assert(loop_ == connection->getLoop());
{
MutexLockGuard guard(mutex_);
assert(connection_ == connection);
connection_.reset();
}
loop_->queueInLoop(boost::bind(&TcpConnection::connectDestroyed, connection));
if (retry_ && connect_)
{
LOG_INFO << "TcpClient::connect[" << name_ << "] - Reconnecting to "
<< connector_->serverAddress().toIpPort();
connector_->restart();
}
}
} // namespace blink
| true |
88c91458e70ff6a593a2f28e425ac669956d5115 | C++ | ZHANG-1921/JobySimlulator | /SimTimer.cpp | UTF-8 | 1,195 | 2.84375 | 3 | [] | no_license |
#include "SimTimer.hpp"
joby::SimTimer::SimTimer(double time_to_run_seconds,
double min_frame_time,
double max_frame_time)
{
mCurrentRunningTime = 0.0;
mLengthToRunSeconds = time_to_run_seconds;
mMinFrameLength = min_frame_time;
mMaxFrameLength = max_frame_time;
mIsStarted = false;
}
void joby::SimTimer::StartTimer()
{
mStartMoment = std::chrono::high_resolution_clock::now();
mPrevMoment = mStartMoment;
mIsStarted = true;
}
double joby::SimTimer::MarkFrameEnd()
{
double frame_seconds = 0.0;
if (mIsStarted)
{
auto end = std::chrono::high_resolution_clock::now();
frame_seconds = std::chrono::duration<double>(end - mPrevMoment).count();
mPrevMoment = end;
}
if (frame_seconds < mMinFrameLength)
{
frame_seconds = mMinFrameLength;
}
else if (frame_seconds > mMaxFrameLength)
{
frame_seconds = mMaxFrameLength;
}
mCurrentRunningTime += frame_seconds;
return frame_seconds;
}
bool joby::SimTimer::IsRunning() const
{
return (mIsStarted &&
(mLengthToRunSeconds > mCurrentRunningTime)) ? true : false;
}
| true |
14ac675d4ed275b3fd5dc5d40126770ab87ccf0e | C++ | Miao4382/Starting-Out-with-Cplusplus | /Chapter 8/Program Example/1+.h | UTF-8 | 1,869 | 3.75 | 4 | [] | no_license | #include<iostream>
#include<vector>
#include<cstdlib>
#include<ctime>
//constant
const int N = 10000;
//function prototype
void initialize_num(int num[], int total);
void find_num(int num[], int array_size, std::vector<int> &position, int &total_match, int number);
int main()
{
int num[N];
int total_match;
int number;
std::vector<int> position;
char choice;
//initialize num[] with random number
initialize_num(num, N);
do
{
//initialize
total_match = 0;
position.clear();
//ask user to input a number
std::cout << "What is the number you looking for: ";
std::cin >> number;
//use the find_num() to find out time of occurance and store subscript in position
find_num(num, N, position, total_match, number);
//print out total times of match and the position
std::cout << "Total times of match: " << total_match << std::endl;
std::cout << "The positions are: \n";
for (int i = 0; i<position.size(); i++)
std::cout << position[i] << std::endl;
//ask for if user wants to repeat or not
std::cout << "Do you want to test another number? (Y/N): ";
std::cin >> choice;
while (choice != 'Y' && choice != 'y' && choice != 'N' && choice != 'n')
{
std::cout << "Invalid input, please input Y or N: ";
std::cin >> choice;
}
} while (choice == 'Y' || choice == 'y');
std::cout << "You quitted.\n";
return 0;
}
void initialize_num(int num[], int total)
{
//initialize random generator
int seed;
seed = time(0);
srand(seed);
int N_max = 1000, N_min = 1;
//begin recording
for (int i = 0; i<total; i++)
num[i] = rand() % (N_max - N_min + 1) + N_min;
}
//find number function
void find_num(int num[], int array_size, std::vector<int> &position, int &total_match, int number)
{
for (int i = 0; i < array_size; i++)
{
if (num[i] == number)
{
total_match++;
position.push_back(i + 1);
}
}
} | true |
9735da64da1a1edecfb778c8a253501421c18574 | C++ | samienne/reactive | /include/reactive/stream/sharedstream.h | UTF-8 | 2,169 | 2.78125 | 3 | [] | no_license | #pragma once
#include "stream.h"
#include "sharedcontrol.h"
namespace reactive
{
namespace stream
{
template <typename T>
class SharedStream
{
template <typename TFunc>
struct OnDelete
{
~OnDelete()
{
callBack();
}
TFunc callBack;
};
public:
SharedStream(std::shared_ptr<SharedControl<T>> control) :
control_(std::move(control))
{
}
template <typename TFunc>
auto fmap(TFunc&& f) const -> Stream<std::invoke_result_t<TFunc, T>>
{
using NewType = std::invoke_result_t<TFunc, T>;
size_t index = nextIndex_++;
auto destructor = [index, control = control_]()
{
for (auto i = control->callbacks.begin();
i != control->callbacks.end(); ++i)
{
if (i->second == index)
control->callbacks.erase(i);
}
};
using NewControl = ControlWithData<NewType, decltype(destructor)>;
auto newControl = std::make_shared<NewControl>(std::move(destructor));
Handle<NewType> newHandle(newControl);
auto callback =
[newHandle=std::move(newHandle), f=std::forward<TFunc>(f)](
T value)
{
newHandle.push(f(std::forward<T>(value)));
};
control_->callbacks.push_back(
std::make_pair(std::move(callback), index));
return Stream<NewType>(std::move(newControl));
}
operator Stream<T>() const
{
return fmap([](T value) { return std::forward<T>(value); });
}
private:
std::shared_ptr<SharedControl<T>> control_;
mutable size_t nextIndex_ = 1;
};
} // stream
} // reactive
| true |
cacaadaf2e9c5dd07f9ec110315d651e9976e04a | C++ | al-ry/ood-labs | /lab7-composite/Composite/CGroup.h | UTF-8 | 752 | 2.890625 | 3 | [] | no_license | #pragma once
#include "IGroup.h"
#include <vector>
class CGroup
: public IGroup
, public std::enable_shared_from_this<IGroup>
{
public:
CGroup();
RectD GetFrame() const override;
void SetFrame(const RectD& frame) override;
OutlineStylePtr GetLineStyle() const override;
StylePtr GetFillStyle() const override;
void Draw(ICanvas& canvas) const override;
IGroupPtr GetGroup() override;
size_t GetShapesCount() const override;
IShapePtr GetShapeAtIndex(size_t index) const override;
void InsertShape(const IShapePtr& shape, size_t index = std::numeric_limits<size_t>::max()) override;
void RemoveShapeAtIndex(size_t index) override;
private:
std::vector<IShapePtr> m_group;
OutlineStylePtr m_outlineColor;
StylePtr m_fillColor;
}; | true |
3fbb0779f1149575e2bb738391c5a6b4d1c17e9a | C++ | Alex-Sindledecker/OpenGL3.3-Demo | /src/CameraFP.cpp | UTF-8 | 2,430 | 3 | 3 | [] | no_license | #include "CameraFP.h"
CameraFP::CameraFP(glm::vec3 pos, float walkSpeed)
{
this->pos = pos;
this->walkSpeed = walkSpeed;
attitude = glm::vec3(0);
front = glm::vec3(0);
sprintButton = sf::Keyboard::LShift;
sprintSpeed = 6;
up = glm::vec3(0, 1, 0);
view = glm::mat4(1.f);
xBounds = glm::vec2(0);
zBounds = glm::vec2(0);
}
CameraFP::~CameraFP()
{
}
void CameraFP::setBounds(glm::vec2 xBounds, glm::vec2 zBounds)
{
this->xBounds = xBounds;
this->zBounds = zBounds;
}
void CameraFP::setPosition(glm::vec3 pos)
{
this->pos = pos;
}
void CameraFP::setPosition(float x, float y, float z)
{
pos = glm::vec3(x, y, z);
}
void CameraFP::move(glm::vec3 displacement)
{
pos += displacement;
}
void CameraFP::move(float dx, float dy, float dz)
{
pos += glm::vec3(dx, dy, dz);
}
void CameraFP::inputProc(sf::Event& event, float dt, float mouseDx, float mouseDy)
{
float speed = walkSpeed;
if (sf::Keyboard::isKeyPressed(sf::Keyboard::LShift))
speed = sprintSpeed;
if (pos.x < xBounds.x + 0.2)
pos.x = xBounds.x + 0.2;
else if (pos.x > xBounds.y - 0.2)
pos.x = xBounds.y - 0.2;
if (pos.z < zBounds.x + 0.2)
pos.z = zBounds.x + 0.2;
else if (pos.z > zBounds.y - 0.2)
pos.z = zBounds.y - 0.2;
if (sf::Keyboard::isKeyPressed(sf::Keyboard::W))
{
pos += glm::normalize(glm::vec3(front.x, 0, front.z)) * dt * speed;
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::S))
{
pos -= glm::normalize(glm::vec3(front.x, 0, front.z)) * dt * speed;
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::A))
{
pos -= glm::normalize(glm::cross(front, up)) * dt * speed;
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::D))
{
pos += glm::normalize(glm::cross(front, up)) * dt * speed;
}
attitude.x += mouseDy;
attitude.y += mouseDx;
attitude.x = attitude.x > 89.f ? 89.f : attitude.x;
attitude.x = attitude.x < -89.f ? -89.f : attitude.x;
front = glm::normalize(glm::vec3(
cos(glm::radians(attitude.y)) * cos(glm::radians(attitude.x)),
sin(glm::radians(attitude.x)),
sin(glm::radians(attitude.y)) * cos(glm::radians(attitude.x))
));
}
void CameraFP::activateView()
{
view = glm::lookAt(pos, pos + front, up);
}
void CameraFP::setView(glm::mat4 view)
{
this->view = view;
}
glm::mat4 CameraFP::getView() const
{
return view;
}
glm::vec3 CameraFP::getPosition() const
{
return pos;
}
| true |
a6e1f10ecaf31140a6b87b8fe5c592de23b9dec8 | C++ | tmforshaw/Operating-System | /src/Kernel_Files/InputOutput/Text/TextPrint.hpp | UTF-8 | 1,267 | 2.765625 | 3 | [] | no_license | #pragma once
#include "../../Types/String.hpp"
#include "../../Types/Types.hpp"
#include "./TextModeColourCodes.hpp"
uint_16 PositionFromCoords(uint_8 x, uint_8 y); // Turn an X and Y value into the index of the position on screen
void PrintString(const char* str, uint_8 colour = DEFAULT_COLOUR); // Used to print a string to the screen
void PrintString(Type::String str, uint_8 colour = DEFAULT_COLOUR); // Used to print a string to the screen
void PrintChar(char chr, uint_8 colour = DEFAULT_COLOUR);
char GetCharAtPos(uint_16 position);
const char* HexToString(uint_8 value);
const char* HexToString(uint_16 value);
const char* HexToString(uint_32 value);
const char* HexToString(uint_64 value);
const char* HexToString(char value);
const char* HexToString(short value);
const char* HexToString(int value);
const char* HexToString(long long value);
const char* IntegerToString(uint_8 value);
const char* IntegerToString(uint_16 value);
const char* IntegerToString(uint_32 value);
const char* IntegerToString(uint_64 value);
const char* IntegerToString(char value);
const char* IntegerToString(short value);
const char* IntegerToString(int value);
const char* IntegerToString(long long value);
const char* FloatToString(float value, uint_8 decimalPlaces); | true |
8a82b1f79beb62919120aa3a4945112772aa1fa6 | C++ | cankoc95/BankManagement | /Account.cpp | UTF-8 | 1,104 | 3.140625 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <fstream>
#include <cctype>
#include <iomanip>
#include "Account.h"
Account* Account::createAccount(std::string name, TYPE type, int amount){
Account *acct = new Account(name, type, amount);
return acct;
}
bool Account::doCheck(u_int32_t num, std::string name){
if (this->acctNum == num and this->name == name) {
return true;
}
return false;
}
void Account::showAccountData(u_int32_t num, std::string name) const {
}
int Account::deposit(int amount, u_int32_t num, std::string name) {
if doCheck(num, name) {
this->depositAmount += amount;
return this->depositAmount;
}
else {
throw "ACCESS DENIED";
return -1;
}
}
int Account::withdraw(int amount, u_int32_t num, std::string name) {
if doCheck(num, name) {
this->depositAmount -= amount;
return this->depositAmount;
}
else {
throw "ACCESS DENIED";
return -1;
}
}
//to be implemented.
int Account::displayAmount() const {
return this->depositAmount;
}
TYPE Account::displayAccountType() const {
std::cout << this->acctType << std::endl;
return this->acctType;
}
| true |
f31bdb704e3ef7aa64208c7d61c781a6574f9153 | C++ | melvinabraham/DSAlgoPrep | /validparanthesis.cpp | UTF-8 | 624 | 3.296875 | 3 | [] | no_license | class Solution {
public:
bool isValid(string s) {
if (s == "")
return true;
stack <char> k;
char c;
for(int i = 0; i < s.size(); ++i) {
if(s[i] == ')' || s[i] == '}' || s[i] == ']') {
if(k.empty()) {
return false;
}
if(s[i] == ')' ||) {
c = '(';
}
else
if(s[i] == '}') {
c = '{';
}
else {
c = '[';
}
if(c != k.top()) {
return false;
}
k.pop();
}
else {
k.push(s[i]);
}
}
return true;
}
}; | true |
d93b961515397b13dbbfbfb2c958fa5b2aa7a133 | C++ | blackeywong/DataStructure | /DS7/tridiagonalAsIrregularArray.h | GB18030 | 5,691 | 3.28125 | 3 | [] | no_license | #pragma once
#ifndef _TIRDIAGONALASIRREGULARARRAY_H
#define _TIRDIAGONALASIRREGULARARRAY_H
#include <iostream>
#include "../DS5/exceptions.h"
#include "matrix.h"
using namespace std;
//ݽṹ㷨Ӧ-C++
//Exercise 25
template<class T>
class tridiagonalAsIrregularArray {
template<class T>
friend ostream& operator<<(ostream&, const tridiagonalAsIrregularArray<T>&);
template<class T>
friend istream& operator>>(istream&, tridiagonalAsIrregularArray<T>&);
public:
tridiagonalAsIrregularArray(int theN = 10);
tridiagonalAsIrregularArray(const tridiagonalAsIrregularArray<T>& m);
~tridiagonalAsIrregularArray();
T get(int i, int j) const;
void set(int i, int j, const T& value);
tridiagonalAsIrregularArray<T>& operator=(const tridiagonalAsIrregularArray<T>&);
tridiagonalAsIrregularArray<T> operator+(const tridiagonalAsIrregularArray<T>&) const;
tridiagonalAsIrregularArray<T> operator-(const tridiagonalAsIrregularArray<T>&) const;
matrix<T> operator*(const tridiagonalAsIrregularArray<T>&) const;
tridiagonalAsIrregularArray<T> transpose();
private:
void checkIndex(int i, int j) const;
void clear();
void initialize();
int n;
T** element;
};
template<class T>
void tridiagonalAsIrregularArray<T>::checkIndex(int i, int j) const {
if (i < 1 || i> n || j <1 || j> n) throw OutOfBounds();
}
template<class T>
ostream& operator<<(ostream& out, const tridiagonalAsIrregularArray<T>& m) {
for (int i = 0; i < m.n; i++) {
for (int j = 0; j < m.n; j++) {
if (i == j || i - j == 1 || i - j == -1) {
if (i == 0 || i == 1) out << m.element[i][j];
else out << m.element[i][j - i + 1]; //j - (i-1)
}
else out << " ";
out << " ";
}
out << endl;
}
return out;
}
template<class T>
istream& operator>>(istream& in, tridiagonalAsIrregularArray<T>& m) {
for (int i = 0; i < m.n; i++) {
for (int j = 0; j < 3; j++) {
if ((i == 0 || i == m.n - 1) && j == 2) break;
if (in) {
in >> m.element[i][j];
}
else
{
m.element[i][j] = 0;
}
}
}
return in;
}
template<class T>
tridiagonalAsIrregularArray<T>::tridiagonalAsIrregularArray(int theN) {
if (theN < 1) throw IllegalParameterValue("matrix size should be >=1");
n = theN;
initialize();
}
template<class T>
tridiagonalAsIrregularArray<T>::tridiagonalAsIrregularArray(const tridiagonalAsIrregularArray<T>& m){
n = m.n;
initialize();
for (int i = 0; i < n; i++) {
for (int j = 0; j < 3; j++) {
if ((i == 0 || i == m.n - 1) && j == 2) break;
element[i][j] = m.element[i][j];
}
}
}
template<class T>
tridiagonalAsIrregularArray<T>::~tridiagonalAsIrregularArray() {
clear();
}
template<class T>
void tridiagonalAsIrregularArray<T>::clear() {
for (int i = 0; i < n; i++) {
delete[] element[i];
}
delete[] element;
element = nullptr;
}
template<class T>
void tridiagonalAsIrregularArray<T>::initialize() {
element = new T * [n];
for (int i = 0; i < n; i++) {
if(i == 0 || i == n - 1)
element[i] = new T[2];
else
element[i] = new T[3];
}
}
template<class T>
T tridiagonalAsIrregularArray<T>::get(int i, int j) const {
checkIndex(i, j);
switch (i - j) {
case 1:
case 0:
case -1:
if (i == 1 || i == 2) return element[i-1][j-1];
else return element[i-1][j - i + 1]; //j - (i-1)
default: return 0;
}
}
template<class T>
void tridiagonalAsIrregularArray<T>::set(int i, int j, const T& value) {
checkIndex(i, j);
switch (i - j) {
case 1:
case 0:
case -1:
if (i == 1 || i == 2) element[i-1][j-1] = value;
else element[i-1][j - i + 1] = value;
break;
default: break;//ignore other positions
}
}
template<class T>
tridiagonalAsIrregularArray<T>& tridiagonalAsIrregularArray<T>::operator=(const tridiagonalAsIrregularArray<T> & m) {
if (&m == this) return *this;
clear();
n = m.n;
initialize();
for (int i = 0; i < n; i++) {
for (int j = 0; j < 3; j++) {
if ((i == 0 || i == n - 1) && j == 2) break;
element[i][j] = m.element[i][j];
}
}
return *this;
}
template<class T>
tridiagonalAsIrregularArray<T> tridiagonalAsIrregularArray<T>::operator+(const tridiagonalAsIrregularArray<T> & m) const {
if (n != m.n) throw IllegalParameterValue("must have same size");
tridiagonalAsIrregularArray<T> result(n);
for (int i = 0; i < n; i++) {
for (int j = 0; j < 3; j++) {
if ((i == 0 || i == n - 1) && j == 2) break;
result.element[i][j] = element[i][j] + m.element[i][j];
}
}
return result;
}
template<class T>
tridiagonalAsIrregularArray<T> tridiagonalAsIrregularArray<T>::operator-(const tridiagonalAsIrregularArray<T> & m) const {
if (n != m.n) throw IllegalParameterValue("must have same size");
tridiagonalAsIrregularArray<T> result(n);
for (int i = 0; i < n; i++) {
for (int j = 0; j < 3; j++) {
if ((i == 0 || i == n - 1) && j == 2) break;
result.element[i][j] = element[i][j] - m.element[i][j];
}
}
return result;
}
template<class T>
matrix<T> tridiagonalAsIrregularArray<T>::operator*(const tridiagonalAsIrregularArray<T> & m) const {
if (n != m.n) throw IllegalParameterValue("must have same size");
matrix<T> result(n, n);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
result(i + 1, j + 1) = 0;
for (int k = 0; k < n; k++) {
result(i + 1, j + 1) += get(i + 1, k + 1) * m.get(k + 1, j + 1);
}
}
}
return result;
}
template<class T>
tridiagonalAsIrregularArray<T> tridiagonalAsIrregularArray<T>::transpose() {
tridiagonalAsIrregularArray<T> result(n);
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
switch (i - j) {
case -1:
case 0:
case 1:
result.set(i, j, get(j, i));
break;
default: break;//ignore others
}
}
}
return result;
}
#endif
| true |
51146236f7b4d51efc12ac6a300038bccc62afd6 | C++ | brijrajk/DataStructuresCodeNCodeSeries | /NumberTheory/L19EulerTotientFuctionFast/EulerTotientFast.cpp | UTF-8 | 599 | 2.75 | 3 | [] | no_license | #include <iostream>
#include <bits/stdc++.h>
using namespace std;
int phi[1000001];
void initialize(int maxN) {
for(int i = 0; i <= maxN; ++i) {
phi[i] = i;
}
for(int i = 2; i <= maxN; ++i) {
if(phi[i] == i) { // this is a prime no.
for(int j = i; j <= maxN; j += i) {
phi[j] /= i;
phi[j] *= (i - 1);
}
}
}
}
int main() {
initialize(1000001);
int t, x;
cin >> t;
while(t --) {
cin >> x;
cout << phi[x] << '\n';
}
return 0;
} | true |
fed798ac8d22052b1b6d49f514043bd22a3ea9bd | C++ | pranshu-09/Launchpad-Coding-Blocks | /Arrays/1-D Array/Array Rotation/7-maximum_rotated_sum.cpp | UTF-8 | 511 | 3.53125 | 4 | [] | no_license | #include<iostream>
using namespace std;
int maxmimum_rotated_sum(int arr[], int n)
{
int arr_sum = 0;
int curr_sum = 0;
for(int i=0;i<n;i++)
{
arr_sum += arr[i];
curr_sum += (i*arr[i]);
}
int max_sum = curr_sum;
for(int j=1;j<n;j++)
{
curr_sum = curr_sum + (arr_sum - n*(arr[n-j]));
if(curr_sum > max_sum)
max_sum = curr_sum;
}
return max_sum;
}
int main()
{
int n;
cin>>n;
int arr[100];
for(int i=0;i<n;i++)
cin>>arr[i];
cout<<maxmimum_rotated_sum(arr, n);
return 0;
} | true |
80f8cdbca9fadb281cfe1cad7ffd65ac8290473f | C++ | AlexeyVKrasnoperov/MWPCReadout | /sensormap.cpp | UTF-8 | 2,554 | 2.515625 | 3 | [] | no_license | #include "sensormap.h"
SensorMap::SensorMap()
{
cnt = 0;
size_t nWires[10] = {192,192,192,192,640,448,576,320,640,320};
for( size_t w = 0 ; w < 17; w++)
for( int c = 0; c < 10; c++ )
ChamberProfiles[c][w].resize(nWires[c],0);
}
SensorMap::~SensorMap()
{
clear();
}
void SensorMap::clear()
{
QMutexLocker locker(&mutex);
cnt = 0;
for(iterator i = begin(); i != end(); ++i)
delete (*i).second;
map::clear();
for( size_t w = 0 ; w < 17; w++)
for( int c = 0; c < 10; c++ )
fill(ChamberProfiles[c][w].begin(),ChamberProfiles[c][w].end(),0);
}
int SensorMap::addData(uint address, uint port, timeval *tv, uchar *data, int dataSize, uint & trgNum)
{
QMutexLocker locker(&mutex);
iterator i = find(address);
Sensor *sensor = 0;
if( i != end() )
sensor = (*i).second;
else
{
sensor = new Sensor(address, port);
insert(value_type(address,sensor));
}
cnt++;
return sensor->addData(tv,data,dataSize,trgNum);
}
bool SensorMap::analizeData(void)
{
if(empty())
return false;
int cnt = 0;
if( mutex.tryLock() )
{
for(iterator i = begin(); i != end(); ++i)
{
Sensor *s = (*i).second;
if( s->analizeData() )
cnt++;
for( uint w = 0; w < 17; w++ )
{
for( uint bid = 0; bid < s->getNBoard(); bid++ )
{
for( uint ch = 0; ch < 32; ch++ )
{
ChamberWire cw;
int wireCnts = s->getChamberWireCounts(bid,ch,w,cw);
if( (cw.chamber < NChambers) && (cw.wire < ChamberProfiles[cw.chamber][w].size()))
ChamberProfiles[cw.chamber][w][cw.wire] = wireCnts;
}
}
}
}
mutex.unlock();
}
return (cnt != 0);
}
const vector<uint> * SensorMap::getHist(uint id, int w)
{
Sensor *s = findSensor(id);
if( s == 0 )
return 0;
uint board = (id & 0x00FF0000) >> 16;
uint hid = (id & 0x0000F000);
if( board <= s->getNBoard() )
{
board -= 1;
if( hid == 0x1000 )
return s->getWindowCnt(board);
if( hid == 0x2000 )
return s->getWireCnt(board,w);
}
return s->getRateCnt();
}
const vector<uint> * SensorMap::getChamberProfile(uint id, int w)
{
return ( (id < NChambers) && (w < 17) ) ? &ChamberProfiles[id][w] : 0;
}
| true |
bdde3ffbc57ecdaca01ce073b934d31d3000ddc8 | C++ | mariokonrad/marnav | /include/marnav/seatalk/message_20.hpp | UTF-8 | 856 | 2.953125 | 3 | [
"BSD-3-Clause",
"BSD-4-Clause"
] | permissive | #ifndef MARNAV_SEATALK_MESSAGE_20_HPP
#define MARNAV_SEATALK_MESSAGE_20_HPP
#include <marnav/seatalk/message.hpp>
namespace marnav::seatalk
{
/// @brief Speed through water
///
/// @code
/// 20 01 XX XX
///
/// Speed through water: XXXX/10 Knots
/// @endcode
///
/// Corresponding NMEA sentence: VHW
///
class message_20 : public message
{
public:
constexpr static const message_id ID = message_id::speed_through_water;
constexpr static size_t SIZE = 4;
message_20();
message_20(const message_20 &) = default;
message_20 & operator=(const message_20 &) = default;
raw get_data() const override;
static std::unique_ptr<message> parse(const raw & data);
private:
uint16_t speed_{0}; // speed in 1/10th of knots
public:
uint16_t get_speed() const noexcept { return speed_; }
void set_speed(uint16_t t) noexcept { speed_ = t; }
};
}
#endif
| true |
5f1b4e84fd25a57e6a7d8c741c9091f4a8734f76 | C++ | GeneLiuXe/PIKACHU-CODE | /ACM-Templates/01_数学/17_多项式卷积/00_FFT.cpp | UTF-8 | 1,623 | 2.625 | 3 | [] | no_license | #include <bits/stdc++.h>
const double PI = acos(-1.0);
using namespace std;
struct FastFourierTransform {
typedef complex<double> cp;
typedef int R;
static const int MAXN = 1e5+5;
// a: a[0]*x^0+a[1]*x^1+...+a[n-1]*x^(n-1)
// b: b[0]*x^0+b[1]*x^1+...+b[m-1]*x^(m-1)
// c: c[0]*x^0+c[1]*x^1+...+c[n+m-2]*x^(n+m-2)
int n, m, len;
cp a[MAXN], b[MAXN];
R c[2*MAXN], rev[2*MAXN];
void FFT(cp *a, R n, R inv) {
R bit = 0;
while((1<<bit)<n) bit++;
for(R i = 0; i < n; i++) {
rev[i] = (rev[i>>1]>>1) | ((i&1)<<(bit-1));
if(i < rev[i]) swap(a[i], a[rev[i]]);
}
for(int len = 2; len <= n; len <<= 1) {
R mid = len >> 1;
cp unit(cos(PI/mid), inv*sin(PI/mid)); // 单位根
for(int i = 0; i < n; i += len) {
// mid << 1 是准备合并序列的长度, i 是合并到了哪一位
cp omega(1, 0);
for(R j = 0; j < mid; j++, omega *= unit) {
// 只扫左边部分, 得到右半部分的答案
cp x = a[i+j], y = omega*a[i+j+mid];
a[i+j] = x+y;
a[i+j+mid] = x-y;
}
}
}
if(inv == -1) for(R i = 0; i <= n; i++) a[i] /= n;
}
void multiply(int len1, R *A, int len2, R *B) {
R bitn = 1;
n = len1, m = len2, len = n+m;
while(bitn < n+m) bitn <<= 1;
memset(a, 0, sizeof(cp)*(bitn+1));
memset(b, 0, sizeof(cp)*(bitn+1));
memset(c, 0, sizeof(R)*(bitn+1));
for(int i = 0; i < n; i++) a[i] = A[i];
for(int i = 0; i < m; i++) b[i] = B[i];
FFT(a, bitn, 1); FFT(b, bitn, 1);
for(int i = 0; i < bitn; i++) a[i] = a[i]*b[i];
FFT(a, bitn, -1); // IFFT
for(int i = 0; i < bitn; i++) c[i] += a[i].real()+0.5;
}
}fft;
int main()
{
return 0;
} | true |
1cdf74150ab3390ce9b366b9547a0fcd9af05214 | C++ | inc00ming/Playlist-Editor | /main_Node.cpp | UTF-8 | 407 | 3.140625 | 3 | [] | no_license | #include <iostream>
#include "Node.hpp"
using namespace std;
int main(){
Node<int>* node5 = new Node<int>(5);
Node<int>* node4 = new Node<int>(4);
Node<int>* node3 = new Node<int>(3);
node5->setNext(node4);
node4->setNext(node3);
Node<int>* temp = node5;
while(temp){
cout << *temp << endl;
temp = temp->getNext();
}
delete node5;
delete node4;
delete node3;
delete temp;
return 0;
} | true |
9e5e4be6c64b643b308878a959544bf245a0ebf4 | C++ | FatemaFawzy/OpenGL-Puzzle-Game | /source/common/mesh/vertex-attributes.hpp | UTF-8 | 932 | 2.703125 | 3 | [
"MIT"
] | permissive | #ifndef OUR_VERTEX_ATTRIBUTES_H
#define OUR_VERTEX_ATTRIBUTES_H
#include <glad/gl.h>
namespace famm {
// Just as convenience, we write which location "we" use for each attribute in our shader.
// If you used different locations, modify these constants or just ignore (dont' use) them
namespace default_attribute_locations {
inline constexpr GLuint POSITION = 0;
inline constexpr GLuint COLOR = 1;
inline constexpr GLuint TEX_COORD = 2;
inline constexpr GLuint NORMAL = 3;
}
// Also for convenience, we will specialize this function for every vertex struct we make to define how it should be sent to the attributes
template<typename T>
void setup_buffer_accessors() {
// Make sure this is specialized for every type it is called for
static_assert(sizeof(T) != sizeof(T), "No accessors defined for this type");
};
}
#endif //OUR_VERTEX_ATTRIBUTES_H
| true |
eb0c8824a113d24cdd5857a3fd400a27a3e5782a | C++ | gtz12345/gao_tianze | /第四章/account/main.cpp | UTF-8 | 872 | 3.1875 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main()
{
float number;
float account;
float balance;
float charge;
float credits;
float limit;
float Newbalance;
while (number!=-1)
{
cout<<"Enter account number(or -1 to quit):";
cin >> number;
cout << "Enter beginning balance:";
cin >> balance;
cout << "Enter total charges:";
cin >> charge;
cout << "Enter total credits:";
cin >> credits;
cout << "Enter credit limit:";
cin >> limit;
Newbalance = balance + charge - credits;
if (Newbalance > limit)
{
cout << "New balance is " << Newbalance << endl;
cout << "Account: " << number << endl;
cout << "Credit limit: " << limit << endl;
cout << "Balance: " << Newbalance << endl;
cout << "Credit Limit Exceeded"<<endl;
}
else
{
cout << "New balance is " << Newbalance << endl;
}
}
}
| true |
37bf22467afafc58de7de6cd23688fedbf68cb98 | C++ | BFH-E3d/AutoPosting | /AutoPosting-app/letter.h | UTF-8 | 739 | 2.78125 | 3 | [
"MIT"
] | permissive | #ifndef LETTER_H
#define LETTER_H
#include <QString>
class Letter
{
private:
QString title;
QString recipient;
QString address;
QString country;
QString content;
qint32 id;
public:
Letter();
Letter(QString title, QString recipient, QString streetNo, QString plzCity, QString content, QString country = "Schweiz");
void setTitle(QString title);
void setRecipient(QString recipient);
void setAddress(QString streetNo, QString plzCity, QString country);
void setContent(QString content);
void setId(qint32 id);
QString getTitle();
QString getRecipient();
QString getAddress();
QString getContent();
qint32 getId();
};
#endif // LETTER_H
| true |
d338af81fa80f26c79c91835f648d3a994848719 | C++ | yutaokamoto/Blog | /20210508/iterator.cpp | UTF-8 | 848 | 3.28125 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int main(){
// 少しポインタの復習
int a = 0;
int* i_p = &a;
(*i_p)++;
cout << *i_p << endl;
// イテレータは、ポインタの一般形
//// コンテナの要素を指す
//// イテレータ自体を移動したり、指す要素の参照・変更が行える
vector<int> vec(3, 0);
//// for文の終了判定条件が「!=」であることに注意!
//// イテレータが指すコンテナの要素の中身を表示するときは、「*」をつける
for(auto i=vec.begin(); i!=vec.end(); i++){
cout << *i << endl;
}
vec = {0,1,2,3,4};
auto iter = find_if(vec.begin(), vec.end(), [](int i){return i%2==0;});
if(iter==vec.end()){cout << "Not find." << endl;}
else{cout << "vecの要素の中で、2で割り切れるものは" << *iter << endl;}
return 0;
} | true |
fabd110e3e481e1005ac8e8ce61d8cafdcf0899d | C++ | mtahernia/Non-Binary-GF-q-LDPC | /GFq.cpp | UTF-8 | 3,763 | 2.90625 | 3 | [
"BSD-3-Clause"
] | permissive | /*
* GFq.cpp
*
* Created on: 22 Dec, 2014
* Author: Mehrdad Tahernia
* User: mehrdad
*/
#include "Functions.h"
#include "GFq.h"
/************************************************************************
*
* GF(q)
*
************************************************************************/
// Static integers
int GFq::q = -1;
GFq GFq::alpha[MAX_Q];
int GFq::reverse_alpha[MAX_Q];
GFq GFq::inverse[MAX_Q];
bool GFq::IsPrimeQ = false;
bool GFq::IsModuloOperations = false;
// Forward declerations FIXME: Why do we need to forward declare static members?
int GFq::log_2_q;
int GFq::mask;
void GFq::Initialize(int p_q) {
if (p_q == GFq::q) // if already initialized with the same q
return;
if (p_q > MAX_Q) {
cout << "GFq::Initialize: p_q exceeds MAX_Q\n";
exit(1);
}
q = p_q;
//-----------------------------------------------------------------------
// Initialize
//-----------------------------------------------------------------------
if ((q > 2) && IsPowerOfTwo(q)) {
// Store for use by other utilities
log_2_q = Intlog2(q);
mask = 0; // Mask is used to select bits.
for (int i = 0; i < log_2_q; i++) {
mask <<= 1;
mask |= 1;
}
switch (q) {
case 4:
GenerateAlphas(2);
break;
case 8:
GenerateAlphas(3);
break;
case 16:
GenerateAlphas(4);
break;
case 32:
GenerateAlphas(5);
break;
case 64:
GenerateAlphas(6);
break;
case 256:
GenerateAlphas(8);
break;
default:
cout << "GFq::Initialize: Unsupported value of q\n";
exit(1);
}
IsPrimeQ = false;
IsModuloOperations = false;
} else {
if (q == 2) {
log_2_q = 1;
mask = 1;
}
IsModuloOperations = true;
IsPrimeQ = IsPrime(q);
}
//-----------------------------------------------------------------------
// Calc inverse table for elemets of GF(q)
//-----------------------------------------------------------------------
for (int i = 1; i < q; i++)
for (int j = 1; j < q; j++) {
GFq g1(i), g2(j);
if ((g1 * g2) == GFq::One())
inverse[i] = g2;
}
} // void GFq::Initialize
// Some predefined generator polynomials for extension fields of 2.
void GFq::GenerateAlphas(int m) {
int generator_polynomial;
int X0 = 1, X1 = 1 << 1, X2 = 1 << 2, X3 = 1 << 3, X4 = 1 << 4, X5 = 1 << 5, X6 = 1 << 6,/* X7 = 1 << 7,*/ X8 = 1 << 8; // X7 was not used
switch (m) {
case 2:
generator_polynomial = X0 ^ X1 ^ X2; // ^ is Bitwise XOR, it acts like modulo 2 adding here
break;
case 3:
generator_polynomial = X0 ^ X1 ^ X3;
break;
case 4:
generator_polynomial = X0 ^ X1 ^ X4;
break;
case 5:
generator_polynomial = X0 ^ X2 ^ X5;
break;
case 6:
generator_polynomial = X0 ^ X1 ^ X6;
break;
case 8:
generator_polynomial = X8 ^ X4 ^ X3 ^ X2 ^ X0;
break;
default:
cout << "GFq::GenerateAlphas: Unidentified Galois field\n";
exit(1);
break;
}
//------------------------------------------------
// Generate alphas
//------------------------------------------------
int x = 1;
int overflow = 1 << m;
for (int i = 0; i < (q - 1); i++) {
alpha[i].val = x;
x <<= 1; // multiply by alpha FIXME: What!!!!!!!!!!!! it looks like multiplication by 2
if (x & overflow) // if overflowed
x ^= generator_polynomial; // FIXME: I don't understand, why add the generator?
}
//------------------------------------------------
// Generate reverse alphas: inverse function
//------------------------------------------------
for (int i = 0; i < (q - 1); i++)
reverse_alpha[alpha[i].val] = i;
}
// static is only used once in decleration
GFq& GFq::One() {
if (IsModuloOperations) {
static GFq ConstOne(1);
return ConstOne;
} else
return alpha[0];
}
bool GFq::operator==(GFq g) { return val == g.val;}
| true |
1707e03979519d1b1b941dd381bba1c9035452de | C++ | nieyu/learncpp_com | /07_Functions/07_04b_returning_value_by_value_reference_and_address/main.cpp | UTF-8 | 714 | 3.15625 | 3 | [] | no_license | //
// main.cpp
// 07_04b_returning_value_by_value_reference_and_address
//
// Created by txc-ios on 2020/9/29.
//
#include <iostream>
#include <tuple>
struct SS {
int m_x;
double m_y;
};
SS returnStruct() {
SS s;
s.m_x = 5;
s.m_y = 6.7;
return s;
};
std::tuple<int, double> returnTuple() {
return { 5, 6.7 };
}
int main(int argc, const char * argv[]) {
SS s{ returnStruct() };
std::cout << s.m_x << ' ' << s.m_y << '\n';
// c++ 11
int a;
double d;
std::tie(a, d) = returnTuple();
std::cout << a << ' ' << d << '\n';
// c++ 17
auto [x, y]{ returnTuple() };
std::cout << x << ' ' << y << '\n';
return 0;
}
| true |
711ebfa94316ffb8c5ba1185309560a557a0bd26 | C++ | shmulik-willinger/PID_controller | /src/PID.cpp | UTF-8 | 684 | 2.84375 | 3 | [] | no_license | #include "PID.h"
#include <iostream>
using namespace std;
PID::PID() {}
PID::~PID() {}
#define WINDOW_SIZE 20
void PID::Init(double Kp, double Ki, double Kd)
{
minError = std::numeric_limits<double>::max();
maxError = std::numeric_limits<double>::min();
PID::Kp = Kp;
PID::Ki = Ki;
PID::Kd = Kd;
p_error = d_error = i_error = cte_prev = 0.0;
}
void PID::UpdateError(double cte)
{
p_error = cte;
i_error += cte;
d_error = cte - cte_prev;
cte_prev = cte;
if (cte > maxError) maxError = cte;
if (cte < minError) minError = cte;
}
double PID::TotalError()
{
return p_error * Kp + i_error * Ki + d_error * Kd;
//total_error_= p_error_ + d_error_ + i_error_;
}
| true |
54956df85df71a5135dc314473311772c16b6291 | C++ | weiwu1248/Cargo-Plane-Simulation | /Cargo-Plane-Simulation/Project Source Code/Project/CargoPlane.cpp | UTF-8 | 12,190 | 3.390625 | 3 | [] | no_license | //This is CargoPlane.cpp
#include "CargoPlane.h"
#include "Cargo.h"
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
CargoPlane::CargoPlane()
{
//initializes the variables in the class.
maxWeight = 0;
maxVolume = 0;
fuelCapacity = 0;
fuelRate = 0;
currentCity = "";
milesFlown = 0;
hoursFlown = 0;
fuelConsumed = 0;
usedVolume = 0;
usedWeight = 0;
maxCargoCount = 0;
loadedCargo = NULL;
}
CargoPlane::CargoPlane(double maxWeight, int maxVolume, int fuelCapacity, int fuelRate, const string& city)
{
//Setting the variables to what is passed in.
this->maxWeight = maxWeight;
this->maxVolume = maxVolume;
this->fuelCapacity = fuelCapacity;
this->fuelRate = fuelRate;
this->currentCity = city;
milesFlown = 0;
hoursFlown = 0;
fuelConsumed = 0;
usedVolume = 0;
usedWeight = 0;
maxCargoCount = 200; //Default size of the cargo array, can be increased here only.
loadedCargo = new Cargo[maxCargoCount]; //Creates the cargo array.
}
void CargoPlane::startCargoPlane_simulation(){
// This funtion controls the flow of the cargo plane simulation program.
// All variables below are used to temporary store the user inputs.
// All inputs are check for errors and used right after input.
string userCommand = "";
string destination = "";
string tempLabel = "";
double tempWeight = 0;
int tempHeight = 0;
int tempWidth = 0;
int tempLength = 0;
int tempInt = 0;
int mileage = 0;
int flightTime = 0;
Cargo tempCargo;
bool run = true; // The on and off swtich.
while (run){
cout << "Please choose one of the following commands: \n";
cout << "FLY, LOAD, UNLOAD, PRINT, QUIT\n";
cout << "Command: ";
cin >> userCommand; //get user command
if (userCommand == "FLY" || userCommand == "fly"){
//This will clear the cin buffer so that the getline() funtion does not get skipped.
//Because a "enter" key will be in the buffer due to the input from the usercommand input.
cin.ignore(256,'\n');
while (true){
//loop that will check the user input. Will continue to ask the user for input if the user inputs a invalid value.
cout << "Input Destination: ";
//Gets the name of the destination,
//multi-worded destinations are allowed with getline() compared to cin which only allows one word.
getline(cin, destination);
//Checks if user entered a blank destination.
if (destination.find_first_not_of(' ') == string::npos){
cout << "Blank destinations are not allowed, please try again.\n";
}
else{
break;
}
}
while (true){
//loop that will check the user input. Will continue to ask the user for input if the user inputs a invalid value.
cout << "Input Mileage: ";
cin >> mileage;
if (mileage < 0 || cin.fail()){
cout << "Invalid input, please try again.\n";
cin.clear();
cin.ignore(255, '\n');
}
else{
break;
}
}
while (true){
//loop that will check the user input. Will continue to ask the user for input if the user inputs a invalid value.
cout << "Input Flight Time: ";
cin >> flightTime;
if (flightTime < 0 || cin.fail()){
cout << "Invalid input, please try again.\n";
cin.clear();
cin.ignore(255, '\n');
}
else{
break;
}
}
if (fly(destination, flightTime, mileage) == true){
cout << "Flight Successful. Arrived at: " << destination << endl << endl;
}
else{
cout << "\nFlight Unsuccessful. Plane Crashed\n";
run = false; //Ends the simulation if plane crashed.
}
}
else if (userCommand == "LOAD" || userCommand == "load"){
bool tempBool = false; //A temp bool to check if the label inputed does not already exist or not.
//This will clear the cin buffer so that the getline() funtion does not get skipped.
//Because a "enter" key will be in the buffer due to the input from the usercommand input.
cin.ignore(256, '\n');
do{
cout << "Cargo Label: ";
getline(cin, tempLabel); //Allows the label to be muli-worded
for (int i = 0; i < maxCargoCount; i++){
//This loop will check if the label the user is trying to input does not already exist or not.
if (loadedCargo[i].getLabel() == tempLabel || tempLabel.find_first_not_of(' ') == string::npos){
cout << "Error in cargo label input.\n"
<< "Either the cargo already exist or you entered a blank label. Please try again.\n";
tempBool = true;
break; //Breaks out of the for loop if a label with the same name is found, or user enters a blank label.
}
else{
tempBool = false; //If not label with the same name is found then the while loop will end.
}
}
} while (tempBool);
while (true){
//loop that will check the user input. Will continue to ask the user for input if the user inputs a invalid value.
cout << "Weight: ";
cin >> tempWeight;
if (tempWeight < 0 || cin.fail()){
cout << "Invalid input, please try again.\n";
cin.clear();
cin.ignore(255, '\n');
}
else{
break;
}
}
while (true){
//loop that will check the user input. Will continue to ask the user for input if the user inputs a invalid value.
cout << "Height: ";
cin >> tempHeight;
if (tempHeight < 0 || cin.fail()){
cout << "Invalid input, please try again.\n";
cin.clear();
cin.ignore(255, '\n');
}
else{
break;
}
}
while (true){
//loop that will check the user input. Will continue to ask the user for input if the user inputs a invalid value.
cout << "Width: ";
cin >> tempWidth;
if (tempWidth < 0 || cin.fail()){
cout << "Invalid input, please try again.\n";
cin.clear();
cin.ignore(255, '\n');
}
else{
break;
}
}
while (true){
//loop that will check the user input. Will continue to ask the user for input if the user inputs a invalid value.
cout << "Length: ";
cin >> tempLength;
if (tempLength < 0 || cin.fail()){
cout << "Invalid input, please try again.\n";
cin.clear();
cin.ignore(255, '\n');
}
else{
break;
}
}
//Sets the temp cargo to the values the user inputed.
tempCargo.set(tempLabel,tempHeight,tempWidth,tempLength,tempWeight);
//Pass in the temp cargo to be loaded.
tempInt = loadCargo(tempCargo);
//tempInt will store the return value of the loadCargo funtion.
if (tempInt == (-3)){
cout << "Volume and Weight limit exceeded. Loading Failed\n";
}
else if (tempInt == (-2)){
cout << "Volume limit exceeded. Loading Failed\n";
}
else if (tempInt == (-1)){
cout << "Weight limit exceeded. Loading Failed\n";
}
else if (tempInt == 1){
cout << "Cargo was successfully loaded.\n\n";
}
}
else if (userCommand == "UNLOAD" || userCommand == "unload"){
cout << "Input Cargo label to be unloaded: ";
cin >> tempLabel;
//attemps to unload the cargo with the label that is inputted
unLoadCargo(tempLabel);
}
else if (userCommand == "PRINT" || userCommand == "print"){
print(); // prints out
}
else if (userCommand == "QUIT" || userCommand == "quit"){
run = false; //Ends the simulation
}
else {
//Will continue to ask the user for input if the user inputs a invalid value.
cout << "Invalid Command. Please try again.\n\n";
}
}
//End of simulation
cout << "\nCargo Plane Simulation Ended\n\n";
}
int CargoPlane::loadCargo(Cargo cargo){
//Checks if the weight and volume would be exceeded or not, returns -3 if true.
if (cargo.getWeight() + usedWeight > maxWeight && cargo.getVolume() + usedVolume > maxVolume){
return (-3);
}
//Checks if only the volume would be exceeded, returns -2 if true.
else if (cargo.getVolume() + usedVolume > maxVolume){
return (-2);
}
//Checks if only the weight would be exceeded, returns -1 if true.
else if (cargo.getWeight() + usedWeight > maxWeight){
return (-1);
}
//If volume or weight would not be exceeded then the cargo will be loaded, and then returns 1.
else {
//Search the loadedCargo array for a unused spot.
//Sets the cargo of that unused spot.
for (int i = 0; i < maxCargoCount;i++){
if (loadedCargo[i].getLabel().empty()){
//sets the values of the unused cargo.
loadedCargo[i].set(cargo.getLabel(), cargo.getHeight(), cargo.getWidth(), cargo.getLength(), cargo.getWeight());
break;//breaks out of for loop, if a unused spot is found.
}
}
usedVolume = usedVolume + cargo.getVolume(); //updates usedVolume
usedWeight = usedWeight + cargo.getWeight(); //updates usedWeight
return 1; //returns 1 when loading is succesful
}
}
void CargoPlane::unLoadCargo(string label){
//This bool is used to check if a cargo was unloaded or not.
bool cargoUnloaded = false;
//Loop that will search the cargo array for a cargo with the same label name.
for (int i = 0; i < maxCargoCount; i++){
if (loadedCargo[i].getLabel() == label){
//If a cargo with the label is found, then usedVolume and usedWeight is updated.
usedVolume = usedVolume - loadedCargo[i].getVolume();
usedWeight = usedWeight - loadedCargo[i].getWeight();
//Sets the variables of the cargo that is to be removed to zero.
loadedCargo[i].set("",0,0,0,0);
cargoUnloaded = true; //Cargo was unloaded.
//Outputs a message to let user know that the cargo was found and unloaded.
cout << "Cargo with label " << label << " was unloaded.\n\n";
break; //Stops the loop, because the cargo was found.
}
}
if (cargoUnloaded == false){
//If cargo was not found then output a message to let user know.
cout << "Cargo with label " << label << " does not exist, Unloading failed.\n\n";
}
}
bool CargoPlane::fly(string city, int hours, int miles){
//Checks the plane would run out of fuel or not, returns false if the plane will run out of fuel.
if ((hours*fuelRate)+fuelConsumed > fuelCapacity){
return false;
}
//Otherwise flight is successful and will return true.
else{
currentCity = city; //updates the currentCity to the new city.
fuelConsumed = fuelConsumed + (hours*fuelRate); //updates the amount of fuel consumed.
milesFlown = milesFlown + miles; //updates miles flown.
hoursFlown = hoursFlown + hours; //updates hours flown.
return true;
}
}
void CargoPlane::print(){
//Prints out everything.
cout << left << setw(15) <<"Current City: " << currentCity << endl;
cout << setw(15) << "Miles Flown: " << milesFlown << endl;
cout << setw(15) << "Hours Flown: " << hoursFlown << endl;
cout << setw(15) << "Fuel Rate: " << fuelRate << " gallons per hour" << endl;
cout << setw(15) << "Fuel Capacity: " << setw(12) << fuelCapacity;
cout << setw(10) << " Consumed: " << setw(12) << fuelConsumed;
cout << " Remaining: " << getRemainingFuel() << endl;
cout << fixed << setprecision(2); //Weight output will be outputed with two decimal places.
cout << setw(15) << "Weight Limit: " << setw(12) << maxWeight;
cout << setw(11) << " Loaded: " << setw(12) << usedWeight;
cout << " Remaining: " << getRemainingWeight() << endl;
cout << setw(15) << "Volume Limit: " << setw(12) << maxVolume;
cout << setw(11) << " Loaded: " << setw(12) << usedVolume;
cout << " Remaining: " << getRemainingVolume() << endl;
cout << "Current Cargo:\n";
bool notEmpty = false; //A temp bool to check if the cargo array has any cargos or not.
//loops through the cargo array and prints out any cargos that is found.
//Cargos with no label is considered to be nonexistent and skiped.
for (int i = 0; i < maxCargoCount; i++){
if (loadedCargo[i].getLabel() != ""){
notEmpty = true; //Cargo array is not empty
loadedCargo[i].print();
}
}
if (notEmpty == false){
//If cargo array is empty then a message will tell the user that there is no cargos on the plane.
cout << "No Cargo On Plane.\n";
}
cout << endl;
}
int CargoPlane::getRemainingFuel(){
return fuelCapacity - fuelConsumed;
}
int CargoPlane::getRemainingVolume(){
return maxVolume - usedVolume;
}
double CargoPlane::getRemainingWeight(){
return maxWeight - usedWeight;
}
CargoPlane::~CargoPlane()
{
delete[] loadedCargo; //Deletes the array of cargos that the pointer is pointing to.
loadedCargo = NULL; //sets the point to point to NULL.
}
| true |
b6fc8a955b351b7b63db57c386cb74dc078c3f4a | C++ | montaser55/Cracking-The-Coding-Interview | /2.LinkedList/2.kthFromLast.cpp | UTF-8 | 1,556 | 3.6875 | 4 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
struct Node
{
int val;
Node *next;
};
void insert(Node *&head, int data)
{
Node *newNode = new Node;
newNode->val = data;
newNode->next = head;
head = newNode;
}
Node *kthfromLast(Node *head, int k)
{
if (head == NULL)
return NULL;
Node *fast = head;
Node *slow = head;
while (k--)
{
if (fast != NULL)
fast = fast->next;
}
while (fast != NULL)
{
fast = fast->next;
slow = slow->next;
}
return slow;
}
void printList(Node *head)
{
while (head != NULL)
{
cout << head->val << "-->";
head = head->next;
}
cout << "NULL" << endl;
}
Node *recursiveHelper(Node *head, int k, int &i)
{
if (head == NULL)
return NULL;
Node *n = recursiveHelper(head->next, k, i);
i = i + 1;
if (i == k)
return head;
return n;
}
Node *kthfromLastRecursive(Node *head, int k)
{
int i=0;
return recursiveHelper(head, k, i);
}
int main()
{
Node *head = NULL;
insert(head, 7);
insert(head, 4);
insert(head, 6);
insert(head, 9);
insert(head, 1);
insert(head, 3);
insert(head, 8);
printList(head);
Node *kth = kthfromLast(head, 4);
if (kth != NULL)
{
cout << kth->val << endl;
}
else
cout << "NULL" << endl;
Node *kthnew = kthfromLastRecursive(head, 4);
if (kthnew != NULL)
{
cout << kthnew->val << endl;
}
else
cout << "NULL" << endl;
}
| true |
3c0a24d5372c3191fe6e73f5f13abd82f62b8e83 | C++ | nidujay/openetk | /doc/examples/isr-service-example.cpp | UTF-8 | 1,734 | 3.1875 | 3 | [] | no_license | #include <iostream>
#include <isr/isr-service.h>
namespace djetk {
// Base class of some peripheral driver. It implements the interrupt
// handler code for that type of device.
// Each instance of this peripheral (e.g. UART1 and UART2) will derive
// from this.
class SomeDriverBase : private IIsrHandler
{
public:
SomeDriverBase (IIsrService &isr_service, int id)
: id_(id)
{
isr_service.RegisterHandler(*this);
}
private:
virtual void HandleIsr(bool &task_woken) override
{
// Interrupt handler code is common to all the derived
// classes of this driver
std::cout << id_ << std::endl;
// Set to true if an interrupt were to wake a higher priority task
// (queues return this value)
task_woken = false;
}
int id_;
};
// Drivers for each peripheral instance
class Device1 : public SomeDriverBase {
public:
Device1(IIsrService &isr_service)
: SomeDriverBase(isr_service, 1)
{
}
};
class Device2 : public SomeDriverBase {
public:
Device2(IIsrService &isr_service)
: SomeDriverBase(isr_service, 2)
{
}
};
// These are the interrupt handler vectors for the two peripherals of the same
// device class
extern "C" void Device1IrqVector()
{
bool task_woken;
IsrService<Device1>::ISR(task_woken);
}
extern "C" void Device2IrqVector()
{
bool task_woken;
IsrService<Device2>::ISR(task_woken);
}
} // namespace djetk
int main()
{
using namespace djetk;
IsrService<Device1> isr_service1;
IsrService<Device2> isr_service2;
Device1 device1(isr_service1);
Device2 device2(isr_service2);
Device1IrqVector();
Device2IrqVector();
return 0;
}
| true |
d9dafc9c38a1ab567cf62e46c160611f372d41ff | C++ | sessamekesh/Indigo-Sapphire | /include/view/cubemap.h | UTF-8 | 511 | 2.53125 | 3 | [] | no_license | #pragma once
#include <glad/glad.h>
#include <vector>
#include <model/imagedata.h>
namespace view
{
class Cubemap
{
public:
Cubemap();
~Cubemap();
Cubemap(const Cubemap&) = delete;
bool init(
const model::ImageData& left,
const model::ImageData& right,
const model::ImageData& top,
const model::ImageData& bottom,
const model::ImageData& front,
const model::ImageData& back
);
bool release();
GLuint texture() const;
protected:
bool isLoaded_;
GLuint texture_;
};
} | true |
1a6aa2265752e068cbc6a1a107c331d68cd6dfd7 | C++ | Man0Sand/Matches-on-Bar-Table | /Matches on Bar Table/screen_buffer.cpp | UTF-8 | 3,777 | 3.03125 | 3 | [] | no_license | #include <Windows.h>
#include "screen_buffer.h"
namespace
{
class ScreenBuffer
{
public:
ScreenBuffer();
~ScreenBuffer();
void SetCursorPosition(COORD coordinates);
void ClearScreen();
COORD GetCursorPosition();
void ClearRow();
void InvertColors();
private:
HANDLE handle_;
};
ScreenBuffer screen_buffer;
}
namespace screenbuffer
{
void SetCursorPosition(const int& x, const int& y)
{
COORD coordinates = { static_cast<SHORT>(x), static_cast<SHORT>(y) };
screen_buffer.SetCursorPosition(coordinates);
}
void GetCursorPosition(int* x, int* y)
{
COORD coordinates = screen_buffer.GetCursorPosition();
*x = coordinates.X;
*y = coordinates.Y;
}
int GetCursorRow()
{
int x, y;
GetCursorPosition(&x, &y);
return y;
}
void ClearScreen()
{
screen_buffer.ClearScreen();
}
void ClearRow()
{
screen_buffer.ClearRow();
}
void InvertColors()
{
screen_buffer.InvertColors();
}
}
namespace
{
ScreenBuffer::ScreenBuffer() :
handle_(GetStdHandle(STD_OUTPUT_HANDLE))
{
CONSOLE_CURSOR_INFO cursor_info;
GetConsoleCursorInfo(handle_, &cursor_info);
cursor_info.bVisible = false;
SetConsoleCursorInfo(handle_, &cursor_info);
}
ScreenBuffer::~ScreenBuffer()
{
}
void ScreenBuffer::SetCursorPosition(COORD coordinates)
{
SetConsoleCursorPosition(handle_, coordinates);
}
void ScreenBuffer::ClearScreen()
{
CONSOLE_SCREEN_BUFFER_INFO buffer_info;
GetConsoleScreenBufferInfo(handle_, &buffer_info);
DWORD number_of_cells = buffer_info.dwSize.X * buffer_info.dwSize.Y;
TCHAR fill_character = ' ';
COORD beginning_point = { 0,0 };
DWORD number_of_inserted_characters;
FillConsoleOutputCharacter(handle_, fill_character, number_of_cells, beginning_point, &number_of_inserted_characters);
FillConsoleOutputAttribute(handle_, buffer_info.wAttributes, number_of_cells, beginning_point, &number_of_inserted_characters);
SetCursorPosition(beginning_point);
}
COORD ScreenBuffer::GetCursorPosition()
{
CONSOLE_SCREEN_BUFFER_INFO buffer_info;
GetConsoleScreenBufferInfo(handle_, &buffer_info);
return buffer_info.dwCursorPosition;
}
void ScreenBuffer::ClearRow()
{
CONSOLE_SCREEN_BUFFER_INFO buffer_info;
GetConsoleScreenBufferInfo(handle_, &buffer_info);
DWORD number_of_cells = buffer_info.dwSize.X;
TCHAR fill_character = ' ';
COORD beginning_point = { 0, GetCursorPosition().Y };
DWORD number_of_inserted_characters;
FillConsoleOutputCharacter(handle_, fill_character, number_of_cells, beginning_point, &number_of_inserted_characters);
SetCursorPosition(beginning_point);
}
void ScreenBuffer::InvertColors()
{
CONSOLE_SCREEN_BUFFER_INFO buffer_info;
GetConsoleScreenBufferInfo(handle_, &buffer_info);
WORD attributes = buffer_info.wAttributes;
WORD background_attributes = (BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_BLUE);
WORD text_attributes = (FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE);
WORD mask = background_attributes | text_attributes;
WORD inverted_desired_bits = (attributes & mask)^mask;
attributes &= ~mask;
attributes |= inverted_desired_bits;
SetConsoleTextAttribute(handle_, attributes);
}
}
| true |
93c07a9a9d8fa9d750e0026d2eb649bbb2fcceec | C++ | SimJung/Baekjoon_20190704 | /p9663.cpp | TIS-620 | 1,257 | 2.8125 | 3 | [] | no_license | #include <iostream>
#include <stack>
#include <cstring>
#define pi pair<int, int>
using namespace std;
int n, ans;
stack<pi> s;
bool possible[15];
pi arr[15];
void print() {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
bool chk = false;
for (int k = 0; k < n; k++) {
if (arr[k].first == i && arr[k].second == j)
{
chk = true;
break;
}
}
if (chk)
cout << "";
else
cout << "";
}
cout << '\n';
}
}
void safe(int i) {
memset(possible, 0, 15);
for (int k = 0; k < i; k++) {
possible[arr[k].second] = true;
int v1 = arr[k].second - arr[k].first + i;
int v2 = arr[k].first + arr[k].second - i;
if (v1 >= 0 && v1 < n)
possible[v1] = true;
if (v2 >= 0 && v2 < n)
possible[v2] = true;
}
for (int k = 0; k < n; k++) {
if (!possible[k])
s.push(make_pair(i, k));
}
}
void queen() {
for (int i = 0; i < n; i++) {
s.push(make_pair(0, i));
}
while (!s.empty()) {
pi p = s.top();
arr[p.first] = p;
s.pop();
if (p.first == n-1) {
ans++;
//print();
//cout<<'\n';
}
else {
safe(p.first+1);
}
}
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
cin >> n;
queen();
cout << ans << '\n';
return 0;
} | true |
003030a966e5f7f440de99b5d1c97d384c47eec8 | C++ | carlos-lopez-garces/ray | /vec3.h | UTF-8 | 3,208 | 3.234375 | 3 | [] | no_license | #ifndef VEC3_H
#define VEC3_H
#include "common.h"
#include <math.h>
#include <stdlib.h>
#include <iostream>
class vec3 {
public:
vec3() : e{0, 0, 0} {}
vec3(double e0, double e1, double e2) : e{e0, e1, e2} {}
inline static vec3 random() {
return vec3(random_double(), random_double(), random_double());
}
inline static vec3 random(double min, double max) {
return vec3(random_double(min, max), random_double(min, max), random_double(min, max));
}
double x() const { return e[0]; }
double y() const { return e[1]; }
double z() const { return e[2]; }
double r() const { return e[0]; }
double g() const { return e[1]; }
double b() const { return e[2]; }
vec3 operator-() const { return vec3(-e[0], -e[1], -e[2]); }
double operator[](int i) const { return e[i]; }
double& operator[](int i) { return e[i]; }
vec3& operator+=(const vec3 &v);
vec3& operator*=(const double t);
vec3& operator/=(const double t);
double length() const {
return sqrt(length_squared());
}
double length_squared() const {
return e[0]*e[0] + e[1]*e[1] + e[2]*e[2];
}
double e[3];
};
vec3& vec3::operator+=(const vec3& v) {
e[0] += v.e[0];
e[1] += v.e[1];
e[2] += v.e[2];
return *this;
}
vec3& vec3::operator*=(const double t) {
e[0] *= t;
e[1] *= t;
e[2] *= t;
return *this;
}
vec3& vec3::operator/=(const double t) {
return *this *= 1 / t;
}
// Aliases.
using point3 = vec3;
using color = vec3;
inline std::ostream& operator<<(std::ostream &out, const vec3 &v) {
return out << v.e[0] << " " << v.e[1] << " " << v.e[2];
}
inline vec3 operator+(const vec3 &u, const vec3 &v) {
return vec3(u.e[0] + v.e[0], u.e[1] + v.e[1], u.e[2] + v.e[2]);
}
inline vec3 operator-(const vec3 &u, const vec3 &v) {
return vec3(u.e[0] - v.e[0], u.e[1] - v.e[1], u.e[2] - v.e[2]);
}
inline vec3 operator*(const vec3 &u, const vec3 &v) {
return vec3(u.e[0] * v.e[0], u.e[1] * v.e[1], u.e[2] * v.e[2]);
}
inline vec3 operator*(double t, const vec3 &v) {
return vec3(t * v.e[0], t * v.e[1], t * v.e[2]);
}
inline vec3 operator/(const vec3 &v, double t) {
return vec3(v.e[0] / t, v.e[1] / t, v.e[2] / t);
}
inline vec3 operator*(const vec3 &v, double t) {
return vec3(v.e[0] * t, v.e[1] * t, v.e[2] * t);
}
inline double dot(const vec3 &u, const vec3 &v) {
return u.e[0]*v.e[0] + u.e[1]*v.e[1] + u.e[2]*v.e[2];
}
inline vec3 cross(const vec3 &u, const vec3 &v) {
return vec3(
u.e[1]*v.e[2] - u.e[2]*v.e[1],
-(u.e[0]*v.e[2] - u.e[2]*v.e[0]),
u.e[0]*v.e[1] - u.e[1]*v.e[0]
);
}
inline vec3 reflect(const vec3& v, const vec3& normal) {
return v - 2 * dot(v, normal) * normal;
}
inline vec3 refract(
const vec3& v, const vec3& normal, double eta_over_etap
) {
// Theta is the angle of incidence.
auto cos_theta = dot(-v, normal);
// I don't understand why these give you the components of the refracted ray.
vec3 refracted_perpendicular
= eta_over_etap * (v + cos_theta * normal);
vec3 refracted_parallel
= -sqrt(fabs(1.0 - refracted_perpendicular.length_squared())) * normal;
return refracted_perpendicular + refracted_parallel;
}
inline vec3 unit_vector(vec3 v) {
return v / v.length();
}
#endif | true |
c6c921ed04302580907de03669234d4fab10b16c | C++ | xiazeyu/OI_Resource | /Cpp_Programs/lougu/201808/origin/T39016.cpp | UTF-8 | 418 | 2.546875 | 3 | [
"Apache-2.0"
] | permissive | #include <bits/stdc++.h>
using namespace std;
long n, m, seed;
int a[123456] = {0};
void generate_array(int a[], int n, int m, int seed) {
unsigned x = seed;
for (int i = 0; i < n; ++i) {
x ^= x << 13;
x ^= x >> 17;
x ^= x << 5;
a[i] = x % m + 1;
}
}
int main(){
scanf("%ld %ld %ld", &n, &m, &seed);
generate_array(a, n, m, seed);
sort(a, a + n);
return 0;
}
| true |
e1bcfe07c9c644a6d61bd25881f08de2f4906d9c | C++ | Krpa/GappedSuffixArray | /src/ArraySuffixMapper.cpp | UTF-8 | 2,667 | 2.78125 | 3 | [] | no_license | //
// Created by luka on 11/15/15.
//
#include "ArraySuffixMapper.h"
std::set<int> ArraySuffixMapper::lookupMatches(char *seed, unsigned int len) {
std::set<int> result;
for(auto &i : lookupMismatch(seed)) {
result.insert(i);
}
for(auto &i : lookupDeletion(seed)) {
result.insert(i);
}
if(len > array->getShapeLen()) {
for (auto &i : lookupInsertion(seed)) {
result.insert(i);
}
}
return result;
}
std::vector<int> ArraySuffixMapper::lookupDeletion(char *seed) {
std::pair<int, int> p = findDeletionLoHi(seed);
int lo = p.first;
int hi = p.second;
if(hi - lo > 0) {
std::vector<int> result(hi - lo);
for (int i = lo; i < hi; i++) {
result[i - lo] = array->getGSA()[i];
}
return result;
}
return std::vector<int>();
}
std::vector<int> ArraySuffixMapper::lookupInsertion(char *seed) {
std::pair<int, int> p = findInsertionLoHi(seed);
int lo = p.first;
int hi = p.second;
if(hi - lo > 0) {
std::vector<int> result(hi - lo);
for (int i = lo; i < hi; i++) {
result[i - lo] = array->getGSA()[i];
}
return result;
}
return std::vector<int>();
}
std::vector<int> ArraySuffixMapper::lookupMismatch(char *seed) {
std::pair<int, int> p = findMismatchLoHi(seed);
int lo = p.first;
int hi = p.second;
if(hi - lo > 0) {
std::vector<int> result(hi - lo);
for (int i = lo; i < hi; i++) {
result[i - lo] = array->getGSA()[i];
}
return result;
}
return std::vector<int>();
}
std::pair<int, int> ArraySuffixMapper::findMismatchLoHi(char *seed) {
return std::pair<int, int>(array->lowerBound(seed), array->upperBound(seed));
}
std::pair<int, int> ArraySuffixMapper::findInsertionLoHi(char *seed) {
unsigned int shape_len = array->getShapeLen();
char query[shape_len];
int i;
for(i = 0; i < shape_len && i != array->getDcPos(); i++) {
query[i] = seed[i];
}
query[i] = 'N';
for(++i; i < shape_len; i++) {
query[i] = seed[i + 1];
}
return std::pair<int, int>(array->lowerBound(query), array->upperBound(query));
}
std::pair<int, int> ArraySuffixMapper::findDeletionLoHi(char *seed) {
unsigned int shape_len = array->getShapeLen();
char query[shape_len];
int i;
for(i = 0; i < shape_len && i != array->getDcPos(); i++) {
query[i] = seed[i];
}
query[i++] = 'N';
for(; i < shape_len; i++) {
query[i] = seed[i-1];
}
return std::pair<int, int>(array->lowerBound(query), array->upperBound(query));
}
| true |
11d78b5e692a0be07d1195def631576d64335dea | C++ | Karamu98/BatchCropper | /BatchCropper/src/Image.h | UTF-8 | 628 | 2.671875 | 3 | [
"Apache-2.0"
] | permissive | #pragma once
#include <string>
class Image
{
public:
Image();
Image(const std::string& a_filePath);
~Image();
void Load(const std::string& a_imagePath);
bool Trim(unsigned int a_fromLeft, unsigned int a_fromRight, unsigned int a_fromTop, unsigned int a_fromBottom);
void Write(const std::string& a_fileDir);
void Destroy();
private:
void LoadImage(const std::string& a_imagePath);
void Unload();
private:
std::string m_filePath, m_fileName;
int m_width, m_height, m_channels;
unsigned char* m_imageData;
bool m_isValid, m_selfAlloc;
};
// TODO: Create a static pool for loaded images and pool for edited image | true |
b4be06a1307e0d2e3a264369d94a4292d85d6a85 | C++ | aditi1403/C-tutorials | /array_challenge_kadane_algo.cpp | UTF-8 | 741 | 3.53125 | 4 | [] | no_license | //PROB_8-->KADANE'S ALGORITHM
#include<iostream>
#include<climits>
using namespace std;
int main(){
int n;
cout<<"Enter the value of n:"<<endl;
cin>>n;
int arr[n];
cout<<"Enter the elements of the array:"<<endl;
for (int i = 0; i < n; i++)
{
cin>>arr[i];
}
cout<<"Your array is as follws:"<<endl;
for (int i = 0; i < n; i++)
{
cout<<arr[i]<<" ";
}
cout<<endl;
int currentsum=0;
int maxsum=INT_MIN;
for (int i = 0; i < n; i++)
{
currentsum+=arr[i];
if (currentsum<0)
{
currentsum=0;
}
maxsum=max(maxsum,currentsum);
}
cout<<"Your ans is as follws:"<<endl;
cout<<maxsum<<endl;
return 0;
}
| true |
dc898534c5112430abed84d6ace073b35449e029 | C++ | runwei/Coding_Problems | /shortestpalindrome.cpp | UTF-8 | 1,043 | 3.421875 | 3 | [] | no_license | /*
Given a string S, you are allowed to convert it to a palindrome by adding 0 or more characters in front of it.
Find the length of the shortest palindrome that you can create from S by applying the above transformation.
Examples:
cca -> 1
aba -> 0
acb -> 2
abcb -> 3
abb -> 2
abcdefg -> 6
*/
#include<vector>
#include<iostream>
#include<algorithm>
#include<unordered_map>
#include<unordered_set>
#include<queue>
#include<stack>
#include<list>
#include<stdlib.h>
#include<ctime>
#include<limits.h>
#include "leetcode.h"
#include "BST.h"
using namespace std;
int shortest_palindrome(string s){
int n=s.size();
s=s+'#'+string(s.rbegin(),s.rend());
vector<int> f(2*n+2,0);
int p1=0,p2=2;
while (p2<=2*n+1) {
if (s[p1]==s[p2-1]) {f[p2++]=++p1;}
else if (p1==0) f[p2++]=0;
else p1=f[p1];
}
return n-f[2*n+1];
}
int main() {
cout<<shortest_palindrome("cca")<<endl;
cout<<shortest_palindrome("aba")<<endl;
cout<<shortest_palindrome("acb")<<endl;
cout<<shortest_palindrome("abcb")<<endl;
cout<<shortest_palindrome("abb")<<endl;
} | true |
9584d4ff15d763941fc735770d62f19e99d333a6 | C++ | Kevin7-net/- | /校门外的树.cpp | GB18030 | 404 | 2.515625 | 3 | [] | no_license | #include<iostream>
using namespace std;
int a[10001],s[101],e[101];
int main(){
int l,m;
int ans=0;
cin>>l>>m;
for(int i=0;i<m;i++){
cin>>s[i]>>e[i];
for(int j=s[i];j<=e[i];j++){
a[j]=1;//·ξλ1
}
}
for(int i=0;i<=l;i++){
if(a[i]==0)
ans++;//ûǹĵ˵û
}
cout<<ans;
return 0;
}
| true |
ed69f2ab2bdd1852fb36b5971388b639d662a132 | C++ | uxtuno/PetitEmu | /petitemu1_gui/myutil.cpp | UTF-8 | 231 | 2.796875 | 3 | [] | no_license | #include "myutil.h"
int inrange(int arg,int min,int max){
return (arg>=min)&&(arg<=max);
}
int isdigits(char* arg){
int i=0;
for(i=0;(i<256)&&(arg[i]!=0);i++){
if(!isdigit(arg[i]))return false;
}
return true;
} | true |
754e0381f9fec024ec3628e413e6d11098d7c220 | C++ | Nicksechko/mapreduce | /table_io.h | UTF-8 | 1,091 | 3.015625 | 3 | [] | no_license | #pragma once
#include <string>
#include <fstream>
#include <vector>
using TableItem = std::pair<std::string, std::string>;
class TableReader {
public:
explicit TableReader(const std::string& table_path);
bool Next();
bool HasNext();
bool Empty();
const std::string& GetKey() const;
const std::string& GetValue() const;
std::string GetRow() const;
TableItem GetItem() const;
std::vector<TableItem> ReadAllItems();
private:
bool empty_ = false;
std::string key_;
std::string value_;
std::ifstream table_stream_;
};
class TableWriter {
public:
explicit TableWriter(const std::string& table_path);
void Write(const std::string& key, const std::string& value);
void Write(const std::string& row);
void Write(const TableItem & item);
void Write(const std::vector<TableItem>& items);
bool WriteKeyBlock(TableReader& reader);
void Append(TableReader& reader, size_t max_count = -1);
void Append(const std::string& source_path, size_t max_conut = -1);
private:
std::ofstream table_stream_;
}; | true |
97359221931b2c4c77c83a18a97555875bd76581 | C++ | Jack-Tanner/SpaceWave | /SpaceWave/SpriteHandler.h | UTF-8 | 1,135 | 2.59375 | 3 | [] | no_license | #pragma once
#include "Sprite.h"
#include "Player.h"
#include "Vector2.h"
#include "Bullet.h"
#include "Enemy.h"
#include "Explosion.h"
#include "MapData.h"
#include <vector>
#include <string>
using namespace std;
using namespace Math;
namespace Game
{
class SpriteHandler
{
public:
SpriteHandler()
{
BulletID = 5;
EnemyID = 2000;
ExplosionID = 4000;
CurrentWave = 0;
}
void AddPlayer(string ImagePath, Vector2 vec);
Player* GetPlayer(){return &Player1;}
void AddBullet(int ImageID, Vector2 Pos, int Direction, bool IsGood);
void AddEnemy(string ImagePath, Vector2 Pos, int WaveID);
void AddExplosion(Vector2 Pos);
void AddWave(MapData wave);
void Tick();
void Draw();
bool CheckBulletHit(int ID, int Damage);
int GetCurrentWave(){return CurrentWave;}
int GetMaxWaves(){return WaveList.size();}
int GetEnemyCount(){return EnemyList.size();}
void Shutdown();
private:
Player Player1;
vector<Bullet> BulletList;
vector<Enemy> EnemyList;
vector<Explosion> ExplosionList;
vector<MapData> WaveList;
int BulletID, EnemyID, ExplosionID;
int NextWaveTime, CurrentWave;
};
} | true |
cb9710202adbe1ea738cf3ddbf9f64bc29656f9c | C++ | dl57934/Algorithms | /2021-02-04/2611/2611.cpp | UTF-8 | 1,234 | 2.609375 | 3 | [] | no_license | #include <cstdio>
#include <vector>
#include <queue>
#include <algorithm>
#define ll long long
#define element pair<ll, ll>
using namespace std;
vector<pair<int, int> > pathInfo[1002];
queue<int> qu;
int N, M;
ll vertex[1002];
vector<int> ingreed[1002];
void topologySort(){
queue <int> qu;
vector<int> history[1002];
for(int i = 1; i <= N; i++)
if(ingreed[i].size() == 0)
qu.push(i);
vector<int> load;
while(!qu.empty()){
int now = qu.front();
qu.pop();
for(auto next : pathInfo[now]){
ingreed[next.second].pop_back();
if(vertex[next.second] < vertex[now] + next.first) {
vertex[next.second] = vertex[now] + next.first;
history[now].push_back(next.second);
history[next.second] = history[now];
history[now].pop_back();
}
if(ingreed[next.second].size() == 0)
qu.push(next.second);
}
}
printf("%lld\n", vertex[1]);
printf("1 ");
for(auto point : history[1])
printf("%d ", point);
}
int main(){
vector<int> result;
int start, end, point;
scanf("%d %d", &N, &M);
for(int i = 0; i < M; i++){
scanf("%d %d %d", &start, &end, &point);
pathInfo[start].push_back(make_pair(point, end));
if(end != 1)
ingreed[end].push_back(start);
}
topologySort();
}
| true |
c2b8a064fc15e51fe1b6f7449937f1be9f0a656e | C++ | gabigt99/IML | /IML/SRT_DST.cpp | UTF-8 | 504 | 2.984375 | 3 | [] | no_license | #include "pch.h"
#include "SRT_DST.h"
const int SRT_DST::getType()
{
return 10;
}
vector<double> SRT_DST::calculate(vector<double> values)
{
for (size_t i = 0; i < values.size(); i++)
{
removeDublicates(values[i], values, i);
}
return values;
}
void SRT_DST::removeDublicates(double number, vector<double> &values, size_t index)
{
for (size_t i = index + 1; i < values.size(); i++)
{
if (values[i] == number)
{
values.erase(values.begin() + i, values.begin() + i + 1);
i--;
}
}
} | true |
097afa6e0bbb4467693d1565486c4a496b858f79 | C++ | nayuki/Nayuki-web-published-code | /zellers-congruence/zeller.cpp | UTF-8 | 5,786 | 3.703125 | 4 | [] | no_license | /*
* Zeller's congruence (C++)
* by Project Nayuki, 2023. Public domain.
* https://www.nayuki.io/page/zellers-congruence
*/
#include <array>
#include <cstdlib>
#include <exception>
#include <iostream>
#include <random>
#include <vector>
/*---- Zeller's congruence function ----*/
/*
* Returns the day-of-week dow for the given date
* (y, m, d) on the proleptic Gregorian calendar.
* Values of dow are 0 = Sunday, 1 = Monday, ..., 6 = Saturday.
* Strict values of m are 1 = January, ..., 12 = December.
* Strict values of d start from 1.
* The handling of months and days-of-month is lenient.
*/
int dayOfWeek(int y, int m, int d) {
m = m % 4800 - 3 + 4800 * 2;
y = y % 400 + 400 + m / 12;
m %= 12;
d = d % 7 + 7;
int temp = y + y / 4 - y / 100 + y / 400;
return (temp + (m * 13 + 12) / 5 + d) % 7;
}
/*---- Helper functions ----*/
static bool isLeapYear(int y) {
return y % 4 == 0 && (y % 100 != 0 || y % 400 == 0);
}
static const int MONTH_LENGTHS[] = {-1, 31, -1, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
static int monthLength(int y, int m) {
if (m != 2)
return MONTH_LENGTHS[m];
else
return isLeapYear(y) ? 29 : 28;
}
static void nextDate(std::array<int,3> &ymd) {
if (!(1 <= ymd[1] && ymd[1] <= 12))
throw std::domain_error("Invalid month");
if (!(1 <= ymd[2] && ymd[2] <= monthLength(ymd[0], ymd[1])))
throw std::domain_error("Invalid day-of-month");
ymd[2]++;
if (ymd[2] > monthLength(ymd[0], ymd[1])) {
ymd[2] = 1;
ymd[1]++;
if (ymd[1] == 13) {
ymd[1] = 1;
ymd[0]++;
}
}
}
static void previousDate(std::array<int,3> &ymd) {
if (!(1 <= ymd[1] && ymd[1] <= 12))
throw std::domain_error("Invalid month");
if (!(1 <= ymd[2] && ymd[2] <= monthLength(ymd[0], ymd[1])))
throw std::domain_error("Invalid day-of-month");
ymd[2]--;
if (ymd[2] == 0) {
ymd[1]--;
ymd[2] = monthLength(ymd[0], ymd[1]);
if (ymd[1] == 0) {
ymd[0]--;
ymd[1] = 12;
ymd[2] = 31;
}
}
}
static int compare(const std::array<int,3> &ymd, int y, int m, int d) {
if (ymd[0] != y)
return ymd[0] < y ? -1 : 1;
else if (ymd[1] != m)
return ymd[1] < m ? -1 : 1;
else if (ymd[2] != d)
return ymd[2] < d ? -1 : 1;
else
return 0;
}
static int dayOfWeekNaive(int y, int m, int d) {
std::array<int,3> ymd = {1600, 1, 1};
int dow = 6;
while (compare(ymd, y, m, d) < 0) {
nextDate(ymd);
dow = (dow + 1) % 7;
}
while (compare(ymd, y, m, d) > 0) {
previousDate(ymd);
dow = (dow - 1 + 7) % 7;
}
return dow;
}
/*---- Test suite ----*/
std::default_random_engine randGen((std::random_device())());
template <typename T>
static void assertEquals(T x, T y) {
if (x != y)
throw std::runtime_error("Value mismatch");
}
static void testSimple() {
struct TestCase {
int y;
int m;
int d;
int dow;
};
const std::vector<TestCase> CASES{
{-679, 9, 8, 1},
{-657, 2, 6, 3},
{-629, 5, 14, 2},
{-567, 8, 25, 0},
{-526, 7, 24, 5},
{-316, 11, 18, 6},
{-270, 7, 17, 1},
{-212, 1, 25, 5},
{-212, 11, 2, 0},
{- 43, 7, 20, 6},
{1619, 10, 16, 3},
{1620, 11, 30, 1},
{1631, 9, 3, 3},
{1637, 2, 18, 3},
{1653, 5, 25, 0},
{1735, 1, 7, 5},
{1753, 8, 28, 2},
{1804, 6, 30, 6},
{1810, 10, 3, 3},
{1835, 3, 2, 1},
{1844, 8, 14, 3},
{1844, 12, 16, 1},
{1899, 5, 23, 2},
{1912, 12, 10, 2},
{1915, 8, 2, 1},
{1938, 6, 18, 6},
{1945, 6, 7, 4},
{1965, 4, 28, 3},
{1998, 6, 18, 4},
{1999, 12, 31, 5},
{2000, 1, 1, 6},
{2000, 2, 1, 2},
{2000, 2, 29, 2},
{2000, 3, 1, 3},
{2001, 3, 1, 4},
{2002, 3, 1, 5},
{2003, 3, 1, 6},
{2004, 3, 1, 1},
{2071, 6, 13, 6},
{2094, 1, 20, 3},
{2124, 7, 26, 3},
{2196, 10, 12, 3},
{2213, 5, 5, 3},
{2216, 3, 15, 5},
{2225, 8, 26, 5},
{2268, 9, 2, 3},
{2306, 7, 25, 3},
{2336, 6, 20, 6},
{2348, 7, 16, 5},
};
for (const TestCase &cs : CASES)
assertEquals(cs.dow, dayOfWeek(cs.y, cs.m, cs.d));
}
static void testAscending() {
std::array<int,3> ymd = {1600, 1, 1};
int dow = 6;
while (ymd[0] < 2400) {
assertEquals(dow, dayOfWeek(ymd[0], ymd[1], ymd[2]));
nextDate(ymd);
dow = (dow + 1) % 7;
}
}
static void testDescending() {
std::array<int,3> ymd = {1600, 1, 1};
int dow = 6;
while (ymd[0] > 800) {
assertEquals(dow, dayOfWeek(ymd[0], ymd[1], ymd[2]));
previousDate(ymd);
dow = (dow - 1 + 7) % 7;
}
}
static void testVsNaiveRandomly() {
const long TRIALS = 1000;
std::uniform_int_distribution<int> yearDist(1600, 2400);
std::uniform_int_distribution<int> monthDist(1, 12);
for (long i = 0; i < TRIALS; i++) {
int y = yearDist(randGen);
int m = monthDist(randGen);
std::uniform_int_distribution<int> dayDist(1, monthLength(y, m));
int d = dayDist(randGen);
assertEquals(dayOfWeekNaive(y, m, d), dayOfWeek(y, m, d));
}
}
static void testLenientRandomly() {
const long TRIALS = 1000000;
std::uniform_int_distribution<int> yearDist(2000, 2400);
std::uniform_int_distribution<int> monthDist(1, 12);
std::uniform_int_distribution<int> yearPerturbDist(-2500, 2500);
std::uniform_int_distribution<int> dayPerturbDist(-500, 500);
for (long i = 0; i < TRIALS; i++) {
int y = yearDist(randGen);
int m = monthDist(randGen);
std::uniform_int_distribution<int> dayDist(1, monthLength(y, m));
int d = dayDist(randGen);
int dow = dayOfWeek(y, m, d);
int temp = yearPerturbDist(randGen);
y += temp;
m -= temp * 12;
d += dayPerturbDist(randGen) * 7;
assertEquals(dow, dayOfWeek(y, m, d));
}
}
int main() {
try {
testSimple();
testAscending();
testDescending();
testVsNaiveRandomly();
testLenientRandomly();
std::cerr << "Test passed" << std::endl;
return EXIT_SUCCESS;
} catch (std::exception &e) {
std::cerr << e.what() << std::endl;
return EXIT_FAILURE;
}
}
| true |
c7c58e3b0aa05afc8d938d4c1de2516f91d64833 | C++ | SergeyVN94/compiler | /lib.cpp | UTF-8 | 350 | 2.640625 | 3 | [] | no_license | #pragma once
#include <fstream>
using namespace std;
long long unsigned int getFileSize(ifstream *fileStream) {
long long unsigned int currentPosition = fileStream->tellg();
fileStream->seekg(0, ios_base::end);
long long unsigned int fileSize = fileStream->tellg();
fileStream->seekg(currentPosition, ios_base::beg);
return fileSize;
}
| true |
461c47d106f045655e758fd61abf644c79985d51 | C++ | gartenriese2/VulkanWrapper | /extern/VulkanWrapper/include/vw/modelId.hpp | UTF-8 | 674 | 2.90625 | 3 | [] | no_license | #pragma once
#include <cstdint>
#include <functional>
namespace vw::scene
{
class ModelID
{
public:
ModelID()
{
static uint64_t s_nextID = 1;
m_id = s_nextID++;
if (s_nextID == 0)
{
throw std::runtime_error("Maximum number of Models reached");
}
}
bool operator==(const ModelID & rhs) const { return m_id == rhs.m_id; }
struct KeyHash
{
std::size_t operator()(const ModelID & k) const
{
return std::hash<uint64_t>()(k.m_id);
}
};
private:
uint64_t m_id;
};
} | true |
d045112654ecb99ac5e100ffbf67a6f9ebf40db1 | C++ | yLim92/PIC10CProject | /status.h | UTF-8 | 6,027 | 2.515625 | 3 | [] | no_license | #ifndef STATUS_H
#define STATUS_H
#include "utility.h" //gc::StatusType, gc::TargetType
#include <map>
class GameUnit;
class Status;
class Ability;
struct LinkedStatus;
class BattleView;
struct AttributeList {
AttributeList() : is_stackable(true), effect_decay(0), effect_magnitude(0), duration(gc::PRACTICALLY_INFINITY), interval(1*gc::FPS), sustain_chance(0), sustain_chance_decay(0), type(gc::StatusType::undefined) {}
~AttributeList() {}
bool is_stackable;
double effect_decay;
double effect_magnitude;
int interval;
int duration;
double sustain_chance;
double sustain_chance_decay;
gc::StatusType type;
};
class AttributeListGroup {
public:
AttributeListGroup() {}
AttributeListGroup(int ma) : main_effect_accuracy(ma) {}
~AttributeListGroup() {}
void add_attribute_list(AttributeList attr, bool self_target, int efc, std::string k);
void set_link_logic(std::vector<std::pair<int, int> > ll) { link_logic = ll; }
const AttributeList& get_attribute_list(int i) { return attributes[i]; }
const bool get_target_logic(int i) const { return targeting_logic[i]; }
const int get_effect_chance (int i) const { return effect_chances[i]; }
const std::string get_id_key (int i) const { return id_keys[i]; }
const int get_main_effect_accuracy() const { return main_effect_accuracy; }
const std::vector<std::pair<int, int> >& get_link_logic() const { return link_logic; }
const int get_status_count() const { return int(attributes.size()); }
private:
std::vector<AttributeList> attributes;
std::vector<bool> targeting_logic;
std::vector<int> effect_chances;
std::vector<std::pair<int, int> > link_logic;
std::vector<std::string> id_keys;
int main_effect_accuracy;
};
class StatusList {
public:
StatusList() {}
StatusList(GameUnit* g) : gu(g) {}
virtual ~StatusList() {}
const std::map<gc::StatusType, double> get_all_status_and_values() const;
const double get_status_mod(gc::StatusType st) const;
const bool is_affected_by(gc::StatusType st) const;
const Status* get_last_status_of_type(gc::StatusType st) const;
void add_status(Status *stat);
//void remove_status(Status *stat);
void remove_individual_status(gc::StatusType st, string k);
void remove_statuses_of_type(gc::StatusType stat_type);
void remove_status_and_links(gc::StatusType st, string k);
void update();
void empty();
void remove_linked_statuses(Status &stat);
void do_ability_statuses(gc::StatusType st, GameUnit &tgt, int magn, double mult, BattleView &bv, Ability &trig_abl, GameUnit ¤t);
void update_duplicate_status(Status &existing, Status &updater) const;
Status* get_status(gc::StatusType st, string k);
protected:
std::map<gc::StatusType, std::vector<Status*> > statuses;
GameUnit* gu;
};
class Status {
friend class Ability;
friend class StatusList;
public:
Status() {};
Status(AttributeList attr, Ability *a, std::string k, StatusList &sl);
virtual ~Status();
const gc::StatusType get_type() const { return attr_list.type; }
const Ability& get_creating_ability() const { return *from_ability; }
const GameUnit& get_source() const;
double mod() const;
//Returns 0 if the status should no longer have an effect
virtual int update(GameUnit* gu);
virtual void link_status(Status* ls);
protected:
AttributeList attr_list;
Ability* from_ability;
vector<LinkedStatus> linked_statuses;
StatusList* status_list;
int timer;
std::string key;
};
struct LinkedStatus {
LinkedStatus() {}
LinkedStatus(StatusList &sl, string k, gc::StatusType st) : s_list(&sl), key(k), type(st) {}
StatusList *s_list;
string key;
gc::StatusType type;
};
class EquipmentList {
public:
EquipmentList() {}
EquipmentList(GameUnit *gu) : owner(gu) {}
virtual ~EquipmentList() {}
private:
GameUnit *owner;
};
class Equipment {
public:
Equipment() {}
Equipment(int ilvl, int rare_bonus);
virtual ~Equipment() {}
int generate_mod(gc::EquipMod eqmod);
virtual const int base_ability_mod() const { return item_level + 4; }
virtual const int base_accuracy_mod() const { return (item_level + 9)/2; }
virtual int base_armor_mod() const { return item_level * 5; }
virtual const int base_armor_pierce_mod() const { return 1 + (item_level)/5; }
virtual const int base_stat_mod() const { return item_level * 2; }
virtual const int base_crit_chance_mod() const { return 1 + item_level/10; }
virtual const int base_crit_damage_mod() const { return 50 + (item_level-1)*3; }
virtual const int base_damage_reduct_mod() const { return 1 + (item_level)/5; }
virtual const int base_dodge_mod() const { return (item_level + 9)/2; }
virtual const int base_effect_chance_mod() const { return 1 + (item_level * 2) / 5; }
virtual const int base_effect_resist_mod() const { return 1 + (item_level * 2) / 5; }
virtual const int base_experience_mod() const { return 1 + (item_level) / 5; }
virtual const int base_gold_mod() const { return 1 + (item_level) / 10; }
virtual const int base_initial_turn_mod() const { return 10 + item_level; }
virtual const int base_max_hp_mod() const { return 10 * item_level; }
virtual const int base_rare_item_mod() const { return 5 * item_level; }
virtual const int base_regen_resource_mod() const { return 5 + item_level - 1; }
virtual const int base_hp_regen_mod() const { return 1 + item_level/5; }
virtual const int base_shield_mod() const { return 20 + item_level * 4; }
virtual const int base_speed_mod() const { return 5 + item_level - 1; }
virtual const int base_vampirism_mod() const { return 1 + item_level/2; }
protected:
int item_level,
gold_value;
gc::EquipRarity rarity;
string name;
};
class MainHandEquip : public Equipment {
public:
MainHandEquip() {}
virtual ~MainHandEquip() {}
private:
};
class BodyEquip : public Equipment {
public:
BodyEquip() {}
virtual ~BodyEquip() {}
private:
};
class HelmetEquip : public Equipment {
public:
HelmetEquip() {}
virtual ~HelmetEquip() {}
private:
};
class BootsEquip : public Equipment {
public:
BootsEquip() {}
virtual ~BootsEquip() {}
private:
};
#endif //STATUS_H | true |
936227e11c250b1c9d4b67a8d060e49a58cc0557 | C++ | andrejlevkovitch/KaliLaska | /src/graphics/ConstIterator.cpp | UTF-8 | 1,414 | 2.609375 | 3 | [] | no_license | // ConstIterator.cpp
#include "KaliLaska/GraphicsScene.hpp"
#include "imp/GraphicsSceneImp.hpp"
namespace KaliLaska {
GraphicsScene::ConstIterator::~ConstIterator() {
}
GraphicsScene::ConstIterator::ConstIterator(std::unique_ptr<SceneIterator> imp)
: imp_{std::move(imp)} {
}
GraphicsScene::ConstIterator::ConstIterator(const ConstIterator &rhs)
: imp_{rhs.imp_->copyItSelf()} {
}
GraphicsScene::ConstIterator &GraphicsScene::ConstIterator::ConstIterator::
operator=(const ConstIterator &rhs) {
imp_ = rhs.imp_->copyItSelf();
return *this;
}
GraphicsItem *GraphicsScene::ConstIterator::operator*() const {
if (imp_) {
return imp_->operator*();
}
return nullptr;
}
GraphicsItem *GraphicsScene::ConstIterator::operator->() const {
if (imp_) {
return imp_->operator->();
}
return nullptr;
}
GraphicsScene::ConstIterator &GraphicsScene::ConstIterator::operator++() {
if (imp_) {
imp_->operator++();
}
return *this;
}
GraphicsScene::ConstIterator &GraphicsScene::ConstIterator::operator++(int) {
if (imp_) {
imp_->operator++();
}
return *this;
}
bool GraphicsScene::ConstIterator::operator==(const ConstIterator &rhs) const {
if (*imp_ == *rhs.imp_) {
return true;
}
return false;
}
bool GraphicsScene::ConstIterator::operator!=(const ConstIterator &rhs) const {
return !(*this == rhs);
}
} // namespace KaliLaska
| true |
190458a2e6e98d45b08af14814b9fabe7f82271a | C++ | Mehwa/Algorithm_Study | /SR_Study/SR_Study/BJ12100_2048.cpp | UHC | 2,848 | 2.96875 | 3 | [] | no_license | /*
2019.04.11
*/
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
int N, result;
int map[20][20], tmap[20][20];
int m[5];
void input() {
result = 0;
cin >> N;
for (int r = 0; r < N; r++) {
for (int c = 0; c < N; c++) {
cin >> map[r][c];
}
}
}
void updateR(int r) { // ش
int tmp[20];
int idx = 0;
for (int c = N - 1; c >= 0; c--) {
if (tmap[r][c] == 0) continue;
tmp[idx++] = tmap[r][c];
tmap[r][c] = 0;
}
int idx2 = N - 1;
for (int i = 0; i < idx; i++) {
tmap[r][idx2--] = tmp[i];
}
}
void moveR() {
for (int r = 0; r < N; r++) {
updateR(r); //* ġ ܾѴ.
for (int c = N - 1; c > 0; c--) {
if (tmap[r][c] == tmap[r][c - 1]) { // ==
tmap[r][c] += tmap[r][c - 1];
tmap[r][c - 1] = 0;
}
}
updateR(r);
}
}
void updateL(int r){
int tmp[20];
int idx = 0;
for (int c = 0; c <= N - 1; c++) {
if (tmap[r][c] == 0) continue;
tmp[idx++] = tmap[r][c];
tmap[r][c] = 0;
}
int idx2 = 0;
for (int i = 0; i < idx; i++) {
tmap[r][idx2++] = tmp[i];
}
}
void moveL() {
for (int r = 0; r < N; r++) {
updateL(r);
for (int c = 0; c < N - 1; c++) {
if (tmap[r][c] == tmap[r][c + 1]) {
tmap[r][c] += tmap[r][c + 1];
tmap[r][c + 1] = 0;
}
}
updateL(r);
}
}
void updateU(int c) {
int tmp[20];
int idx = 0;
for (int r = 0; r <= N - 1; r++) {
if (tmap[r][c] == 0) continue;
tmp[idx++] = tmap[r][c];
tmap[r][c] = 0;
}
int idx2 = 0;
for (int i = 0; i < idx; i++) {
tmap[idx2++][c] = tmp[i];
}
}
void moveU() {
for (int c = 0; c < N; c++) {
updateU(c);
for (int r = 0; r < N - 1; r++) {
if (tmap[r][c] == tmap[r + 1][c]) {
tmap[r][c] += tmap[r + 1][c];
tmap[r + 1][c] = 0;
}
}
updateU(c);
}
}
void updateD(int c) {
int tmp[20];
int idx = 0;
for (int r = N - 1; r >= 0; r--) {
if (tmap[r][c] == 0) continue;
tmp[idx++] = tmap[r][c];
tmap[r][c] = 0;
}
int idx2 = N - 1;
for (int i = 0; i < idx; i++) {
tmap[idx2--][c] = tmp[i];
}
}
void moveD() {
for (int c = 0; c < N; c++) {
updateD(c);
for (int r = N - 1; r > 0; r--) {
if (tmap[r][c] == tmap[r - 1][c]) {
tmap[r][c] += tmap[r - 1][c];
tmap[r - 1][c] = 0;
}
}
updateD(c);
}
}
int score() {
int max_score = 0;
for (int r = 0; r < N; r++) {
for (int c = 0; c < N; c++) {
max_score = max(max_score, tmap[r][c]);
}
}
return max_score;
}
void dfs(int d) {
if (d == 5) {
memcpy(tmap, map, sizeof(map));
for (int i = 0; i < 5; i++) {
if (m[i] == 0) moveU();
else if (m[i] == 1) moveD();
else if (m[i] == 2) moveL();
else moveR();
}
result = max(result, score());
return;
}
for (int i = 0; i < 4; i++) {
m[d] = i;
dfs(d + 1);
}
}
int main() {
freopen("input12100.txt", "r", stdin);
input();
dfs(0);
cout << result;
} | true |
006b2cc8d8ab153c9a42f9956707a71e3ddc8059 | C++ | j10kay/Computer-Science-1-Coursework | /Lab16.cpp | UTF-8 | 1,296 | 3.640625 | 4 | [] | no_license | #include <iostream>
#include <string>
#include <fstream>
#include <iomanip>
using namespace std;
void get_data(int&, int&); //Function Prototypes
void print_data(int, int);
void heading();
int main()
{
int user_miles;
int user_hours;
heading();
get_data(user_miles, user_hours);
print_data(user_miles, user_hours);
system("pause");
return 0;
}
void get_data(int& user_miles, int& user_hours) { //Obtain data from user
cout << "Enter the number of miles: ";
cin >> user_miles;
cout << "Enter the number of hours: ";
cin >> user_hours;
}
void print_data(int miles, int hours) { //Print function
cout << fixed << showpoint;
cout << "The number of miles is " << setprecision(2) << miles << endl;
cout << "The number of hours is " << setprecision(2) << hours << endl;
cout << "The number of miles per hour is " << setprecision(2) << float(miles)/hours << endl;
}
void heading() //Header Function for my output
{
cout << "****************************************************************************************************" << endl;
cout << "Chijioke E Kamanu" << endl;
cout << "@02840667" << endl;
cout << "March 29, 2018" << endl;
cout << "Lab 9" << endl;
cout << "****************************************************************************************************" << endl;
}
| true |
cdd03a810bf10c0dcc3c5308ecd814d8ed5b500f | C++ | ptryfon/loxim-stats | /src/SystemStats/StoreStats.h | UTF-8 | 2,435 | 2.78125 | 3 | [] | no_license | /*
* StoreStats.h
*
* Created on: 12-nov-2009
* Author: paweltryfon
*/
#ifndef STORESTATS_H_
#define STORESTATS_H_
#include <SystemStats/AbstractStats.h>
#include <SystemStats/DiskUsageStats.h>
namespace SystemStatsLib{
/*
* Store stats collect stats related with store module:
* - amount of readed pages in memory (or disk)
* - amount of readed pages from disk
* - hit ratio - (1 - disk reads / all reads)
* - the same for write
* - minimum, maximum and average time of page read
*/
class AbstractStoreStats;
class StoreStats;
class EmptyStoreStats;
/* Forward declarations.
*/
class AbstractStoreStats : public AbstractStats {
public:
AbstractStoreStats() : AbstractStats("STORE_STATS") {}
virtual AbstractDiskUsageStats& get_disk_usage_stats() = 0;
virtual ~AbstractStoreStats() {}
void add_disk_page_reads(int count) { this->get_disk_usage_stats().add_disk_page_reads(count); }
void add_page_reads(int count) { this->get_disk_usage_stats().add_page_reads(count); }
void add_disk_page_writes(int count) { this->get_disk_usage_stats().add_disk_page_writes(count); }
void add_page_writes(int count) { this->get_disk_usage_stats().add_page_writes(count); }
void add_read_time(int bytes, double milisec) {this->get_disk_usage_stats().add_read_time(bytes, milisec);}
virtual AbstractStoreStats & operator +=(const StoreStats &rhs) = 0;
AbstractStoreStats & operator +=(const EmptyStoreStats &) {return *this;}
};
class StoreStats: public AbstractStoreStats{
protected:
DiskUsageStats disk_usage_stats;
public:
StoreStats():disk_usage_stats(){};
DiskUsageStats& get_disk_usage_stats() {return disk_usage_stats;}
AbstractStoreStats & operator +=(const StoreStats &rhs)
{
disk_usage_stats += rhs.disk_usage_stats;
return *this;
}
StatsOutput * get_stats_output() const
{
StatsOutput* retval = disk_usage_stats.get_stats_output("store");
retval->stats_id = STORE_STATS_ID;
return retval;
}
};
class EmptyStoreStats: public AbstractStoreStats{
protected:
EmptyDiskUsageStats disk_usage_stats;
public:
EmptyStoreStats(): disk_usage_stats(EmptyDiskUsageStats()){};
EmptyDiskUsageStats& get_disk_usage_stats() {return disk_usage_stats;}
AbstractStoreStats & operator +=(const StoreStats &) {return *this;}
StatsOutput * get_stats_output() const {EMPTY_STATS_OUTPUT}
};
}
#endif /* STORESTATS_H_ */
| true |