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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
b5610448e31b0538314b01ef0000af474e69b6fc | C++ | alexandraback/datacollection | /solutions_5631989306621952_0/C++/chocimir/a.cpp | UTF-8 | 940 | 2.609375 | 3 | [] | no_license | #include<algorithm>
#include<cassert>
#include<cctype>
#include<cmath>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<deque>
#include<iostream>
#include<list>
#include<map>
#include<queue>
#include<set>
#include<string>
#include<vector>
#include<sstream>
using namespace std;
typedef long long LL;
typedef long double LD;
#define dprintf(...) fprintf(stderr, __VA_ARGS__)
int cond = 1;
#define DB(X) {if(cond){cerr<<"Line:"<<__LINE__<<", "<<#X<<" = "<<X<<endl;}}
string solve() {
string s; cin >> s;
ostringstream os;
char c = s[0];
deque<char> q;
for(int i = 0; i < s.length(); ++i) {
if (s[i] >= c) {
q.push_back(s[i]);
c = s[i];
}
else {
q.push_front(s[i]);
}
}
while (!q.empty()) {
char c = q.back();
q.pop_back();
os << c;
}
return os.str();
}
int main() {
int t; cin >> t;
for(int x = 1; x <= t; ++x){
cout << "Case #" << x << ": " << solve() << endl;//result
}
return 0;
}
| true |
7dadf4ddb58cc4437c87e8910fb621c6cbdafc92 | C++ | davidstudy/2018_git | /0827面试准备v3/0827面试准备v3/DWZ基础知识/笔试面试编程题/360numgame/main.cpp | UTF-8 | 560 | 2.859375 | 3 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
int main(int argc, const char * argv[])
{
int a, b, res;
bool flag = false;
while (cin >> a >> b)
{
flag = a % 2;//
int tmp = (1 + a) / 2;
if (flag)//
{
if (b >= tmp) res = b - 1;
else res = b + 1;
}
else//
{
if (b > tmp) res = b - 1;
else res = b + 1;
}
if (res < 1) res = 1;
else if (res >= a) res = a;
cout << res << endl;
}
return 0;
}
| true |
6e08a11d162beed0e65492660e42f63ff9080c8e | C++ | waelaboulezz/curve-fitting | /main.cpp | UTF-8 | 5,346 | 2.515625 | 3 | [] | no_license | #include "Coursework1/Coursework1lib.h"
using namespace std;
int main()
{
vector<vector<double>> v = {{2, 1, -1}, {1, 4, 3}, {-1, 2, 7}};
Matrix A = Matrix(v);
vector<double> b = {0, 14, 30};
SolveGaussElimination x = SolveGaussElimination(A, b, true);
SolveSeidle y = SolveSeidle(A, b, 30, true);
v = {{2, -1, 0}, {1, -3, 1}, {-1, 1, -3}};
A = Matrix(v);
b = {2, -2, 6};
x = SolveGaussElimination(A, b, true);
y = SolveSeidle(A, b, 30, true);
v = {{5, 6, 7}, {6, 3, 9}, {7, 9, 10}};
A = Matrix(v);
b = {18, 18, 26};
x = SolveGaussElimination(A, b, true);
y = SolveSeidle(A, b, 30, false);
v = {{10, 2, -1, 2}, {1, 5, 1, 0}, {1, -2, -5, 1}, {3, 0, 0, 9}};
A = Matrix(v);
b = {-4, 1, 2, 10};
x = SolveGaussElimination(A, b, true);
y = SolveSeidle(A, b, 30, false);
v = {{-1, 1, -1, 1}, {1, 1, 1, 1}, {8, 4, 2, 1}, {27, 9, 3, 1}};
A = Matrix(v);
b = {1, 1, -2, 1};
x = SolveGaussElimination(A, b, true);
y = SolveSeidle(A, b, 30, false);
PlynomialRegression P(2);
CSVReader csv = CSVReader("./datasets/part_2/a/2_a_dataset_1.csv");
P.fit(csv.data[0], csv.data[1], 1, true);
vector<double> y_guass = P.predict(0, 10, 0.1);
P.fit(csv.data[0], csv.data[1], 2, true);
vector<double> y_seidle = P.predict(0, 10, 0.1);
PlynomialRegression P_2(2);
CSVReader csv_2 = CSVReader("./datasets/part_2/a/2_a_dataset_2.csv");
P_2.fit(csv_2.data[0], csv_2.data[1], 1, true);
vector<double> y_guass2 = P_2.predict(0, 10, 1);
P_2.rmse(csv_2.data[1], y_guass2);
P_2.fit(csv_2.data[0], csv_2.data[1], 2, true);
vector<double> y_seidle2 = P_2.predict(0, 10, 1);
CSVReader csv_3 = CSVReader("./datasets/kaggle_Housing.csv");
MultipleLinearRegression M;
M.fit(csv_3.data[2], csv_3.data[1], csv_3.data[0], 1, true);
vector<double> y_housing = M.predict(csv_3.data[2], csv_3.data[1]);
std::vector<std::pair<std::string, std::vector<double>>> dataset_1 = read_csv("./datasets/part_3/3_dataset_1.csv");
std::vector<std::pair<std::string, std::vector<double>>> dataset_2 = read_csv("./datasets/part_3/3_dataset_2.csv");
vector<double> x1 = dataset_1.at(0).second;
vector<double> y1 = dataset_1.at(1).second;
vector<double> x2 = dataset_2.at(0).second;
vector<double> y2 = dataset_2.at(1).second;
NewtonInterpolator Newton;
vector<double> a1 = Newton.fit(x1, y1);
cout << "Newton Interpolation Polynomial: ";
Newton.writeNewtonPolynomial(a1);
vector<double> a2 = Newton.fit(x2, y2);
cout << "Newton Interpolation Polynomial: ";
Newton.writeNewtonPolynomial(a2);
std::vector<string> colnames(2);
colnames[0] = "Newton Coefficients Dataset 1";
colnames[1] = "Newton Coefficients Dataset 2";
std::vector<vector<double>> coeff(2);
coeff[0] = a1;
coeff[1] = a2;
write_csv("Newton Polynomial Coefficients.csv", colnames, coeff);
std::vector<string> colnamesnewp(2);
colnamesnewp[0] = "X";
colnamesnewp[1] = "Y";
vector<vector<double>> newPointsNewton2D1 = getPointsNewton(x1, y1, x1.size(), Newton, a1);
write_csv("Newton 2 Times Dataset1.csv", colnamesnewp, newPointsNewton2D1);
vector<vector<double>> newPointsNewton4D1 = getPointsNewton(x1, y1, x1.size() * 3, Newton, a1);
write_csv("Newton 4 Times Dataset1.csv", colnamesnewp, newPointsNewton4D1);
vector<vector<double>> newPointsNewton2D2 = getPointsNewton(x2, y2, x2.size(), Newton, a2);
write_csv("Newton 2 Times Dataset2.csv", colnamesnewp, newPointsNewton2D2);
vector<vector<double>> newPointsNewton4D2 = getPointsNewton(x2, y2, x2.size() * 3, Newton, a2);
write_csv("Newton 4 Times Dataset2.csv", colnamesnewp, newPointsNewton4D2);
Spline s;
vector<vector<double>> cSpline1 = s.fitSpline(x1, y1);
vector<vector<double>> newPointsSpline2D1 = getPointsSpline(x1, y1, x1.size(), s);
write_csv("Spline 2 Times Dataset1.csv", colnamesnewp, newPointsSpline2D1);
vector<vector<double>> newPointsSpline4D1 = getPointsSpline(x1, y1, x1.size() * 3, s);
write_csv("Spline 4 Times Dataset1.csv", colnamesnewp, newPointsSpline4D1);
vector<vector<double>> newPointsSpline2D2 = getPointsSpline(x2, y2, x2.size(), s);
write_csv("Spline 2 Times Dataset2.csv", colnamesnewp, newPointsSpline2D2);
vector<vector<double>> newPointsSpline4D2 = getPointsSpline(x2, y2, x2.size() * 3, s);
write_csv("Spline 4 Times Dataset2.csv", colnamesnewp, newPointsSpline4D2);
std::vector<string> colnamesSpline1(5);
colnamesSpline1[0] = "Spline x Dataset 1";
colnamesSpline1[1] = "Spline a Dataset 1";
colnamesSpline1[2] = "Spline b Dataset 1";
colnamesSpline1[3] = "Spline c Dataset 1";
colnamesSpline1[4] = "Spline y Dataset 1";
write_csv("Cubic Spline Interpolator Dataset 1.csv", colnamesSpline1, cSpline1);
vector<vector<double>> cSpline2 = s.fitSpline(x2, y2);
std::vector<string> colnamesSpline2(5);
colnamesSpline2[0] = "Spline x Dataset 2";
colnamesSpline2[1] = "Spline a Dataset 2";
colnamesSpline2[2] = "Spline b Dataset 2";
colnamesSpline2[3] = "Spline c Dataset 2";
colnamesSpline2[4] = "Spline y Dataset 2";
write_csv("Cubic Spline Interpolator Dataset 2.csv", colnamesSpline2, cSpline2);
return (0);
} | true |
6119b6f5641083e66cffd08e65d97f802a8bb191 | C++ | hrachyahakobyan/Pandemic | /core/include/core/GovGrantAction.h | UTF-8 | 485 | 2.515625 | 3 | [] | no_license | #pragma once
#include "ActionBase.h"
namespace pan{
/**
* @brief Encapsulates the parameters of GovGrant event action
* @author Hrachya Hakobyan
*/
class GovGrantAction : public ActionImpl<GovGrantAction, ActionBase>
{
public:
GovGrantAction();
GovGrantAction(pan::PlayerIndex player, pan::CityIndex index);
/**
* The initiating player
*/
PlayerIndex player;
/**
* The city to build a research station in
*/
CityIndex city;
std::string description() const;
};
}
| true |
dae1fc4a02d8facc472721519af58312f8a6a12f | C++ | lm-chinhtran/atcoder | /src/pass2_h.cpp | UTF-8 | 2,619 | 2.78125 | 3 | [] | no_license | //
// pass2_h.cpp
// learningCplusplus
//
// Created by Tran Duc Chinh on 2020/04/04.
// Copyright © 2020 Tran Duc Chinh. All rights reserved.
//
#include <iostream>
#include <queue>
#include <map>
#include <algorithm>
#include <math.h>
using namespace std;
typedef long long ll;
ll mod = 998244353;
ll INF = 1000000007;
#define PI 3.14159265
pair<int, int> dijsktra(int x, char des, int n, vector<pair<int, char> > *adj) {
priority_queue<pair<pair<int, char>, int> > q; // (-d, x) current distance to node x is d, using -d to find minimum distance
bool processed[n];
pair<int, char> distance[n];
for (int i=0; i<n; i++) {
distance[i].first = INF;
distance[i].second = '0';
processed[i] = false;
}
// find from x
distance[x] = make_pair(0, '0');
q.push({distance[x], x});
while (!q.empty()) {
int a = q.top().second;
q.pop();
if (processed[a]) continue;;
processed[a] = true;
for (auto u: adj[a]) {
int b = u.first; // node b
char label = u.second;
int w = 1; // distance from a to b is w
if (distance[b].first > distance[a].first + w) {
distance[b] = make_pair(distance[a].first + w, label);
q.push({{-distance[b].first, label}, b});
}
}
}
int l = INF;
int end = 0;
// std::cout << "distance from " << x << std::endl;
for (int i = 0; i < n; i++) {
if (distance[i].first==INF) continue;
if (distance[i].second == des && distance[i].first < l) {
l = distance[i].first;
end = i;
}
// std::cout << " distance to " << i << ": " << distance[i] << std::endl;
}
return make_pair(l, end);
}
int main() {
int n, m;
std::cin >> n >> m;
int dp[11][n][m];
vector<pair<int, int> > p[11];
for (int i = 0; i < 11; i++) {
for (int r = 0; r < n; r++) {
for (int c = 0; c < m; c++) {
dp[i][r][c] = INF;
}
}
}
for (int i = 0; i < n; i++) {
string t;
std::cin >> t;
for (int j = 0; j < m; j++) {
if (t[j] == 'S') { p[0].push_back({i, j}); dp[0][i][j] = 0; }
else if (t[j] == 'G') p[10].push_back({i, j});
else p[t[j]-'0'].push_back({i, j});
}
}
for (int i = 1; i < 11; i++) {
for (auto u: p[i]) {
int ri = u.first;
int ci = u.second;
for (auto v: p[i-1]) {
int ri1 = v.first;
int ci1 = v.second;
dp[i][ri][ci] = min(dp[i][ri][ci], abs(ri1-ri) + abs(ci1-ci) + dp[i-1][ri1][ci1]);
}
}
}
int ans = dp[10][p[10][0].first][p[10][0].second];
if (ans >= INF) {
std::cout << -1 << std::endl;
}
else {
std::cout << ans << std::endl;
}
return 0;
} | true |
1bcad8f72448b48ace5bc8d06b7eabdc08cbc3a6 | C++ | joseroman1/CSC_17A_48983 | /Homework/Assignment 4/Gaddis_8thEd_Chapter11_Problem12/main.cpp | UTF-8 | 3,060 | 3.5625 | 4 | [] | no_license | /*
* File: main.cpp
* Author: Jose Roman
* Created on October 8, 2015
*/
//System Libraries
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
//User Libraries
struct stdnt{ //Student
string sName;//Name of the student
string sID;//ID of the student
int *sScore;//pointer to an array of scores
float average;//average of sScore
char cGrade;//the final cGrade
};
//Global Constants
//Function Prototypes
stdnt getInfo(int);
void pntInfo(stdnt);
//Execution begins here
int main(int argc, char** argv) {
int testNum,//how many test
sdtNum;//How many students
//prompt user for the number of test
do {
cout<<"Input the number of test for the course?";
cin>>testNum;
if(testNum<1)
cout<<"Wrong input"<<endl;
} while(testNum<1);
//prompt user for the number of student
do {
cout<<"How many students?";
cin>>sdtNum;
if(sdtNum<1)
cout<<"Wrong input"<<endl;
} while(sdtNum<1);
//dynamic allocate memory for all student
stdnt*stud=new stdnt[sdtNum];
//prompt user input data
for(int i=0;i<sdtNum;i++) {
cout<<endl<<"Student "<<(i+1)<<": "<<endl;
stud[i]=getInfo(testNum);
}
//output the result
for(int i=0;i<sdtNum;i++) {
cout<<"Student "<<(i+1)<<": ";
pntInfo(stud[i]);
}
//deallocate memory
delete [] stud;
stud=0;
//Exit stage right
return 0;
}
stdnt getInfo(int testNum) {
stdnt stu;
stu.sScore=new int[testNum];
stu.average=0;
bool valid;
//get the Name
cout<<"Student Name"<<": ";
cin.ignore();
getline(cin,stu.sName);
//input the ID
do {
valid=true;
cout<<"Student ID: ";
cin>>stu.sID;
//check the id number
for(int j=0;j<stu.sID.length();j++) {
if(stu.sID.at(j)<48||stu.sID.at(j)>57)
valid=false;
}
if(!valid)
cout<<"Wrong input"<<endl;
}while(!valid);
//ask for input for all the test
for(int j=0;j<testNum;j++) {
do {
cout<<"Test #"<<(j+1)<<": ";
cin>>stu.sScore[j];
if(stu.sScore[j]<0||stu.sScore[j]>100)
cout<<"Wrong input"<<endl;
} while(stu.sScore[j]<0||stu.sScore[j]>100);
stu.average+=stu.sScore[j];
}
//calculate the average of the student test score
stu.average=stu.average/static_cast<float>(testNum);
//Grade
if(stu.average>=91) {
stu.cGrade='A';
} else if(stu.average>=81) {
stu.cGrade='B';
} else if(stu.average>=71) {
stu.cGrade='C';
} else if(stu.average>=61) {
stu.cGrade='D';
} else {
stu.cGrade='F';
}
//deallocate memory
delete [] stu.sScore;
//return the structure
return stu;
}
void pntInfo(stdnt s) {
cout<<"Name: "<<s.sName<<" ID: "<<s.sID<<endl;
cout<<" The average test Score: "<<s.average<<" Class Grade: "<<s.cGrade<<endl;
} | true |
cedf621cc128cfd392e81f62eac0a501bcdcf081 | C++ | liweiliv/history | /util/logger.h | GB18030 | 5,232 | 2.59375 | 3 | [
"Apache-2.0"
] | permissive | /*
* Copyright (c) 2012, Taobao.com
* All rights reserved.
*
* ļƣlogger.h
* ժҪlog4cpp־
* ߣBenkong <benkong@taobao.com>
* ڣ2012.7.2
*/
#ifndef _LOGGER_H_
#define _LOGGER_H_
#include <stdio.h>
#include <stdarg.h>
/**
* ͵־
* @param logger Loggerʵ
* @param fmt ־ĸʽοprintf
* @return 0: ɹ; <0: ִ
*/
#define logDebug( logger, fmt, ...) (logger)->log(__FILE__, __LINE__, L_DEBUG, fmt, ##__VA_ARGS__)
#define logInfo( logger, fmt, ...) (logger)->log(__FILE__, __LINE__, L_INFO, fmt, ##__VA_ARGS__)
#define logNotice(logger, fmt, ...) (logger)->log(__FILE__, __LINE__, L_NOTICE, fmt, ##__VA_ARGS__)
#define logWarn( logger, fmt, ...) (logger)->log(__FILE__, __LINE__, L_WARN, fmt, ##__VA_ARGS__)
#define logError( logger, fmt, ...) (logger)->log(__FILE__, __LINE__, L_ERROR, fmt, ##__VA_ARGS__)
#define logCrit( logger, fmt, ...) (logger)->log(__FILE__, __LINE__, L_CRIT, fmt, ##__VA_ARGS__)
#define logFatal( logger, fmt, ...) (logger)->log(__FILE__, __LINE__, L_FATAL, fmt, ##__VA_ARGS__)
#define logDebug_r( logger, fmt, ...) (logger)->log_r(__FILE__, __LINE__, L_DEBUG, fmt, ##__VA_ARGS__)
#define logInfo_r( logger, fmt, ...) (logger)->log_r(__FILE__, __LINE__, L_INFO, fmt, ##__VA_ARGS__)
#define logNotice_r(logger, fmt, ...) (logger)->log_r(__FILE__, __LINE__, L_NOTICE, fmt, ##__VA_ARGS__)
#define logWarn_r( logger, fmt, ...) (logger)->log_r(__FILE__, __LINE__, L_WARN, fmt, ##__VA_ARGS__)
#define logError_r( logger, fmt, ...) (logger)->log_r(__FILE__, __LINE__, L_ERROR, fmt, ##__VA_ARGS__)
#define logCrit_r( logger, fmt, ...) (logger)->log_r(__FILE__, __LINE__, L_CRIT, fmt, ##__VA_ARGS__)
#define logFatal_r( logger, fmt, ...) (logger)->log_r(__FILE__, __LINE__, L_FATAL, fmt, ##__VA_ARGS__)
// ־𣬴ӵ͵
enum LLEVEL_T
{
L_MIN_LEVEL= 0,
L_DEBUG = 1,
L_INFO = 2,
L_NOTICE = 3,
L_WARN = 4,
L_ERROR = 5,
L_CRIT = 6,
L_FATAL = 7,
TOTAL_LEVEL
};
struct LogHandle;
class Logger
{
public:
virtual ~Logger();
/**
* ͨļʼ־
* @param profile ־ļ
* @param section ļ
* @return NULLɹ; NULL: ʼʧ
*
* ļ¸ʽ
* [log]
* root_path = . # ־·
* prefix = std # ־ļǰΪ"std"豸
* show_pid = YES # ǷpidȡֵYES/NO
* show_line = YES # Ƿļ/кţȡ֮YES/NO
* base_level = TRACE # ־𣬿ȡֵӵ͵DEBUG/INFO/NOTICE/WARN/ERROR/CRIT/FATAL
* show_level = YES # ǷϢȡֵYES/NO
* switch_by = SIZE # ֻʽȡֵSIZE/TIME
* switch_size= 100 # ֻļСswitch_byΪsizeʱЧλΪM
* max_fileage= 1440 # ʱֻڣswitch_byΪtimeʱЧλΪӡ, 1440
* rolling_num= 7 # ־Թ255ȱʡΪ7
*/
static Logger* createLoggerFromProfile(const char *profile, const char *section);
/**
* ־"_r"Ϊ̰߳ȫĺ
* @param fileName øúԴļ
* @param lineNo øúԴļк
* @param level ־
* @param format ־ĸʽοprintf
* @return 0: ɹ; <0: ִ
*/
int log( const char *fileName, int lineNo, int level, const char *format, ...);
int log_r(const char *fileName, int lineNo, int level, const char *format, ...);
/**
* ־(תӿڵĵ)"_r"Ϊ̰߳ȫĺ
* @param level ־
* @param format ־ĸʽοprintf
* @param ap ӿڵĿɱб
* @return 0: ɹ; <0: ִ
*/
int log( int level, const char *format, va_list &ap);
int log_r(int level, const char *format, va_list &ap);
/**
* û
* @param baseLevel
* @return 0: ; >0: ɵĻ
*/
int setBaseLevel(int baseLevel);
/**
* ־
* @param rollingNum ־
* return <0: ; >=0: ɵ־
*/
int setRollingNum(int rollingNum);
/**
* ģlog4cpp
* @param prgName
* @param modName
*/
void setPrgAndModName(const char *prgName, const char *modName);
/**
* ѱʾַ־תΪӦ
* @param szLevel ־"INFO"/"DEBUG"
* @return szLevelϷӦ; szLevelϷ0
*/
static int strToLevel(const char* level);
protected:
Logger();
int init(const char *logPath, const char *filePrefix, int options, const char *timeFmt, int switchSize);
LogHandle *m_log;
public:
static Logger *m_logger; // ȫlogger
};
#endif
| true |
7423b68744e5af0f8e5b8c951063de1745268dac | C++ | xiweihuang/Primer | /july_algorithm/ch02/string_03.cpp | UTF-8 | 696 | 3.578125 | 4 | [] | no_license | /**********
【字符串查找问题 -- 暴力求解】
**********/
#include <iostream>
#include <string>
using namespace std;
int BruteForceSearch(const string& str, const string& pat)
{
int i = 0; // 当前匹配到的原始串首位
int j = 0; // 模式串的匹配位置
int size1 = str.size();
int size2 = pat.size();
int last = size1 - size2;
while ((i <= last) && (j < size2)) {
if (str[i+j] == pat[j])
++j;
else { // 不匹配,则比对下一个位置,模式串回溯到首位
++i;
j = 0;
}
}
if (j >= size2)
return i;
return -1;
}
int main()
{
string str = "ABCDE";
string pat = "DE";
cout << BruteForceSearch(str, pat) << endl;
return 0;
} | true |
ab58bd30fdf06db23532b9036b799718d33f8a70 | C++ | kimyunil/algospot | /JumpGame.cpp | UTF-8 | 1,023 | 2.6875 | 3 | [] | no_license | #define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <memory.h>
#define MAX 100
int map[MAX][MAX];
bool cache[MAX][MAX];
int T, N;
bool find(int x, int y) {
if (x >= N || y>= N )
return false;
if (map[y][x] == 0)
return true;
if (cache[y][x] == false)
return false;
if (find(x+map[y][x], y) || find(x, y+map[y][x]))
return true;
cache[y][x] = false;
return false;
}
int main(int argc, char* argv[])
{
//freopen("input.txt", "r", stdin);
scanf("%d", &T);
for (int test_case = 1; test_case <= T; test_case++)
{
scanf("%d", &N);
for (int y = 0; y < N; y++)
for (int x = 0; x < N; x++)
scanf("%d", &map[y][x]);
//memset(cache, 0, sizeof(int)*N*N);
//memset(cache, true, sizeof(bool)*N*N);
for (int y = 0; y < N; y++)
for (int x = 0; x < N; x++)
cache[y][x]=true;
/*
for (int y = 0; y < N; y++) {
for (int x = 0; x < N; x++)
printf("%3d", map[y][x]);
printf("\n");
}
*/
if (find(0, 0))
printf("YES\n");
else
printf("NO\n");
}
return 0;
}
| true |
14e3d0485099951c59851183f6f49f43273b1252 | C++ | github188/MyCode-1 | /codechef/12MarchLong/LUCKY2/LUCKY2.cpp | UTF-8 | 1,900 | 2.578125 | 3 | [] | no_license | #include<stdio.h>
#include<string.h>
int mod=1000000007;
int c[1001][1001],eight[1001],two[1001],f[1001][1001],a[1001];
char s1[1001],s2[1001];
bool isL(char s[])
{
int ln=0,len=strlen(s);
for (int i=0;i<len;i++)
if ((s[i]=='4')||(s[i]=='7')) ln++;
for (int i=1;i<=a[0];i++) if (a[i]==ln) return true;
return false;
}
int work(char s[])
{
int ln=0,len=strlen(s),ans=0;
for (int i=0;i<len;i++)
{
for (int no=0;no<s[i]-'0';no++)
{
int l=ln;
if ((no==4)||(no==7)) l++;
for (int j=1;j<=a[0];j++)
if (a[j]-l>len-i-1) {break;}
else
{
if (a[j]-l>=0) ans=(ans+f[len-i-1][a[j]-l])%mod;
}
}
if ((s[i]=='4')||(s[i]=='7')) ln++;
}
if (isL(s)) ans++;ans%=mod;
return ans;
}
int main()
{
eight[0]=two[0]=1;c[0][0]=1;
for (int i=1;i<=1000;i++)
{
c[i][0]=1;
two[i]=(two[i-1]*2)%mod;
long long u=eight[i-1],v=8,mm=mod;u=(u*v)%mm;
eight[i]=u;
}
for (int i=1;i<=1000;i++)
for (int j=1;j<=i;j++) c[i][j]=(c[i-1][j]+c[i-1][j-1])%mod;
for (int i=0;i<=1000;i++)
for (int j=0;j<=i;j++)
{
long long u=eight[i-j],v=c[i][j],w=two[j],mm=mod;
u=(u*v)%mm;
u=(u*w)%mm;
f[i][j]=u;
}
a[0]=0;
for (int i=1;i<=1000;i++)
{
int k=i,j=0;
bool check=true;
while (k!=0)
{
if (((k%10)!=4)&&((k%10)!=7)) {check=false;}
j++;k/=10;
}
if (check)
{
a[0]++;
a[a[0]]=i;
}
}
int tt;scanf("%d",&tt);gets(s1);
while (tt>0)
{
tt--;
scanf("%s %s",&s1,&s2);
int u=work(s1),v=work(s2);
v-=u;
if (v<0) v+=mod;
if (isL(s1)) v++;
v%=mod;
printf("%d\n",v);
}
return 0;
}
| true |
4434960ce53e6d0d7b09b74deff9eccfe1c069fc | C++ | herrkong/UserInputAssistant | /src3/MyDict.cc | UTF-8 | 1,801 | 2.8125 | 3 | [] | no_license | #include "MyDict.h"
#include <fstream>
#include <sstream>
namespace hk
{
//初始化中英文词典和索引表
void MyDict::en_init(const char * EnDictFilePath,const char * EnIndexFilePath)
{
ifstream ifsEnDict(EnDictFilePath);//文件流
string word;
int wordFreq;
while(ifsEnDict>>word>>wordFreq)
{
_dict.push_back(make_pair(word,wordFreq));
}
ifsEnDict.close();
string line;
ifstream ifsEnIndex(EnIndexFilePath);
int location,k=1;
while(getline(ifsEnIndex,line)) //换行符也拿到了
{
stringstream ss(line);//字符串流
if(k%2 != 0) //奇数行是字母
{
while(ss>>word);
}
else //偶数行是索引下标
{
while(ss>>location)
{
_indexTable[word].insert(location);
}
}
k++;
}//while
ifsEnIndex.close();
}
#if 0 //有些瑕疵
void MyDict::init(const char * dictFilePath,const char * indexFilePath)
{
ifstream ifsDict(dictFilePath);
string word;
int wordFreq;
while(ifsDict>>word>>wordFreq)
{
_dict.push_back(make_pair(word,wordFreq));
}
ifsDict.close();
ifstream ifsIndex(indexFilePath);
string ch;
while(ifsIndex>>ch)
{
string line;
getline(ifsIndex,line);//读取字母后面的换行符
getline(ifsIndex,line);
stringstream ss(line);
int num;
while(ss>>num)
{
_indexTable[ch].insert(num);
}
ifsIndex.close();
}
}
#endif
Dict & MyDict::getDict()
{
return _dict;
}
IndexTable & MyDict::getIndexTable()
{
return _indexTable;
}
MyDict * MyDict::_pInstance = MyDict::getInstance(); //饱汉模式
}//end of namespace hk
| true |
7cd06d30666465a7ccbf4ea8a4f9c92688603e28 | C++ | jtahstu/iCode | /workspace/Smartoj/src/P1003.cpp | GB18030 | 519 | 2.578125 | 3 | [] | no_license | /**
* Project Name: Smartoj
* File Name: P1003.cpp
* Created on: 2015419 11:24:33
* Author: jtahstu
* Copyright (c) 2015, jtahstu , All Rights Reserved.
*/
//
//123 500
//
//623
//-377
//61500
//0
#include<iostream>
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<string>
using namespace std;
int main1003()
{
long long a,b;
cin>>a>>b;
cout<<a+b<<endl;
cout<<a-b<<endl;
cout<<a*b<<endl;
cout<<a/b<<endl;
return 0;
}
| true |
2c52ed5110822cc9be9fb2b4777cdac80f548022 | C++ | angelamyu/2DAnimator | /QTOpenGL/sceneNode.cpp | UTF-8 | 4,625 | 2.671875 | 3 | [] | no_license | #include "sceneNode.h"
//#include <qDebug>
#include "gMatrix3.h"
#include "gVector3.h"
#include "math.h"
#define PI atan(1.0f)*4.0f
using namespace std;
sceneNode::sceneNode(){
geometry = new rPolygon();
translateX = 0;
translateY = 0;
scaleX = 1;
scaleY = 1;
rotation = 0;
transfM = gMatrix3().identity();
rotPointX = 0;
rotPointY = 0;
keyFrameCheck = false;
}
sceneNode::sceneNode(gMatrix3 tm, vector<sceneNode*> c, rPolygon* g){
transfM = tm;
children = c;
geometry = g;
translateX = 0;
translateY = 0;
scaleX = 1;
scaleY = 1;
rotation = 0;
rotPointX = 0;
rotPointY = 0;
keyFrameCheck = false;
}
sceneNode::~sceneNode(){
delete geometry;
}
rPolygon* sceneNode::getGeometry(){
return geometry;
}
vector<sceneNode*> sceneNode::getChildren(){
return children;
}
void sceneNode::setGeometry(rPolygon* p){
geometry = p;
}
void sceneNode::setChildren(vector<sceneNode*> c){
children = c;
}
void sceneNode::setColor(float r,float g,float b){
geometry->setRed(r);
geometry->setGreen(g);
geometry->setBlue(b);
}
bool sceneNode::hasChildren(){
return !children.empty();
}
bool sceneNode::hasGeometry(){
return !geometry->checkEmptyPolygon();
}
gMatrix3 sceneNode::getTransfMatrixCalculated(){
//gMatrix3 calc = gMatrix3().translation2D(translateX, translateY)* gMatrix3().rotation2D(rotation)* gMatrix3().scale2D(scaleX, scaleY);
gMatrix3 calc = gMatrix3().translation2D(rotPointX, rotPointY)* gMatrix3().translation2D(translateX, translateY)* gMatrix3().rotation2D(rotation)*
gMatrix3().scale2D(scaleX, scaleY)*gMatrix3().translation2D(-rotPointX, -rotPointY) ;
//gMatrix3 calc = gMatrix3().rotation2D(rotation)* gMatrix3().scale2D(scaleX, scaleY) * gMatrix3().translation2D(translateX, translateY);
return calc;
}
void sceneNode::setTranslateX(float x){
translateX = x;
}
void sceneNode::setTranslateY(float y){
translateY = y;
}
void sceneNode::setRotation(float r){
rotation = r;
}
void sceneNode::setScaleX(float sx){
scaleX = sx;
}
void sceneNode::setScaleY(float sy){
scaleY = sy;
}
void sceneNode::setRotPointX(float rpx){
rotPointX = rpx;
}
void sceneNode::setRotPointY(float rpy){
rotPointY = rpy;
}
float sceneNode::getTranslateX(){
return translateX;
}
float sceneNode::getTranslateY(){
return translateY;
}
float sceneNode::getRotation(){
return rotation;
}
float sceneNode::getScaleX(){
return scaleX;
}
float sceneNode::getScaleY(){
return scaleY;
}
float sceneNode::getRotPointX(){
return rotPointX;
}
float sceneNode::getRotPointY(){
return rotPointY;
}
void sceneNode::addTranslateX(float x){
translateX = translateX + x;
}
void sceneNode::addTranslateY(float y){
translateY = translateY + y;
}
void sceneNode::addRotation(float r){
rotation = rotation +r;
}
void sceneNode::addScaleX(float sx){
scaleX = scaleX*sx;
}
void sceneNode::addScaleY(float sy){
scaleY = scaleY*sy;
}
void sceneNode::deleteNode(sceneNode* sn){
if(hasChildren() == true){
vector<sceneNode*> c = getChildren();
vector<sceneNode*>::iterator it;
vector<sceneNode*> ret;
for ( it=c.begin() ; it < c.end(); it++ ){
sceneNode* temp = *it;
if(sn==*it)
{
removeChild(sn);
vector<sceneNode*>::iterator it2;
for(it2 = c.begin(); it2< c.end(); it2++)
{
sceneNode* ugh = *it2;
if(ugh != sn){
ret.push_back(ugh);
}
}
setChildren(ret);
break;
}
else{
(temp)->deleteNode(sn);
}
}
}
}
void sceneNode::resetNode(){
geometry = new rPolygon();
translateX = 0;
translateY = 0;
scaleX = 1;
scaleY = 1;
rotation = 0;
transfM = gMatrix3().identity();
vector<sceneNode*> s;
children = s;
}
sceneNode* sceneNode::copy(){
rPolygon* g = geometry->copy();
gMatrix3 tm = transfM;
vector<sceneNode*> c;
vector<sceneNode*>::iterator it;
for(it = children.begin(); it< children.end(); it++)
{
sceneNode* ugh = (*it)->copy();
c.push_back(ugh);
}
sceneNode* cpy = new sceneNode(transfM, c, g);
cpy->setTranslateX(translateX);
cpy->setTranslateY(translateY);
cpy->setScaleX(scaleX);
cpy->setScaleY(scaleY);
cpy->setRotation(rotation);
cpy->name=name;
cpy->keyFrameCheck=keyFrameCheck;
return cpy;
}
void sceneNode::addAnotherChild(sceneNode* a){
children.push_back(a);
}
void sceneNode::setBlack(sceneNode* root){
if(root->hasGeometry() == true){
root->setColor(0,0,0);
}
if(root->hasChildren() == true){
vector<sceneNode*> c = root->getChildren();
vector<sceneNode*>::iterator it;
for ( it=c.begin() ; it < c.end(); it++ ){
sceneNode* temp = *it;
setBlack(temp);
}
}
} | true |
5b5fcad07e2d548757392b07f625123400aa1c32 | C++ | jl3937/leetcode | /SubstringWithConcatenationOfAllWords.cpp | UTF-8 | 1,165 | 2.609375 | 3 | [] | no_license | class Solution {
public:
vector<int> findSubstring(string S, vector<string>& L) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<int> r;
map<string, int> l;
int step = L[0].length();
int m = S.length();
int n = L.size() * step;
for (int i = 0; i < L.size(); i++) {
if (l.count(L[i]) == 0) {
l[L[i]] = 1;
} else {
l[L[i]]++;
}
}
for (int i = 0; i < step; i++) {
map<string, int> cur = l;
int start = i;
for (int j = i; j + step - 1 < m; j += step) {
if (start + n == j) {
string s = S.substr(start, step);
cur[s]++;
start += step;
}
string s = S.substr(j, step);
if (cur.count(s) && cur[s] > 0) {
cur[s]--;
if (start + n == j + step) {
r.push_back(start);
}
} else {
while (true) {
string s_head = S.substr(start, step);
start += step;
if (s_head == s) {
break;
}
cur[s_head]++;
}
}
}
}
return r;
}
};
| true |
63f99257f133fc5d9429e1f713a37b575a365bcd | C++ | Danter54/OP-20-21 | /Lab_7/Main/Main.cpp | UTF-8 | 567 | 2.703125 | 3 | [] | no_license | #include <iostream>
#include <stdio.h>
#include <math.h>
int main()
{
setlocale(LC_ALL, "ru");
short n = 0;
double x = 0, y = 0, h=0;
printf("| X | Y |\n");
printf("|------------|------------|\n");
for (n; n < 5;n++) {
x = 0;
for (x; x < 4;x+=0.25) {
if (x<1) {
y = sqrt(1-(x-1)*(x-1));
}
else y = (4-x) / 3;
printf("| %10.2lf | %10.7lf |", x+n*4, y);
h = y*10+1;
for (; h > 0; h-=0.8) printf(" ");
printf("*\n");
}
printf("Нажмите клавишу Enter...");
getchar();
}
return 0;
} | true |
77cbe42debb17ee5883424737ab9b8b5826ac677 | C++ | paukert/fit-ctu-bi-pa2 | /src/EGameStatus.h | UTF-8 | 816 | 3.234375 | 3 | [] | no_license | /**
* @author Lukas Paukert
* @date 03.05.2020
*/
#pragma once
#include <iostream>
/**
* Enum class that represents state of the current game
*/
enum class EGameStatus {
CREATING_CHARACTER = 0,
RUNNING,
END
};
/**
* @brief Prints EGameStatus to ostream
* @param[out] out ostream to which should be EGameStatus printed
* @param[in] self EGameStatus which is printed
* @return std::ostream& with printed EGameStatus
*/
std::ostream & operator<<(std::ostream & out, const EGameStatus & self);
/**
* @brief Loads EGameStatus from istream
* @param[in] in istream from which should be EGameStatus loaded
* @param[out] self EGameStatus to which is status loaded
* @return std::istream& with remaining stream
*/
std::istream & operator>>(std::istream & in, EGameStatus & self);
| true |
b821de8fe9bb8c9e7595c572be338eac2d2ecedc | C++ | anantgehi/Post-Graduate-Diploma-in-Advanced-Computing-CDAC | /OOPs with C++ Programming/CPP/9_RTTI_AdvancedTypeCasting/SlideExamples/const_cast.cpp | UTF-8 | 222 | 2.703125 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main()
{ const int a=10;
volatile int v = 20;
int *sp = const_cast<int*>(&a);
int *vp = const_cast<int*>(&v);
cout<<"\n"<<*sp;
cout<<"\n"<<vp;
return 0;
}
| true |
ad5dce47f455b1fe6317e0c24920f5e5afb825ee | C++ | palomacalado/estrutura_de_dados | /team.cpp | UTF-8 | 2,462 | 3.234375 | 3 | [] | no_license | #include <iostream>
using namespace std;
class Queue{
private:
int rear;
int arr[1000001];
public:
int front;
int numTeams=1000001;
Queue(){
front = -1;
rear = -1;
for(int i=0;i<numTeams;i++){
arr[i]=0;
}
}
bool isEmpty(){
if(front ==-1 && rear ==-1)
return true;
else
return false;
}
bool isFull(){
if(rear == numTeams-1)
return true;
else
return false;
}
void enqueue(int val){
if(isFull()){
cout << "Fila Cheia"<< endl;
return;
} else if(isEmpty()){
rear=0;
front =0;
arr[rear] = val;
} else{
rear++;
arr[rear]= val;
}
}
int dequeue(){
int x;
if(isEmpty()){
cout << "Fila vazia"<< endl;
return 0;
} else if( front == rear){
x=arr[front];
arr[front]=0;
rear = -1;
front = -1;
return x;
}else{
x=arr[front];
arr[front] =0;
front++;
return x;
}
}
int count(){
if(rear==-1 && front==-1)
return 0;
else
return rear-front+1;
}
};
int teamBelongTo[1000001];
int main()
{
int T = 1;
int numTeams;
Queue teamQueue[1001];
while (cin >> numTeams, numTeams)
{
for (int t = 0; t < numTeams; ++t)
{
while (!teamQueue[t].isEmpty())
teamQueue[t].dequeue();
int numElem;
cin >> numElem;
while (numElem--)
{
int elem;
cin >> elem;
teamBelongTo[elem] = t;
}
}
Queue combinedQueue;
cout << "Scenario #" << T++ << '\n';
string command;
while (cin >> command, command[0] != 'S')
{
if (command[0] == 'E')
{
int num;
cin >> num;
int team = teamBelongTo[num];
if (teamQueue[team].isEmpty())
{
combinedQueue.enqueue(team);
}
teamQueue[team].enqueue(num);
}
else
{
int team = combinedQueue.front;
cout << teamQueue[team].front << '\n';
teamQueue[team].dequeue();
if (teamQueue[team].isEmpty())
combinedQueue.dequeue();
}
}
cout << '\n';
}
}
| true |
54f6f5d8fd1fb8b3977495e972e6f0c964264b61 | C++ | mcreaded/csci1113 | /volpy001/FightSimulator/Warhammer.cpp | UTF-8 | 6,997 | 3.390625 | 3 | [] | no_license | #include <iostream>
#include <iomanip>
#include <cmath>
#include <initializer_list>
#include <ctime>
#include "FightSimulator.hpp"
using namespace std;
/*
Current Version:
Steps:
1.) Roll off to see who goes first.
2.) The x1 that goes first moves, shoots, and charges.
3.) If x1 charges, x2 gets to Overwatch
4.) If Overwatch doesn't kill x1, then x1 gets Hammer of Wrath (if applicable)
5.) Then they fight based on personal Stats until one of them has 0 Wounds left
*/
void numRollResults();
int rollResults[];
void foo();
int main()
{
srand(time(nullptr));
foo();
return 0;
}
void foo()
{
Zarakynel z1;
Anggrath a1;
Base *bases[] = {&z1, &a1};
for (auto b : bases)
{
b->nonVirtualFunction();
}
for (auto b : bases)
{
b->virtualFunction();
}
return;
for (auto b : bases) //What does the auto b: bases do?
{
cout << b->getBallisticSkill() << endl;
}
z1.setBallisticSkill(10); //What does this do if we've already got it hard coded? Does this change it?
for (auto b : bases)
{
cout << b->getBallisticSkill() << endl;
}
}
/*
void firstMove(const base &x1, const base &x2)
{
if (rollOff(x1, x2) == true) war(x1, x2);
else
{
war(x2,x1); //switch the
}
}
void war(const base &x1, const base &x2)
{
if (x1 != combat) // Need a new bool to check if in combat or not.
{
move() // need to make a function to move them. This isn't super important now as current iteration of the FightSimulator is just what's outlined above.
cout << "Number of Shooting hits: " << toHitRangedCount() << endl; //just for testing.
toWound(x1, x2);
save(x2); //how to get Wounds to return here to check?
if (x2.Wounds() == 0) return; //need Wounds to be a & or * so that changes in save() will change it here.
}
if (charge() == true)
{
//Overwatch
//Hammer of Wrath
//check initiative of x1 vs. x2. the one with > Initiative goes first
cout << "Number of Combat hits by " << x1 << " : " << toHitCombatCount() << endl;
toWound(x1, x2); //definitely need to rename x1 and x2 as it gets confusing. x1 is the one that is doing the action. x2 is the one that gets the action done to it.
save(x2);
if (x2.Wounds() == 0) return;
auto temp = x2; //not sure what the type is since we need to switch x1 and x2 for this section
x1 = x2;
x2 = temp;
cout << "Number of Combat hits by " << x1 << " : " << toHitCombatCount() << endl;
toWound(x1, x2); //definitely need to rename x1 and x2 as it gets confusing. x1 is the one that is doing the action. x2 is the one that gets the action done to it.
save(x2);
if (x2.Wounds() == 0) return;
while (true) //is it better to do: x1.Wounds() != 0 || x2.Wouds() != 0
{
//check initiative of x1 vs. x2. the one with > Initiative goes first
cout << "Number of Combat hits by " << x1 << " : " << toHitCombatCount() << endl;
toWound(x1, x2); //definitely need to rename x1 and x2 as it gets confusing. x1 is the one that is doing the action. x2 is the one that gets the action done to it.
save(x2);
if (x2.Wounds() == 0) return;
auto temp = x2; //not sure what the type is since we need to switch x1 and x2 for this section
x1 = x2;
x2 = temp;
cout << "Number of Combat hits by " << x1 << " : " << toHitCombatCount() << endl;
toWound(x1, x2); //definitely need to rename x1 and x2 as it gets confusing. x1 is the one that is doing the action. x2 is the one that gets the action done to it.
save(x2);
if (x2.Wounds() == 0) return;
}
}
}
void zarakynel(//bunch of &'s to her abilities and weapons) //There must be a better way but I want to be able to do all of her character specific things in her class/functions
{
Gargantuan() // create a class called Gargantuan that has certain rules that can be overwritten by user specific rules but are otherwise all used.
CCWeapon::souleaterSword() //every CCWeapon has an int Str, int AP, and string type. The number of times it's used is x1.getAttacks();
{
Str = getStrength();
AP = 1;
instantDeath(); //make a function that does Instant Death
specialistWeapon(); //don't need it now but need to make a function Specialist Weapon;
if (x2.Wounds(Final) < x2.Wounds(Initial)) //need a way to check if other person's Wounds went down.
{
if (rollD6() > 1 && x1.Wounds() < 10) ++x1.Wounds();
}
}
RWeapon::deathlyRapture() //every RWeapon has a int Range, int Str, int AP, int numShots,
{
Range = 36;
Str = 6;
AP = 3;
numShots = diceRoll();
Pinning (); // doesn't matter for this one but create a Pinning function.
}
reRollToHitCombat(); //create a function that allows to re-roll To Hits in combat
reRollToWound(); //create a function that allows to re-roll To Wounds
assaultGrenades(); // create a function that does assault grenades
if (charge == true) //same charge from void war()
{
x1.Attacks() += rollD3(); //make this a temporary change.
}
if (x2 != "fearless") //need a way to search in x2 if they are fearless or not. No idea how to do that
{
if (x2.passLeadership() == false) //
{
//x2 cannot attack
}
}
demonOfSlaanesh(); // make a class Demon of Slaanesh that contains Demon(), Fleet(), Hatred(demonsOfKhorne), Rending, Run an additional 3",
}
void anggrath(//bunch of &'s to her abilities and weapons)
{
FlyingGargantuan() // create a class called FlyingGargantuan that has certain rules that can be overwritten by user specific rules but are otherwise all used.
CCWeapon::axeOfKhorne()
{
Str = x1.getStrength();
AP = 2;
void decapitatingBlow()
{
if ([//need a way to get ToWound's rollD6 but I don't really want to store it] == 6)
{
insatntDeath();
}
}
specialistWeapon();
}
RWeapon::bloodlashOfKhorne()
{
Range = 12;
Str = 7;
AP = 3;
numShots = 2;
}
bloodFrenzy(); //doesn't matter here
assaultGrenades(); // create a function that does assault grenades
if (charge == true) //same charge from void war()
{
x1.Attacks() += rollD6(); //make this a temporary change.
}
demonOfKhorne(); // create a class DemonofKhorne that contains Demon(), FuriousCharge(), Hatred(demonsOfSlaanesh)
}
*/
| true |
0e999b157aea706a34f7398e9605ae0a31118f58 | C++ | 1kzpro/international | /Vladimir/COMP 2710/project3_Eganov_vze0008.cpp | UTF-8 | 4,271 | 3.3125 | 3 | [] | no_license | //============================================================================
// Name : project3_Eganov_vze0008.cpp
// Author : Eganov Vladimir
// Version : Summer 2020
// Copyright : Auburn University
// Description : COMP2710 Software Construction Project 3
// Compile : g++ project2_Eganov_vze0008.cpp -o project3_Eganov_vze0008.cpp.out
// Run : ./project3_Eganov_vze0008.out
//============================================================================
//Sample code for Project 3
#include <fstream>
#include <iostream>
#include <vector>
using namespace std;
//int readfile( int inputArray[], ifstream& instream);
void write_file(string, vector <int>); // writes data in file
vector <int> merge( vector<int>, vector<int>); // returns vector of sorted data
bool check_file(string); // checks file for readability
vector<int> read_file(string); // reads data into vector
bool check_file(string file) {
/* Input file stream. (ifstream) */
ifstream stream;
/* Check whether file exists. */
stream.open(file.c_str());
if (stream.fail()) {
cout<<"error occured while opening file ";//print that error occured
return false;
}
stream.close();
return true;
}
vector<int> read_file(string file) {
/* Input file stream. (ifstream) */
ifstream stream;
/* Vector containing numbers from file. (vector<int>) */
vector <int> v;
/* Integer read from file. (int) */
int i;
/* Add each number in the file to a vector. */
stream.open(file);
stream >> i;
while (!stream.eof()) {
v.push_back(i);
stream >> i;
}
return v;
}
void write_file(string file, vector<int> v) {
/* Output file stream. (ofstream) */
ofstream stream;
stream.open(file);
for(int i; i < v.size();i++){
stream << v[i]<<"\n";
}
}
vector<int> merge(vector<int> v1, vector<int> v2 ) {
/* Compare both vectors. */
vector<int> v3;
int i1, i2;
i1=0;
i2=0;
while( (i1 < v1.size()) && (i2 < v2.size()) ) {
if (v1[i1] > v2[i2]) {
v3.push_back(v2[i2]);
i2++;
} else
{
v3.push_back(v1[i1]);
i1++;
}
}
/* Add any remaining numbers from vector one. */
if (i1 < v1.size()) {
for(;i1 < v1.size();i1++ ){
v3.push_back(v1[i1]);
}
}
/* Add any remaining numbers from vector two. */
if (i2 < v2.size()) {
for(;i2 < v2.size();i1++ ){
v3.push_back(v2[i2]);
}
}
return v3;
}
int main(){
ifstream inStream1;
ifstream inStream2;
vector <int> iArray1;
int iArray1_size;
vector <int> iArray2;
int iArray2_size;
vector <int> output;
string file1;
string file2;
string file3;
cout<<"*** Welcome to Eganov's sorting program ***\n";
do {
cout<<"Enter the first input file name: ";
cin>>file1;
/* user friendly interfaces */
} while (cin.fail() || !check_file(file1));
cout<<"list of numbers in the file\n";
inStream1.open(file1);
iArray1 = read_file(file1);
inStream1.close();
for(int i = 0;i < iArray1.size();i++ ){
cout<<iArray1[i]<<"\n";
}
do {
cout<<"Enter the second input file name: ";
cin>>file2;
/* user friendly interfaces */
} while (cin.fail() || !check_file(file2));
inStream2.open( file2);
iArray2 = read_file(file2);
cout<<"list of numbers in the file\n";
for(int i = 0;i < iArray2.size();i++ ){
cout<<iArray2[i]<<"\n";
}
inStream2.close();
output = merge(iArray1,iArray2);
//cout<<"processing\n";
cout<<"The sorted list of numbers is:";
for(int i = 0;i < output.size();i++ ){
cout<<output[i]<<" ";
}
/* Get name of output file. */
do {
cout<<"\ntype in output file ";
cin>>file3;
//to_string(file3,output);
//cout<<output;
/* user friendly interfaces */
} while (cin.fail());
//cout<<"processing\n";
/* Write combined vector to output file. */
write_file(file3, output);
cout<<"\n*** Please check the new file - "<<file3<< "***\n*** Goodbye. ***";
//write_file(out, output);
return 0;
}
| true |
e4ec79055ec4b144637f11b1f3ba92a4658ee136 | C++ | yrrSelena/Computer-BasicKnowledge | /华为机试/字符串最后一个单词的长度.cpp | UTF-8 | 588 | 3.734375 | 4 | [] | no_license | /*
题目:
计算字符串最后一个单词的长度,单词以空格隔开。
输入描述:
一行字符串,非空,长度小于5000。
输出描述:
整数N,最后一个单词的长度。
示例1
输入
hello world
输出
5
思路:(题目非常简单)
利用cin以空格为间隔读取字符串的特点,循环读取字符串,直至最后一个字符串,输出单词长度。
*/
#include<iostream>
#include<string>
using namespace std;
int main(){
string s;
int len;
while(cin>>s){
len = s.size();
}
cout<<len<<endl;
return 0;
}
| true |
c06c610e4c48b98c0cf96659c03f0078f8ec39f7 | C++ | AadityaJ/Algorithms-Practice | /DS/hashing/printPair.cpp | UTF-8 | 468 | 3.046875 | 3 | [] | no_license | #include <stdio.h>
#include <map>
using namespace std;
bool isPair(int *arr,int n,int sum){
map<int,bool> m;
bool flag=0;
for(int i=0;i<n;i++){
if(m[sum-arr[i]]!=0){
printf("%d %d\n",arr[i],sum-arr[i]);
flag=1;
}
else{m[arr[i]]=1;}
}
return flag;
}
int main(int argc, char const *argv[]) {
int arr[]={1,2,3,4,5};
int n=6;
int sum=9;
printf("%d\n",isPair(arr,n,sum));
return 0;
}
| true |
e74605fbdc3d063918bd7f0517e5eaf24ba8f3f4 | C++ | LawyerMorty97/aicore | /src/steerpipe.cpp | UTF-8 | 7,030 | 2.546875 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | /*
* Defines the pipeline steering system.
*
* Part of the Artificial Intelligence for Games system.
*
* Copyright (c) Ian Millington 2003-2006. All Rights Reserved.
*
* This software is distributed under licence. Use of this software
* implies agreement with all terms and conditions of the accompanying
* software licence.
*/
#include <stdlib.h>
#include <stdio.h>
#include "../include/aicore/aicore.h"
#include <cassert>
namespace aicore
{
Goal::Goal()
{
clear();
}
void Goal::clear()
{
positionSet = orientationSet = velocitySet = rotationSet = false;
}
void Goal::updateGoal(const Goal& goal)
{
// Make sure we can merge
assert(canMergeGoals(goal));
if (goal.positionSet)
{
position = goal.position;
positionSet = true;
}
if (goal.orientationSet)
{
orientation = goal.orientation;
orientationSet = true;
}
if (goal.velocitySet)
{
velocity = goal.velocity;
velocitySet = true;
}
if (goal.rotationSet)
{
rotation = goal.rotation;
rotationSet = true;
}
}
bool Goal::canMergeGoals(const Goal& goal) const
{
return !(
positionSet && goal.positionSet ||
orientationSet && goal.orientationSet ||
velocitySet && goal.velocitySet ||
rotationSet && goal.rotationSet
);
}
real Path::getMaxPriority()
{
return (character->position - goal.position).magnitude();
}
SteeringPipe::SteeringPipe()
:
fallback(0),
constraintSteps(100),
path(0)
{
}
SteeringPipe::~SteeringPipe()
{
if (path) delete path;
}
void SteeringPipe::setActuator(aicore::Actuator *a)
{
actuator = a;
if (path) delete path;
path = 0;
}
void SteeringPipe::getSteering(SteeringOutput* output)
{
Goal goal;
std::list<Targeter*>::iterator ti;
for (ti = targeters.begin(); ti != targeters.end(); ti++)
{
Goal targeterResult = (*ti)->getGoal();
if (goal.canMergeGoals(targeterResult))
{
goal.updateGoal(targeterResult);
}
}
std::list<Decomposer*>::iterator di;
for (di = decomposers.begin(); di != decomposers.end(); di++)
{
goal = (*di)->decomposeGoal(goal);
}
// Create an ampty path object of the correct type.
if (!path) path = actuator->createPathObject();
std::list<Constraint*>::iterator ci;
real shortestViolation, currentViolation, maxViolation;
Constraint *violatingConstraint;
for (unsigned i = 0; i < constraintSteps; i++)
{
// Find the path to this goal
actuator->getPath(path, goal);
// Find the constraint that is violated first
maxViolation = shortestViolation = path->getMaxPriority();
for (ci = constraints.begin(); ci != constraints.end(); ci++)
{
// Clear the flags that indicate the constraints used
if (i == 0) (*ci)->suggestionUsed = false;
// Check to see if this constraint is violated early than any other.
currentViolation = (*ci)->willViolate(path, shortestViolation);
if (currentViolation > 0 && currentViolation < shortestViolation)
{
shortestViolation = currentViolation;
violatingConstraint = *ci;
}
}
// Check if we found a violation
if (shortestViolation < maxViolation)
{
// Update the goal and check constraints again.
goal = violatingConstraint->suggest(path);
violatingConstraint->suggestionUsed = true;
}
else
{
// We've found a solution - use it and return
actuator->getSteering(output, path);
return;
}
}
// We've run out of constraint iterations, so use the fallback
if (fallback) fallback->getSteering(output);
}
void SteeringPipe::registerComponents()
{
std::list<Targeter*>::iterator ti;
for (ti = targeters.begin(); ti != targeters.end(); ti++)
{
(*ti)->pipe = this;
}
std::list<Decomposer*>::iterator di;
for (di = decomposers.begin(); di != decomposers.end(); di++)
{
(*di)->pipe = this;
}
std::list<Constraint*>::iterator ci;
for (ci = constraints.begin(); ci != constraints.end(); ci++)
{
(*ci)->pipe = this;
}
actuator->pipe = this;
}
// --------------------------------------------------------------------------
// Basic implementations
Goal FixedGoalTargeter::getGoal()
{
return goal;
}
real AvoidSpheresConstraint::willViolate(const Path* path, real maxPriority)
{
real priority = REAL_MAX;
real thisPriority;
std::list<Sphere*>::iterator soi;
for (soi = obstacles.begin(); soi != obstacles.end(); soi++)
{
thisPriority = willViolate(path, priority, *(*soi));
if (thisPriority < priority) priority = thisPriority;
}
return priority;
}
real AvoidSpheresConstraint::willViolate(
const Path* path,
real maxPriority,
Sphere &obstacle
)
{
// Make sure we've got a positional goal
if (!path->goal.positionSet) return REAL_MAX;
// Alias the character object
const Kinematic *character = pipe->character;
// Work out where we're going
Vector3 direction = path->goal.position - character->position;
// Make sure we're moving
if (direction.squareMagnitude() > 0)
{
// Find the distance from the line we're moving along to the obstacle.
Vector3 movementNormal = direction.unit();
Vector3 characterToObstacle = obstacle.position - character->position;
real distanceSquared = characterToObstacle * movementNormal;
distanceSquared = characterToObstacle.squareMagnitude() -
distanceSquared*distanceSquared;
// Check for collision
real radius = obstacle.radius + avoidMargin;
if (distanceSquared < radius*radius)
{
// Find how far along our movement vector the closest pass is
real distanceToClosest = characterToObstacle * movementNormal;
// Make sure this isn't behind us and is closer than our lookahead.
if (distanceToClosest > 0 && distanceToClosest < maxPriority)
{
// Find the closest point
Vector3 closestPoint =
character->position + movementNormal*distanceToClosest;
// Find the point of avoidance
suggestion.position =
obstacle.position +
(closestPoint - obstacle.position).unit() *
(obstacle.radius + avoidMargin);
suggestion.positionSet = true;
return distanceToClosest;
}
}
}
return REAL_MAX;
}
Goal AvoidSpheresConstraint::suggest(const Path* path)
{
return suggestion;
}
Path* BasicActuator::createPathObject()
{
return new Path;
}
void BasicActuator::getPath(Path* path, const Goal& goal)
{
path->character = pipe->character;
path->goal = goal;
}
void BasicActuator::getSteering(SteeringOutput* output, const Path* path)
{
if (path->goal.positionSet)
{
seek.character = pipe->character;
seek.target = &path->goal.position;
seek.maxAcceleration = maxAcceleration;
seek.getSteering(output);
}
else
{
output->clear();
}
}
} // end of namespace
| true |
04ad4a6bc308fdee0438a7088a2dd4bc3cb8b157 | C++ | thirdeye18/CS161 | /Module 5/Box/testingBox.cpp | UTF-8 | 643 | 2.796875 | 3 | [] | no_license | /*********************************************************************
** Author: Justin Hammel
** Date: 2/5/2017
** Description: Main function for testing other files
*********************************************************************/
#include <iostream>
#include "Box.hpp"
int main ()
{
Box box1(5.0, 5.0, 5.0);
Box box2;
double volume1 = box1.getVolume();
std::cout << volume1 << "\n";
double surfaceArea1 = box1.getSurfaceArea();
std::cout << surfaceArea1 << "\n";
double volume2 = box2.getVolume();
std::cout << volume2 << "\n";
double surfaceArea2 = box2.getSurfaceArea();
std::cout << surfaceArea2 << "\n";
return 0;
}
| true |
db88b1c85eef0dbc62ce6020a73718b5c3316060 | C++ | thirtythreeforty/mipssion-impossible | /tests/test_mem.cpp | UTF-8 | 1,307 | 2.734375 | 3 | [] | no_license | #include <gtest/gtest.h>
#include "datapath/MEM.h"
#include "instructions.h"
#include "controller.h"
#include "datapath/register_file.h"
#include "program_memory.h"
//Load word from memory into register
TEST(MEM, lw)
{
//MemRead always 1
Memory mem;
EXMEM exmem;
MEMWB memwb;
MEM memoryblock;
MEMControls memcontrols;
//Hardcode register value to read back
mem.set(0x0002, 0x1234);
exmem.mem_controls.mem_write = 0;
exmem.alu_output = 0x0002;
memoryblock.signals_in(exmem);
memoryblock.tick(mem);
memoryblock.tock(mem);
ASSERT_EQ(0x1234, memoryblock.signals_out().memory_data);
}
TEST(MEM, move_to_buffer)
{
Memory mem;
EXMEM exmem;
MEMWB memwb;
MEM memoryblock;
exmem.alu_output = 0x0002;
exmem.mem_controls.mem_write = false;
memoryblock.signals_in(exmem);
memoryblock.tick(mem);
memoryblock.tock(mem);
EXPECT_EQ(exmem.alu_output, memoryblock.signals_out().alu_output);
}
//Load word from register into memory
//Writes WriteData to the address specified
TEST(MEM, sw)
{
//ReadData always 1
Memory mem;
EXMEM exmem;
MEMWB memwb;
MEM memoryblock;
exmem.mem_controls.mem_write = 1;
exmem.alu_output = 0x0002;
exmem.write_data = 0x1234;
memoryblock.signals_in(exmem);
memoryblock.tick(mem);
memoryblock.tock(mem);
EXPECT_EQ(0x1234, mem.get(0x0002));
} | true |
b78ce8481b5631c97c70fcc8731ebac6800910b2 | C++ | mandeep168/dsa_prep | /linked_list/deletion.cpp | UTF-8 | 951 | 3.515625 | 4 | [] | no_license | // #include<iostream>
// using namespace std;
//
// template<typename T>
// class Node{
// T data;
// Node<T> *next;
// public:
// Node(T data){
// this->data = data;
// next = nullptr;
// }
// }
// struct Node{
// int data;
// Node* next;
// Node(int d){
// data = d;
// next = nullptr;
// }
// };
// void deletionAtBegin(Node** head){
// if((*head)==nullptr) return;
// Node* node = (*head);
// (*head) = (*head)->next;
// free(node);
// }
// void deletionAtLast(Node** head){
// if((*head)==nullptr) return;
// Node* node = (*head);
// if(node->next==nullptr) {
// (*head) = nullptr;
// free(node);
// }
// }
// void forward_traversal(Node *head){
// while(head!=nullptr){
// cout<<head->data<<" ";
// head=head->next;
// }
// cout<<"\n";
// }
// int main(){
// Node* head = new Node(10);
// head->next = new Node(15);
// deletionAtBegin(&head);
// forward_traversal(head);
// } | true |
fb818e0e83261bd73c79ec758ccea35ef0373aa6 | C++ | Limitless-Rasul-Power/Dictionary | /Class Task 8/Pair.cpp | UTF-8 | 1,119 | 3.5625 | 4 | [
"MIT"
] | permissive | #include <iostream>
#include <assert.h>
#include "Pair.h"
Pair::Pair():key(""), value("")
{}
Pair::Pair(const Pair& other)
{
Set_key(other.key);
Set_value(other.value);
}
Pair& Pair::operator = (const Pair& other)
{
Set_key(other.key);
Set_value(other.value);
return *this;
}
Pair& Pair::operator = (const std::string& value)
{
Set_value(value);
return *this;
}
inline Pair::Pair(const std::string& key)
{
Set_key(key);
}
Pair::Pair(const std::string& key, const std::string& value)
:Pair(key)
{
Set_value(value);
}
void Pair::Set_key(const std::string& key)
{
assert(key.empty() == false && "Key is Empty!");
this->key = key;
}
std::string Pair::Get_key() const
{
return key;
}
void Pair::Set_value(const std::string& value)
{
assert(value.empty() == false && "Value is Empty!");
this->value = value;
}
std::string Pair::Get_value() const
{
return value;
}
std::ostream& operator << (std::ostream& out, const Pair& pair)
{
out << "English: " << pair.key << '\n';
out << "Azerbaijani: " << pair.value << "\n\n";
return out;
} | true |
ec343da360a7027e12fbabd7d045bbec101b516b | C++ | Sorrow321/prac_4_sem | /cpp/mz01/5.cpp | UTF-8 | 2,097 | 3.453125 | 3 | [] | no_license | #include <iostream>
#include <stdio.h>
#include <iomanip>
#include <string>
class Rational
{
private:
int a, b;
public:
Rational(int p, int q = 1) : a{p}, b{q}
{
normalize();
}
Rational() : a{0}, b{1}
{
}
Rational& operator =(const Rational& p)
{
this->a = p.a;
this->b = p.b;
return *this;
}
void normalize()
{
int c = gcd(a, b);
a /= c;
b /= c;
if (b < 0) {
b *= -1;
a *= -1;
}
}
int gcd(int m, int n)
{
if (!n) {
return m;
}else{
return gcd(n, m % n);
}
}
long long gcd(long long m, long long n)
{
if (!n) {
return m;
}else{
return gcd(n, m % n);
}
}
Rational& Add(const Rational& q)
{
long long lo = a * q.b + b * q.a;
long long lu = b * q.b;
long long gc = gcd(lo, lu);
lo /= gc;
lu /= gc;
a = lo;
b = lu;
normalize();
return *this;
}
Rational& Substract(const Rational& q)
{
return Add(Rational(-q.a, q.b));
}
Rational& Multiply(const Rational& q)
{
long long lo = a * q.a;
long long lu = b * q.b;
long long gc = gcd(lo, lu);
lo /= gc;
lu /= gc;
a = lo;
b = lu;
normalize();
return *this;
}
Rational& Divide(const Rational& q)
{
if(q.a > 0) {
return Multiply(Rational(q.b, q.a));
}else{
return Multiply(Rational(-q.b, -q.a));
}
}
bool IsInteger() const
{
return (b == 1)? true : false;
}
bool EqualTo(const Rational& q) const
{
return (a * q.b == b * q.a)? true : false;
}
int CompareTo(const Rational& q)
{
return a * q.b - b * q.a;
}
std::string ToString() const
{
return std::to_string(a) + ":" + std::to_string(b);
}
};
| true |
4e54f46d7e19afc657ec4bb6d8f52519775e1b05 | C++ | techmatt/layer-extraction | /LocallyLinearEmbedding/BaseCodeDLL/BaseCodeDLL.cpp | UTF-8 | 5,121 | 2.6875 | 3 | [] | no_license | #include "Main.h"
BASECODEDLL_API void* __stdcall BCInit()
{
App *app = new App;
AllocConsole();
#ifdef _DEBUG
Console::WriteLine("DLL compiled in debug mode");
#else
Console::WriteLine("DLL compiled in release mode");
#endif
app->Init();
return app;
}
BASECODEDLL_API UINT32 __stdcall BCProcessCommand(void *context, const char *s)
{
if(context == NULL) return 1;
App &app = *(App*)context;
UINT32 result = app.ProcessCommand(String(s));
return result;
}
BASECODEDLL_API const char* __stdcall BCQueryStringByName(void *context, const char *s)
{
if(context == NULL) return NULL;
App &app = *(App*)context;
return app.QueryStringByName(s);
}
BASECODEDLL_API int __stdcall BCQueryIntegerByName(void *context, const char *s)
{
if(context == NULL) return 0;
App &app = *(App*)context;
return app.QueryIntegerByName(s);
}
BASECODEDLL_API BCBitmapInfo* __stdcall BCQueryBitmapByName(void *context, const char *s)
{
if(context == NULL) return 0;
App &app = *(App*)context;
return app.QueryBitmapByName(s);
}
BASECODEDLL_API BCLayers* __stdcall BCExtractLayers(void *context, BCBitmapInfo bitmap, const double* palette, int paletteSize, const char *constraints, const bool autoCorrect, const char* imageFile)
{
if (context == NULL) return 0;
App *app = (App*) context;
Vector<Vec3f> p;
int numColors = paletteSize;
double* data = (double*)palette;
for (int i=0; i<numColors; i++)
p.PushEnd(Vec3f((float)data[3*i], (float)data[3*i+1], (float)data[3*i+2]));
return app->ExtractLayers(bitmap, p, constraints, autoCorrect, imageFile);
}
BASECODEDLL_API BCBitmapInfo* __stdcall BCSegmentImage(void* context, BCBitmapInfo bitmap)
{
if (context == NULL) return 0;
App *app = (App*) context;
return app->SegmentImage(bitmap);
}
BASECODEDLL_API BCLayers* __stdcall BCSynthesizeLayers(void* context)
{
if (context == NULL) return 0;
App *app = (App*) context;
return app->SynthesizeLayers();
}
BASECODEDLL_API void BCOutputMesh(void* context, BCBitmapInfo bitmap, const double* palette, int paletteSize, const char* filename)
{
if (context == NULL) return;
App *app = (App*)context;
Vector<Vec3f> p;
int numColors = paletteSize;
double* data = (double*)palette;
for (int i=0; i<numColors; i++)
p.PushEnd(Vec3f((float)data[3*i], (float)data[3*i+1], (float)data[3*i+2]));
app->OutputMesh(bitmap, p, filename);
}
BASECODEDLL_API void BCGetWords(void* context, const char* filename)
{
if (context == NULL) return;
App *app = (App*)context;
app->GetWords(filename);
}
BASECODEDLL_API void BCLoadVideo(void* context, const char* filename, int paletteSize)
{
if (context == NULL) return;
App *app = (App*) context;
app->LoadVideo(filename, paletteSize);
}
BASECODEDLL_API int BCGetVideoPaletteSize(void* context)
{
if (context == NULL) return 0;
App *app = (App*) context;
return app->GetVideoPaletteSize();
}
BASECODEDLL_API byte BCGetVideoPalette(void* context, int paletteindex, int index)
{
if (context == NULL) return 0;
App *app = (App*) context;
return app->GetVideoPalette(paletteindex, index);
}
BASECODEDLL_API void BCSetVideoPalette(void* context, int paletteindex, byte r, byte g, byte b)
{
if (context == NULL) return;
App *app = (App*) context;
app->SetVideoPalette(paletteindex, r, g, b);
}
BASECODEDLL_API byte BCGetOriginalVideoPalette(void* context, int paletteindex, int index)
{
if (context == NULL) return 0;
App *app = (App*) context;
return app->GetOriginalVideoPalette(paletteindex, index);
}
BASECODEDLL_API void BCSaveVideoFrames(void* context)
{
if (context == NULL) return;
App *app = (App*) context;
app->SaveVideoFrames();
}
BASECODEDLL_API void BCSetVideoPreviewLayerIndex( void* context, int index )
{
if (context == NULL) return;
App *app = (App*) context;
app->SetVideoPreviewLayerIndex(index);
}
BASECODEDLL_API void BCSaveVideoPaletteImage(void* context)
{
if (context == NULL) return;
App *app = (App*) context;
app->saveVideoPaletteImage();
}
BASECODEDLL_API int __stdcall BCGetVideoHeight(void *context)
{
if(context == NULL) return 0;
App &app = *(App*)context;
return app.GetVideoHeight();
}
BASECODEDLL_API int __stdcall BCGetVideoWidth(void *context)
{
if(context == NULL) return 0;
App &app = *(App*)context;
return app.GetVideoWidth();
}
BASECODEDLL_API int __stdcall BCLoadSuggestedRecolorings(void *context)
{
if(context == NULL) return 0;
App &app = *(App*)context;
return app.LoadSuggestions();
}
BASECODEDLL_API void __stdcall BCLoadSuggestion(void *context, int index)
{
if (context == NULL) return;
App *app = (App*) context;
app->LoadSuggestion(index);
}
BASECODEDLL_API byte __stdcall BCGetSuggestPalette(void *context, int index, int paletteindex, int channel)
{
if (context == NULL) return 0;
App *app = (App*) context;
return app->GetSuggestPalette(index, paletteindex, channel);
} | true |
9c3f0b2e30e14e615befe6f3bd4065917dfc7140 | C++ | JINKOO/BJ_Algorithm_Code | /Greedy/Greedy/problem_2875.cpp | UHC | 1,785 | 3.734375 | 4 | [] | no_license | /*
#. [ ȸ or ]
#.
شб ȸ 2 л 1 л Ἲؼ Ģ̴.
( Բ ڴ.)
شб پ ؿ N л M л ã ִ.
ȸ Ϸ л K ݵ Ͻ α ؾ Ѵ.
Ͻ ϴ л ȸ Ѵ.
شб پ , ̴ּ.
л N, л M, Ͻ ؾϴ ο K ־
ִ ִ ϸ ȴ.
#. Է
ù° ٿ N, M, K ־. (0 M 100, 0 N 100, 0 K M+N),
#.
ִ ִ ϸ ȴ.
#. Է 1
6 3 2
#. 1
2
*/
#include <iostream>
using namespace std;
int solution(int n, int m, int k)
{
int answer = 0;
//
//remain 2 1 ¥ ̴.
int remain = n + m - k;
//л 2, л 1 ٿ.
// л remain 3̸ ̻ .
while (n >= 2 && m >= 1 && remain >= 3)
{
n = n - 2;
m = m - 1;
remain = remain - 3;
answer++;
}
//
return answer;
}
int main()
{
int n, m, k;
cin >> n >> m >> k;
cout << solution(n, m, k) << "\n";
return 0;
}
| true |
4826d0f97e6e207080f52a15f7ce8e812a92cbad | C++ | oplugin/ITMO.CPP | /Lab1.ControlTask.1/Lab1.ControlTask.1.cpp | UTF-8 | 1,393 | 3.453125 | 3 | [] | no_license | // Lab1.ControlTask.1.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int sqrGauss(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4, int x5, int y5);
int main()
{
system("chcp 1251");
int x1, y1;
int x2, y2;
int x3, y3;
int x4, y4;
int x5, y5;
int A; // площать пятиугольника
cout << "Введите координаты вершин x1, y1,\n";
cin >> x1;
cin >> y1;
cout << "Введите координаты вершин x2, y2,\n";
cin >> x2;
cin >> y2;
cout << "Введите координаты вершин x3, y3,\n";
cin >> x3;
cin >> y3;
cout << "Введите координаты вершин x4, y4,\n";
cin >> x4;
cin >> y4;
cout << "Введите координаты вершин x5, y5,\n";
cin >> x5;
cin >> y5;
sqrGauss(x1, y1, x2, y2, x3, y3, x4, y4, x5, y5);
}
int sqrGauss(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4, int x5, int y5)
{
int A = (x1 * y2 + x2 * y3 + x3 * y4 + x4 * y5 + x5 * y1 - x2 * y1 - x3 * y2 - x4 * y3 - x5 * y4 - x1 * y5) / 2;
if (A < 0)
A = A * -1;
cout << "Площадь многоуольника равна : " << A;
return A;
}
| true |
bbc4d0015f0b6df86137b036ff9bd0f28fc7aa8f | C++ | rathoresrikant/competitive-programming-solutions | /Others/quick_sort.cpp | UTF-8 | 612 | 3.34375 | 3 | [] | no_license | #include<iostream>
using namespace std;
void swap(int &a, int &b){
int c = a;
a = b;
b = c;
}
int partition(int l, int r, int a[]){
int pivot = a[(l+r)/2],i=l,j=r;
while(i<j){
while(i!=r&&a[i]<=pivot){
i++;
}
while(j!=l&&(j==(l+r)/2||a[j]>pivot)){
j--;
}
if(i<j){
swap(a[i],a[j]);
}
}
swap(a[(l+r)/2],a[j]);
return j;
}
void quicksort(int l, int r, int a[]){
if(l<r){
int j = partition(l, r, a);
quicksort(l, j-1, a);
quicksort(j+1, r, a);
}
else
return;
}
int main(){
int a[] = {14,41,93,40,98};
quicksort(0,4,a);
for(int i=0;i<5;i++)
cout<<a[i]<<" ";
return 0;
}
| true |
8eced919e3554dd5eb1e7aa21e289bb036dfced9 | C++ | Michaelwolf95/XEngine | /GameEngine_Prototype/Includes/XEngine/LineDrawer.h | UTF-8 | 618 | 2.65625 | 3 | [
"MIT"
] | permissive | #pragma once
#include "Drawer.h"
#include <glm/glm.hpp>
#include <glad/glad.h>
// This is designed to be an optimal solution for drawing lines.
// However... its not as necessary as I thought when implementing it.
// Keeping this here
class LineDrawer : public Drawer
{
public:
GLfloat verts[6];
glm::vec4 color = glm::vec4(1.0, 1.0, 1.0, 1.0);
unsigned int size = 5;
bool isUsed = false; // Used for the frame.
LineDrawer();
~LineDrawer();
void Draw() override;
void SetToDraw(glm::vec3 point1, glm::vec3 point2, glm::vec4 color, unsigned int size);
void SetPoints(glm::vec3 point1, glm::vec3 point2);
};
| true |
6a5fb3e56e4662f744d11dedeb9715175f70758b | C++ | dbecaj/ZombieGame | /game/entities/bullet.h | UTF-8 | 689 | 2.90625 | 3 | [] | no_license | #ifndef BULLET_H
#define BULLET_H
#include <QGraphicsPixmapItem>
#include <QPointF>
#define BULLET_SIZE 10.0f
enum Direction
{
UP = 0,
UP_LEFT = 1,
UP_RIGHT = 2,
DOWN = 3,
DOWN_LEFT = 4,
DOWN_RIGHT = 5,
LEFT = 6,
RIGHT = 7
};
class Bullet : public QGraphicsPixmapItem
{
Direction direction;
QPointF position;
float speed;
public:
Bullet(QPointF position, Direction direction);
void update(); // This just moves the bullet in the set direction ps: Would be better if we had a float angle not just 8 directions
Direction getDirection() { return direction; }
QPointF getPosition() { return position; }
};
#endif // BULLET_H
| true |
6a9c48a8cb17142c49b7a4549371d6d3c1f4a0b6 | C++ | Dwarfius/GP1 | /Coursework/cGrid.cpp | UTF-8 | 2,271 | 3.234375 | 3 | [] | no_license | #include "cGrid.h"
#pragma warning (disable : 4244)
cGrid::cGrid(int pWidth, int pHeight) //creates a fixed size grid with fixed amount of nodes
{
width = pWidth;
height = pHeight;
gridW = width / NODE_SIZE;
gridH = height / NODE_SIZE;
count = gridW * gridH;
grid = (vector<cGameObject*>**)malloc(sizeof(vector<cGameObject*>**) * count); //each node can contain a set of objects
for (int i = 0; i < count; i++)
grid[i] = new vector<cGameObject*>();
bounds = { center.x - width / 2, center.y - height / 2, center.x + width / 2, center.y + height / 2 }; //calculating the bounds for ignoring out of bounds objects
}
cGrid::~cGrid()
{
for (int i = 0; i < count; i++)
delete grid[i];
free(grid);
}
void cGrid::SetPos(glm::vec2 pos)
{
center = pos;
bounds = { center.x - width / 2, center.y - height / 2, center.x + width / 2, center.y + height / 2 };
}
void cGrid::Clear()
{
for (int i = 0; i < count; i++)
grid[i]->clear();
}
void cGrid::Add(cGameObject *obj)
{
RECTF r = obj->GetRect();
if (RECTF::Intersects(bounds, r)) //only add the in bounds objects - can ignore other too far of screen
{
//transforming to grid nodes
int top = glm::max((r.top - bounds.top) / NODE_SIZE, 0.f);
int bottom = glm::min((r.bottom - bounds.top) / NODE_SIZE, (float)gridH - 1);
int left = glm::max((r.left - bounds.left) / NODE_SIZE, 0.f);
int right = glm::min((r.right - bounds.left) / NODE_SIZE, (float)gridW - 1);
for (int y = top; y <= bottom; y++)
for (int x = left; x <= right; x++)
grid[y * gridW + x]->push_back(obj); //adding the object in to every node it partially covers
}
}
void cGrid::Get(vector<cGameObject*> &ret, RECTF r)
{
if (!RECTF::Intersects(bounds, r)) //if out of bounds - ignore
return;
//transforming the rect in to node coordinates
int top = glm::max((r.top - bounds.top) / NODE_SIZE, 0.f);
int bottom = glm::min((r.bottom - bounds.top) / NODE_SIZE, (float)gridH - 1);
int left = glm::max((r.left - bounds.left) / NODE_SIZE, 0.f);
int right = glm::min((r.right - bounds.left) / NODE_SIZE, (float)gridW - 1);
for (int y = top; y <= bottom; y++)
for (int x = left; x <= right; x++)
ret.insert(ret.end(), grid[y * gridW + x]->begin(), grid[y * gridW + x]->end()); //collecting every object in the rect
} | true |
d545293c14268b949211b67c64a011149372f507 | C++ | lilyht/OJ_code | /HDU/1421(dp好,再看).cpp | GB18030 | 723 | 2.515625 | 3 | [] | no_license | #include <iostream>
#include <string.h>
#include <algorithm>
using namespace std;
const int MAXN = 2005;
const int MAXK = 1005;
//2020-09-06 13:11:32 Accepted 1421 265MS 8248K 622 B G++
bool cmp(int x, int y) {
return x > y;
}
int a[MAXN];
int dp[MAXK][MAXN];
int main() {
int n, k;
while(cin>>n>>k) {
for(int i=1; i<=n; i++)
cin>>a[i];
sort(a+1, a+n+1, cmp);
for(int i=1; i<=k; i++)
for(int j=1; j<=n; j++)
dp[i][j] = 0x3f3f3f3f;
for(int i=1; i<=n; i++)
dp[0][i] = 0;
for(int i=1; i<=k; i++) {
for(int j=2*i; j<=n; j++) { //Ϊʲôjʼ1Ͳܹأ
dp[i][j] = min(dp[i][j-1], dp[i-1][j-2] + (a[j]-a[j-1])*(a[j]-a[j-1]));
}
}
cout<<dp[k][n]<<endl;
}
return 0;
}
| true |
982b8e73ae1723c042fde1da62fa953d1ddf177c | C++ | HadrienMarcellin/ProDroneTasks | /PCL_Tuto/src/Filtering/voxel_grid.cpp | UTF-8 | 1,075 | 2.5625 | 3 | [] | no_license | #include <iostream>
#include <pcl/io/pcd_io.h>
#include <pcl/point_types.h>
#include <pcl/filters/voxel_grid.h>
int main(int argc, char **argv)
{
pcl::PCLPointCloud2::Ptr cloud(new pcl::PCLPointCloud2 ());
pcl::PCLPointCloud2::Ptr cloud_filtered (new pcl::PCLPointCloud2 ());
//Fill in the cloud data
pcl::PCDReader reader;
reader.read("../pcd/table_scene_lms400.pcd", *cloud);
std::cout << "PointCloud before filtering: " << cloud-> width * cloud-> height << " data points (" << pcl::getFieldsList(*cloud) << ")." << std::endl;
//Create Filtering object
pcl::VoxelGrid<pcl::PCLPointCloud2> sor;
sor.setInputCloud(cloud);
sor.setLeafSize(0.01f, 0.01f, 0.01f);
sor.filter(*cloud_filtered);
std::cout << "PointCloud after filtering: " << cloud_filtered -> width * cloud_filtered-> height << " data points (" << pcl::getFieldsList(*cloud_filtered) << ")." << std::endl;
pcl::PCDWriter writer;
writer.write("../pcd/table_scene_lms400_downsampled.pcd", *cloud_filtered, Eigen::Vector4f::Zero(), Eigen::Quaternionf::Identity(), false);
return (0);
}
| true |
7fba1d497a5d8ce357ce6251d168aa17c6ddf56b | C++ | vladislavadd/NETB375_Mensche_aergere_dich_nicht | /QT_Project_Mensche_Aergere_dich_nicht/template_stack_class.h | UTF-8 | 639 | 3.546875 | 4 | [] | no_license | #ifndef TEMPLATE_STACK_CLASS_H
#define TEMPLATE_STACK_CLASS_H
#include <iostream>
#include <string>
#include <cstdlib>
template <typename T> class Stack
{
T arr[4];
int top;
public:
Stack<T>()
{
top = -1;
for(int i = 0; i < 4; i++)
{
arr[i] = NULL;
}
}
void push(T x)
{
arr[++top] = x;
}
T pop()
{
return arr[top--];
}
bool is_empty()
{
return (top < 0);
}
bool is_full()
{
return (top == 3);
}
bool not_empty()
{
return (top >= 0);
}
};
#endif // TEMPLATE_STACK_CLASS_H
| true |
5c11d4c0106a65268e2bdc81a79c4d714b4a39c7 | C++ | NordicArts/NordicEngine | /NordicEngine/Files/Format/BitMap/BitMap.cpp | UTF-8 | 3,525 | 2.59375 | 3 | [] | no_license | #include <NordicEngine/Files/Format/BitMap/BitMap.hpp>
#include <NordicEngine/OS/OpenGL.hpp>
namespace NordicArts {
namespace NordicEngine {
namespace Files {
BitMap::BitMap() : Handler(true) {
}
BitMap::BitMap(std::string cFileName) : Handler(cFileName, true) {
}
unsigned int BitMap::loadBitMap() {
std::string cFile = getFilePath();
m_cFileName = cFile;
unsigned char cHeader[54];
unsigned int iDataPos;
unsigned char *cData;
// Open the file
FILE *pFile = fopen(cFile.c_str(), "rb");
if (!pFile) {
throwError(__FUNCTION__ + std::string(" cant open file"));
return 0;
}
// Needs to be at least 54 bytes
if (fread(cHeader, 1, 54, pFile) != 54) {
throwError(__FUNCTION__ + std::string(" not a BMP file"));
return 0;
}
// BMPs have BM at start of file
if ((cHeader[0] != 'B') || (cHeader[1] != 'M')) {
throwError(__FUNCTION__ + std::string(" not a valid BMP file"));
return 0;
}
// 24bpp
if ((*(int *)&(cHeader[0x1E]) != 0) || (*(int *)&(cHeader[0x1C]) != 24)) {
throwError(__FUNCTION__ + std::string(" not a valid BMP file"));
return 0;
}
// Read the info for file
iDataPos = *(int *)&(cHeader[0x0A]);
m_iImageSize = *(int *)&(cHeader[0x22]);
m_iWidth = *(int *)&(cHeader[0x12]);
m_iHeight = *(int *)&(cHeader[0x16]);
// Realign the data
if (m_iImageSize == 0) { m_iImageSize = (m_iWidth * m_iHeight * 3); }
if (iDataPos == 0) { iDataPos = 54; }
// Create buffer
cData = new unsigned char[m_iImageSize];
// Add data to buffer
fread(cData, 1, m_iImageSize, pFile);
// Close the file
fclose(pFile);
// OpenGL texture
glGenTextures(1, &m_iTextureID);
// Bind texture
glBindTexture(GL_TEXTURE_2D, m_iTextureID);
// Send Image to OpenGL
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, m_iWidth, m_iHeight, 0, GL_BGR, GL_UNSIGNED_BYTE, cData);
// Delete data
SAFE_DELETE_ARRAY(cData);
// Filtering
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glGenerateMipmap(GL_TEXTURE_2D);
// Get TextureID
return m_iTextureID;
}
unsigned int BitMap::getTextureID() const {
return m_iTextureID;
}
unsigned int BitMap::getWidth() const {
return m_iWidth;
}
unsigned int BitMap::getHeight() const {
return m_iHeight;
}
};
};
};
| true |
d3cf708073faa49584aba7982b347f9b2df4a638 | C++ | vladimir2809/gensAlgorithm1 | /map.h | WINDOWS-1251 | 3,120 | 2.953125 | 3 | [] | no_license | #include <SFML/Graphics.hpp>
using namespace sf;
using namespace std;
const int countWall = 50;//
const int map_width = 40;//
const int map_height = 20;//
const int map_size = 20;//
const int quantityFood = 10;
const int quantityPoison = 10;
int countFood = 0;
int countPoison =0;
class Map
{
int points[map_width][map_height];//
public:
void changePoint(int x, int y,int value)
{
points[x][y] = value;
}
void bePointEmpty(int x,int y)//
{
points[x][y] = 0;
}
int isPoint(int x, int y)//
{
return points[x][y];
}
void createMap()//
{
for (int i = 0; i < map_width; i++)
{
for (int j = 0; j < map_height; j++)
{
points[i][j] = 0;
}
}
int rx = 0, ry = 0;
for (int i = 0; i < countWall; i++)
{
do
{
rx = rand()%map_width;
ry = rand() % map_height;
}
while (isPoint(rx,ry)!=0);
points[rx][ry] = 1;
}
for (int i = 0; i < quantityFood; i++)
{
do
{
rx = rand() % map_width;
ry = rand() % map_height;
} while (isPoint(rx, ry) != 0);
points[rx][ry] = 2;
countFood++;
}
for (int i = 0; i < quantityPoison; i++)
{
do
{
rx = rand() % map_width;
ry = rand() % map_height;
} while (isPoint(rx, ry) != 0);
points[rx][ry] = 3;
countPoison++;
}
}
void servis()//
{
int rx = 0, ry = 0;
/// int r = rand() % 100;
if (countFood<quantityFood)
{
do
{
rx = rand() % map_width;
ry = rand() % map_height;
} while (isPoint(rx, ry) != 0);
points[rx][ry] = 2;
countFood++;
}
if (countPoison<quantityPoison)
{
do
{
rx = rand() % map_width;
ry = rand() % map_height;
} while (isPoint(rx, ry) != 0);
points[rx][ry] = 3;
countPoison++;
}
}
void Draw(RenderWindow &window)// ,
{
RectangleShape rectangle(Vector2f(map_size, map_size));
rectangle.setFillColor(Color(128, 128, 128));
for (int i = 0; i < map_width; i++)
{
for (int j = 0; j < map_height; j++)
{
if (points[i][j] == 1)//
{
rectangle.setFillColor(Color(128, 128, 128));
rectangle.setPosition(i*map_size, j*map_size);
window.draw(rectangle);
}
if (points[i][j] ==2)//
{
rectangle.setFillColor(Color(0, 255, 0));
rectangle.setPosition(i*map_size, j*map_size);
window.draw(rectangle);
}
if (points[i][j] == 3)//
{
rectangle.setFillColor(Color(255, 0, 0));
rectangle.setPosition(i*map_size, j*map_size);
window.draw(rectangle);
}
}
DrawLine(window, map_width*map_size , 0,
map_width*map_size, map_height*map_size, Color(128, 128, 128));
}
}
}; | true |
1f85125adfd63da0fb848d68f0f14f1db1d4da2c | C++ | cnxtech/mpc-walkgen | /test/test-humanoid-cop-constraint.cpp | UTF-8 | 2,658 | 2.65625 | 3 | [] | no_license | ////////////////////////////////////////////////////////////////////////////////
///
///\file test-humanoid-cop-constraint.cpp
///\brief Test of the CoP constraint function
///\author de Gourcuff Martin
///
////////////////////////////////////////////////////////////////////////////////
#include <gtest/gtest.h>
#include <mpc-walkgen/type.h>
#include <mpc-walkgen/constant.h>
#include <mpc-walkgen/humanoid_feet_supervisor.h>
#include <mpc-walkgen/function/humanoid_cop_constraint.h>
using namespace MPCWalkgen;
typedef float Real;
class HumanoidCopConstraintTest: public ::testing::Test
{
protected:
typedef Type<Real>::MatrixX MatrixX;
typedef Type<Real>::VectorX VectorX;
typedef Type<Real>::Vector2 Vector2;
typedef Type<Real>::vectorOfVector2 vectorOfVector2;
virtual void SetUp()
{
using namespace MPCWalkgen;
int nbSamples = 3;
Real samplingPeriod = 1.0;
bool autoCompute = true;
VectorX variable;
variable.setZero(2*nbSamples);
Real feedbackPeriod = 0.5;
vectorOfVector2 p(3);
p[0] = Vector2(1.0, 1.0);
p[1] = Vector2(-1.0, 1.0);
p[2] = Vector2(1.0, -1.0);
HumanoidFeetSupervisor<Real> feetSupervisor(nbSamples,
samplingPeriod);
feetSupervisor.setLeftFootCopConvexPolygon(ConvexPolygon<Real>(p));
feetSupervisor.setRightFootCopConvexPolygon(ConvexPolygon<Real>(p));
feetSupervisor.updateTimeline(variable, feedbackPeriod);
LIPModel<Real> lip(nbSamples, samplingPeriod, autoCompute);
lip.setFeedbackPeriod(feedbackPeriod);
HumanoidCopConstraint<Real> copCtr(lip, feetSupervisor);
VectorX x0 = VectorX::Zero(6);
function_ = copCtr.getFunction(x0);
gradient_ = copCtr.getGradient(x0.rows());
supBounds_ = copCtr.getSupBounds(x0);
infBounds_ = copCtr.getInfBounds(x0);
}
VectorX function_;
MatrixX gradient_;
VectorX supBounds_;
VectorX infBounds_;
};
TEST_F(HumanoidCopConstraintTest, functionValue)
{
using namespace MPCWalkgen;
ASSERT_TRUE(function_.isZero(Constant<Real>::EPSILON));
for (int i=0; i<3; i++)
{
ASSERT_NEAR(gradient_(i, i), -2, Constant<Real>::EPSILON);
ASSERT_NEAR(gradient_(i, i + 3), -2, Constant<Real>::EPSILON);
}
ASSERT_TRUE(supBounds_.isConstant(1, Constant<Real>::EPSILON));
ASSERT_TRUE(infBounds_.isConstant(-Constant<Real>::MAXIMUM_BOUND_VALUE, Constant<Real>::EPSILON));
}
TEST_F(HumanoidCopConstraintTest, sizeOfValues)
{
using namespace MPCWalkgen;
ASSERT_EQ(function_.rows(), 3);
ASSERT_EQ(gradient_.rows(), 3);
ASSERT_EQ(gradient_.cols(), 6);
ASSERT_EQ(supBounds_.rows(), 6);
ASSERT_EQ(infBounds_.rows(), 6);
}
| true |
429e6ffd4d0e11ab448f73f9983f7468d2decfb3 | C++ | tim-yuan/Molecular-simulations | /MD/CPP/initposvel.cpp | UTF-8 | 2,714 | 2.515625 | 3 | [] | no_license | #include <iostream>
#include <cmath>
#include <random>
#include <fstream>
#include <iomanip>
#include <stdio.h>
using namespace std;
int initpos(int n, double pos_vel[][6], double rho)
{
double lattice = cbrt(rho);
int a = round(cbrt(n));
int num=0;
for (int i =0; i<a; i++)
{
for (int j =0; j<a; j++)
{
for (int k =0; k<a; k++)
{
pos_vel[num][0]=i*lattice+lattice/2.;
pos_vel[num][1]=j*lattice+lattice/2.;
pos_vel[num][2]=k*lattice+lattice/2.;
num+=1;
}
}
}
return 0;
}
int initvel(int n, double pos_vel[][6], double v_std)
{
int a = 0;
random_device rd;
mt19937 mt(rd());
normal_distribution<double> dist(a, v_std);
for (int i=0; i<n; i++)
{
pos_vel[i][3]=dist(mt);
pos_vel[i][4]=dist(mt);
pos_vel[i][5]=dist(mt);
}
double sumvx=0;
double sumvy=0;
double sumvz=0;
for (int i=0; i<n; i++)
{
sumvx += pos_vel[i][3];
sumvy += pos_vel[i][4];
sumvz += pos_vel[i][5];
}
double avevx=sumvx/n;
double avevy=sumvy/n;
double avevz=sumvz/n;
// double fsumvx=0.;
// double fsumvy=0.;
// double fsumvz=0.;
for (int i=0; i<n; i++)
{
pos_vel[i][3]=pos_vel[i][3]-avevx;
pos_vel[i][4]=pos_vel[i][4]-avevy;
pos_vel[i][5]=pos_vel[i][5]-avevz;
// fsumvx+= pos_vel[i][3];
// fsumvy+= pos_vel[i][4];
// fsumvz+= pos_vel[i][5];
}
// cout<<fsumvx<<"\t"<<fsumvy<<"\t"<<fsumvz<<endl;
return 0;
}
int output(int n, double pos_vel[][6],double x,double y ,double z)
{
// ofstream outfile ("initial.gro");
// outfile << "initial"<< "\n";
// outfile << n << "\n";
FILE * outfile;
outfile = fopen ("initial.gro", "w");
fprintf (outfile, "%s\n", "initial.gro");
fprintf (outfile, "%d\n", n);
for (int i=0;i<n;i++)
{
// outfile <<fixed<<setprecision(8)<<"\t"<<i<<"LJP\t"<<"LJP\t"<<i+1<<"\t"<<pos_vel[i][0]<<"\t"<< pos_vel[i][1]<<"\t"<<pos_vel[i][2]<<"\t"<<pos_vel[i][3]<<"\t"<<pos_vel[i][4]<<"\t"<<pos_vel[i][5]<<"\n";
// printf("%5d%-5s%5s%5d%8.3f%8.3f%8.3f%8.4f%8.4f%8.4f", i, "LJP", "LJP",i,pos_vel[i][0],pos_vel[i][1],pos_vel[i][2],pos_vel[i][3],pos_vel[i][4],pos_vel[i][5]);
fprintf (outfile, "%5d%-5s%5s%5d%8.3f%8.3f%8.3f%8.4f%8.4f%8.4f\n", (i+1), "LJP", "LJP",(i+1),pos_vel[i][0],pos_vel[i][1],pos_vel[i][2],pos_vel[i][3],pos_vel[i][4],pos_vel[i][5]);
}
// outfile << x <<"\t"<< y <<"\t"<< z <<"\t" << "\n";
// outfile.close();
fprintf (outfile, "%f\t %f\t %f\n", x,y,z);
fclose (outfile);
return 0;
}
| true |
6debe8b1e8b4a863868887ceb5bf882ef84537a2 | C++ | PillVic/ACM | /HDU/2109/2109/源.cpp | UTF-8 | 874 | 3.578125 | 4 | [] | no_license | #include<iostream>
#include<algorithm>
using namespace std;
int *buildTeam(int Number);
void Fight(int Hdu[], int Japan[], int Number);
int main() {
int Number;
while (cin >> Number) {
if (Number == 0) {
break;
}
int *Hdu = buildTeam(Number);
int *Japan = buildTeam(Number);
Fight(Hdu, Japan, Number);
free(Hdu);
free(Japan);
}
}
int* buildTeam(int Number) {
int *team = (int*)malloc(Number * sizeof(int));
for (int index = 0; index < Number; index++) {
cin >> team[index];
}
sort(team, team+Number);
return team;
}
void Fight(int Hdu[], int Japan[], int Number) {
int hdu = 0;
int japan = 0;
for (int index = 0; index < Number; index++) {
if (Hdu[index] > Japan[index]) {
hdu += 2;
}
else if (Hdu[index] == Japan[index]) {
hdu += 1;
japan += 1;
}
else {
japan += 2;
}
}
cout << hdu << " vs " << japan << endl;
}
| true |
d5e0c9889dc8ed00b78dba0af0c0988759aa0a91 | C++ | holondo/Arquivos-Grafos | /BTREE/Node.h | UTF-8 | 332 | 2.6875 | 3 | [] | no_license | #ifndef NODE_CLASS
#define NODE_CLASS
#define DEFAULT -1;
using namespace std;
class Node
{
private:
int key;
long recordRRN;
public:
Node();
Node(int key, long recordRRN);
void setKey(int key);
void setRRN(long RRN);
int getKey();
long getRRN();
};
#endif | true |
9a2f7229c1475b692d536b2f19baeca014922208 | C++ | emankov/hcc-clang-upgrade | /test/CodeGenHCC/register-control.cpp | UTF-8 | 3,529 | 2.546875 | 3 | [
"NCSA"
] | permissive | // RUN: %clang_cc1 -famp-is-device -fhsa-ext -std=c++amp -x hc-kernel -triple amdgcn -target-cpu fiji -emit-llvm -disable-llvm-passes -o - %s| FileCheck %s
//
// This test emulates parallel-for-each and grid launch without relying on HCC header files.
// By using pseudo definitions of some HCC types this test can generate the trampoline functions which are
// needed for testing the register control attributes.
// The objective is to focus on language aspects without introducing unnecessary declarations in the header files.
class accelerator_view { int dummy; };
class extent { int dummy; };
struct index {
index() __attribute__((annotate("__cxxamp_opencl_index"))){}
int x;
};
struct array {
int x;
void foo() restrict(amp) {}
};
template <typename Kernel>
__attribute__((noinline,used)) void parallel_for_each(
const accelerator_view& av, const extent& compute_domain, const Kernel& f) [[hc]] {
auto foo = &Kernel::__cxxamp_trampoline;
auto bar = &Kernel::operator();
}
typedef struct {int x,y,z;} grid_launch_parm;
int* foo(int x)[[hc]];
// Test grid lanuch functions.
// CHECK-LABEL: define void @_Z7kernel116grid_launch_parmPi
// CHECK-SAME: #[[ATTR1:[0-9]+]]
__attribute__((hc_grid_launch))
void kernel1(grid_launch_parm glp, int *x)
[[hc_waves_per_eu(1,2)]]
[[hc_flat_workgroup_size(1,2)]]
[[hc_max_workgroup_dim(1,2,3,"gfx803")]]
[[hc_max_workgroup_dim(4,5,6,"gfx800")]]
{
foo(1);
}
int main() {
grid_launch_parm glp;
int x[10];
kernel1(glp, x);
accelerator_view acc;
extent ext;
array arr;
// Test parallel-for-each with functor.
class A {
public:
void foo()restrict(amp){}
// CHECK-LABEL: define internal amdgpu_kernel void @_ZZ4mainEN1A19__cxxamp_trampolineEi(i32)
// CHECK-SAME: #[[ATTR2:[0-9]+]]
void operator()(index& i)
[[hc]]
[[hc_waves_per_eu(3)]]
[[hc_flat_workgroup_size(1,1)]]
[[hc_flat_workgroup_size(2,2,"gfx700")]]
[[hc_flat_workgroup_size(3,3,"gfx701")]]
[[hc_flat_workgroup_size(7,7,"gfx803")]]
[[hc_flat_workgroup_size(4,4,"gfx800")]]
[[hc_flat_workgroup_size(5,5,"gfx801")]]
[[hc_flat_workgroup_size(6,6,"gfx802")]]
[[hc_max_workgroup_dim(4,5,6)]]
{ x = i.x; }
int x;
} a;
parallel_for_each(acc, ext, a);
// Test parallel-for-each with lambda function.
// CHECK-LABEL: define internal amdgpu_kernel void @"_ZZ4mainEN3$_019__cxxamp_trampolineEP5array"(%struct.array*)
// CHECK-SAME: #[[ATTR3:[0-9]+]]
parallel_for_each(acc, ext, [&](index& i)
[[hc]]
[[hc_waves_per_eu(4)]]
[[hc_flat_workgroup_size(5)]]
[[hc_max_workgroup_dim(6,7,8)]]
{
arr.x = 123;
});
// Test parallel-for-each with lambda function.
// CHECK-LABEL: define internal amdgpu_kernel void @"_ZZ4mainEN3$_119__cxxamp_trampolineEP5array"(%struct.array*)
// CHECK-SAME: #[[ATTR4:[0-9]+]]
parallel_for_each(acc, ext, [&](index& i)
[[hc]]
[[hc_max_workgroup_dim(3,4,5)]]
{
arr.x = 123;
});
return 0;
}
// CHECK: attributes #[[ATTR1]] ={{.*}}"amdgpu-flat-work-group-size"="1,2" "amdgpu-max-work-group-dim"="1,2,3" "amdgpu-waves-per-eu"="1,2"
// CHECK: attributes #[[ATTR2]] ={{.*}}"amdgpu-flat-work-group-size"="7,7" "amdgpu-max-work-group-dim"="4,5,6" "amdgpu-waves-per-eu"="3"
// CHECK: attributes #[[ATTR3]] ={{.*}}"amdgpu-flat-work-group-size"="5" "amdgpu-max-work-group-dim"="6,7,8" "amdgpu-waves-per-eu"="4"
// CHECK: attributes #[[ATTR4]] ={{.*}}"amdgpu-flat-work-group-size"="1,60" "amdgpu-max-work-group-dim"="3,4,5"
| true |
f7de81cf0ae405fed9b005da94b312094600c141 | C++ | mahmud085/ACM_Code | /12577.cpp | UTF-8 | 269 | 2.71875 | 3 | [] | no_license | #include<stdio.h>
#include<string.h>
char arr[7];
int main()
{
int i=1,j,k;
while(gets(arr))
{
if(!strcmp(arr,"*"))
break;
if(strcmp(arr,"Hajj")==0)
printf("Case %d: Hajj-e-Akbar\n",i);
else
printf("Case %d: Hajj-e-Asghar\n",i);
i++;
}
return 0;
} | true |
affe2f65ae6fb493620084027baa9e9050bd8a8e | C++ | BioMyth/CHIP-8 | /Chip 8 Emulator/WindowHandler.h | UTF-8 | 1,183 | 2.71875 | 3 | [] | no_license | #ifndef _WINDOW_HANDLER_H_
#define _WINDOW_HANDLER_H_
#include <Windows.h>
class Window{
public:
void Register();
private:
HWND window;
RECT rect;
HANDLE hOut;
CONSOLE_SCREEN_BUFFER_INFO SBInfo;
COORD NewSBSize;
};
void Window::Register(){
// Register the window class.
const wchar_t CLASS_NAME[] = L"Sample Window Class";
WNDCLASS wc = { };
wc.lpfnWndProc = WindowProc;
wc.hInstance = wWinMain.hInstance;//hInstance;
wc.lpszClassName = CLASS_NAME;
RegisterClass(&wc);
// Create the window.
HWND hwnd = CreateWindowEx(
0, // Optional window styles.
CLASS_NAME, // Window class
L"Learn to Program Windows", // Window text
WS_OVERLAPPEDWINDOW, // Window style
// Size and position
CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
NULL, // Parent window
NULL, // Menu
hInstance, // Instance handle
NULL // Additional application data
);
if (hwnd == NULL)
{
return 0;
}
ShowWindow(hwnd, nCmdShow);
}
#endif | true |
d83c4dd575a35986a0efc5b1070a9639497d7374 | C++ | NovaEric/ENova_Cplusplus | /Multi_Map.cpp | UTF-8 | 3,020 | 3.640625 | 4 | [] | no_license | #include<map> // part of STL or standard template library
#include<iostream>
#include <string>
using namespace std;
// using typdef to create an alias....like const clause
typedef multimap <int, string> MMAP_INT_STRING; //created alias of MMAP_INT_STRING
int main()
{
MMAP_INT_STRING mmapIntToString;
//Use insert function to insert a key AND a value
//uses a balanced binary tree as the underlying structure
mmapIntToString.insert(MMAP_INT_STRING::value_type(3, "Three"));
mmapIntToString.insert(MMAP_INT_STRING::value_type(45, "Forty Five"));
mmapIntToString.insert(MMAP_INT_STRING::value_type(-1, "Minus One"));
mmapIntToString.insert(MMAP_INT_STRING::value_type(1000, "Thousand"));
// multimap can store dupliactes, map can not
mmapIntToString.insert(MMAP_INT_STRING::value_type(1000, "Thousand"));
// now let's look at the values we just inserted and the size of the multi-map structure
cout << "The multimap contains " << mmapIntToString.size();
cout << " key-value pars " << endl;
cout << "The elements in the multimap are:" << endl;
//define an iterator
MMAP_INT_STRING::const_iterator iMultiMapPairLocator;
for (iMultiMapPairLocator = mmapIntToString.begin(); iMultiMapPairLocator != mmapIntToString.end(); ++iMultiMapPairLocator)
{
cout << "Key: " << iMultiMapPairLocator->first; // first node in the b-tree
cout << ", Value: " << iMultiMapPairLocator->second << endl;
}
cout << endl;
cout << "Finding all key value pairs with 1000 as their key: " << endl;
//find an element in the multimap using the 'find' function
MMAP_INT_STRING::const_iterator iElementFound;
iElementFound = mmapIntToString.find(1000); // find the value if key 10000
// check if find suceeded
if (iElementFound != mmapIntToString.end())
{
//Find the number of pairs that have the same supplied key
size_t nNumPairsInMap = mmapIntToString.count(1000);
cout << "The number of pairs in the multimap with 1000 as key: ";
cout << nNumPairsInMap << endl;
//output those values
cout << "The values corresponding to the key 1000 are: " << endl;
for (size_t nValuesCounter = 0; nValuesCounter < nNumPairsInMap; ++nValuesCounter)
{
cout << "Key: " << iElementFound->first;
cout << ", Value [" << nValuesCounter << "] = ";
cout << iElementFound->second << endl;
++iElementFound;
}
}
else
cout << "Element not found in the multimap";
// erasing contents with key of -1
cout << endl << "erasing contents with key of -1" << endl << endl;
mmapIntToString.erase(-1);
//display map again
cout << "The elements in the multimap are:" << endl;
for (iMultiMapPairLocator = mmapIntToString.begin(); iMultiMapPairLocator != mmapIntToString.end(); ++iMultiMapPairLocator)
{
cout << "Key: " << iMultiMapPairLocator->first; // first node in the b-tree
cout << ", Value: " << iMultiMapPairLocator->second << endl;
}
cout << endl;
system("pause");
return 0;
} | true |
e18b23a721798d8f4631d0b1d6db05b8e5215c61 | C++ | adamvm/testing | /bowling/testFiles.cpp | UTF-8 | 986 | 2.65625 | 3 | [] | no_license | #include "Files.hpp"
#include <gtest/gtest.h>
class FilesTest : public ::testing::Test {
public:
Files files{"../results"};
std::map<std::string, std::string> expectedContent{
{"lane1.txt", "Name1:X|4-|3\n"
"Name2:34|X|0-\n"
":X|22|33"},
{"lane2.txt", ""},
{"lane3.txt", "Michael:X|7/|9-|X|-8|8/|-6|X|X|X||81\n"
"Radek:9-|9-|9-|9-|9-|9-|9-|9-|9-|9-||"}};
};
TEST_F(FilesTest, ListAllFilesInDirectory) {
std::set<std::string> expectedResult;
for (const auto &el : expectedContent)
expectedResult.emplace(el.first);
ASSERT_EQ(expectedResult, files.listResultsFiles());
}
TEST_F(FilesTest, ReadFileContent) {
auto filename = "lane1.txt";
auto fileContent = expectedContent[filename];
ASSERT_EQ(fileContent, files.readFile(filename));
}
TEST_F(FilesTest, ReadAllFilescontent) {
std::map<std::string, std::string> result = files.readAllFiles();
ASSERT_EQ(expectedContent, result);
}
| true |
203a58cd8dbb246c90f2cccce0af45b0e68008ad | C++ | benishor/morse-writer | /src/libmorse/implementation/MorseDictionary.cpp | UTF-8 | 2,512 | 3.09375 | 3 | [] | no_license | #include <MorseDictionary.h>
#include <iostream>
#include <algorithm>
MorseDictionary::MorseDictionary() {
// std::cout << "Creating morse dictionary instance" << std::endl;
}
MorseDictionary MorseDictionary::defaultDictionary() {
MorseDictionary result;
result
.add('a', ".-").add('b', "-...").add('c', "-.-.").add('d', "-..")
.add('e', ".").add('f', "..-.").add('g', "--.").add('h', "....")
.add('i', "..").add('j', ".---").add('k', "-.-").add('l', ".-..")
.add('m', "--").add('n', "-.").add('o', "---").add('p', ".--.")
.add('q', "--.-").add('r', ".-.").add('s', "...").add('t', "-")
.add('u', "..-").add('v', "...-").add('w', ".--").add('x', "-..-")
.add('y', "-.--").add('z', "--..");
result
.add('0', "-----").add('1', ".----").add('2', "..---")
.add('3', "...--").add('4', "....-").add('5', ".....")
.add('6', "-....").add('7', "--...").add('8', "---..")
.add('9', "----.");
result
.add('.', ".-.-.-")
.add(',', "--..--")
.add('?', "..--..")
.add('=', "-...-")
.add('-', "-....-")
.add('/', "-..-.")
.add('"', ".----.")
.add('(', "-.--.")
.add(')', "-.--.-");
return result;
}
MorseDictionary& MorseDictionary::add(char character, const std::string& morsePattern) {
dictionary.insert(std::pair<char, const std::string&>(std::toupper(character), morsePattern));
dictionary.insert(std::pair<char, const std::string&>(std::tolower(character), morsePattern));
return *this;
}
const static std::string EMPTY_PATTERN {""};
bool MorseDictionary::contains(char character) const {
auto it = dictionary.find(character);
return it != dictionary.end();
}
const std::string& MorseDictionary::characterTemplate(char character) const {
auto it = dictionary.find(character);
if (it == dictionary.end()) {
return EMPTY_PATTERN;
} else {
return it->second;
}
}
std::string& MorseDictionary::filter(std::string& content) const {
// Unfortunatelly gcc 4.8.2 does not yet have support for regex
// Transform new lines into spaces so that we won't have
// sentences on subsequent lines starting one after another
for_each(content.begin(), content.end(), [](char& val) {
val = val == '\n' ? ' ' : val;
});
// Remove invalid characters from the string
content.erase(remove_if(content.begin(), content.end(), [this](char val) {
return val != ' ' && !this->contains(val);
}), content.end());
return content;
} | true |
2205c8103f7dc4d02d1b5382318f5ccd9d8b39d0 | C++ | HuntingSHEEP/GameEngine | /main.cpp | UTF-8 | 19,728 | 3.109375 | 3 | [] | no_license | /*
* sudo apt install libgtk-3-dev
*/
#include <gtk/gtk.h>
#include <iostream>
#include <thread>
#include <unistd.h>
#include <math.h>
using namespace std;
double modulo(double a){
if(0 <= a){
return a;
}else{
return -a;
}
}
int signum(double a){
if(0 < a){return 1;}
else if(a == 0){return 0;}
else{return -1;}
}
class Point{
public:
double x;
double y;
Point(){
this->x = 0;
this->y = 0;
}
Point(double x, double y){
this->x = x;
this->y = y;
}
void setPosition(double x, double y){
this->x = x;
this->y = y;
}
void moveBy(double dx, double dy){
this->x += dx;
this->y += dy;
}
private:
};
class Line{
public:
Point aPoint, bPoint;
Line(){
this->aPoint = Point();
this->bPoint = Point();
}
Line(Point A, Point B){
this->aPoint = A;
this->bPoint = B;
}
void drawMe(cairo_t *cr, GdkRGBA *color){
//TODO >> SET COLOR METHOD?
cairo_move_to(cr, aPoint.x, aPoint.y);
cairo_line_to(cr, bPoint.x, bPoint.y);
cairo_close_path(cr);
cairo_stroke_preserve(cr);
gdk_cairo_set_source_rgba (cr, color);
cairo_fill(cr);
}
};
class Crosshair{
public:
int R, r;
Point middlePoint;
Crosshair(Point middlePoint, int R, int r){
this->middlePoint = middlePoint;
this->R = R;
this->r = r;
setupLines();
}
void setPosition(Point p){
this->middlePoint.setPosition(p.x, p.y);
updateLines();
}
void setPosition(double x, double y){
this->middlePoint.setPosition(x, y);
updateLines();
}
void drawMe(cairo_t *cr, GdkRGBA *color){
lineZero.drawMe(cr, color);
lineOne.drawMe(cr, color);
lineTwo.drawMe(cr, color);
lineThree.drawMe(cr, color);
}
private:
Line lineZero, lineOne, lineTwo, lineThree;
void setupLines(){
lineZero = Line(Point(middlePoint.x, middlePoint.y-r), Point(middlePoint.x, middlePoint.y-R));
lineOne = Line(Point(middlePoint.x+r, middlePoint.y), Point(middlePoint.x+R, middlePoint.y));
lineTwo = Line(Point(middlePoint.x, middlePoint.y+r), Point(middlePoint.x, middlePoint.y+R));
lineThree = Line(Point(middlePoint.x-r, middlePoint.y), Point(middlePoint.x-R, middlePoint.y));
}
void updateLines(){
//UPDATE THE UPPER VERTICAL LINE
lineZero.aPoint.setPosition(middlePoint.x, middlePoint.y-r);
lineZero.bPoint.setPosition(middlePoint.x, middlePoint.y-R);
//UPDATE THE RIGHT HORIZONTAL LINE
lineOne.aPoint.setPosition(middlePoint.x+r, middlePoint.y);
lineOne.bPoint.setPosition(middlePoint.x+R, middlePoint.y);
//UPDATE THE LOWER VERTICAL LINE
lineTwo.aPoint.setPosition(middlePoint.x, middlePoint.y+r);
lineTwo.bPoint.setPosition(middlePoint.x, middlePoint.y+R);
//UPDATE THE LEFT HORIZONTAL LINE
lineThree.aPoint.setPosition(middlePoint.x-r, middlePoint.y);
lineThree.bPoint.setPosition(middlePoint.x-R, middlePoint.y);
}
};
class Vector{
public:
double x, y, z;
bool X, Y, Z;
Vector(){
}
Vector(double x, double y){
this->x = x;
this->y = y;
this->z = 0;
}
Vector(double x, double y, double z){
this->x = x;
this->y = y;
this->z = z;
}
void add(Vector vector){
this->x += vector.x;
this->y += vector.y;
this->z += vector.z;
}
void add(double x, double y, double z){
this->x += x;
this->y += y;
this->z += z;
}
void multiply(double scale){
this->x *= scale;
this->y *= scale;
this->z *= scale;
}
double length(){
return sqrt(x*x + y*y + z*z);
}
};
class Object{
public:
double width, height;
Point leftUpperVertex;
void setPosition(Point p){
this->leftUpperVertex.setPosition(p.x, p.y);
}
void setPosition(double x, double y){
this->leftUpperVertex.setPosition(x, y);
}
void moveBy(double dx, double dy){
this->leftUpperVertex.moveBy(dx, dy);
}
Point getPosition(){
return leftUpperVertex;
}
};
class PhysicComponent: public Object{
public:
Vector v, a, collision;
// PhysicComponent(Vector v, Vector a) : v(v), a(a){}
PhysicComponent(){
}
PhysicComponent(Vector v, Vector a){
this->a = a;
this->v = v;
this->collision = Vector();
}
void addForce(Vector vector){
v.add(vector);
}
void addAcceleration(Vector vector){
a.add(vector);
}
void addSpeed(Vector vector){
v.add(vector);
}
void setGravity(double g){
addAcceleration(Vector(0, g));
}
void calculatePhysic(double deltaTime){
//zmiana położenia
double dx = v.x*deltaTime + (a.x/2)*deltaTime*deltaTime;
double dy = v.y*deltaTime + (a.y/2)*deltaTime*deltaTime;
//nowa prędkość
double dvx = a.x*deltaTime;
double dvy = a.y*deltaTime;
//aktualizacja położenia
//leftUpperVertex.moveBy(dx, dy);
moveBy(dx, dy);
//aktualizacja prędkości
v.add(dvx, dvy, 0);
}
};
class Rectangle: public PhysicComponent{
public:
Line bounds[4];
Rectangle(int width, int height)
// : PhysicComponent(Vector(0, 0, 0), Vector(0, 0))
{
this->width = width;
this->height = height;
this->leftUpperVertex = Point(0, 0);
Line a = Line(leftUpperVertex, Point(width, 0));
Line b = Line(Point(width, 0), Point(width, height));
Line c = Line(Point(width, height), Point(0, height));
Line d = Line(Point(0, height), Point(0,0));
this->bounds[0] = a;
this->bounds[1] = b;
this->bounds[2] = c;
this->bounds[3] = d;
}
Rectangle(int width, int height, Point leftUpperVertex)
// : PhysicComponent(Vector(0, 0, 0), Vector(0, 0))
{
this->width = width;
this->height = height;
this->leftUpperVertex = leftUpperVertex;
Line a = Line(leftUpperVertex, Point(leftUpperVertex.x+width, leftUpperVertex.y));
Line b = Line(Point(leftUpperVertex.x+width, leftUpperVertex.y), Point(leftUpperVertex.x+width, leftUpperVertex.y + height));
Line c = Line(Point(leftUpperVertex.x+width, leftUpperVertex.y + height), Point(leftUpperVertex.x, leftUpperVertex.y + height));
Line d = Line(Point(leftUpperVertex.x, leftUpperVertex.y + height), leftUpperVertex);
this->bounds[0] = a;
this->bounds[1] = b;
this->bounds[2] = c;
this->bounds[3] = d;
}
void drawMe(cairo_t *cr, GdkRGBA *color){
cairo_rectangle(cr, leftUpperVertex.x, leftUpperVertex.y, width, height);
gdk_cairo_set_source_rgba (cr, color);
cairo_fill(cr);
}
void drawBounds(cairo_t *cr, GdkRGBA *color){
bounds[0].drawMe(cr, color);
for(int i=0; i<4; i++){
bounds[i].drawMe(cr, color);
}
}
bool collision(Point p){
bool w1 = (leftUpperVertex.x <= p.x) & (p.x <= leftUpperVertex.x + width);
bool w2 = (leftUpperVertex.y <= p.y) & (p.y <= leftUpperVertex.y + height);
return w1 & w2;
}
bool collision(double x, double y){
bool w1 = (leftUpperVertex.x <= x) & (x <= leftUpperVertex.x + width);
bool w2 = (leftUpperVertex.y <= y) & (y <= leftUpperVertex.y + height);
return w1 & w2;
}
Point getMiddle(){
double x = this->leftUpperVertex.x + this->width/2;
double y = this->leftUpperVertex.y + this->height/2;
return Point(x, y);
}
Vector getWeightPointsVector(Rectangle rect){
Point a = this->getMiddle();
Point b = rect.getMiddle();
Vector w = Vector(a.x - b.x, a.y - b.y);
return w;
}
bool collision(Rectangle rect){
//TODO: KOLIZJA BEZ WIERZCHOŁKÓW WEWNATRZ DRUGIEGO PROSTOKĄTA
bool w1 = (collision(rect.leftUpperVertex) || \
collision(rect.leftUpperVertex.x + rect.width, rect.leftUpperVertex.y) || \
collision(rect.leftUpperVertex.x + rect.width, rect.leftUpperVertex.y + rect.height) || \
collision(rect.leftUpperVertex.x, rect.leftUpperVertex.y + rect.height));
bool w2 = (rect.collision(leftUpperVertex)) ||\
rect.collision(leftUpperVertex.x + width, leftUpperVertex.y) ||\
rect.collision(leftUpperVertex.x + width, leftUpperVertex.y + height) ||\
rect.collision(leftUpperVertex.x , leftUpperVertex.y + height);
return w1 || w2;
}
void collisionResponse(Rectangle rect) {
//wersja mocno uproszczona
Vector w = getWeightPointsVector(rect);
Vector qVector = Vector(rect.width/2 + width/2, rect.height/2 + height/2);
double q = modulo(qVector.y / qVector.x);
double k = modulo(w.y / w.x);
double bounceScale = 0.3;
if(q <= k){
//REACT ON Y-AXIS
if(signum(w.y) == -1){
if(0 < v.y){
v.y *= -1 * bounceScale;
}
}else{
if(v.y < 0){
v.y *= -1 * bounceScale;
}
}
}else{
//REACT ON X-AXIS
if(signum(w.x) == -1){
if(0 < v.x){
v.x *= -1 * bounceScale;
}
}else{
if(v.x < 0){
v.x *= -1 * bounceScale;
}
}
}
}
};
class Key{
public:
bool isPressed;
bool pressedAgain;
bool resetDone;
Key(){
this->isPressed = false;
this->pressedAgain = false;
this->resetDone = true;
}
Key(bool isPressed, bool pressedAgain){
this->isPressed = isPressed;
this->pressedAgain = pressedAgain;
this->resetDone = true;
}
};
class Input{
public:
Key w, s, a, d;
Key space;
Input(){
w = Key();
s = Key();
d = Key();
a = Key();
space = Key();
}
};
//*****************************************************************************************************************
int n = 1;
int z = 1;
int x = 40;
int y = 40;
int xOffset = -10;
int yOffset = -50;
Line kreska = Line(Point(40, 40), Point(400, 160));
Crosshair celownik = Crosshair(Point(50, 50), 40, 5);
Rectangle platforma = Rectangle(300, 20, Point(100, 300));
Rectangle platforma1 = Rectangle(500, 20, Point(150, 500));
Rectangle platforma2 = Rectangle(300, 20, Point(700, 600));
Rectangle platforma3 = Rectangle(300, 20, Point(300, 700));
Rectangle kwadrat2 = Rectangle(40, 40, Point(500, 200));
Input klawiatura = Input();
void wyswietlaniePozycjiOkna(GtkWindow *okno, GdkEvent *zdarzenie, gpointer dane){
int x, y;
char polozenie[10];
x = zdarzenie->configure.x;
y = zdarzenie->configure.y;
sprintf(polozenie, "%d, %d", x, y);
gtk_window_set_title(okno, polozenie);
}
gboolean draw_callback (GtkWidget *widget, cairo_t *cr, gpointer data)
{
guint width, height;
GdkRGBA color = { 1,1,1,1};
GdkRGBA clr = { 0.1,0.1,0.1,1};
width = gtk_widget_get_allocated_width (widget);
height = gtk_widget_get_allocated_height (widget);
//cairo_arc (cr, n, height / 2.0,MIN (width, height) / 2.0,0, 2 * G_PI);
//białe tło
cairo_rectangle(cr, 0, 0, width, height);
gdk_cairo_set_source_rgba (cr, &color);
cairo_fill (cr);
color = { 0,0,1,1};
//cairo_rectangle(cr, xk, yk, 50, 50);
gdk_cairo_set_source_rgba (cr, &color);
cairo_fill (cr);
color = { 0.1,0.5,0.5,1};
platforma.drawMe(cr, &color);
platforma.drawBounds(cr, &clr);
platforma1.drawMe(cr, &color);
platforma1.drawBounds(cr, &clr);
platforma2.drawMe(cr, &color);
platforma2.drawBounds(cr, &clr);
platforma3.drawMe(cr, &color);
platforma3.drawBounds(cr, &clr);
color = { 1,0,0,1};
kwadrat2.drawMe(cr, &color);
color = {0.2929,0,0.5, 1};
color = { 0,1,1,1};
//draw to me the LINE
celownik.drawMe(cr, &color);
gtk_widget_queue_draw(widget);
return FALSE;
}
void buttonFunction (GtkButton *button, gpointer user_data) /* No extra parameter here ! */
{
/* you cast to the type of what you passed as last argument of g_signal_connect */
int *pn = (gint *) user_data;
cout<<*pn<<endl;
}
double microsecond = 1000;
double deltaTime = microsecond/150000;
int skok = 20;
[[noreturn]] void silnikFizyki(){
while(true){
//SKAKANIE
if(klawiatura.space.isPressed & (!klawiatura.space.pressedAgain) ){
kwadrat2.addSpeed(Vector(0, -50));
klawiatura.space.resetDone = false;
klawiatura.space.pressedAgain = true;
}
//OŚ PIONOWA
if(klawiatura.w.isPressed & (!klawiatura.w.pressedAgain) ){
kwadrat2.addAcceleration(Vector(0, -skok));
klawiatura.w.resetDone = false;
klawiatura.w.pressedAgain = true;
}else if(klawiatura.s.isPressed & (! klawiatura.s.pressedAgain)){
kwadrat2.addAcceleration(Vector(0, skok));
klawiatura.s.resetDone = false;
klawiatura.s.pressedAgain = true;
}
//OŚ POZIOMA
if(klawiatura.a.isPressed & (!klawiatura.a.pressedAgain) ){
kwadrat2.addAcceleration(Vector(-skok, 0));
klawiatura.a.resetDone = false;
klawiatura.a.pressedAgain = true;
}else if(klawiatura.d.isPressed & (! klawiatura.d.pressedAgain)){
kwadrat2.addAcceleration(Vector( skok, 0));
klawiatura.d.resetDone = false;
klawiatura.d.pressedAgain = true;
}
//blok rezygnacji
if((!klawiatura.w.isPressed) & (!klawiatura.w.resetDone)){
kwadrat2.addAcceleration(Vector( 0, skok ));
klawiatura.w.resetDone = true;
}else if((!klawiatura.s.isPressed) & (!klawiatura.s.resetDone)){
kwadrat2.addAcceleration(Vector(0, -skok));
klawiatura.s.resetDone = true;
}
if((!klawiatura.a.isPressed) & (!klawiatura.a.resetDone)){
kwadrat2.addAcceleration(Vector( skok, 0));
klawiatura.a.resetDone = true;
}else if((!klawiatura.d.isPressed) & (!klawiatura.d.resetDone)){
kwadrat2.addAcceleration(Vector(-skok, 0));
klawiatura.d.resetDone = true;
}
if(kwadrat2.collision(platforma)){
kwadrat2.collisionResponse(platforma);
}
if(kwadrat2.collision(platforma1)){
kwadrat2.collisionResponse(platforma1);
}
if(kwadrat2.collision(platforma2)){
kwadrat2.collisionResponse(platforma2);
}
if(kwadrat2.collision(platforma3)){
kwadrat2.collisionResponse(platforma3);
}
kwadrat2.calculatePhysic(deltaTime);
usleep(microsecond);
}
}
void wcisnietoGuzik(GtkWidget *widget, GdkEventKey *event, gpointer data){
//Obsługa zdarzeń klawiatury
if(event->keyval == GDK_KEY_space){
if(!klawiatura.space.isPressed){
klawiatura.space.isPressed = true;
}else{
klawiatura.space.pressedAgain = true;
}
}
if(event->keyval == GDK_KEY_w){
if(!klawiatura.w.isPressed){
klawiatura.w.isPressed = true;
}else{
klawiatura.w.pressedAgain = true;
}
}
if(event->keyval == GDK_KEY_s){
if(!klawiatura.s.isPressed){
klawiatura.s.isPressed = true;
}else{
klawiatura.s.pressedAgain = true;
}
}
if(event->keyval == GDK_KEY_a) {
if(!klawiatura.a.isPressed){
klawiatura.a.isPressed = true;
}else{
klawiatura.a.pressedAgain = true;
}
}
if(event->keyval == GDK_KEY_d){
if(!klawiatura.d.isPressed){
klawiatura.d.isPressed = true;
}else{
klawiatura.d.pressedAgain = true;
}
}
if(event->hardware_keycode == 16){
cout<<"MOUSE CLICKED"<<endl;
}
}
void puszczonoGuzik(GtkWidget *widget, GdkEventKey *event, gpointer data){
if(event->keyval == GDK_KEY_space){
klawiatura.space.isPressed = false;
klawiatura.space.pressedAgain = false;
}
if(event->keyval == GDK_KEY_w){
klawiatura.w.isPressed = false;
klawiatura.w.pressedAgain = false;
}
if(event->keyval == GDK_KEY_s){
klawiatura.s.isPressed = false;
klawiatura.s.pressedAgain = false;
}
if(event->keyval == GDK_KEY_a) {
klawiatura.a.isPressed = false;
klawiatura.a.pressedAgain = false;
}
if(event->keyval == GDK_KEY_d){
klawiatura.d.isPressed = false;
klawiatura.d.pressedAgain = false;
}
}
static gboolean mouse_moved(GtkWidget *widget,GdkEvent *event, gpointer user_data) {
if (event->type==GDK_MOTION_NOTIFY) {
GdkEventMotion* e=(GdkEventMotion*)event;
x = (guint)e->x + xOffset;
y = (guint)e->y + yOffset;
kreska.aPoint.setPosition(x,y);
celownik.setPosition(x,y);
return true;
}
return false;
}
int main (int argc, char *argv[]) {
GtkWidget *okno;
GtkWidget *kontener, *przycisk;
gtk_init (&argc, &argv);
kwadrat2.setGravity(15);
okno = gtk_window_new (GTK_WINDOW_TOPLEVEL);
kontener = gtk_fixed_new();
gtk_container_add(GTK_CONTAINER(okno), kontener);
//przycisk = gtk_button_new_with_label("ELOOPSZ");
//g_signal_connect(G_OBJECT(przycisk), "clicked", G_CALLBACK(buttonFunction), &n);
//gtk_widget_set_size_request(przycisk, 180, 35);
gtk_window_set_default_size(GTK_WINDOW(okno), 1000+10+10+300, 700+50+10+200);
gtk_window_set_position(GTK_WINDOW(okno), GTK_WIN_POS_CENTER);
gtk_window_set_title(GTK_WINDOW(okno), "Dzień dobry");
g_signal_connect(G_OBJECT(okno), "destroy", G_CALLBACK(gtk_main_quit), NULL);
g_signal_connect(G_OBJECT(okno), "configure-event", G_CALLBACK(wyswietlaniePozycjiOkna), NULL);
GtkWidget *drawing_area = gtk_drawing_area_new ();
gtk_widget_set_size_request (drawing_area, 1000+300, 700+200);
g_signal_connect (G_OBJECT (drawing_area), "draw",G_CALLBACK (draw_callback), NULL);
gtk_fixed_put(GTK_FIXED(kontener), drawing_area, 10, 50);
//OBSŁUGA KLAWIATURY
gtk_widget_add_events(okno, GDK_KEY_PRESS_MASK);
g_signal_connect(G_OBJECT(okno), "key_press_event", G_CALLBACK(wcisnietoGuzik), NULL);
g_signal_connect(G_OBJECT(okno), "key_release_event", G_CALLBACK(puszczonoGuzik), NULL);
//obsługa myszy
g_signal_connect (G_OBJECT (okno), "motion-notify-event",G_CALLBACK (mouse_moved), NULL);
g_signal_connect (G_OBJECT (okno), "button-press-event",G_CALLBACK (wcisnietoGuzik), NULL);
gtk_widget_set_events(okno, GDK_POINTER_MOTION_MASK|GDK_BUTTON_PRESS_MASK|GDK_KEY_PRESS_MASK );
gtk_fixed_put(GTK_FIXED(kontener), przycisk, 100, 50);
gtk_widget_show_all(okno);
std::thread silnik(&silnikFizyki);
//silnik.join();
gtk_main();
return 0;
}
| true |
6f16c0974e3e383275602634e072426a773b4a12 | C++ | Azure/azure-sdk-for-cpp | /sdk/core/azure-core/src/http/retry_policy.cpp | UTF-8 | 8,379 | 2.640625 | 3 | [
"MIT",
"LicenseRef-scancode-generic-cla",
"curl",
"LGPL-2.1-or-later",
"BSD-3-Clause",
"ISC"
] | permissive | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#include "azure/core/http/policies/policy.hpp"
#include "azure/core/internal/diagnostics/log.hpp"
#include <algorithm>
#include <cstdlib>
#include <limits>
#include <sstream>
#include <thread>
using Azure::Core::Context;
using namespace Azure::Core::Http;
using namespace Azure::Core::Http::Policies;
using namespace Azure::Core::Http::Policies::_internal;
namespace {
bool GetResponseHeaderBasedDelay(RawResponse const& response, std::chrono::milliseconds& retryAfter)
{
// Try to find retry-after headers. There are several of them possible.
auto const& responseHeaders = response.GetHeaders();
auto const responseHeadersEnd = responseHeaders.end();
auto header = responseHeadersEnd;
if (((header = responseHeaders.find("retry-after-ms")) != responseHeadersEnd)
|| ((header = responseHeaders.find("x-ms-retry-after-ms")) != responseHeadersEnd))
{
// The headers above are in milliseconds.
retryAfter = std::chrono::milliseconds(std::stoi(header->second));
return true;
}
if ((header = responseHeaders.find("retry-after")) != responseHeadersEnd)
{
// This header is in seconds.
retryAfter = std::chrono::seconds(std::stoi(header->second));
return true;
// Tracked by https://github.com/Azure/azure-sdk-for-cpp/issues/262
// ----------------------------------------------------------------
//
// To be accurate, the Retry-After header is EITHER seconds, or a DateTime. So we need to
// write a parser for that (and handle the case when parsing seconds fails).
// More info:
// * Retry-After header: https://developer.mozilla.org/docs/Web/HTTP/Headers/Retry-After
// * HTTP Date format: https://developer.mozilla.org/docs/Web/HTTP/Headers/Date
// * Parsing the date: https://en.cppreference.com/w/cpp/locale/time_get
// * Get system datetime: https://en.cppreference.com/w/cpp/chrono/system_clock/now
// * Subtract datetimes to get duration:
// https://en.cppreference.com/w/cpp/chrono/time_point/operator_arith2
}
return false;
}
/**
* @brief Calculate the exponential delay needed for this retry.
*
* @param retryOptions Options controlling the delay algorithm.
* @param attempt Which attempt is this?
* @param jitterFactor Test hook removing the randomness from the delay algorithm.
*
* @returns Number of milliseconds to delay.
*
* @remarks This function calculates the exponential backoff needed for each retry, including a
* jitter factor.
*/
std::chrono::milliseconds CalculateExponentialDelay(
RetryOptions const& retryOptions,
int32_t attempt,
double jitterFactor)
{
if (jitterFactor < 0.8 || jitterFactor > 1.3)
{
// jitterFactor is a random double number in the range [0.8 .. 1.3]
jitterFactor
= 0.8 + ((static_cast<double>(static_cast<int32_t>(std::rand())) / RAND_MAX) * 0.5);
}
constexpr auto beforeLastBit
= std::numeric_limits<int32_t>::digits - (std::numeric_limits<int32_t>::is_signed ? 1 : 0);
// Scale exponentially: 1 x RetryDelay on 1st attempt, 2x on 2nd, 4x on 3rd, 8x on 4th ... all the
// way up to std::numeric_limits<int32_t>::max() * RetryDelay.
auto exponentialRetryAfter = retryOptions.RetryDelay
* (((attempt - 1) <= beforeLastBit) ? (1 << (attempt - 1))
: std::numeric_limits<int32_t>::max());
// Multiply exponentialRetryAfter by jitterFactor
exponentialRetryAfter = std::chrono::milliseconds(static_cast<std::chrono::milliseconds::rep>(
(std::chrono::duration<double, std::chrono::milliseconds::period>(exponentialRetryAfter)
* jitterFactor)
.count()));
return std::min(exponentialRetryAfter, retryOptions.MaxRetryDelay);
}
bool WasLastAttempt(RetryOptions const& retryOptions, int32_t attempt)
{
return attempt > retryOptions.MaxRetries;
}
Context::Key const RetryKey;
} // namespace
int32_t RetryPolicy::GetRetryCount(Context const& context)
{
int32_t number = -1;
// Context with no data abut sending request with retry policy = -1
// First try = 0
// Second try = 1
// third try = 2
// ...
int32_t* ptr = &number;
context.TryGetValue<int32_t*>(RetryKey, ptr);
return *ptr;
}
std::unique_ptr<RawResponse> RetryPolicy::Send(
Request& request,
NextHttpPolicy nextPolicy,
Context const& context) const
{
using Azure::Core::Diagnostics::Logger;
using Azure::Core::Diagnostics::_internal::Log;
// retryCount needs to be apart from RetryNumber attempt.
int32_t retryCount = 0;
auto retryContext = context.WithValue(RetryKey, &retryCount);
for (int32_t attempt = 1;; ++attempt)
{
std::chrono::milliseconds retryAfter{};
request.StartTry();
// creates a copy of original query parameters from request
auto originalQueryParameters = request.GetUrl().GetQueryParameters();
try
{
auto response = nextPolicy.Send(request, retryContext);
// If we are out of retry attempts, if a response is non-retriable (or simply 200 OK, i.e
// doesn't need to be retried), then ShouldRetry returns false.
if (!ShouldRetryOnResponse(*response.get(), m_retryOptions, attempt, retryAfter))
{
// If this is the second attempt and StartTry was called, we need to stop it. Otherwise
// trying to perform same request would use last retry query/headers
return response;
}
}
catch (const TransportException& e)
{
if (Log::ShouldWrite(Logger::Level::Warning))
{
Log::Write(Logger::Level::Warning, std::string("HTTP Transport error: ") + e.what());
}
if (!ShouldRetryOnTransportFailure(m_retryOptions, attempt, retryAfter))
{
throw;
}
}
if (Log::ShouldWrite(Logger::Level::Informational))
{
std::ostringstream log;
log << "HTTP Retry attempt #" << attempt << " will be made in "
<< std::chrono::duration_cast<std::chrono::milliseconds>(retryAfter).count() << "ms.";
Log::Write(Logger::Level::Informational, log.str());
}
// Sleep(0) behavior is implementation-defined: it may yield, or may do nothing. Let's make sure
// we proceed immediately if it is 0.
if (retryAfter.count() > 0)
{
// Before sleeping, check to make sure that the context hasn't already been cancelled.
context.ThrowIfCancelled();
std::this_thread::sleep_for(retryAfter);
}
// Restore the original query parameters before next retry
request.GetUrl().SetQueryParameters(std::move(originalQueryParameters));
// Update retry number
retryCount += 1;
}
}
bool RetryPolicy::ShouldRetryOnTransportFailure(
RetryOptions const& retryOptions,
int32_t attempt,
std::chrono::milliseconds& retryAfter,
double jitterFactor) const
{
// Are we out of retry attempts?
if (WasLastAttempt(retryOptions, attempt))
{
return false;
}
retryAfter = CalculateExponentialDelay(retryOptions, attempt, jitterFactor);
return true;
}
bool RetryPolicy::ShouldRetryOnResponse(
RawResponse const& response,
RetryOptions const& retryOptions,
int32_t attempt,
std::chrono::milliseconds& retryAfter,
double jitterFactor) const
{
using Azure::Core::Diagnostics::Logger;
using Azure::Core::Diagnostics::_internal::Log;
// Are we out of retry attempts?
if (WasLastAttempt(retryOptions, attempt))
{
return false;
}
// Should we retry on the given response retry code?
{
auto const& statusCodes = retryOptions.StatusCodes;
auto const sc = response.GetStatusCode();
if (statusCodes.find(sc) == statusCodes.end())
{
if (Log::ShouldWrite(Logger::Level::Informational))
{
Log::Write(
Logger::Level::Informational,
std::string("HTTP status code ") + std::to_string(static_cast<int>(sc))
+ " won't be retried.");
}
return false;
}
else if (Log::ShouldWrite(Logger::Level::Informational))
{
Log::Write(
Logger::Level::Informational,
std::string("HTTP status code ") + std::to_string(static_cast<int>(sc))
+ " will be retried.");
}
}
if (!GetResponseHeaderBasedDelay(response, retryAfter))
{
retryAfter = CalculateExponentialDelay(retryOptions, attempt, jitterFactor);
}
return true;
}
| true |
11f171035c04bffe4850462b6b14845c1220c0ea | C++ | bitcpf/JH2018 | /arista/sizeprint.cpp | UTF-8 | 320 | 3.15625 | 3 | [] | no_license |
#include <stdio.h>
#include <string.h>
/* Find the size */
int main() {
const char *s1 = "hello";
char *s3 = "hello";
char s2[] = "world";
printf( "sizeof s1 : %ld sizeof s2 : %ld\n", sizeof(s1), sizeof(s2) );
printf( "sizeof s3 : %ld\n", sizeof(s3) );
printf( "lenof s2 : %ld\n", strlen(s2) );
}
| true |
ed7729c252cbbc0ac8433ad85cf4379afea36a6b | C++ | HoogDooo/MoravaEngine | /MoravaEngine/src/Hazel/Renderer/HazelImage.h | UTF-8 | 1,711 | 2.609375 | 3 | [
"Apache-2.0"
] | permissive | #pragma once
#include "Hazel/Core/Base.h"
#include "Hazel/Core/Buffer.h"
#include "Hazel/Core/Ref.h"
namespace Hazel {
enum class HazelImageFormat
{
None = 0,
RGB,
RGBA,
RGBA16F,
RGBA32F,
RG32F,
SRGB,
DEPTH32F,
DEPTH24STENCIL8,
// Defaults
Depth = DEPTH24STENCIL8
};
class HazelImage : public RefCounted
{
public:
virtual ~HazelImage() {}
virtual void Invalidate() = 0;
virtual void Release() = 0;
virtual uint32_t GetWidth() const = 0;
virtual uint32_t GetHeight() const = 0;
virtual HazelImageFormat GetFormat() const = 0;
virtual Buffer GetBuffer() const = 0;
virtual Buffer& GetBuffer() = 0;
virtual uint64_t GetHash() const = 0;
// TODO: usage (eg. shader read)
};
class HazelImage2D : public HazelImage
{
public:
static Ref<HazelImage2D> Create(HazelImageFormat format, uint32_t width, uint32_t height, Buffer buffer);
static Ref<HazelImage2D> Create(HazelImageFormat format, uint32_t width, uint32_t height, const void* data = nullptr);
};
namespace Utils {
inline uint32_t GetImageFormatBPP(HazelImageFormat format)
{
switch (format)
{
case HazelImageFormat::RGB:
case HazelImageFormat::SRGB: return 3;
case HazelImageFormat::RGBA: return 4;
case HazelImageFormat::RGBA16F: return 2 * 4;
case HazelImageFormat::RGBA32F: return 4 * 4;
}
HZ_CORE_ASSERT(false);
return 0;
}
inline uint32_t CalculateMipCount(uint32_t width, uint32_t height)
{
return (uint32_t)std::floor(std::log2(glm::min(width, height))) + 1;
}
inline uint32_t GetImageMemorySize(HazelImageFormat format, uint32_t width, uint32_t height)
{
return width * height * GetImageFormatBPP(format);
}
}
}
| true |
c6309fe02dbb033e8208fe044dbfc901353cacff | C++ | NicolasVelasquez99/Practica3 | /Punto 1/Mes.h | UTF-8 | 405 | 3.046875 | 3 | [] | no_license | /*
* Cabecera objeto Mes
*/
#ifndef MES_H
#define MES_H
#include <string>
using std::string;
class Mes{
private:
string nombreMes;
int numeroMes;
public:
Mes(string nombreM, int numeroM);
~Mes();
string getNombreMes();
int getNumeroMes();
void setNombreMes(string nombreM);
void setNumeroMes(int numeroM);
};
#endif // MES_H
| true |
8e3d70ffb766b04fe1b404a17e36063e5bfb2be0 | C++ | vinx13/naivedb | /src/file.cpp | UTF-8 | 1,556 | 2.828125 | 3 | [
"BSD-3-Clause"
] | permissive | #include "file.h"
namespace naivedb {
FileMgr::FileMgr(const std::string &prefix) : prefix_(prefix) {
}
FileMgr::~FileMgr() {
closeAllFiles();
}
void FileMgr::openAllFiles(int num_files) {
for (int i = 1; i <= num_files; i++) {
files_.push_back(new MemoryMappedFile(getFileName(i)));
// TODO: check existence
}
}
void FileMgr::closeAllFiles() {
for (MemoryMappedFile *file:files_) {
file->close();
delete file;
}
files_.clear();
}
std::string FileMgr::getFileName(int file_no) {
return prefix_ + std::to_string(file_no);
}
FileHeader *FileMgr::getFileHeader() {
void *p = files_[0]->get();
assert(p);
return reinterpret_cast<FileHeader *>(p);
}
void FileMgr::createFile() {
int file_no = getFileHeader()->num_files;
MemoryMappedFile *file = new MemoryMappedFile(getFileName(file_no));
assert(!file->isExist());
file->create(getFileSize());
files_.push_back(file);
getFileHeader()->num_files++;
initFile(file_no);
}
void *FileMgr::get(const Location &location) {
assert(location.file_no >= 0 && location.file_no < files_.size());
void *p = files_[location.file_no]->get(location.offset);
assert(p);
return p;
}
void FileMgr::init() {
MemoryMappedFile *file = new MemoryMappedFile(getFileName(0));
files_.push_back(file);
if (file->isExist()) {
FileHeader *header = getFileHeader();
openAllFiles(header->num_files);
} else {
file->create(getHeaderSize());
initHeader();
}
}
} | true |
8145a33cd0c4d94c5cab59fcb5774e4b874b7035 | C++ | QuestionC/advent2017 | /advent17.cpp | UTF-8 | 532 | 2.71875 | 3 | [] | no_license | #include "advent.hpp"
#define MAGIC 376
int main (void) {
int len = 1;
int firstVals[MAGIC + 1];
firstVals[0] = 0;
int pos = 0;
for (int i = 1; i <= 50'000'000; ++i) {
int next = (pos + MAGIC) % len + 1;
if (next < MAGIC) {
std::move(firstVals + next, firstVals + MAGIC - 1, firstVals + next + 1);
firstVals[next] = i;
}
pos = next;
++len;
}
DPRINT(firstVals[0]);
DPRINT(firstVals[1]);
DPRINT(firstVals[2]);
return 0;
}
| true |
f92bb31bb9a52302524e09b45631e2595383c9b9 | C++ | ToyotaResearchInstitute/common_robotics_utilities | /include/common_robotics_utilities/cru_namespace.hpp | UTF-8 | 744 | 2.6875 | 3 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | #pragma once
/** Downstream projects can adjust these macros to tweak the project namespace.
When set, they should refer to a C++ inline namespace:
https://en.cppreference.com/w/cpp/language/namespace#Inline_namespaces
The inline namespace provides symbol versioning to allow multiple copies of
common_robotics_utilities to be linked into the same image. In many cases,
the namespace will also be marked hidden so that linker symbols are private.
Example:
#define CRU_NAMESPACE_BEGIN \
inline namespace v1 __attribute__ ((visibility ("hidden"))) {
#define CRU_NAMESPACE_END }
*/
#ifndef CRU_NAMESPACE_BEGIN
# define CRU_NAMESPACE_BEGIN inline namespace v1 {
#endif
#ifndef CRU_NAMESPACE_END
# define CRU_NAMESPACE_END }
#endif
| true |
f534d12b4627198acf7e665d7765be8256b46fee | C++ | Sikurity/StudyAlgorithm | /Normal/2156_DrinkWine.cpp | UTF-8 | 847 | 2.890625 | 3 | [] | no_license | /**
* @link https://www.acmicpc.net/problem/2156
* @date 2016. 05. 09 23:04
* @author Sikurity
* @method Dynamic Programming
*/
#include <stdio.h>
#include <string.h>
int N, R;
int W[10000];
int DP[10001][3];
int algorithm(int, int);
int main()
{
int i;
scanf("%d", &N);
R = 0;
memset(DP, 0, sizeof(DP));
for(i = 0 ; i < N ; i++)
scanf("%d", &W[i]);
R = algorithm(N, 0);
printf("%d\n", R);
return 0;
}
int algorithm(int n, int s)
{
int ret, tmp;
ret = 0;
tmp = 0;
if(n < 0)
return 0;
if(DP[n][s])
return DP[n][s];
if(s == 0)
{
ret = algorithm(n - 1, 2);
tmp = algorithm(n - 1, 1);
if(ret < tmp)
ret = tmp;
tmp = algorithm(n - 1, 0);
if(ret < tmp)
ret = tmp;
}
else if(s == 1)
ret = algorithm(n - 1, 0) + W[n];
else if(s == 2)
ret = algorithm(n - 1, 1) + W[n];
return DP[n][s] = ret;
} | true |
c68a1a5f4708f888ec1d69a1019e812414c362da | C++ | Pappskiva/Lean | /Lean/SentenceClass.cpp | ISO-8859-1 | 8,300 | 2.53125 | 3 | [] | no_license | #include "SentenceClass.h"
#define WBOX(x) MessageBox(NULL, x, L"Application Error!!", MB_OK | MB_ICONASTERISK);
SentenceClass::SentenceClass()
{
mFont = 0;
mFontShader = 0;
mSentence = 0;
}
SentenceClass::~SentenceClass()
{
}
bool SentenceClass::Initialize(D3D* d3d, const char* alignment, float letterScale, int sentenceMaxLength, int screenWidth, int screenHeight)
{
bool result;
mPosX = 0;
mPosY = 0;
mLetterScale = letterScale;
mScreenWidth = screenWidth;
mScreenHeight = screenHeight;
mBaseViewMatrix = m4(1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 1, 1);
if (alignment == "center")
{
mAlignment = ALIGNMENT_CENTER;
}
else if (alignment == "right")
{
mAlignment = ALIGNMENT_RIGHT;
}
else if (alignment == "vertical")
{
mAlignment = ALIGNMENT_VERTICAL;
}
else
{
mAlignment = ALIGNMENT_LEFT; // Left som default
}
// Skapa font objektet
mFont = new FontClass;
if (!mFont)
{
return false;
}
// Initialisera font objektet
result = mFont->Initialize(d3d, "data/fontdata_picross.txt", L"data/font_picross.png", letterScale, mAlignment);
if (!result)
{
return false;
}
// Skapa och initiera fontShaderClass objekt
D3D11_INPUT_ELEMENT_DESC fontShaderElem[] =
{
{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 },
};
mFontShader = d3d->LoadVertexShader(ShaderInfo("shader/font.vs", "FontVertexShader", "vs_4_0"),
fontShaderElem,
2);
if (!mFontShader)
{
return false;
}
if (!d3d->LoadShaderStageIntoShader(ShaderInfo("shader/font.ps", "FontPixelShader", "ps_4_0"),
mFontShader,
SVF_PIXELSHADER))
{
return false;
}
// Initialisera meningen
result = InitializeSentence(sentenceMaxLength, d3d);
if (!result)
{
return false;
}
// Stt default text
result = SetText("0", d3d);
if (!result)
{
return false;
}
return true;
}
void SentenceClass::Shutdown()
{
// Slpp meningen
if (mSentence)
{
if (mSentence->vertexBuffer)
{
mSentence->vertexBuffer->Release();
mSentence->vertexBuffer = 0;
}
if (mSentence->indexBuffer)
{
mSentence->indexBuffer->Release();
mSentence->indexBuffer = 0;
}
delete mSentence;
mSentence = 0;
}
// Slpp font objektet
if (mFont)
{
mFont->Shutdown();
mFont = 0;
}
// Slpp shader objektet
if (mFontShader)
{
mFontShader->Flush();
mFontShader = 0;
}
}
void SentenceClass::Render(D3D* d3d)
{
m4 worldMatrix, orthoMatrix;
q4 pixelColor;
unsigned int stride = sizeof(Vertex);
unsigned int offset = 0;
d3d->GetDeviceContext()->IASetVertexBuffers(0, 1, &mSentence->vertexBuffer, &stride, &offset);
d3d->GetDeviceContext()->IASetIndexBuffer(mSentence->indexBuffer, DXGI_FORMAT_R32_UINT, 0);
d3d->GetDeviceContext()->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
// Hmta matriser
d3d->GetWorldMatrix(worldMatrix);
d3d->GetOrthoMatrix(orthoMatrix);
// Stt frgvrden fr textfrgen
pixelColor = q4(1.0f, mSentence->red, mSentence->green, mSentence->blue); // ARGB i q4 ????
// Translatera texten
if (mAlignment == ALIGNMENT_CENTER)
{
worldMatrix = worldMatrix * m4::CreateTranslation(v3(mPosX - (20 * mLetterScale * mSentenceLength / 2), -mPosY, 0));
}
else if (mAlignment == ALIGNMENT_RIGHT)
{
worldMatrix = worldMatrix * m4::CreateTranslation(v3(mPosX - (20 * mLetterScale * mSentenceLength), -mPosY, 0));
}
else
{
worldMatrix = worldMatrix * m4::CreateTranslation(v3(mPosX, -mPosY, 0));
}
// Stt shader variabler
mFontShader->SetVariable("worldMatrix", &worldMatrix, sizeof(m4));
mFontShader->SetVariable("viewMatrix", &mBaseViewMatrix, sizeof(m4));
mFontShader->SetVariable("projectionMatrix", &orthoMatrix, sizeof(m4));
mFontShader->SetVariable("pixelColor", &pixelColor, sizeof(q4));
d3d->SetShader(mFontShader);
d3d->ApplyConstantBuffers();
d3d->ApplyTexture(mFont->GetTexture(), 0);
d3d->GetDeviceContext()->DrawIndexed(mSentence->indexCount, 0, 0);
}
bool SentenceClass::SetText(char* text, D3D* d3d)
{
int numLetters;
Vertex* vertices;
float drawX, drawY;
HRESULT result;
D3D11_MAPPED_SUBRESOURCE mappedResource;
Vertex* verticesPtr;
// Kolla s textlngden inte verskrider bufferstorleken
numLetters = (int)strlen(text);
if (numLetters > mSentence->maxLength)
{
WBOX(L"Buffer overflow! Sentence too long.");
return false;
}
else
{
// Spara lngden p meningen
mSentenceLength = numLetters;
}
// Skapa och initialisera vertex arrayen
vertices = new Vertex[mSentence->vertexCount];
if (!vertices)
{
return false;
}
memset(vertices, 0, (sizeof(Vertex)* mSentence->vertexCount));
// Rkna ut pixel positionen att brja rita till (vre vnstra hrnet)
drawX = (float)(((mScreenWidth / 2) * -1) + 0);
drawY = (float)((mScreenHeight / 2) - 0);
// Bygg upp meningen
mFont->BuildVertexArray((void*)vertices, text, drawX, drawY);
// Ls vertex buffern s den kan skrivas till
result = d3d->GetDeviceContext()->Map(mSentence->vertexBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
if (FAILED(result))
{
return false;
}
// F en pekare till datan i vertex buffern
verticesPtr = (Vertex*)mappedResource.pData;
// Kopiera datan till vertex buffern
memcpy(verticesPtr, (void*)vertices, (sizeof(Vertex)* mSentence->vertexCount));
// Ls upp vertex buffern
d3d->GetDeviceContext()->Unmap(mSentence->vertexBuffer, 0);
delete[] vertices;
vertices = 0;
// Stt den nya positionen
//SetPosition(mPosX, mPosY);
return true;
}
void SentenceClass::SetPosition(int posX, int posY)
{
this->mPosX = posX;
this->mPosY = posY;
}
void SentenceClass::SetColor(float r, float g, float b)
{
this->mSentence->red = r;
this->mSentence->green = g;
this->mSentence->blue = b;
}
float SentenceClass::GetLetterScale() const
{
return this->mLetterScale;
}
void SentenceClass::OffsetPosition(int xOffset, int yOffset)
{
this->mPosX += xOffset;
this->mPosY += yOffset;
}
bool SentenceClass::InitializeSentence(int maxLength, D3D* d3d)
{
Vertex* vertices;
unsigned long* indices;
D3D11_BUFFER_DESC vertexBufferDesc, indexBufferDesc;
D3D11_SUBRESOURCE_DATA vertexData, indexData;
HRESULT result;
// Skapa Sentence objektet
mSentence = new Sentence;
if (!mSentence)
{
return false;
}
// Stt default frg
this->mSentence->red = 1.0f;
this->mSentence->green = 1.0f;
this->mSentence->blue = 1.0f;
// Initialisera Sentence variablerna
mSentence->vertexBuffer = 0;
mSentence->indexBuffer = 0;
mSentence->maxLength = maxLength;
mSentence->vertexCount = 6 * maxLength;
mSentence->indexCount = mSentence->vertexCount;
// Skapa vertex arrayen
vertices = new Vertex[mSentence->vertexCount];
if (!vertices)
{
return false;
}
// Skapa index arrayen
indices = new unsigned long[mSentence->indexCount];
if (!indices)
{
return false;
}
// Initialisera vertex arrayen
memset(vertices, 0, (sizeof(Vertex)* mSentence->vertexCount));
// Initialisera index arrayen
for (int i = 0; i < mSentence->indexCount; i++)
{
indices[i] = i;
}
vertexBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
vertexBufferDesc.ByteWidth = sizeof(Vertex)* mSentence->vertexCount;
vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
vertexBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
vertexBufferDesc.MiscFlags = 0;
vertexBufferDesc.StructureByteStride = 0;
vertexData.pSysMem = vertices;
vertexData.SysMemPitch = 0;
vertexData.SysMemSlicePitch = 0;
// Skapa vertex buffern
result = d3d->GetDevice()->CreateBuffer(&vertexBufferDesc, &vertexData, &mSentence->vertexBuffer);
if (FAILED(result))
{
return false;
}
indexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
indexBufferDesc.ByteWidth = sizeof(unsigned long)* mSentence->indexCount;
indexBufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;
indexBufferDesc.CPUAccessFlags = 0;
indexBufferDesc.MiscFlags = 0;
indexBufferDesc.StructureByteStride = 0;
indexData.pSysMem = indices;
indexData.SysMemPitch = 0;
indexData.SysMemSlicePitch = 0;
// Skapa index buffern
result = d3d->GetDevice()->CreateBuffer(&indexBufferDesc, &indexData, &mSentence->indexBuffer);
if (FAILED(result))
{
return false;
}
delete[] vertices;
vertices = 0;
delete[] indices;
indices = 0;
return true;
} | true |
1d84e806a9f002da82756ceab39684cf8ad0b285 | C++ | 11l-lang/_11l_to_cpp | /tests/python_to_cpp/Shed Skin Examples/9.yopyra.cpp | UTF-8 | 16,318 | 2.640625 | 3 | [
"MIT"
] | permissive | #include "C:\!!BITBUCKET\11l-lang\_11l_to_cpp\11l.hpp"
auto MAX_DIST = 1999999999.0;
auto PI_SOBRE_180 = 0.017453292;
auto PEQUENO = 0.000000001;
class Vector
{
public:
double x;
double y;
double z;
template <typename T1 = decltype(0.0), typename T2 = decltype(0.0), typename T3 = decltype(0.0)> Vector(const T1 &vx = 0.0, const T2 &vy = 0.0, const T3 &vz = 0.0)
{
assign_from_tuple(x, y, z, make_tuple(vx, vy, vz));
}
template <typename T1> auto pEscalar(const T1 &vv)
{
return (x * vv.x + y * vv.y + z * vv.z);
}
template <typename T1> auto pVectorial(const T1 &vv)
{
auto r = Vector();
r.x = vv.y * z - vv.z * y;
r.y = vv.z * x - vv.x * z;
r.z = vv.x * y - vv.y * x;
return r;
}
auto modulo()
{
return sqrt(x * x + y * y + z * z);
}
auto normalizar()
{
auto m = modulo();
if (m != 0.0) {
x /= m;
y /= m;
z /= m;
}
return *this;
}
template <typename T1> auto operator+(const T1 &other) const
{
return Vector(x + other.x, y + other.y, z + other.z);
}
template <typename Ty> auto &operator+=(const Ty &t)
{
*this = *this + t;
return *this;
}
template <typename T1> auto operator-(const T1 &other) const
{
return Vector(x - other.x, y - other.y, z - other.z);
}
template <typename Ty> auto &operator-=(const Ty &t)
{
*this = *this - t;
return *this;
}
template <typename T1> auto operator*(const T1 &other) const
{
return Vector(x * other, y * other, z * other);
}
template <typename Ty> auto &operator*=(const Ty &t)
{
*this = *this * t;
return *this;
}
};
class Color
{
public:
double r;
double g;
double b;
template <typename T1 = decltype(0.0), typename T2 = decltype(0.0), typename T3 = decltype(0.0)> Color(const T1 &vr = 0.0, const T2 &vg = 0.0, const T3 &vb = 0.0)
{
assign_from_tuple(r, g, b, make_tuple(vr, vg, vb));
}
template <typename T1> auto operator+(const T1 &other) const
{
return Color(r + other.r, g + other.g, b + other.b);
}
template <typename Ty> auto &operator+=(const Ty &t)
{
*this = *this + t;
return *this;
}
template <typename T1> auto operator*(const T1 &other) const
{
return Color(r * other, g * other, b * other);
}
template <typename Ty> auto &operator*=(const Ty &t)
{
*this = *this * t;
return *this;
}
operator String() const
{
return u"#. #. #."_S.format(to_int(max(0.0, min(r * 255.0, 255.0))), to_int(max(0.0, min(g * 255.0, 255.0))), to_int(max(0.0, min(b * 255.0, 255.0))));
}
};
class Luz
{
public:
Vector posicion;
Color color;
String tipo;
template <typename T1, typename T2, typename T3> Luz(const T1 &posicion, const T2 &color, const T3 &tipo) :
posicion(posicion),
color(color),
tipo(tipo)
{
}
};
class Material
{
public:
Color color;
double cDifuso;
double cEspecular;
double dEspecular;
double cReflexion;
double cTransmitividad;
double iRefraccion;
template <typename T1, typename T2 = decltype(0.0), typename T3 = decltype(0.0), typename T4 = decltype(0.0), typename T5 = decltype(0.0), typename T6 = decltype(0.0), typename T7 = decltype(0.0)> Material(const T1 &color, const T2 &cDifuso = 0.0, const T3 &cEspecular = 0.0, const T4 &dEspecular = 0.0, const T5 &cReflexion = 0.0, const T6 &cTransmitividad = 0.0, const T7 &iRefraccion = 0.0) :
color(color),
cDifuso(cDifuso),
cEspecular(cEspecular),
dEspecular(dEspecular),
cReflexion(cReflexion),
cTransmitividad(cTransmitividad),
iRefraccion(iRefraccion)
{
}
};
class Cuerpo;
class Rayo
{
public:
Vector origen;
Vector direccion;
double disInter;
Cuerpo *objInter;
template <typename T1, typename T2> Rayo(const T1 &origen, const T2 &direccion) :
origen(origen),
direccion(direccion)
{
disInter = ::MAX_DIST;
objInter = nullptr;
}
};
class Cuerpo
{
public:
String tipo;
int material;
template <typename T1, typename T2> auto init(const T1 &tipo, const T2 &material)
{
this->tipo = tipo;
this->material = material;
}
virtual bool intersecta(Rayo &r) = 0;
virtual Vector getNormal(const Vector &punto) = 0;
};
class Esfera : public Cuerpo
{
public:
Vector posicion;
double radio;
template <typename T1, typename T2, typename T3> Esfera(const T1 &material, const T2 &posicion, const T3 &radio) :
posicion(posicion),
radio(radio)
{
init(u"esfera"_S, material);
}
virtual bool intersecta(Rayo &r) override
{
auto esfera_rayo = posicion - r.origen;
auto v = esfera_rayo.pEscalar(r.direccion);
if (v - radio > r.disInter)
return false;
auto distChoque = radio * radio + v * v - esfera_rayo.x * esfera_rayo.x - esfera_rayo.y * esfera_rayo.y - esfera_rayo.z * esfera_rayo.z;
if (distChoque < 0.0)
return false;
distChoque = v - sqrt(distChoque);
if (distChoque > r.disInter || distChoque < 0.0)
return false;
r.disInter = distChoque;
r.objInter = &*this;
return true;
}
virtual Vector getNormal(const Vector &punto) override
{
auto normal = punto - posicion;
return normal.normalizar();
}
};
class Plano : public Cuerpo
{
public:
Vector normal;
double distancia;
template <typename T1, typename T2, typename T3> Plano(const T1 &material, const T2 &normal, const T3 &distancia) :
normal(normal),
distancia(distancia)
{
init(u"plano"_S, material);
this->normal.normalizar();
}
virtual bool intersecta(Rayo &r) override
{
auto v = normal.pEscalar(r.direccion);
if (v == 0.0)
return false;
auto distChoque = -(normal.pEscalar(r.origen) + distancia) / v;
if (distChoque < 0.0)
return false;
if (distChoque > r.disInter)
return false;
r.disInter = distChoque;
r.objInter = &*this;
return true;
}
virtual Vector getNormal(const Vector &punto) override
{
return normal;
}
};
class Scene
{
public:
int endline;
Vector posCamara;
Vector lookCamara;
Vector upCamara;
int anchoGrid;
int altoGrid;
Vector look;
Vector Vhor;
Vector Vver;
Vector Vp;
Array<std::unique_ptr<Cuerpo>> lObjetos;
Array<Luz> lLuces;
Array<Material> lMateriales;
decltype(320) imgAncho = 320;
decltype(200) imgAlto = 200;
decltype(3) profTrazado = 3;
decltype(1) oversampling = 1;
decltype(60.0) campoVision = 60.0;
decltype(0) startline = 0;
template <typename T1> Scene(const T1 &scene_filename)
{
auto lines = File(scene_filename).read_lines(true).filter([](const auto &l){return l.trim(make_tuple(u" "_S, u"\t"_S, u"\r"_S, u"\n"_S)) != u"" && _get<0>(l.trim(make_tuple(u" "_S, u"\t"_S, u"\r"_S, u"\n"_S))) != u'#';}).map([](const auto &l){return l.split_py();});
endline = imgAlto - 1;
for (auto line : lines) {
auto word = _get<0>(line);
line = line[range_ei(1)];
if (word == u"size") {
imgAncho = to_int(_get<0>(line));
imgAlto = to_int(_get<1>(line));
endline = imgAlto - 1;
}
else if (word == u"nbounces")
profTrazado = to_int(_get<0>(line));
else if (word == u"oversampling")
oversampling = to_int(_get<0>(line));
else if (word == u"vision")
campoVision = to_float(_get<0>(line));
else if (word == u"renderslice") {
startline = max(0, to_int(_get<0>(line)));
endline = min(imgAlto - 1, to_int(_get<1>(line)));
}
else if (word == u"posCamara")
posCamara = parse_vector(line);
else if (word == u"lookCamara")
lookCamara = parse_vector(line);
else if (word == u"upCamara")
upCamara = parse_vector(line);
else if (word == u"sphere") {
auto sph = std::make_unique<Esfera>(to_int(_get<0>(line)), parse_vector(line[range_el(1, 4)]), to_float(line.last()));
lObjetos.append(std::move(sph));
}
else if (word == u"plano") {
auto pl = std::make_unique<Plano>(to_int(_get<0>(line)), parse_vector(line[range_el(1, 4)]), to_float(line.last()));
lObjetos.append(std::move(pl));
}
else if (word == u"light") {
auto light = Luz(parse_vector(line[range_el(0, 3)]), parse_color(line[range_el(3, 6)]), line.last());
lLuces.append(light);
}
else if (word == u"material") {
auto mat = parse_material(line);
lMateriales.append(mat);
}
}
anchoGrid = imgAncho * oversampling;
altoGrid = imgAlto * oversampling;
look = lookCamara - posCamara;
Vhor = look.pVectorial(upCamara);
Vhor.normalizar();
Vver = look.pVectorial(Vhor);
Vver.normalizar();
auto fl = anchoGrid / (2 * tan((0.5 * campoVision) * ::PI_SOBRE_180));
auto Vp = look;
Vp.normalizar();
Vp.x = Vp.x * fl - 0.5 * (anchoGrid * Vhor.x + altoGrid * Vver.x);
Vp.y = Vp.y * fl - 0.5 * (anchoGrid * Vhor.y + altoGrid * Vver.y);
Vp.z = Vp.z * fl - 0.5 * (anchoGrid * Vhor.z + altoGrid * Vver.z);
this->Vp = Vp;
}
template <typename T1> auto parse_vector(const T1 &line)
{
return Vector(to_float(_get<0>(line)), to_float(_get<1>(line)), to_float(_get<2>(line)));
}
template <typename T1> auto parse_color(const T1 &line)
{
return Color(to_float(_get<0>(line)), to_float(_get<1>(line)), to_float(_get<2>(line)));
}
template <typename T1> auto parse_material(const T1 &line)
{
auto f = line[range_ei(3)].map([](const auto &x){return to_float(x);});
return Material(parse_color(line[range_el(0, 3)]), _get<0>(f), _get<1>(f), _get<2>(f), _get<3>(f), _get<4>(f), _get<5>(f));
}
};
auto scene_namefile = u"testdata/scene.txt"_S;
auto scene = Scene(scene_namefile);
template <typename T2> auto calculaSombra(Rayo &r, const T2 &objChoque)
{
auto sombra = 1.0;
for (auto &&obj : ::scene.lObjetos) {
r.objInter = nullptr;
r.disInter = ::MAX_DIST;
if (obj->intersecta(r) && &*obj != objChoque)
sombra *= ::scene.lMateriales[obj->material].cTransmitividad;
}
return sombra;
}
template <typename T2> Color trazar(Rayo &r, const T2 &prof)
{
auto c = Color();
for (auto &&obj : ::scene.lObjetos)
obj->intersecta(r);
if (r.objInter != nullptr) {
auto matIndex = r.objInter->material;
auto pInterseccion = r.origen + r.direccion * r.disInter;
auto vIncidente = pInterseccion - r.origen;
auto vVueltaOrigen = r.direccion * -1.0;
vVueltaOrigen.normalizar();
auto vNormal = r.objInter->getNormal(pInterseccion);
for (auto &&luz : ::scene.lLuces)
if (luz.tipo == u"ambiental")
c += luz.color;
else if (luz.tipo == u"puntual") {
auto dirLuz = luz.posicion - pInterseccion;
dirLuz.normalizar();
auto rayoLuz = Rayo(pInterseccion, dirLuz);
auto sombra = calculaSombra(rayoLuz, r.objInter);
auto NL = vNormal.pEscalar(dirLuz);
if (NL > 0.0) {
if (::scene.lMateriales[matIndex].cDifuso > 0.0) {
auto colorDifuso = luz.color * ::scene.lMateriales[matIndex].cDifuso * NL;
colorDifuso.r *= ::scene.lMateriales[matIndex].color.r * sombra;
colorDifuso.g *= ::scene.lMateriales[matIndex].color.g * sombra;
colorDifuso.b *= ::scene.lMateriales[matIndex].color.b * sombra;
c += colorDifuso;
}
if (::scene.lMateriales[matIndex].cEspecular > 0.0) {
auto rr = (vNormal * 2 * NL) - dirLuz;
auto espec = vVueltaOrigen.pEscalar(rr);
if (espec > 0.0) {
espec = ::scene.lMateriales[matIndex].cEspecular * pow(espec, ::scene.lMateriales[matIndex].dEspecular);
auto colorEspecular = luz.color * espec * sombra;
c += colorEspecular;
}
}
}
}
if (prof < ::scene.profTrazado) {
if (::scene.lMateriales[matIndex].cReflexion > 0.0) {
auto t = vVueltaOrigen.pEscalar(vNormal);
if (t > 0.0) {
auto vDirRef = (vNormal * 2 * t) - vVueltaOrigen;
auto vOffsetInter = pInterseccion + vDirRef * ::PEQUENO;
auto rayoRef = Rayo(vOffsetInter, vDirRef);
c += trazar(rayoRef, prof + 1.0) * ::scene.lMateriales[matIndex].cReflexion;
}
}
if (::scene.lMateriales[matIndex].cTransmitividad > 0.0) {
auto RN = vNormal.pEscalar(vIncidente * -1.0);
double n1;
double n2;
vIncidente.normalizar();
if (vNormal.pEscalar(vIncidente) > 0.0) {
vNormal = vNormal * -1.0;
RN = -RN;
n1 = ::scene.lMateriales[matIndex].iRefraccion;
n2 = 1.0;
}
else {
n2 = ::scene.lMateriales[matIndex].iRefraccion;
n1 = 1.0;
}
if (n1 != 0.0 && n2 != 0.0) {
auto par_sqrt = sqrt(1 - (n1 * n1 / n2 * n2) * (1 - RN * RN));
auto vDirRefrac = vIncidente + (vNormal * RN) * (n1 / n2) - (vNormal * par_sqrt);
auto vOffsetInter = pInterseccion + vDirRefrac * ::PEQUENO;
auto rayoRefrac = Rayo(vOffsetInter, vDirRefrac);
c += trazar(rayoRefrac, prof + 1.0) * ::scene.lMateriales[matIndex].cTransmitividad;
}
}
}
}
return c;
}
template <typename T1, typename T2> auto renderPixel(T1 x, T2 y)
{
auto c = Color();
x *= ::scene.oversampling;
y *= ::scene.oversampling;
for (auto i : range_el(0, ::scene.oversampling)) {
for (auto j : range_el(0, ::scene.oversampling)) {
auto direc = Vector();
direc.x = x * ::scene.Vhor.x + y * ::scene.Vver.x + ::scene.Vp.x;
direc.y = x * ::scene.Vhor.y + y * ::scene.Vver.y + ::scene.Vp.y;
direc.z = x * ::scene.Vhor.z + y * ::scene.Vver.z + ::scene.Vp.z;
direc.normalizar();
auto r = Rayo(::scene.posCamara, direc);
c += trazar(r, 1.0);
y++;
}
x++;
}
auto srq_oversampling = ::scene.oversampling * ::scene.oversampling;
c.r /= srq_oversampling;
c.g /= srq_oversampling;
c.b /= srq_oversampling;
return c;
}
int main()
{
print(u"Rendering: "_S & scene_namefile);
auto fileout = File(scene_namefile & u".ppm"_S, u"w"_S);
fileout.write(u"P3\n"_S);
fileout.write(String(scene.imgAncho) & u" "_S & String(scene.endline - scene.startline + 1) & u"\n"_S);
fileout.write(u"255\n"_S);
print(u"Line (from #. to #.):"_S.format(scene.startline, scene.endline), u" "_S);
for (auto y : range_ee(scene.startline, scene.endline)) {
for (auto x : range_el(0, scene.imgAncho))
fileout.write(String(renderPixel(x, y)) & u" "_S);
fileout.write(u"\n"_S);
print(y, u" "_S);
_stdout.flush();
}
}
| true |
9ce19c9fe08be43867a838c16c73d9526c2d68db | C++ | agrawalabhishek/NAOS | /include/NAOS/rk54.hpp | UTF-8 | 12,283 | 2.5625 | 3 | [
"MIT"
] | permissive | /*
* Copyright (c) 2016 Abhishek Agrawal (abhishek.agrawal@protonmail.com)
* Distributed under the MIT License.
* See accompanying file LICENSE.md or copy at http://opensource.org/licenses/MIT
*/
#ifndef RK54_HPP
#define RK54_HPP
#include <vector>
#include <limits>
#include <stdexcept>
#include "NAOS/constants.hpp"
#include "NAOS/ellipsoidGravitationalAcceleration.hpp"
namespace naos
{
//! RK5(4) integrator
/*!
* The RK5(4) integrator routine to integrate a set of
* first order differential equations. The equations have to be provided in a seperate header file
* in a struct. See orbiterEquationsOfMotion.hpp for an example.
*
* @param[in] Xcurrent currently known state vector value i.e. before the integration
* @param[in] t current time value for which the state vector is known
* @param[in] stepSize the step size of integration
* @param[out] Xnext the state vector value after integration i.e. at next time step
* @param[in] derivatives An object of the struct containing the differential equations. The
* object should have already gotten the initializing values before
* passing it to the argument of the function rk4.
*/
template< typename Vector, class orbiterEquationsOfMotion >
void rk54(
Vector &Xcurrent,
const double t,
const double stepSize,
Vector &Xnext,
Vector &delta,
orbiterEquationsOfMotion &derivatives )
{
const double h = stepSize;
const int numberOfElements = Xcurrent.size( );
// declare the coefficients for the RK5(4) algorithm
const std::vector< double > c { 0.0,
1.0 / 5.0,
3.0 / 10.0,
4.0 / 5.0,
8.0 / 9.0,
1.0,
1.0 };
const std::vector< std::vector< double > > a {
{ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 },
{ 1.0 / 5.0, 0.0, 0.0, 0.0, 0.0, 0.0 },
{ 3.0 / 40.0, 9.0 / 40.0, 0.0, 0.0, 0.0, 0.0 },
{ 44.0 / 45.0, -56.0 / 15.0, 32.0 / 9.0, 0.0, 0.0, 0.0 },
{ 19372.0 / 6561.0, -25360.0 / 2187.0, 64448.0 / 6561.0, -212.0 / 729.0, 0.0, 0.0 },
{ 9017.0 / 3168.0, -355.0 / 33.0, 46732.0 / 5247.0, 49.0 / 176.0, -5103.0 / 18656.0, 0.0 },
{ 35.0 / 384.0, 0.0, 500.0 / 1113.0, 125.0 / 192.0, -2187.0 / 6784.0, 11.0 / 84.0 } };
const std::vector< double > b { 35.0 / 384.0,
0.0,
500.0 / 1113.0,
125.0 / 192.0,
-2187.0 / 6784.0,
11.0 / 84.0,
0.0 };
const std::vector< double > bStar { 5179.0 / 57600.0,
0.0,
7571.0 / 16695.0,
393.0 / 640.0,
-92097.0 / 339200.0,
187.0 / 2100.0,
1.0 / 40.0 };
// declare the vector that stores the values for the right hand side of the EOMs
Vector dXdt( numberOfElements );
// Evaluate K1 step in RK5(4) algorithm.
Vector K1( numberOfElements );
derivatives( t, Xcurrent, dXdt );
for( int i = 0; i < numberOfElements; i++ )
{
K1[ i ] = h * dXdt[ i ];
}
// Evaluate K2 step in RK5(4) algorithm.
Vector K2( numberOfElements );
const double t_K2 = t + c[ 1 ] * h;
Vector X_K2( numberOfElements );
for( int i = 0; i < numberOfElements; i++ )
{
X_K2[ i ] = Xcurrent[ i ] + a[ 1 ][ 0 ] * K1[ i ];
}
derivatives( t_K2, X_K2, dXdt );
for( int i = 0; i < numberOfElements; i++ )
{
K2[ i ] = h * dXdt[ i ];
}
// Evaluate K3 step in RK5(4) algorithm.
Vector K3( numberOfElements );
const double t_K3 = t + c[ 2 ] * h;
Vector X_K3( numberOfElements );
for( int i = 0; i < numberOfElements; i++ )
{
X_K3[ i ] = Xcurrent[ i ] + a[ 2 ][ 0 ] * K1[ i ]
+ a[ 2 ][ 1 ] * K2[ i ];
}
derivatives( t_K3, X_K3, dXdt );
for( int i = 0; i < numberOfElements; i++ )
{
K3[ i ] = h * dXdt[ i ];
}
// Evaluate K4 step in RK5(4) algorithm.
Vector K4( numberOfElements );
const double t_K4 = t + c[ 3 ] * h;
Vector X_K4( numberOfElements );
for( int i = 0; i < numberOfElements; i++ )
{
X_K4[ i ] = Xcurrent[ i ] + a[ 3 ][ 0 ] * K1[ i ]
+ a[ 3 ][ 1 ] * K2[ i ]
+ a[ 3 ][ 2 ] * K3[ i ];
}
derivatives( t_K4, X_K4, dXdt );
for( int i = 0; i < numberOfElements; i++ )
{
K4[ i ] = h * dXdt[ i ];
}
// Evaluate K5 step in RK5(4) algorithm.
Vector K5( numberOfElements );
const double t_K5 = t + c[ 4 ] * h;
Vector X_K5( numberOfElements );
for( int i = 0; i < numberOfElements; i++ )
{
X_K5[ i ] = Xcurrent[ i ] + a[ 4 ][ 0 ] * K1[ i ]
+ a[ 4 ][ 1 ] * K2[ i ]
+ a[ 4 ][ 2 ] * K3[ i ]
+ a[ 4 ][ 3 ] * K4[ i ];
}
derivatives( t_K5, X_K5, dXdt );
for( int i = 0; i < numberOfElements; i++ )
{
K5[ i ] = h * dXdt[ i ];
}
// Evaluate K6 step in RK5(4) algorithm.
Vector K6( numberOfElements );
const double t_K6 = t + c[ 5 ] * h;
Vector X_K6( numberOfElements );
for( int i = 0; i < numberOfElements; i++ )
{
X_K6[ i ] = Xcurrent[ i ] + a[ 5 ][ 0 ] * K1[ i ]
+ a[ 5 ][ 1 ] * K2[ i ]
+ a[ 5 ][ 2 ] * K3[ i ]
+ a[ 5 ][ 3 ] * K4[ i ]
+ a[ 5 ][ 4 ] * K5[ i ];
}
derivatives( t_K6, X_K6, dXdt );
for( int i = 0; i < numberOfElements; i++ )
{
K6[ i ] = h * dXdt[ i ];
}
// Final step, evaluate the weighted summation.
for( int i = 0; i < numberOfElements; i++ )
{
Xnext[ i ] = Xcurrent[ i ]
+ b[ 0 ] * K1[ i ]
+ b[ 1 ] * K2[ i ]
+ b[ 2 ] * K3[ i ]
+ b[ 3 ] * K4[ i ]
+ b[ 4 ] * K5[ i ]
+ b[ 5 ] * K6[ i ];
}
// calculate the embedded fourth order solution
Vector XnextStar = Xnext;
for( int i = 0; i < numberOfElements; i++ )
{
XnextStar[ i ] = Xcurrent[ i ]
+ bStar[ 0 ] * K1[ i ]
+ bStar[ 1 ] * K2[ i ]
+ bStar[ 2 ] * K3[ i ]
+ bStar[ 3 ] * K4[ i ]
+ bStar[ 4 ] * K5[ i ]
+ bStar[ 5 ] * K6[ i ];
}
// calculate delta, the difference vector
for( int i = 0; i < numberOfElements; i++ )
{
delta[ i ] = Xnext[ i ] - XnextStar[ i ];
}
}
//! RK54 integrator general wrapper
/*!
* perform the step integration for any set of differential equations using RK54 routine.
*
* @param[in] Xcurrent current known state vector value
* @param[in] t time
* @param[in] stepSize step size of integration
* @param[in] Xnext next or integrated state vector
*/
template< typename Vector, class equationsOfMotion >
void rk54GeneralIntegrator(
Vector &Xcurrent,
const double t,
double &stepSize,
Vector &Xnext,
equationsOfMotion derivatives,
bool &stepReject,
double &previousErrorValue )
{
// specify tolerance values
const double absoluteTolerance = 10.0e-4;
const double relativeTolerance = 10.0e-9;
// run the step integrator for using rk54 routine
bool coldStart = true;
// Declare the output variables
const double numberOfElements = Xcurrent.size( );
Vector integratedState( numberOfElements );
Vector delta( numberOfElements );
// declare the error storing variable
double errorValue = 0.0;
// set safety factor, and max and min scaling factors for scaling the step size
const double safetyFactor = 0.8;
// new step size should not increase or decrease by a factor of 10 or 0.5 respectively.
const double maxScale = 4.0;
const double minScale = 0.1;
double scalingFactor = 0.0;
// terms to be used in the PI adaptive step size control algorithm
const double alphaExponent = 1.0 / 5.0;
const double betaExponent = 0.04;
double oldErrorValue = previousErrorValue; // from previous integration step
const double eps = 10.0 * std::numeric_limits< double >::epsilon( );
while( coldStart || stepReject )
{
coldStart = false;
if( stepSize < eps )
{
std::ostringstream errorMessage;
errorMessage << std::endl;
errorMessage << "ERROR: step size underflow!" << std::endl;
errorMessage << std::endl;
throw std::runtime_error( errorMessage.str( ) );
}
rk54< Vector, equationsOfMotion >( Xcurrent,
t,
stepSize,
integratedState,
delta,
derivatives );
// compute the error
Vector scale( numberOfElements );
double sum = 0.0;
for( int i = 0; i < numberOfElements; i++ )
{
scale[ i ] = absoluteTolerance
+ relativeTolerance * std::max( Xcurrent[ i ], integratedState[ i ] );
sum += ( delta[ i ] / scale[ i ] ) * ( delta[ i ] / scale[ i ] );
}
errorValue = std::sqrt( sum / numberOfElements );
// check if error is <= 1.0
if( errorValue <= 1.0 )
{
// accept the step
stepReject = false;
// calculate the stepsize value for the next integration step
if( errorValue == 0.0 )
{
// choose the maximum scaling factor for the next step size
scalingFactor = maxScale;
}
else
{
// choose the scaling factor as per equation 17.2.12 in numerical recipes in C book
scalingFactor = safetyFactor * std::pow( ( 1.0 / errorValue ), alphaExponent )
* std::pow( oldErrorValue, betaExponent );
if( scalingFactor < minScale )
{
scalingFactor = minScale;
}
if( scalingFactor > maxScale )
{
scalingFactor = maxScale;
}
}
// if the previous step was rejected, the new step size for the next integration step
// should not be increased
if( stepReject )
{
scalingFactor = std::min( scalingFactor, 1.0 );
stepSize = stepSize * scalingFactor;
stepReject = false;
break; // exit the while loop and return the integrated state
}
else
{
// choose the next step size
stepSize = stepSize * scalingFactor;
stepReject = false;
break; // exit the while loop and return the integrated state
}
}
else
{
// truncation error is large, redo the integration step with a reduced step size value
stepReject = true;
scalingFactor = safetyFactor * std::pow( ( 1.0 / errorValue ), alphaExponent );
// scaling factor of the step size shouldn't go below the min value
scalingFactor = std::max( scalingFactor, minScale );
stepSize = stepSize * scalingFactor;
}
} // break in while loop leads here
previousErrorValue = errorValue;
// give back the final result
Xnext = integratedState;
}
} // namespace naos
#endif // RK54_HPP
| true |
a2f51238d7547bb180539258b54036f048de66b7 | C++ | luluci/lulib | /libs/type_traits/is_instance_of_1.cpp | UTF-8 | 781 | 2.921875 | 3 | [] | no_license |
#include <lulib/type_traits/is_instance_of.hpp>
template<typename T, typename U>
struct test1 {};
template<typename T, std::size_t S, typename U>
struct test2 {};
namespace hoge {
LULIB_GENERATE_IS_INSTANCE_OF(
(typename X, typename Y),
test1,
(X,Y)
)
}
namespace huga {
LULIB_GENERATE_IS_INSTANCE_OF(
(typename X, std::size_t S, typename Y),
test2,
(X,S,Y)
)
}
#include <iostream>
template<typename T>
void func() {
std::cout << hoge::is_instance_of_test1<T>::value << std::endl;
}
template<typename T>
void func2() {
std::cout << huga::is_instance_of_test2<T>::value << std::endl;
}
int main() {
std::cout << std::boolalpha;
func< test1<int,char> >();
func< test2<int,2,short> >();
func2< test1<int,char> >();
func2< test2<int,2,short> >();
}
| true |
3b7829614498d1239451cf54222b10cac9cf7180 | C++ | jimmybeckett/BigInteger | /src/operators/modulus.cpp | UTF-8 | 610 | 2.65625 | 3 | [] | no_license | #include "../../include/BigInteger.h"
#include <math.h>
namespace euler {
BigInteger BigInteger::operator%(const BigInteger& other) const {
if (*this == other || *this == BigInteger (0))
return BigInteger (0);
if (other == BigInteger (0))
return BigInteger (0); //Throw exception
if (other == BigInteger (2))
return BigInteger((*this)[this->digits() - 1] % 2);
BigInteger remainder;
this->abs().divideAndRemainder(other.abs(), remainder);
remainder.isNegative = *this < BigInteger (0);
return remainder;
}
}
| true |
e9bd2d71471e52b3ae042b9bb1aa74bf20d9af3b | C++ | ArpitSingla/LeetCode | /Dynamic Programming/338. Counting Bits.cpp | UTF-8 | 573 | 2.875 | 3 | [] | no_license | class Solution {
public:
vector<int> countBits(int num) {
vector<int> ans(num+1,0);
ans[0]=0;
if(num==0){
return ans;
}
int count=0;
int count1=count-1;
for(int i=1;i<=num;i++){
int temp=pow(2,count);
if(i==temp){
count++;
count1++;
ans[i]=1;
}
else{
int var=pow(2,count1);
ans[i]=ans[i-var]+1;
}
}
return ans;
}
};
| true |
2d85af1ccc428b61d98b831b0d13eaf37aba8f21 | C++ | KeiHasegawa/ISO_IEC_14882 | /10_Derived_classes/0_Derived_classes/test013.cpp | UTF-8 | 384 | 3.53125 | 4 | [] | no_license | #include <stdio.h>
struct A {
int a;
int f(){ return a; }
};
struct B {
int b;
int f(){ return b; }
};
struct C : public A, public B {
int f(){ return A::f() + B::f(); }
};
int main()
{
C x;
x.a = 1;
x.b = 2;
printf("x.f() return value : %d\n", x.f());
x.a = 3;
x.b = 4;
printf("x.f() return value : %d\n", x.f());
return 0;
}
| true |
65b1ea769921f0d1e263ff913780d26f2e2f2a94 | C++ | RussianKreker/Laba_2_4sem | /Laba_2_4sem/RBTree.h | UTF-8 | 2,689 | 2.984375 | 3 | [] | no_license | #ifndef RBTree_H
#define RBTree_H
#include"NodeBRTree.h"
#include"stack.h"
#include"List.h"
#include"List_Huffman.h"
#include"queue.h"
class RBTree
{
public:
RBTree()
{
Root = NULL;
}
~RBTree()
{
clear();
Root = nullptr;
}
Node* Root;
void clear()
{
preorder(Root);
Root = nullptr;
}
void preorder(Node* node)
{
if (node == nullptr) return;
preorder(node->Lnext);
preorder(node->Rnext);
delete node;
}
List<std::string>* get_keys()
{
if (Root == NULL) {
throw("There is no element");
}
stack stackKey;
List<std::string>* listKey = new List<std::string>;
stackKey.push(Root);
bool flag = true;
Node* temp = stackKey.head->date;
while (!stackKey.isEmpty())
{
listKey->push_back(temp->key);
if (temp->Rnext != NULL)
{
if (flag) {
stackKey.pop_front();
flag = false;
}
stackKey.push(temp->Rnext);
}
if (temp->Lnext != NULL)
{
temp = temp->Lnext;
}
else
{
if (flag) {
stackKey.pop_front();
}
if (!stackKey.isEmpty())
{
temp = stackKey.head->date;
}
flag = true;
}
}
return listKey;
}
List<char>* get_values()
{
if (Root == NULL)
{
throw("There is no element");
}
stack stackValue;
List<char>* listValue = new List<char>;
stackValue.push(Root);
bool flag = true;
Node* temp = stackValue.head->date;
while (!stackValue.isEmpty())
{
listValue->push_back(temp->word);
if (temp->Rnext != NULL)
{
if (flag) {
stackValue.pop_front();
flag = false;
}
stackValue.push(temp->Rnext);
}
if (temp->Lnext != NULL)
{
temp = temp->Lnext;
}
else
{
if (flag)
{
stackValue.pop_front();
}
if (!stackValue.isEmpty())
{
temp = stackValue.head->date;
}
flag = true;
}
}
return listValue;
}
List<int>* get_count()
{
if (Root == NULL)
{
throw("There is no element");
}
stack stackValue;
List<int>* listValue = new List<int>;
stackValue.push(Root);
bool flag = true;
Node* temp = stackValue.head->date;
while (!stackValue.isEmpty())
{
listValue->push_back(temp->count);
if (temp->Rnext != NULL)
{
if (flag)
{
stackValue.pop_front();
flag = false;
}
stackValue.push(temp->Rnext);
}
if (temp->Lnext != NULL)
{
temp = temp->Lnext;
}
else
{
if (flag)
{
stackValue.pop_front();
}
if (!stackValue.isEmpty())
{
temp = stackValue.head->date;
}
flag = true;
}
}
return listValue;
}
void create(queue* priority_queue);
void Huffman(List_Hu* Huffman_table);
void coding(Node* node,std::string& key);
};
#endif | true |
4119b89887cda24f23d2564d007d4b81341c8553 | C++ | gsemac/hvn3-engine | /hvn3/include/hvn3/math/GeometryUtils.h | UTF-8 | 17,409 | 2.84375 | 3 | [] | no_license | #pragma once
#include "hvn3/math/Rectangle.h"
#include "hvn3/math/Circle.h"
#include "hvn3/math/Line.h"
#include "hvn3/math/Vector2d.h"
#include "hvn3/math/MathUtils.h"
#include <hvn3/utility/BitFlags.h>
#include <array>
#include <functional>
#include <utility>
namespace hvn3 {
namespace Math {
namespace Geometry {
enum class CohenSutherlandOutCode {
Inside = 0b0000,
Left = 0b0001,
Right = 0b0010,
Bottom = 0b0100,
Top = 0b1000
};
ENABLE_BITFLAG_OPERATORS(CohenSutherlandOutCode);
struct CommonTangentsResult {
CommonTangentsResult() : Tangents{
LineF(0.0f, 0.0f, 0.0f, 0.0f),
LineF(0.0f, 0.0f, 0.0f, 0.0f),
LineF(0.0f, 0.0f, 0.0f, 0.0f),
LineF(0.0f, 0.0f, 0.0f, 0.0f),
},
Count(0) {}
LineF Tangents[4];
size_t Count;
};
template<typename ValueType, int SIZE>
struct IntersectionPointsResult {
typedef std::array<Point2d<ValueType>, SIZE> array_type;
bool infinite;
int count;
array_type points;
IntersectionPointsResult() {
infinite = false;
count = 0;
}
typename array_type::const_iterator begin() const {
return points.begin();
}
typename array_type::const_iterator end() const {
return points.begin() + (std::min(count, SIZE));
}
explicit operator bool() const {
return count > 0 || infinite;
}
};
// Returns the distance squared between two points.
template <typename T>
T PointDistanceSquared(const Point2d<T>& a, const Point2d<T>& b) {
T dx = b.X() - a.X();
T dy = b.Y() - a.Y();
return dx * dx + dy * dy;
}
// Returns the distance squared between a point and a rectangle.
float PointDistanceSquared(const PointF& point, const RectangleF& rectangle);
// Returns the distance between two points.
template <typename T>
T PointDistance(const Point2d<T>& a, const Point2d<T>& b) {
return (std::sqrt)(PointDistanceSquared(a, b));
}
// Returns the distance from the given point to the given line.
float PointDistance(const PointF& point, const LineF& line);
// Returns the distance from the given point to the given rectangle.
float PointDistance(const PointF& point, const RectangleF& rectangle);
// Returns the point at the given distance from the starting point in the given direction.
PointF PointInDirection(const PointF& point, float degrees, float distance);
// Returns the point at the given distance from the first point in the direction of the second point.
PointF PointInDirection(const PointF& p1, const PointF& p2, float distance);
PointF PointInDirection(const PointF& point, const Vector2d& direction_vector);
// Returns the angle between two points.
float PointDirection(float x1, float y1, float x2, float y2);
// Returns the angle between two points.
float PointDirection(const PointF& a, const PointF& b);
// Rotates the given point about the origin point by the given number of degrees.
template<typename T>
Point2d<T> PointRotate(const Point2d<T>& point, const Point2d<T>& origin, float degrees) {
Point2d<T> new_point = point;
float rad = Math::DegreesToRadians(degrees);
float s = std::sin(rad);
float c = std::cos(rad);
// Translate the point to the origin.
new_point -= origin;
// Rotate the point.
float xnew = new_point.X() * c - new_point.Y() * s;
float ynew = new_point.X() * s + new_point.Y() * c;
// Translate the point back.
new_point.SetX(xnew + origin.X());
new_point.SetY(ynew + origin.Y());
return new_point;
}
// Returns true if the given point is inside of the given rectangle.
template <typename T>
bool PointIn(const Point2d<T>& point, const Rectangle<T>& rect) {
return (point.X() >= rect.X() && point.X() < rect.X2() && point.Y() >= rect.Y() && point.Y() < rect.Y2());
}
// Returns true if the given point is inside of the given circle.
template <typename T>
bool PointIn(const Point2d<T>& point, const Circle<T>& circle) {
return PointDistanceSquared(point, circle.Position()) < (circle.Radius() * circle.Radius());
}
// Returns the two points of contact of the lines tangent to the circle passing through the given point.
std::pair<PointF, PointF> TangentThroughPoint(const CircleF& circle, const PointF& point);
// Returns the number of common tangents between two circles. Assumes that the two circles are not the same circle.
int NumberOfCommonTangents(const CircleF& a, const CircleF& b);
CommonTangentsResult CommonTangents(const CircleF& a, const CircleF& b);
// Translates the given point by an offset.
template <typename T>
Positionable2dBase<T>& TranslatePoint(Positionable2dBase<T>& obj, T x_offset, T y_offset) {
obj.SetX(obj.X() + x_offset);
obj.SetY(obj.Y() + y_offset);
return obj;
}
// Returns the distance between two rectangles.
template <typename T>
float Distance(const Rectangle<T>& a, const Rectangle<T>& b) {
// If the two rectangles intersect, the distance between them is zero.
if (Intersects(a, b)) return 0.0f;
// Otherwise, the distance is the distance to the closest corner of the other rectangle.
bool left = b.Right() < a.Left(); // b is on the left of a
bool right = b.Left() > a.Right(); // b is on the right of a
bool bottom = b.Top() > a.Bottom(); // b is below a
bool top = b.Bottom() < a.Top(); // b is above a
if (top && left)
return PointDistance(b.BottomRight(), a.TopLeft());
else if (left && bottom)
return PointDistance(b.TopRight(), a.BottomLeft());
else if (bottom && right)
return PointDistance(b.TopLeft(), a.BottomRight());
else if (right && top)
return PointDistance(b.BottomLeft(), a.TopRight());
else if (left)
return a.Left() - b.Right();
else if (right)
return b.Left() - a.Right();
else if (bottom)
return b.Top() - a.Bottom();
else
return a.Top() - b.Bottom();
}
// Returns the distance between two circles.
template <typename T>
T Distance(const Circle<T>& a, const Circle<T>& b) {
T dist = PointDistance(a.Position(), b.Position());
T rsum = a.Radius() + b.Radius();
if (dist > rsum)
return dist - rsum;
else
return static_cast<T>(0);
}
template <typename T>
CohenSutherlandOutCode GetCohenSutherlandOutCode(const Rectangle<T>& rectangle, const Point2d<T>& point) {
CohenSutherlandOutCode out_code = CohenSutherlandOutCode::Inside;
if (point.X() < rectangle.Left())
out_code |= CohenSutherlandOutCode::Left;
else if (point.X() > rectangle.Right())
out_code |= CohenSutherlandOutCode::Right;
if (point.Y() < rectangle.Top())
out_code |= CohenSutherlandOutCode::Top;
else if (point.Y() > rectangle.Bottom())
out_code |= CohenSutherlandOutCode::Bottom;
return out_code;
}
template <typename T>
std::pair<CohenSutherlandOutCode, CohenSutherlandOutCode> GetCohenSutherlandOutCodes(const Rectangle<T>& rectangle, const Line<T>& line) {
auto result = std::make_pair(GetCohenSutherlandOutCode(rectangle, line.First()), GetCohenSutherlandOutCode(rectangle, line.Second()));
return result;
}
template<typename ValueType>
IntersectionPointsResult<ValueType, 1> GetIntersectionPoints(const Line<ValueType>& line1, const Line<ValueType>& line2) {
IntersectionPointsResult<ValueType, 1> result;
auto s1 = line1.GetStandardForm();
auto s2 = line2.GetStandardForm();
ValueType determinant = (s1.A * s2.B) - (s2.A * s1.B);
Point2d<ValueType> point;
if (Math::IsZero(determinant)) {
// The lines are parallel. If one line lines on the other, they intersect.
// Take whichever end point is closest to the start point of the first line.
float dist_sq = std::numeric_limits<float>::max();
if (line1.ContainsPoint(line2.First())) {
point = line2.First();
dist_sq = Math::Geometry::PointDistanceSquared(line1.First(), line2.First());
result.count = 1;
}
if (line1.ContainsPoint(line2.Second())) {
float try_dist_sq = Math::Geometry::PointDistanceSquared(line1.First(), line2.Second());
if (try_dist_sq < dist_sq) {
point = line2.Second();
try_dist_sq = dist_sq;
result.count = 1;
}
}
result.points[0] = point;
result.infinite = true;
return result;
}
// Calculate the potential point of intersection.
point.x = (s2.B * s1.C - s1.B * s2.C) / determinant;
point.y = (s1.A * s2.C - s2.A * s1.C) / determinant;
// Make sure that the point is on both of the line segments.
// Don't kid yourself into thinking these IsGreaterThan/IsLessThan calls are unnecessary.
// Comparing with epsilon is vital for floating point types; a lot of cases will be erroneously rejected otherwise.
if (Math::IsGreaterThan((std::min)(line1.X(), line1.X2()), point.x) || Math::IsLessThan((std::max)(line1.X(), line1.X2()), point.x) ||
Math::IsGreaterThan((std::min)(line1.Y(), line1.Y2()), point.y) || Math::IsLessThan((std::max)(line1.Y(), line1.Y2()), point.y) ||
Math::IsGreaterThan((std::min)(line2.X(), line2.X2()), point.x) || Math::IsLessThan((std::max)(line2.X(), line2.X2()), point.x) ||
Math::IsGreaterThan((std::min)(line2.Y(), line2.Y2()), point.y) || Math::IsLessThan((std::max)(line2.Y(), line2.Y2()), point.y))
return result;
// The point is on both lines, so we have an intersection.
result.points[0] = point;
result.count = 1;
return result;
}
template<typename ValueType>
Point2d<ValueType> GetIntersectionPoints(const LineSlopeInterceptForm<ValueType>& line1, const LineSlopeInterceptForm<ValueType>& line2) {
Point2d<ValueType> point;
point.x = (line2.intercept - line1.intercept) / (line1.slope - line2.slope);
point.y = (line1.slope * point.x + line1.intercept);
return point;
}
template<typename ValueType>
IntersectionPointsResult<ValueType, 2> GetIntersectionPoints(const Line<ValueType>& line, const Rectangle<ValueType>& rect) {
IntersectionPointsResult<ValueType, 2> result;
// If the line is collinear with one of the rectangle's edges, there are infinite intersection points.
if (line.X() == line.X2() && (line.X() == rect.Left() || line.X() == rect.Right()) ||
line.Y() == line.Y2() && (line.Y() == rect.Top() || line.Y() == rect.Bottom())) {
result.infinite = true;
return result;
}
auto out_codes = GetCohenSutherlandOutCodes(rect, line);
// Check if both points are inside of the rectangle. If so, there are no intersection points.
if (static_cast<int>(out_codes.first | out_codes.second) == 0)
return result;
// Check if both points are on the same side of the rectangle. If so, there are no intersection points.
if (static_cast<int>(out_codes.first & out_codes.second) != 0)
return result;
// Get the intersection point closest to the first point of the line.
if (out_codes.first != CohenSutherlandOutCode::Inside) {
IntersectionPointsResult<ValueType, 1> test;
CohenSutherlandOutCode out_code = out_codes.first;
if (!test && HasFlag(out_code, CohenSutherlandOutCode::Top))
test = GetIntersectionPoints(line, rect.TopEdge());
if (!test && HasFlag(out_code, CohenSutherlandOutCode::Left))
test = GetIntersectionPoints(line, rect.LeftEdge());
if (!test && HasFlag(out_code, CohenSutherlandOutCode::Right))
test = GetIntersectionPoints(line, rect.RightEdge());
if (!test && HasFlag(out_code, CohenSutherlandOutCode::Bottom))
test = GetIntersectionPoints(line, rect.BottomEdge());
if (test) {
result.points[result.count++] = test.points[0];
result.infinite = test.infinite;
}
}
// Get the intersection point closest to the second point of the line.
if (out_codes.second != CohenSutherlandOutCode::Inside) {
IntersectionPointsResult<ValueType, 1> test;
CohenSutherlandOutCode out_code = out_codes.second;
if (!test && HasFlag(out_code, CohenSutherlandOutCode::Top))
test = GetIntersectionPoints(line, rect.TopEdge());
if (!test && HasFlag(out_code, CohenSutherlandOutCode::Left))
test = GetIntersectionPoints(line, rect.LeftEdge());
if (!test && HasFlag(out_code, CohenSutherlandOutCode::Right))
test = GetIntersectionPoints(line, rect.RightEdge());
if (!test && HasFlag(out_code, CohenSutherlandOutCode::Bottom))
test = GetIntersectionPoints(line, rect.BottomEdge());
if (test) {
result.points[result.count++] = test.points[0];
result.infinite = test.infinite;
}
}
return result;
}
template<typename ValueType>
IntersectionPointsResult<ValueType, 2> GetIntersectionPoints(const Rectangle<ValueType>& rect, const Line<ValueType>& line) {
return GetIntersectionPoints(line, rect);
}
template <typename T>
bool TestIntersection(const Rectangle<T>& a, const Rectangle<T>& b) {
return (a.X() < b.X2() && a.X2() > b.X() && a.Y() < b.Y2() && a.Y2() > b.Y());
}
template <typename T>
bool TestIntersection(const Circle<T>& a, const Line<T>& b) {
// Note: This procedure uses the same logic as PointDistance, but avoids using the costly sqrt function.
float _a = a.X() - b.First().X();
float _b = a.Y() - b.First().Y();
float _c = b.Second().X() - b.First().X();
float _d = b.Second().Y() - b.First().Y();
float dot = _a * _c + _b * _d;
float len_sq = _c * _c + _d * _d;
float param = -1.0f;
if (len_sq != 0)
param = dot / len_sq;
float xx, yy;
if (param < 0) {
xx = b.First().X();
yy = b.First().Y();
}
else if (param > 1) {
xx = b.Second().X();
yy = b.Second().Y();
}
else {
xx = b.First().X() + param * _c;
yy = b.First().Y() + param * _d;
}
float dx = a.X() - xx;
float dy = a.Y() - yy;
return (dx * dx + dy * dy) < (std::pow)(a.Radius(), 2.0f);
// return PointDistance(Point(a.X(), a.Y), b) <= a.Radius();
}
template <typename T>
bool TestIntersection(const Line<T>& a, const Line<T>& b) {
T x1 = a.First().X();
T x2 = a.Second().X();
T x3 = b.First().X();
T x4 = b.Second().X();
T y1 = a.First().Y();
T y2 = a.Second().Y();
T y3 = b.First().Y();
T y4 = b.Second().Y();
T det = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4);
// If the determinant is 0, then there is no intersection.
if (Math::IsZero(det))
return false;
// Calculate the (potential) point of intersection.
T pre = (x1 * y2 - y1 * x2);
T post = (x3 * y4 - y3 * x4);
T x = (pre * (x3 - x4) - (x1 - x2) * post) / det;
T y = (pre * (y3 - y4) - (y1 - y2) * post) / det;
// Check that the point is on the lines.
if (Math::IsLessThan(x, Math::Min(x1, x2)) ||
Math::IsGreaterThan(x, Math::Max(x1, x2)) ||
Math::IsLessThan(x, Math::Min(x3, x4)) ||
Math::IsGreaterThan(x, Math::Max(x3, x4)))
return false;
if (Math::IsLessThan(y, Math::Min(y1, y2)) ||
Math::IsGreaterThan(y, Math::Max(y1, y2)) ||
Math::IsLessThan(y, Math::Min(y3, y4)) ||
Math::IsGreaterThan(y, Math::Max(y3, y4)))
return false;
return true;
}
template <typename T>
bool TestIntersection(const Rectangle<T>& a, const Circle<T>& b) {
return PointIn(Point2d<T>(b.X(), b.Y()), a) ||
TestIntersection(b, Line<T>(a.X(), a.Y(), a.X2(), a.Y())) || // top
TestIntersection(b, Line<T>(a.X(), a.Y2(), a.X2(), a.Y2())) || // bottom
TestIntersection(b, Line<T>(a.X(), a.Y(), a.X(), a.Y2())) || // left
TestIntersection(b, Line<T>(a.X2(), a.Y(), a.X2(), a.Y2())); // right
}
template <typename T>
bool TestIntersection(const Rectangle<T>& a, const Line<T>& b) {
// https://en.wikipedia.org/wiki/Cohen%E2%80%93Sutherland_algorithm
auto out_codes = GetCohenSutherlandOutCodes(a, b);
// One of the points is inside of the rectangle.
if (out_codes.first == CohenSutherlandOutCode::Inside || out_codes.second == CohenSutherlandOutCode::Inside)
return true;
// Both points on one side of the rectangle (top, left, bottom, or right).
if (static_cast<int>(out_codes.first & out_codes.second) != 0)
return false;
// Line passes through the rectangle (top/bottom or left/right).
if (((out_codes.first | out_codes.second) == (CohenSutherlandOutCode::Left | CohenSutherlandOutCode::Right)) ||
((out_codes.first | out_codes.second) == (CohenSutherlandOutCode::Top | CohenSutherlandOutCode::Bottom)))
return true;
// At this point, we know one point is to the left or the right, and one is to the top or the bottom.
// We only need to test the two corresponding edges.
Line<T> edge1 = HasFlag(out_codes.first | out_codes.second, CohenSutherlandOutCode::Left) ? a.LeftEdge() : a.RightEdge();
Line<T> edge2 = HasFlag(out_codes.first | out_codes.second, CohenSutherlandOutCode::Top) ? a.TopEdge() : a.BottomEdge();
return TestIntersection(b, edge1) || TestIntersection(b, edge2);
}
template <typename T>
bool TestIntersection(const Circle<T>& a, const Circle<T>& b) {
return PointDistance(Point2d<T>(a.X(), a.Y()), Point2d<T>(b.X(), b.Y())) < (a.Radius() + b.Radius());
}
}
}
} | true |
e0ee6dc70d055a3eb022879277995289a26438b8 | C++ | optimisticlucifer/My_Cpp_Journey | /TowerofHanoi.cpp | UTF-8 | 334 | 3.046875 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int i;
void toh(int n,char src,char dest,char helper){
if(n==0){
return;
}
toh(n-1,src,helper,dest);
cout<<"move from "<<src<<"to"<<dest<<endl;
toh(n-1,helper,dest,src);
i++;
}
int main(){
toh(6,'A','C','B');
cout<<("steps are " + to_string(i));
} | true |
891956d2bbc42e7275a8d4e959edbacfc9a078ce | C++ | exp111/Cocaine | /Counter-Strike Source v34/VmtSwap.cpp | UTF-8 | 1,207 | 2.546875 | 3 | [] | no_license | #include "VmtSwap.hpp"
#include "Debug.hpp"
#include "Crypt.hpp"
namespace Memory
{
VmtSwap::VmtSwap()
: m_ppInstance( nullptr ),
m_pBackupVmt( nullptr ),
m_pCustomVmt( nullptr ),
m_nSize( 0 )
{
}
bool VmtSwap::Apply( const void* pInstance )
{
if( !pInstance )
{
DPRINT( XorStr( "[VmtSwap::Apply] Can't hook at invalid address! (0x%X)" ), pInstance );
return false;
}
m_ppInstance = ( std::uintptr_t** )pInstance;
m_pBackupVmt = *m_ppInstance;
while( m_pBackupVmt[ m_nSize ] )
m_nSize++;
m_pCustomVmt = std::make_unique< std::uintptr_t[ ] >( m_nSize );
memcpy( m_pCustomVmt.get(), m_pBackupVmt, m_nSize * sizeof( std::uintptr_t ) );
Replace();
return true;
}
void VmtSwap::Release()
{
Restore();
}
void VmtSwap::Replace()
{
ScopedMemProtect ProtectGuard( m_ppInstance, sizeof( std::uintptr_t ), PAGE_READWRITE );
*m_ppInstance = m_pCustomVmt.get();
}
void VmtSwap::Restore()
{
ScopedMemProtect ProtectGuard( m_ppInstance, sizeof( std::uintptr_t ), PAGE_READWRITE );
*m_ppInstance = m_pBackupVmt;
}
void VmtSwap::Hook( const void* pHooked, const std::size_t nIndex )
{
m_pCustomVmt[ nIndex ] = ( std::uintptr_t )pHooked;
}
} | true |
c1c4be2138567b3f7475e1e94531d643c73df08d | C++ | 59412/Monopoly-----Cplusplus | /dctim.cc | UTF-8 | 3,247 | 3.046875 | 3 | [] | no_license | #include "dctim.h"
#include "player.h"
#include <string>
#include <iostream>
using namespace std;
const int turnInDc = 3;
const int lastIndex = 39;
DcTim::DcTim(){
name = "DC Tims Line";
prev = nullptr;
next = nullptr;
coordX = 0;
coordY = 10;
number = 10;
}
//DcTim::~DcTim(){}
void DcTim::leaveDC(Player *p,int point){
if(p->locationIndex + point > lastIndex){
p->locationIndex = p->locationIndex + point-1;
}else{
p->locationIndex += point;
}
for(int i = 0; i < point; i++){
p->position = p->position->getNext();
}
p->coordX = p->position->getX();
p->coordY = p->position->getY();
p->turnInDC = turnInDc;
}
void DcTim::notify(Player* p){
if(p->turnInDC == 3)
{
cout << "Player passed DC Tims line but don't want a cup of coffee" << endl;
}
else
{
cout << p->name << " stayed in DC Tims for " << p->turnInDC + 1;
cout << "rounds already" << endl;
int sum;
srand((int)time(0));
int roll1 = 1+rand()%6;
int roll2 = 1+rand()%6;
sum = roll1 + roll2;
if(roll1 == roll2)
{
leaveDC(p,sum);
}
else if(p->turnInDC == 0)
{
if(p->getCup() != 0 && p->getCash() >= 50)
{
cout << "Input 1 to pay by cash or 2 to pay by Rim cup!" << endl;
int choice;
cin >> choice;
while(cin.fail() || (choice != 1 && choice != 2))
{
cout << "Invalid input! Only input 1 or 2 please" << endl;
}
if(choice == 1)
{
p->pay(50);
leaveDC(p,sum);
}
else
{
p->lostCup();
leaveDC(p,sum);
}
}
else if(p->getCup() == 0 && p->getCash() >= 50)
{
cout << "You lost $50 for leaving DC Tims!" << endl;
p->pay(50);
leaveDC(p,sum);
}
else if(p->getCup() > 0 && p->getCash() < 50)
{
cout << "You lost a Rim cup for leaving DC Tims!" << endl;
p->lostCup();
leaveDC(p,sum);
}
// no cup no money
else
{
p->pay(50);
}
}
else
{
if(p->getCup() != 0 && p->getCash() >= 50)
{
cout << "Input 1 to pay by cash or 2 to pay by Rim cup to leave early!" << endl;
cout << "Or input anything else to choose to stay!" << endl;
int choice;
cin >> choice;
if(cin.fail() || (choice != 1 && choice != 2))
{
p->turnInDC--;
}
else if(choice == 1)
{
p->pay(50);
leaveDC(p,sum);
}
else
{
p->lostCup();
leaveDC(p,sum);
}
}
else if(p->getCup() == 0 && p->getCash() >= 50)
{
cout << "Do you want to pay $50 for leaving DC Tims?" << endl;
cout << "Input Y to accept or refuse by inputting anything else!" << endl;
string acceptPayment;
cin >> acceptPayment;
if(acceptPayment == "Y")
{
p->pay(50);
leaveDC(p,sum);
}
else
{
p->turnInDC--;
}
}
else if(p->getCup() != 0 && p->getCash() < 50)
{
cout << "Do you want to pay a Rim cup for leaving DC Tims?" << endl;
cout << "Input Y to accept or refuse by inputting anything else!" << endl;
string acceptPayment;
cin >> acceptPayment;
if(acceptPayment == "Y")
{
p->lostCup();
leaveDC(p,sum);
}
else
{
p->turnInDC--;
}
}
// no cup no money
else
{
p->turnInDC--;
}
}
//ask if use ask
//or let him pay
//add one on the vector of player of times he has been in dc??????
}
}
| true |
2f5966013009114ca2755b39a42b07cabd87ac43 | C++ | anshuljindal876/Shortest-Path-Linear- | /shortestPath.h | UTF-8 | 850 | 2.796875 | 3 | [] | no_license | /*
shortestPath.h - Header file for shortest path algorithm valid for linear open path with unit node distances.
Created by Anshul Jindal, July 04, 2018.
Only for VSSUT Robotics Club Members.
*/
#ifndef shortestPath_h
#define shortestPath_h
#include "Arduino.h"
class shortestPath
{
private:
int prev_from; // for temporary storage of previous value of j
int prev_dist = 0; // for temporary storage of previous value of dist
int err_val;
bool motion_dir = true;
int from_realT = 0, to_realT = 0;
int _numNodes;
int _connection[20][20];
int nearest_newNode(int ref, bool typ);
bool visited_nodes[20];
public:
int dist = 0;
int node_path[20];
void reset();
void calc_path(int numNodes, int connection[20][20], int starting_node, int target_node);
};
#endif | true |
db2b37f1608ffd8cc9c7f3bb4f1e467caefcc0fa | C++ | laurannaa/ED1A2-2017 | /A0301/Exb.cpp | UTF-8 | 1,592 | 3.75 | 4 | [] | no_license | /*
* File: main.cpp
* Author: ana
*
2-Com base no programa anterior crie um novo de forma que sejam
solicitados 10 nomes e 10 endereços.
Ao terminar a digitação o sistema entrará em um laço, solicitando
um número referente à ordem de digitação realizada.
Uma vez informado,o sistema deverá exibir o nome e o endereço
correspondente. Utilize apenas vetores.
Caso o usuário informe um número fora do intervalo de 1 a 10,
o sistema deverá alertar o usuário e solicitar a digitação
novamente (Lembre-se que em C 0 primeiro índice é 0, logo 1 irá
se referir ao elemento 0).
*/
#include <cstdlib>
#include <stdio.h>
using namespace std;
/*
*
*/
int main() {
char end[10][100];
char nome[10][50];
int cont, num = 1;
for (cont = 0; cont <= 9; cont++) {
printf("Informe um nome: \n");
gets(nome[cont]);
}
for (cont = 0; cont <= 9; cont++) {
printf("Informe o endereço de %s: \n", nome[cont]);
gets(end[cont]);
}
////////////////////////
while ((num >= 1) && (num <= 10)) {
printf("\nInforme um número: ");
scanf("%d", &num);
while ((num < 1) || (num > 10)) {
printf("\nValor inválido! Tente novamente!");
printf("\nInforme um número: ");
scanf("%d", &num);
if (num == -1) {
exit(0);
}
}
printf("\nO nome armazenado eh: %s \n", nome[num - 1]);
printf("\nO endereço armazenado eh: %s \n", end[num - 1]);
}
////////////////////////
return 0;
}
| true |
f541d81f1b3c5cd49aa45c999a9f5228e550e5b0 | C++ | Oh-kyung-tak/Algorithm | /Baekjoon/baekjoon_10176.cpp | UTF-8 | 711 | 2.65625 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
#include <vector>
#include <map>
#include <string>
#include <string.h>
#include <math.h>
#include <set>
using namespace std;
string word;
int N;
int alpa[26];
int main()
{
cin >> N;
while (N--)
{
bool ck = true;
cin >> word;
memset(alpa, 0, sizeof(alpa));
for (int i = 0; i < word.size(); i++)
{
if (word[i] >= 'A' && word[i] <= 'Z')
word[i] += 32;
alpa[word[i] - 'a']++;
}
for (int i = 0; i < word.size(); i++)
{
if(word[i] >= 'a' && word[i] <= 'z')
if (!alpa[word[i] - 'a'] || !alpa['z' - word[i]])
{
ck = false;
break;
}
}
if (ck)
cout << "Yes" << endl;
else
cout << "No" << endl;
}
}
| true |
58c8fcb85447612e7af333d5fb6a149910d25dc7 | C++ | wangchenwc/leetcode_cpp | /700_799/703_kth_largest.h | UTF-8 | 657 | 2.96875 | 3 | [] | no_license | //
// 703_kth_largest.h
// cpp_code
//
// Created by zhongyingli on 2018/8/23.
// Copyright © 2018 zhongyingli. All rights reserved.
//
#ifndef _03_kth_largest_h
#define _03_kth_largest_h
class KthLargest {
public:
KthLargest(int k, vector<int> nums) :
k_(k) {
for (const auto& num : nums) {
add(num);
}
}
int add(int val) {
min_heap_.emplace(val);
if (min_heap_.size() > k_) {
min_heap_.pop();
}
return min_heap_.top();
}
private:
const int k_;
priority_queue<int, vector<int>, greater<int>> min_heap_;
};
#endif /* _03_kth_largest_h */
| true |
c64a4a98864104871b8be27fa76c76ba4d98f7ee | C++ | prriyanayak/GFG_Solved | /basic/MaxValueAfterMOperations.cpp | UTF-8 | 683 | 2.546875 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
// vector<int> array;
int main()
{
//code
int t;
cin >> t;
while(t--)
{
int n, m;
cin >> n >> m;
int arr[n];
int as[m], bs[m], values[m];
memset(arr, 0, n*sizeof(int));
for(int i = 0; i < m; i++)
{
cin >> as[i] >> bs[i] >> values[i];
for(int j = as[i]; j <= bs[i]; j++)
{
arr[j] += values[i];
}
}
int max = arr[0];
for(int i = 0; i < n; i++)
{
if (arr[i] > max)
max = arr[i];
}
cout << max << endl;
}
return 0;
}
| true |
9fc3469b1fdff9ec14c15b28532c7f1c9a7741b6 | C++ | omri-peer/Linear-Algebra | /Matrix.h | UTF-8 | 48,268 | 3.375 | 3 | [] | no_license | // Templated matrix implementation (for the linear algebra library).
#pragma once
#include "Vector.h"
#include <algorithm>
#include <cmath>
#include <iostream>
#include <vector>
template <class T>
class Matrix {
using vector_t = std::vector<T>;
private:
unsigned int rows; // num of rows
unsigned int cols; // num of columns
mutable T determinant = 0; // irrelevant in a non-square matrix. Stored as a class member for better performances.
mutable unsigned int rank = 0; // Stored as a class member for better performances.
mutable bool det_updated = true; // dirty bit, may still be true in the irrelevant case of a non-square matrix
mutable bool rank_updated = true; // dirty bit
std::vector<vector_t> data; // the matrix's entries, stored as a vector of rows of the matrix, in row major fashion.
// if matrix is square, the function computes the inverse if exists and updates the rank and det
// if the matrix is not square, it only updates the rank
Matrix gaussian_elimination() const
{
rank = cols; // later will perform Gaussian elimination and substract 1 for each column without leading element
determinant = 1; // row operations might modify this this value
Matrix copy(*this); // the matrix to perform elimination on
Matrix inverse(rows, rows); // return value
// set inverse to unit matrix. Later will be eliminated in parallel
for (unsigned int i = 0; i < rows; ++i) {
inverse(i, i) = 1;
}
unsigned int first_non_zero = 0; // column number in which we expect to find the first nonzero element of some row
for (unsigned int row = 0; row < rows && first_non_zero < cols;) { // operate on rows one by one
for (unsigned int lower_row = row + 1; lower_row < rows && copy(row, first_non_zero) == 0; ++lower_row) { // if starts with 0, swap it
if (copy(lower_row, first_non_zero) != 0) { // swap the rows and update the data.
copy.swap_rows(row, lower_row);
inverse.swap_rows(row, lower_row);
determinant *= -1;
}
}
if (copy(row, first_non_zero) != 0) {
T scalar = copy(row, first_non_zero); // first element
copy.multiply_row_by_scalar(row, 1 / scalar); // start with 1.
inverse.multiply_row_by_scalar(row, 1 / scalar); // parallel elimination.
determinant *= scalar;
// set all other rows to zero in the first_non_zero-th index
for (unsigned int other_row = 0; other_row < rows; ++other_row) {
scalar = copy(other_row, first_non_zero);
if (other_row != row && scalar != 0) {
copy.add_multiplied_row(other_row, row, scalar * (-1));
inverse.add_multiplied_row(other_row, row, scalar * (-1));
}
}
++first_non_zero; // next
++row; // next
}
else { // no row starting (in first_non_zero) with a nonzero element was found
determinant = 0; // not invertible
++first_non_zero; // go on
--rank;
}
}
rank_updated = true;
det_updated = true;
if (determinant != 0) { // invertible
inverse.determinant = 1 / determinant; // of course
inverse.det_updated = true;
inverse.rank = rows;
inverse.rank_updated = true;
}
return std::move(inverse);
}
// max(s: 2^s<=x) x must be nonegative
unsigned int round_up_power_2(unsigned int x)
{
unsigned int i = 0;
while (x > (1 << i)) {
++i;
}
return i;
}
// set C1 = A1 + B1, where A1, B1 and C1 are square submatrices of A, B and C, with given starting indices in A, B, C and the size
static void add_to_place(const Matrix& A, const Matrix& B, Matrix& C, unsigned int xA, unsigned int yA, unsigned int xB, unsigned int yB, unsigned int xC, unsigned int yC, unsigned int size)
{
for (unsigned int i = 0; i < size; i++) {
for (unsigned int j = 0; j < size; j++) {
C(xC + i, yC + j) = A(xA + i, yA + j) + B(xB + i, yB + j);
}
}
}
// set C1 = A1 - B1, where A1, B1 and C1 are square submatrices of A, B and C, with given starting indices in A, B, C and the size
static void sub_to_place(const Matrix& A, const Matrix& B, Matrix& C, unsigned int xA, unsigned int yA, unsigned int xB, unsigned int yB, unsigned int xC, unsigned int yC, unsigned int size)
{
for (unsigned int i = 0; i < size; i++) {
for (unsigned int j = 0; j < size; j++) {
C(xC + i, yC + j) = A(xA + i, yA + j) - B(xB + i, yB + j);
}
}
}
// function just for Strassen multiplication
// loop unrolling code for multiplying two 8X8 matrices
static void base_case8(const Matrix& A, const Matrix& B, Matrix& C, unsigned int xA, unsigned int yA, unsigned int xB, unsigned int yB, unsigned int xC, unsigned int yC);
// function just for Strassen multiplication
// loop unrolling code for multiplying two 4X4 matrices
static void base_case4(const Matrix& paddedA, const Matrix& paddedB, Matrix& paddedProd);
// function just for Strassen multiplication
// recursive multiplication the of square matrices of dimension = power of two >= 8
// matrices may be given as submatrices of larger matrices A and B, by starting indices and actual size
static void add_mul(const Matrix& A, const Matrix& B, Matrix& C, unsigned int xA, unsigned int yA, unsigned int xB, unsigned int yB, unsigned int xC, unsigned int yC, unsigned int size)
{
// the actual Strassen login: partition to 4 blocks of half size, and recursive operation:
if (size == 8) { // base case
Matrix::base_case8(A, B, C, xA, yA, xB, yB, xC, yC);
return;
}
unsigned int half_size = size / 2; // blocks size
// blocks which are meant to store all the relevant information for the calculations
// of the new blocks that will compose the result.
Matrix X(half_size, half_size);
Matrix Y(half_size, half_size);
// in Strassen's algorithm denote:
// M1 = (A11 + A22) * (B11 + B22)
// M2 = (A21 + A22) * B11
// M3 = A11 * (B12 - B22)
// M4 = A22 * (B21 - B11)
// M5 = (A11 + A12) * B22
// M6 = (A21 - A11) * (B11 + B12)
// M7 = (A12 - A22) * (B21 + B22)
//
// and then:
//
// C11 = M1 + M4 - M5 + M7
// C12 = M3 + M5
// C21 = M2 + M4
// C22 = M1 - M2 + M3 + M6
//
// where
//
// A11 | A12S
// A = ----------
// A21 | A22
//
// and similarly to B and C.
// here we don't initialize Aij, Bij and Mi, but instead perform most of them in the
// designated cells: X, Y and M.
// M1
add_to_place(A, A, X, xA, yA, xA + half_size, yA + half_size, 0, 0, half_size);
add_to_place(B, B, Y, xB, yB, xB + half_size, yB + half_size, 0, 0, half_size);
sub_to_place(C, C, C, xC + half_size, yC + half_size, xC, yC, xC + half_size, yC + half_size, half_size);
add_mul(X, Y, C, 0, 0, 0, 0, xC, yC, half_size);
add_to_place(C, C, C, xC + half_size, yC + half_size, xC, yC, xC + half_size, yC + half_size, half_size);
// M2
add_to_place(A, A, X, xA + half_size, yA, xA + half_size, yA + half_size, 0, 0, half_size);
Y *= 0;
add_mul(X, B, Y, 0, 0, xB, yB, 0, 0, half_size);
add_to_place(C, Y, C, xC + half_size, yC, 0, 0, xC + half_size, yC, half_size);
sub_to_place(C, Y, C, xC + half_size, yC + half_size, 0, 0, xC + half_size, yC + half_size, half_size);
// M3
sub_to_place(B, B, Y, xB, yB + half_size, xB + half_size, yB + half_size, 0, 0, half_size);
X *= 0;
add_mul(A, Y, X, xA, yA, 0, 0, 0, 0, half_size);
add_to_place(C, X, C, xC, yC + half_size, 0, 0, xC, yC + half_size, half_size);
add_to_place(C, X, C, xC + half_size, yC + half_size, 0, 0, xC + half_size, yC + half_size, half_size);
// M4
sub_to_place(B, B, Y, xB + half_size, yB, xB, yB, 0, 0, half_size);
X *= 0;
add_mul(A, Y, X, xA + half_size, yA + half_size, 0, 0, 0, 0, half_size);
add_to_place(C, X, C, xC, yC, 0, 0, xC, yC, half_size);
add_to_place(C, X, C, xC + half_size, yC, 0, 0, xC + half_size, yC, half_size);
// M5
add_to_place(A, A, X, xA, yA, xA, yA + half_size, 0, 0, half_size);
Y *= 0;
add_mul(X, B, Y, 0, 0, xB + half_size, yB + half_size, 0, 0, half_size);
sub_to_place(C, Y, C, xC, yC, 0, 0, xC, yC, half_size);
add_to_place(C, Y, C, xC, yC + half_size, 0, 0, xC, yC + half_size, half_size);
// M6
sub_to_place(A, A, X, xA + half_size, yA, xA, yA, 0, 0, half_size);
add_to_place(B, B, Y, xB, yB, xB, yB + half_size, 0, 0, half_size);
add_mul(X, Y, C, 0, 0, 0, 0, xC + half_size, yC + half_size, half_size);
// M7
sub_to_place(A, A, X, xA, yA + half_size, xA + half_size, yA + half_size, 0, 0, half_size);
add_to_place(B, B, Y, xB + half_size, yB, xB + half_size, yB + half_size, 0, 0, half_size);
add_mul(X, Y, C, 0, 0, 0, 0, xC, yC, half_size);
}
public:
// default constructor. Constructs a 1X1 with 0
explicit Matrix() : rows(1), cols(1), data(std::vector<vector_t>(1, vector_t(1, 0)))
{
}
// constructs an rXc matrix, filled with 0's
explicit Matrix(unsigned int r, unsigned int c) : rows(r), cols(c), data(std::vector<vector_t>(rows, vector_t(cols, 0)))
{
}
// constructor by const reference to std::vector of vector_t (the entries)
// assumes the std::vector's in entries are of the same length
explicit Matrix(const std::vector<vector_t>& entries) : rows(entries.size()), cols(entries[0].size()), data(entries), det_updated(false), rank_updated(false)
{
}
// constructor by rvalue reference to std::vector of vector_t (the entries)
// assumes the std::vector's in entries are of the same length
explicit Matrix(std::vector<vector_t>&& entries) : rows(entries.size()), cols(entries[0].size()), data(std::move(entries)), det_updated(false), rank_updated(false)
{
}
// copy constructor. Constructs a copy of a given matrix
Matrix(const Matrix& m) : rows(m.rows), cols(m.cols), data(m.data), det_updated(m.det_updated), rank_updated(m.rank_updated), determinant(m.determinant), rank(m.rank)
{
}
// move constructor by rvalue reference of a different matrix
Matrix(Matrix&& m) noexcept : rows(m.rows), cols(m.cols), data(std::move(m.data)), det_updated(m.det_updated), rank_updated(m.rank_updated), determinant(m.determinant), rank(m.rank)
{
}
// copy assignment by const reference
Matrix& operator=(const Matrix& m)
{
rows = m.rows;
cols = m.cols;
data = m.data;
determinant = m.determinant;
rank = m.rank;
rank_updated = m.rank_updated;
det_updated = m.det_updated;
}
// move assignment by rvalue reference
Matrix& operator=(Matrix&& m) noexcept
{
data = std::move(m.data);
rows = m.rows;
cols = m.cols;
determinant = m.determinant;
rank = m.rank;
rank_updated = m.rank_updated;
det_updated = m.det_updated;
return *this;
}
// return whether the given matrix has the same entries.
// for programmers: it also updates the det or rank if the matrices are equal and one of the has the data up to date.
bool operator==(const Matrix& m) const
{
bool result = data == m.data;
if (result) {
if (det_updated && !m.det_updated) {
m.determinant = determinant;
m.det_updated = true;
}
else if (m.det_updated && !det_updated) {
determinant = m.determinant;
det_updated = true;
}
if (rank_updated && !m.rank_updated) {
m.rank = rank;
m.rank_updated = true;
}
else if (m.rank_updated && !rank_updated) {
rank = m.rank;
rank_updated = true;
}
}
return result;
}
// return whether the given matrix has the different entries.
bool operator!=(const Matrix& m) const
{
return !(*this == m);
}
// returns the number of rows
unsigned int get_rows() const
{
return rows;
}
// returns the number of columns
unsigned int get_cols() const
{
return cols;
}
// get: matrix(i, j) - the matrix's entry at the i'th row and j'th column, zero based
// indices must be in the appropriate range.
const T& operator()(unsigned int i, unsigned int j) const
{
return data[i][j];
}
// set: matrix(i, j) - the matrix's entry at the i'th row and j'th column, zero based
// indices must be in the appropriate range.
T& operator()(unsigned int i, unsigned int j)
{
rank_updated = false; // entries might change now
det_updated = false;
return data[i][j];
}
// get: matrix(i) is the matrix's i'th row, zero based
// index should be in the appropriate range.
const vector_t& operator()(unsigned int i) const
{
return data[i];
}
// set: matrix(i) is the matrix's i'th row, zero based
// index should be in the appropriate range.
vector_t& operator()(unsigned int i)
{
det_updated = false; // entries might change now
rank_updated = false;
return data[i];
}
// changes the matrix to its transposed form
// assumes the matrix is squared!
void transpose_in_place()
{
for (unsigned int i = 0; i < rows; ++i) {
for (unsigned int j = 0; j < i; ++j) {
std::swap((*this)(i, j), (*this)(j, i));
}
}
}
// returns the transposed matrix.
Matrix transpose() const
{
Matrix transed(cols, rows);
for (unsigned int i = 0; i < rows; ++i) {
for (unsigned int j = 0; j < cols; ++j) {
transed(j, i) = (*this)(i, j);
}
}
return std::move(transed);
}
// in-place matrices addition
// assumes they are the same size.
Matrix& operator+=(const Matrix& m)
{
for (unsigned int i = 0; i < rows; ++i) {
for (unsigned int j = 0; j < cols; ++j) {
(*this)(i, j) += m(i, j);
}
}
rank_updated = false; // will take time to update - might hurt performance when irrelevant
det_updated = false;
return *this;
}
// matrices addition
// assumes they are the same size.
Matrix operator+(const Matrix& m) const
{
Matrix sum(rows, cols);
for (unsigned int i = 0; i < rows; ++i) {
for (unsigned int j = 0; j < cols; ++j) {
sum(i, j) = (*this)(i, j) + m(i, j);
}
}
return std::move(sum);
}
// matrices multiplication
// assumes they are mutiplicable.
Matrix operator*(const Matrix& m) const
{
Matrix prod(rows, m.get_cols());
for (unsigned int i = 0; i < rows; ++i) {
for (unsigned int j = 0; j < m.cols; ++j) {
prod(i, j) = 0;
for (unsigned int k = 0; k < cols; ++k) {
prod(i, j) += (*this)(i, k) * m(k, j);
}
}
}
if (det_updated && m.det_updated) // can compute the new det
{
prod.determinant = m.determinant * determinant;
prod.det_updated = true;
}
return std::move(prod);
}
// faster multiplication of two matrices.
// assumes they are mutiplicable.
Matrix strassen(const Matrix<T>& B)
{
Matrix A = *this;
unsigned int power = round_up_power_2(std::max({A.get_rows(), A.get_cols(), B.get_cols()}));
unsigned int size = 1 << power;
// padding the matrices by zeroes to be parts of a power of 2 dimensional squared matrices.
Matrix paddedA(size, size);
Matrix paddedB(size, size);
for (unsigned int i = 0; i < A.get_rows(); ++i) {
for (unsigned int j = 0; j < A.get_cols(); ++j) {
paddedA(i, j) = A(i, j);
}
}
for (unsigned int i = 0; i < B.get_rows(); ++i) {
for (unsigned int j = 0; j < B.get_cols(); ++j) {
paddedB(i, j) = B(i, j);
}
}
Matrix paddedProd = Matrix(size, size);
if (size == 1) { // case too small to mul
paddedProd(0, 0) = A(0, 0) * B(0, 0);
}
else if (size == 2) { // case too small to mul
paddedProd(0, 0) = A(0, 0) * B(0, 0) + A(0, 1) * B(1, 0);
paddedProd(0, 1) = A(0, 0) * B(0, 1) + A(0, 1) * B(1, 1);
paddedProd(1, 0) = A(1, 0) * B(0, 0) + A(1, 1) * B(1, 0);
paddedProd(1, 1) = A(1, 0) * B(0, 1) + A(1, 1) * B(1, 1);
}
else if (size == 4) { // case too small to mul
base_case4(paddedA, paddedB, paddedProd);
}
else {
// calculate the product with add_mul()
add_mul(paddedA, paddedB, paddedProd, 0, 0, 0, 0, 0, 0, size);
}
// unpad the product
Matrix prod = Matrix(A.get_rows(), B.get_cols());
for (unsigned int i = 0; i < prod.get_rows(); ++i) {
for (unsigned int j = 0; j < prod.get_cols(); ++j) {
prod(i, j) = paddedProd(i, j);
}
}
if (det_updated && B.det_updated) // can compute the new det
{
prod.determinant = determinant * B.determinant;
prod.det_updated = true;
}
return std::move(prod);
}
// matrix negation
// assumes they are the same size.
Matrix operator-() const
{
return (*this) * (-1);
}
// in-place matrices substraction
// assumes they are the same size.
Matrix& operator-=(const Matrix& m)
{
for (unsigned int i = 0; i < rows; ++i) {
for (unsigned int j = 0; j < cols; ++j) {
(*this)(i, j) -= m(i, j);
}
}
rank_updated = false;
det_updated = false;
return *this;
}
// matrices substraction
// assumes they are the same size.
Matrix operator-(const Matrix& m) const
{
Matrix diff(rows, cols);
for (unsigned int i = 0; i < rows; ++i) {
for (unsigned int j = 0; j < cols; ++j) {
diff(i, j) = (*this)(i, j) - m(i, j);
}
}
return std::move(diff);
}
// in-place matrix by scalar multiplication
// assumes they are multiplicable.
Matrix& operator*=(const T& s)
{
bool det_up = det_updated; // assignment might mark as dirty
bool rank_up = rank_updated; // assignment might mark as dirty
for (unsigned int i = 0; i < rows; ++i) {
for (unsigned int j = 0; j < cols; ++j) {
(*this)(i, j) *= s;
}
}
det_updated = det_up;
rank_updated = rank_up;
if (det_updated) {
determinant *= pow(s, rows);
}
if (s == 0) {
rank = 0;
rank_updated = true;
}
return *this;
}
// matrix by vector multiplication
// assumes they are multiplicable.
Vector<T> operator*(const Vector<T>& v) const
{
Vector<T> res(this->get_rows()); // output
for (unsigned int i = 0; i < this->get_rows(); ++i) {
res(i) = 0;
for (unsigned int j = 0; j < this->get_cols(); ++j) {
res(i) += (*this)(i, j) * v(j);
}
}
return std::move(res);
}
// matrix by scalar multiplication (both directions)
friend Matrix operator*(const Matrix<T>& m, const T& s)
{
Matrix prod(m);
prod *= s;
return std::move(prod);
}
friend Matrix operator*(const T& s, const Matrix& m)
{
return std::move(m * s);
}
// gets two rows and swap them
// the rows should have a valid range
void swap_rows(unsigned int i, unsigned int j)
{
// remember the values so that the "set" operations will not mark them as dirty
bool det_up = det_updated;
bool rank_up = rank_updated;
std::swap((*this)(i), (*this)(j));
determinant *= -1;
det_updated = det_up;
rank_updated = rank_up;
}
// gets a row of the matrix and a scalar, and multiplies (in place) the row by the scalar.
void multiply_row_by_scalar(unsigned int row, T scalar)
{
// remember the values so that the "set" operations will not mark them as dirty
bool det_up = det_updated;
bool rank_up = rank_updated;
for (unsigned int i = 0; i < cols; ++i) { // multiply the row
(*this)(row, i) *= scalar;
}
determinant *= scalar;
det_updated = det_up;
if (scalar == 0) {
rank_updated = false;
}
else {
rank_updated = rank_up;
}
}
// adds a multiplication of some row to another row (in place)
void add_multiplied_row(unsigned int row1, unsigned int row2, T scalar)
{
// remember the values so that the "set" operations will not mark them as dirty
bool det_up = det_updated;
bool rank_up = rank_updated;
for (unsigned int i = 0; i < cols; ++i) {
(*this)(row1, i) += (*this)(row2, i) * scalar;
}
det_updated = det_up;
rank_updated = rank_up;
}
// returns the determinant of a matrix
// assumes the matrix is square
T get_det() const
{
if (!det_updated) {
gaussian_elimination();
}
return determinant;
}
// assumes the matrix has inverse
Matrix find_inverse() const
{
return gaussian_elimination();
}
//
unsigned int get_rank() const
{
if (!rank_updated) {
gaussian_elimination();
}
return rank;
}
};
// sending to output stream using <<
template <class T>
std::ostream& operator<<(std::ostream& strm, const Matrix<T>& m)
{
strm << "["; // formatting nicely
for (unsigned int i = 0; i < m.get_rows(); ++i) {
strm << "("; // row opener
for (unsigned int j = 0; j < m.get_cols() - 1; ++j) {
strm << m(i, j) << ", "; // values seperator
}
strm << m(i, m.get_cols() - 1) << ")\n";
}
strm << "]" << std::endl; // end
return strm;
}
template <class T>
inline void Matrix<T>::base_case8(const Matrix<T>& A, const Matrix<T>& B, Matrix<T>& C, unsigned int xA, unsigned int yA, unsigned int xB, unsigned int yB, unsigned int xC, unsigned int yC)
{
C(xC + 0, yC + 0) += A(xA + 0, yA + 0) * B(xB + 0, yB + 0) + A(xA + 0, yA + 1) * B(xB + 1, yB + 0) + A(xA + 0, yA + 2) * B(xB + 2, yB + 0) + A(xA + 0, yA + 3) * B(xB + 3, yB + 0) + A(xA + 0, yA + 4) * B(xB + 4, yB + 0) + A(xA + 0, yA + 5) * B(xB + 5, yB + 0) + A(xA + 0, yA + 6) * B(xB + 6, yB + 0) + A(xA + 0, yA + 7) * B(xB + 7, yB + 0);
C(xC + 0, yC + 1) += A(xA + 0, yA + 0) * B(xB + 0, yB + 1) + A(xA + 0, yA + 1) * B(xB + 1, yB + 1) + A(xA + 0, yA + 2) * B(xB + 2, yB + 1) + A(xA + 0, yA + 3) * B(xB + 3, yB + 1) + A(xA + 0, yA + 4) * B(xB + 4, yB + 1) + A(xA + 0, yA + 5) * B(xB + 5, yB + 1) + A(xA + 0, yA + 6) * B(xB + 6, yB + 1) + A(xA + 0, yA + 7) * B(xB + 7, yB + 1);
C(xC + 0, yC + 2) += A(xA + 0, yA + 0) * B(xB + 0, yB + 2) + A(xA + 0, yA + 1) * B(xB + 1, yB + 2) + A(xA + 0, yA + 2) * B(xB + 2, yB + 2) + A(xA + 0, yA + 3) * B(xB + 3, yB + 2) + A(xA + 0, yA + 4) * B(xB + 4, yB + 2) + A(xA + 0, yA + 5) * B(xB + 5, yB + 2) + A(xA + 0, yA + 6) * B(xB + 6, yB + 2) + A(xA + 0, yA + 7) * B(xB + 7, yB + 2);
C(xC + 0, yC + 3) += A(xA + 0, yA + 0) * B(xB + 0, yB + 3) + A(xA + 0, yA + 1) * B(xB + 1, yB + 3) + A(xA + 0, yA + 2) * B(xB + 2, yB + 3) + A(xA + 0, yA + 3) * B(xB + 3, yB + 3) + A(xA + 0, yA + 4) * B(xB + 4, yB + 3) + A(xA + 0, yA + 5) * B(xB + 5, yB + 3) + A(xA + 0, yA + 6) * B(xB + 6, yB + 3) + A(xA + 0, yA + 7) * B(xB + 7, yB + 3);
C(xC + 0, yC + 4) += A(xA + 0, yA + 0) * B(xB + 0, yB + 4) + A(xA + 0, yA + 1) * B(xB + 1, yB + 4) + A(xA + 0, yA + 2) * B(xB + 2, yB + 4) + A(xA + 0, yA + 3) * B(xB + 3, yB + 4) + A(xA + 0, yA + 4) * B(xB + 4, yB + 4) + A(xA + 0, yA + 5) * B(xB + 5, yB + 4) + A(xA + 0, yA + 6) * B(xB + 6, yB + 4) + A(xA + 0, yA + 7) * B(xB + 7, yB + 4);
C(xC + 0, yC + 5) += A(xA + 0, yA + 0) * B(xB + 0, yB + 5) + A(xA + 0, yA + 1) * B(xB + 1, yB + 5) + A(xA + 0, yA + 2) * B(xB + 2, yB + 5) + A(xA + 0, yA + 3) * B(xB + 3, yB + 5) + A(xA + 0, yA + 4) * B(xB + 4, yB + 5) + A(xA + 0, yA + 5) * B(xB + 5, yB + 5) + A(xA + 0, yA + 6) * B(xB + 6, yB + 5) + A(xA + 0, yA + 7) * B(xB + 7, yB + 5);
C(xC + 0, yC + 6) += A(xA + 0, yA + 0) * B(xB + 0, yB + 6) + A(xA + 0, yA + 1) * B(xB + 1, yB + 6) + A(xA + 0, yA + 2) * B(xB + 2, yB + 6) + A(xA + 0, yA + 3) * B(xB + 3, yB + 6) + A(xA + 0, yA + 4) * B(xB + 4, yB + 6) + A(xA + 0, yA + 5) * B(xB + 5, yB + 6) + A(xA + 0, yA + 6) * B(xB + 6, yB + 6) + A(xA + 0, yA + 7) * B(xB + 7, yB + 6);
C(xC + 0, yC + 7) += A(xA + 0, yA + 0) * B(xB + 0, yB + 7) + A(xA + 0, yA + 1) * B(xB + 1, yB + 7) + A(xA + 0, yA + 2) * B(xB + 2, yB + 7) + A(xA + 0, yA + 3) * B(xB + 3, yB + 7) + A(xA + 0, yA + 4) * B(xB + 4, yB + 7) + A(xA + 0, yA + 5) * B(xB + 5, yB + 7) + A(xA + 0, yA + 6) * B(xB + 6, yB + 7) + A(xA + 0, yA + 7) * B(xB + 7, yB + 7);
C(xC + 1, yC + 0) += A(xA + 1, yA + 0) * B(xB + 0, yB + 0) + A(xA + 1, yA + 1) * B(xB + 1, yB + 0) + A(xA + 1, yA + 2) * B(xB + 2, yB + 0) + A(xA + 1, yA + 3) * B(xB + 3, yB + 0) + A(xA + 1, yA + 4) * B(xB + 4, yB + 0) + A(xA + 1, yA + 5) * B(xB + 5, yB + 0) + A(xA + 1, yA + 6) * B(xB + 6, yB + 0) + A(xA + 1, yA + 7) * B(xB + 7, yB + 0);
C(xC + 1, yC + 1) += A(xA + 1, yA + 0) * B(xB + 0, yB + 1) + A(xA + 1, yA + 1) * B(xB + 1, yB + 1) + A(xA + 1, yA + 2) * B(xB + 2, yB + 1) + A(xA + 1, yA + 3) * B(xB + 3, yB + 1) + A(xA + 1, yA + 4) * B(xB + 4, yB + 1) + A(xA + 1, yA + 5) * B(xB + 5, yB + 1) + A(xA + 1, yA + 6) * B(xB + 6, yB + 1) + A(xA + 1, yA + 7) * B(xB + 7, yB + 1);
C(xC + 1, yC + 2) += A(xA + 1, yA + 0) * B(xB + 0, yB + 2) + A(xA + 1, yA + 1) * B(xB + 1, yB + 2) + A(xA + 1, yA + 2) * B(xB + 2, yB + 2) + A(xA + 1, yA + 3) * B(xB + 3, yB + 2) + A(xA + 1, yA + 4) * B(xB + 4, yB + 2) + A(xA + 1, yA + 5) * B(xB + 5, yB + 2) + A(xA + 1, yA + 6) * B(xB + 6, yB + 2) + A(xA + 1, yA + 7) * B(xB + 7, yB + 2);
C(xC + 1, yC + 3) += A(xA + 1, yA + 0) * B(xB + 0, yB + 3) + A(xA + 1, yA + 1) * B(xB + 1, yB + 3) + A(xA + 1, yA + 2) * B(xB + 2, yB + 3) + A(xA + 1, yA + 3) * B(xB + 3, yB + 3) + A(xA + 1, yA + 4) * B(xB + 4, yB + 3) + A(xA + 1, yA + 5) * B(xB + 5, yB + 3) + A(xA + 1, yA + 6) * B(xB + 6, yB + 3) + A(xA + 1, yA + 7) * B(xB + 7, yB + 3);
C(xC + 1, yC + 4) += A(xA + 1, yA + 0) * B(xB + 0, yB + 4) + A(xA + 1, yA + 1) * B(xB + 1, yB + 4) + A(xA + 1, yA + 2) * B(xB + 2, yB + 4) + A(xA + 1, yA + 3) * B(xB + 3, yB + 4) + A(xA + 1, yA + 4) * B(xB + 4, yB + 4) + A(xA + 1, yA + 5) * B(xB + 5, yB + 4) + A(xA + 1, yA + 6) * B(xB + 6, yB + 4) + A(xA + 1, yA + 7) * B(xB + 7, yB + 4);
C(xC + 1, yC + 5) += A(xA + 1, yA + 0) * B(xB + 0, yB + 5) + A(xA + 1, yA + 1) * B(xB + 1, yB + 5) + A(xA + 1, yA + 2) * B(xB + 2, yB + 5) + A(xA + 1, yA + 3) * B(xB + 3, yB + 5) + A(xA + 1, yA + 4) * B(xB + 4, yB + 5) + A(xA + 1, yA + 5) * B(xB + 5, yB + 5) + A(xA + 1, yA + 6) * B(xB + 6, yB + 5) + A(xA + 1, yA + 7) * B(xB + 7, yB + 5);
C(xC + 1, yC + 6) += A(xA + 1, yA + 0) * B(xB + 0, yB + 6) + A(xA + 1, yA + 1) * B(xB + 1, yB + 6) + A(xA + 1, yA + 2) * B(xB + 2, yB + 6) + A(xA + 1, yA + 3) * B(xB + 3, yB + 6) + A(xA + 1, yA + 4) * B(xB + 4, yB + 6) + A(xA + 1, yA + 5) * B(xB + 5, yB + 6) + A(xA + 1, yA + 6) * B(xB + 6, yB + 6) + A(xA + 1, yA + 7) * B(xB + 7, yB + 6);
C(xC + 1, yC + 7) += A(xA + 1, yA + 0) * B(xB + 0, yB + 7) + A(xA + 1, yA + 1) * B(xB + 1, yB + 7) + A(xA + 1, yA + 2) * B(xB + 2, yB + 7) + A(xA + 1, yA + 3) * B(xB + 3, yB + 7) + A(xA + 1, yA + 4) * B(xB + 4, yB + 7) + A(xA + 1, yA + 5) * B(xB + 5, yB + 7) + A(xA + 1, yA + 6) * B(xB + 6, yB + 7) + A(xA + 1, yA + 7) * B(xB + 7, yB + 7);
C(xC + 2, yC + 0) += A(xA + 2, yA + 0) * B(xB + 0, yB + 0) + A(xA + 2, yA + 1) * B(xB + 1, yB + 0) + A(xA + 2, yA + 2) * B(xB + 2, yB + 0) + A(xA + 2, yA + 3) * B(xB + 3, yB + 0) + A(xA + 2, yA + 4) * B(xB + 4, yB + 0) + A(xA + 2, yA + 5) * B(xB + 5, yB + 0) + A(xA + 2, yA + 6) * B(xB + 6, yB + 0) + A(xA + 2, yA + 7) * B(xB + 7, yB + 0);
C(xC + 2, yC + 1) += A(xA + 2, yA + 0) * B(xB + 0, yB + 1) + A(xA + 2, yA + 1) * B(xB + 1, yB + 1) + A(xA + 2, yA + 2) * B(xB + 2, yB + 1) + A(xA + 2, yA + 3) * B(xB + 3, yB + 1) + A(xA + 2, yA + 4) * B(xB + 4, yB + 1) + A(xA + 2, yA + 5) * B(xB + 5, yB + 1) + A(xA + 2, yA + 6) * B(xB + 6, yB + 1) + A(xA + 2, yA + 7) * B(xB + 7, yB + 1);
C(xC + 2, yC + 2) += A(xA + 2, yA + 0) * B(xB + 0, yB + 2) + A(xA + 2, yA + 1) * B(xB + 1, yB + 2) + A(xA + 2, yA + 2) * B(xB + 2, yB + 2) + A(xA + 2, yA + 3) * B(xB + 3, yB + 2) + A(xA + 2, yA + 4) * B(xB + 4, yB + 2) + A(xA + 2, yA + 5) * B(xB + 5, yB + 2) + A(xA + 2, yA + 6) * B(xB + 6, yB + 2) + A(xA + 2, yA + 7) * B(xB + 7, yB + 2);
C(xC + 2, yC + 3) += A(xA + 2, yA + 0) * B(xB + 0, yB + 3) + A(xA + 2, yA + 1) * B(xB + 1, yB + 3) + A(xA + 2, yA + 2) * B(xB + 2, yB + 3) + A(xA + 2, yA + 3) * B(xB + 3, yB + 3) + A(xA + 2, yA + 4) * B(xB + 4, yB + 3) + A(xA + 2, yA + 5) * B(xB + 5, yB + 3) + A(xA + 2, yA + 6) * B(xB + 6, yB + 3) + A(xA + 2, yA + 7) * B(xB + 7, yB + 3);
C(xC + 2, yC + 4) += A(xA + 2, yA + 0) * B(xB + 0, yB + 4) + A(xA + 2, yA + 1) * B(xB + 1, yB + 4) + A(xA + 2, yA + 2) * B(xB + 2, yB + 4) + A(xA + 2, yA + 3) * B(xB + 3, yB + 4) + A(xA + 2, yA + 4) * B(xB + 4, yB + 4) + A(xA + 2, yA + 5) * B(xB + 5, yB + 4) + A(xA + 2, yA + 6) * B(xB + 6, yB + 4) + A(xA + 2, yA + 7) * B(xB + 7, yB + 4);
C(xC + 2, yC + 5) += A(xA + 2, yA + 0) * B(xB + 0, yB + 5) + A(xA + 2, yA + 1) * B(xB + 1, yB + 5) + A(xA + 2, yA + 2) * B(xB + 2, yB + 5) + A(xA + 2, yA + 3) * B(xB + 3, yB + 5) + A(xA + 2, yA + 4) * B(xB + 4, yB + 5) + A(xA + 2, yA + 5) * B(xB + 5, yB + 5) + A(xA + 2, yA + 6) * B(xB + 6, yB + 5) + A(xA + 2, yA + 7) * B(xB + 7, yB + 5);
C(xC + 2, yC + 6) += A(xA + 2, yA + 0) * B(xB + 0, yB + 6) + A(xA + 2, yA + 1) * B(xB + 1, yB + 6) + A(xA + 2, yA + 2) * B(xB + 2, yB + 6) + A(xA + 2, yA + 3) * B(xB + 3, yB + 6) + A(xA + 2, yA + 4) * B(xB + 4, yB + 6) + A(xA + 2, yA + 5) * B(xB + 5, yB + 6) + A(xA + 2, yA + 6) * B(xB + 6, yB + 6) + A(xA + 2, yA + 7) * B(xB + 7, yB + 6);
C(xC + 2, yC + 7) += A(xA + 2, yA + 0) * B(xB + 0, yB + 7) + A(xA + 2, yA + 1) * B(xB + 1, yB + 7) + A(xA + 2, yA + 2) * B(xB + 2, yB + 7) + A(xA + 2, yA + 3) * B(xB + 3, yB + 7) + A(xA + 2, yA + 4) * B(xB + 4, yB + 7) + A(xA + 2, yA + 5) * B(xB + 5, yB + 7) + A(xA + 2, yA + 6) * B(xB + 6, yB + 7) + A(xA + 2, yA + 7) * B(xB + 7, yB + 7);
C(xC + 3, yC + 0) += A(xA + 3, yA + 0) * B(xB + 0, yB + 0) + A(xA + 3, yA + 1) * B(xB + 1, yB + 0) + A(xA + 3, yA + 2) * B(xB + 2, yB + 0) + A(xA + 3, yA + 3) * B(xB + 3, yB + 0) + A(xA + 3, yA + 4) * B(xB + 4, yB + 0) + A(xA + 3, yA + 5) * B(xB + 5, yB + 0) + A(xA + 3, yA + 6) * B(xB + 6, yB + 0) + A(xA + 3, yA + 7) * B(xB + 7, yB + 0);
C(xC + 3, yC + 1) += A(xA + 3, yA + 0) * B(xB + 0, yB + 1) + A(xA + 3, yA + 1) * B(xB + 1, yB + 1) + A(xA + 3, yA + 2) * B(xB + 2, yB + 1) + A(xA + 3, yA + 3) * B(xB + 3, yB + 1) + A(xA + 3, yA + 4) * B(xB + 4, yB + 1) + A(xA + 3, yA + 5) * B(xB + 5, yB + 1) + A(xA + 3, yA + 6) * B(xB + 6, yB + 1) + A(xA + 3, yA + 7) * B(xB + 7, yB + 1);
C(xC + 3, yC + 2) += A(xA + 3, yA + 0) * B(xB + 0, yB + 2) + A(xA + 3, yA + 1) * B(xB + 1, yB + 2) + A(xA + 3, yA + 2) * B(xB + 2, yB + 2) + A(xA + 3, yA + 3) * B(xB + 3, yB + 2) + A(xA + 3, yA + 4) * B(xB + 4, yB + 2) + A(xA + 3, yA + 5) * B(xB + 5, yB + 2) + A(xA + 3, yA + 6) * B(xB + 6, yB + 2) + A(xA + 3, yA + 7) * B(xB + 7, yB + 2);
C(xC + 3, yC + 3) += A(xA + 3, yA + 0) * B(xB + 0, yB + 3) + A(xA + 3, yA + 1) * B(xB + 1, yB + 3) + A(xA + 3, yA + 2) * B(xB + 2, yB + 3) + A(xA + 3, yA + 3) * B(xB + 3, yB + 3) + A(xA + 3, yA + 4) * B(xB + 4, yB + 3) + A(xA + 3, yA + 5) * B(xB + 5, yB + 3) + A(xA + 3, yA + 6) * B(xB + 6, yB + 3) + A(xA + 3, yA + 7) * B(xB + 7, yB + 3);
C(xC + 3, yC + 4) += A(xA + 3, yA + 0) * B(xB + 0, yB + 4) + A(xA + 3, yA + 1) * B(xB + 1, yB + 4) + A(xA + 3, yA + 2) * B(xB + 2, yB + 4) + A(xA + 3, yA + 3) * B(xB + 3, yB + 4) + A(xA + 3, yA + 4) * B(xB + 4, yB + 4) + A(xA + 3, yA + 5) * B(xB + 5, yB + 4) + A(xA + 3, yA + 6) * B(xB + 6, yB + 4) + A(xA + 3, yA + 7) * B(xB + 7, yB + 4);
C(xC + 3, yC + 5) += A(xA + 3, yA + 0) * B(xB + 0, yB + 5) + A(xA + 3, yA + 1) * B(xB + 1, yB + 5) + A(xA + 3, yA + 2) * B(xB + 2, yB + 5) + A(xA + 3, yA + 3) * B(xB + 3, yB + 5) + A(xA + 3, yA + 4) * B(xB + 4, yB + 5) + A(xA + 3, yA + 5) * B(xB + 5, yB + 5) + A(xA + 3, yA + 6) * B(xB + 6, yB + 5) + A(xA + 3, yA + 7) * B(xB + 7, yB + 5);
C(xC + 3, yC + 6) += A(xA + 3, yA + 0) * B(xB + 0, yB + 6) + A(xA + 3, yA + 1) * B(xB + 1, yB + 6) + A(xA + 3, yA + 2) * B(xB + 2, yB + 6) + A(xA + 3, yA + 3) * B(xB + 3, yB + 6) + A(xA + 3, yA + 4) * B(xB + 4, yB + 6) + A(xA + 3, yA + 5) * B(xB + 5, yB + 6) + A(xA + 3, yA + 6) * B(xB + 6, yB + 6) + A(xA + 3, yA + 7) * B(xB + 7, yB + 6);
C(xC + 3, yC + 7) += A(xA + 3, yA + 0) * B(xB + 0, yB + 7) + A(xA + 3, yA + 1) * B(xB + 1, yB + 7) + A(xA + 3, yA + 2) * B(xB + 2, yB + 7) + A(xA + 3, yA + 3) * B(xB + 3, yB + 7) + A(xA + 3, yA + 4) * B(xB + 4, yB + 7) + A(xA + 3, yA + 5) * B(xB + 5, yB + 7) + A(xA + 3, yA + 6) * B(xB + 6, yB + 7) + A(xA + 3, yA + 7) * B(xB + 7, yB + 7);
C(xC + 4, yC + 0) += A(xA + 4, yA + 0) * B(xB + 0, yB + 0) + A(xA + 4, yA + 1) * B(xB + 1, yB + 0) + A(xA + 4, yA + 2) * B(xB + 2, yB + 0) + A(xA + 4, yA + 3) * B(xB + 3, yB + 0) + A(xA + 4, yA + 4) * B(xB + 4, yB + 0) + A(xA + 4, yA + 5) * B(xB + 5, yB + 0) + A(xA + 4, yA + 6) * B(xB + 6, yB + 0) + A(xA + 4, yA + 7) * B(xB + 7, yB + 0);
C(xC + 4, yC + 1) += A(xA + 4, yA + 0) * B(xB + 0, yB + 1) + A(xA + 4, yA + 1) * B(xB + 1, yB + 1) + A(xA + 4, yA + 2) * B(xB + 2, yB + 1) + A(xA + 4, yA + 3) * B(xB + 3, yB + 1) + A(xA + 4, yA + 4) * B(xB + 4, yB + 1) + A(xA + 4, yA + 5) * B(xB + 5, yB + 1) + A(xA + 4, yA + 6) * B(xB + 6, yB + 1) + A(xA + 4, yA + 7) * B(xB + 7, yB + 1);
C(xC + 4, yC + 2) += A(xA + 4, yA + 0) * B(xB + 0, yB + 2) + A(xA + 4, yA + 1) * B(xB + 1, yB + 2) + A(xA + 4, yA + 2) * B(xB + 2, yB + 2) + A(xA + 4, yA + 3) * B(xB + 3, yB + 2) + A(xA + 4, yA + 4) * B(xB + 4, yB + 2) + A(xA + 4, yA + 5) * B(xB + 5, yB + 2) + A(xA + 4, yA + 6) * B(xB + 6, yB + 2) + A(xA + 4, yA + 7) * B(xB + 7, yB + 2);
C(xC + 4, yC + 3) += A(xA + 4, yA + 0) * B(xB + 0, yB + 3) + A(xA + 4, yA + 1) * B(xB + 1, yB + 3) + A(xA + 4, yA + 2) * B(xB + 2, yB + 3) + A(xA + 4, yA + 3) * B(xB + 3, yB + 3) + A(xA + 4, yA + 4) * B(xB + 4, yB + 3) + A(xA + 4, yA + 5) * B(xB + 5, yB + 3) + A(xA + 4, yA + 6) * B(xB + 6, yB + 3) + A(xA + 4, yA + 7) * B(xB + 7, yB + 3);
C(xC + 4, yC + 4) += A(xA + 4, yA + 0) * B(xB + 0, yB + 4) + A(xA + 4, yA + 1) * B(xB + 1, yB + 4) + A(xA + 4, yA + 2) * B(xB + 2, yB + 4) + A(xA + 4, yA + 3) * B(xB + 3, yB + 4) + A(xA + 4, yA + 4) * B(xB + 4, yB + 4) + A(xA + 4, yA + 5) * B(xB + 5, yB + 4) + A(xA + 4, yA + 6) * B(xB + 6, yB + 4) + A(xA + 4, yA + 7) * B(xB + 7, yB + 4);
C(xC + 4, yC + 5) += A(xA + 4, yA + 0) * B(xB + 0, yB + 5) + A(xA + 4, yA + 1) * B(xB + 1, yB + 5) + A(xA + 4, yA + 2) * B(xB + 2, yB + 5) + A(xA + 4, yA + 3) * B(xB + 3, yB + 5) + A(xA + 4, yA + 4) * B(xB + 4, yB + 5) + A(xA + 4, yA + 5) * B(xB + 5, yB + 5) + A(xA + 4, yA + 6) * B(xB + 6, yB + 5) + A(xA + 4, yA + 7) * B(xB + 7, yB + 5);
C(xC + 4, yC + 6) += A(xA + 4, yA + 0) * B(xB + 0, yB + 6) + A(xA + 4, yA + 1) * B(xB + 1, yB + 6) + A(xA + 4, yA + 2) * B(xB + 2, yB + 6) + A(xA + 4, yA + 3) * B(xB + 3, yB + 6) + A(xA + 4, yA + 4) * B(xB + 4, yB + 6) + A(xA + 4, yA + 5) * B(xB + 5, yB + 6) + A(xA + 4, yA + 6) * B(xB + 6, yB + 6) + A(xA + 4, yA + 7) * B(xB + 7, yB + 6);
C(xC + 4, yC + 7) += A(xA + 4, yA + 0) * B(xB + 0, yB + 7) + A(xA + 4, yA + 1) * B(xB + 1, yB + 7) + A(xA + 4, yA + 2) * B(xB + 2, yB + 7) + A(xA + 4, yA + 3) * B(xB + 3, yB + 7) + A(xA + 4, yA + 4) * B(xB + 4, yB + 7) + A(xA + 4, yA + 5) * B(xB + 5, yB + 7) + A(xA + 4, yA + 6) * B(xB + 6, yB + 7) + A(xA + 4, yA + 7) * B(xB + 7, yB + 7);
C(xC + 5, yC + 0) += A(xA + 5, yA + 0) * B(xB + 0, yB + 0) + A(xA + 5, yA + 1) * B(xB + 1, yB + 0) + A(xA + 5, yA + 2) * B(xB + 2, yB + 0) + A(xA + 5, yA + 3) * B(xB + 3, yB + 0) + A(xA + 5, yA + 4) * B(xB + 4, yB + 0) + A(xA + 5, yA + 5) * B(xB + 5, yB + 0) + A(xA + 5, yA + 6) * B(xB + 6, yB + 0) + A(xA + 5, yA + 7) * B(xB + 7, yB + 0);
C(xC + 5, yC + 1) += A(xA + 5, yA + 0) * B(xB + 0, yB + 1) + A(xA + 5, yA + 1) * B(xB + 1, yB + 1) + A(xA + 5, yA + 2) * B(xB + 2, yB + 1) + A(xA + 5, yA + 3) * B(xB + 3, yB + 1) + A(xA + 5, yA + 4) * B(xB + 4, yB + 1) + A(xA + 5, yA + 5) * B(xB + 5, yB + 1) + A(xA + 5, yA + 6) * B(xB + 6, yB + 1) + A(xA + 5, yA + 7) * B(xB + 7, yB + 1);
C(xC + 5, yC + 2) += A(xA + 5, yA + 0) * B(xB + 0, yB + 2) + A(xA + 5, yA + 1) * B(xB + 1, yB + 2) + A(xA + 5, yA + 2) * B(xB + 2, yB + 2) + A(xA + 5, yA + 3) * B(xB + 3, yB + 2) + A(xA + 5, yA + 4) * B(xB + 4, yB + 2) + A(xA + 5, yA + 5) * B(xB + 5, yB + 2) + A(xA + 5, yA + 6) * B(xB + 6, yB + 2) + A(xA + 5, yA + 7) * B(xB + 7, yB + 2);
C(xC + 5, yC + 3) += A(xA + 5, yA + 0) * B(xB + 0, yB + 3) + A(xA + 5, yA + 1) * B(xB + 1, yB + 3) + A(xA + 5, yA + 2) * B(xB + 2, yB + 3) + A(xA + 5, yA + 3) * B(xB + 3, yB + 3) + A(xA + 5, yA + 4) * B(xB + 4, yB + 3) + A(xA + 5, yA + 5) * B(xB + 5, yB + 3) + A(xA + 5, yA + 6) * B(xB + 6, yB + 3) + A(xA + 5, yA + 7) * B(xB + 7, yB + 3);
C(xC + 5, yC + 4) += A(xA + 5, yA + 0) * B(xB + 0, yB + 4) + A(xA + 5, yA + 1) * B(xB + 1, yB + 4) + A(xA + 5, yA + 2) * B(xB + 2, yB + 4) + A(xA + 5, yA + 3) * B(xB + 3, yB + 4) + A(xA + 5, yA + 4) * B(xB + 4, yB + 4) + A(xA + 5, yA + 5) * B(xB + 5, yB + 4) + A(xA + 5, yA + 6) * B(xB + 6, yB + 4) + A(xA + 5, yA + 7) * B(xB + 7, yB + 4);
C(xC + 5, yC + 5) += A(xA + 5, yA + 0) * B(xB + 0, yB + 5) + A(xA + 5, yA + 1) * B(xB + 1, yB + 5) + A(xA + 5, yA + 2) * B(xB + 2, yB + 5) + A(xA + 5, yA + 3) * B(xB + 3, yB + 5) + A(xA + 5, yA + 4) * B(xB + 4, yB + 5) + A(xA + 5, yA + 5) * B(xB + 5, yB + 5) + A(xA + 5, yA + 6) * B(xB + 6, yB + 5) + A(xA + 5, yA + 7) * B(xB + 7, yB + 5);
C(xC + 5, yC + 6) += A(xA + 5, yA + 0) * B(xB + 0, yB + 6) + A(xA + 5, yA + 1) * B(xB + 1, yB + 6) + A(xA + 5, yA + 2) * B(xB + 2, yB + 6) + A(xA + 5, yA + 3) * B(xB + 3, yB + 6) + A(xA + 5, yA + 4) * B(xB + 4, yB + 6) + A(xA + 5, yA + 5) * B(xB + 5, yB + 6) + A(xA + 5, yA + 6) * B(xB + 6, yB + 6) + A(xA + 5, yA + 7) * B(xB + 7, yB + 6);
C(xC + 5, yC + 7) += A(xA + 5, yA + 0) * B(xB + 0, yB + 7) + A(xA + 5, yA + 1) * B(xB + 1, yB + 7) + A(xA + 5, yA + 2) * B(xB + 2, yB + 7) + A(xA + 5, yA + 3) * B(xB + 3, yB + 7) + A(xA + 5, yA + 4) * B(xB + 4, yB + 7) + A(xA + 5, yA + 5) * B(xB + 5, yB + 7) + A(xA + 5, yA + 6) * B(xB + 6, yB + 7) + A(xA + 5, yA + 7) * B(xB + 7, yB + 7);
C(xC + 6, yC + 0) += A(xA + 6, yA + 0) * B(xB + 0, yB + 0) + A(xA + 6, yA + 1) * B(xB + 1, yB + 0) + A(xA + 6, yA + 2) * B(xB + 2, yB + 0) + A(xA + 6, yA + 3) * B(xB + 3, yB + 0) + A(xA + 6, yA + 4) * B(xB + 4, yB + 0) + A(xA + 6, yA + 5) * B(xB + 5, yB + 0) + A(xA + 6, yA + 6) * B(xB + 6, yB + 0) + A(xA + 6, yA + 7) * B(xB + 7, yB + 0);
C(xC + 6, yC + 1) += A(xA + 6, yA + 0) * B(xB + 0, yB + 1) + A(xA + 6, yA + 1) * B(xB + 1, yB + 1) + A(xA + 6, yA + 2) * B(xB + 2, yB + 1) + A(xA + 6, yA + 3) * B(xB + 3, yB + 1) + A(xA + 6, yA + 4) * B(xB + 4, yB + 1) + A(xA + 6, yA + 5) * B(xB + 5, yB + 1) + A(xA + 6, yA + 6) * B(xB + 6, yB + 1) + A(xA + 6, yA + 7) * B(xB + 7, yB + 1);
C(xC + 6, yC + 2) += A(xA + 6, yA + 0) * B(xB + 0, yB + 2) + A(xA + 6, yA + 1) * B(xB + 1, yB + 2) + A(xA + 6, yA + 2) * B(xB + 2, yB + 2) + A(xA + 6, yA + 3) * B(xB + 3, yB + 2) + A(xA + 6, yA + 4) * B(xB + 4, yB + 2) + A(xA + 6, yA + 5) * B(xB + 5, yB + 2) + A(xA + 6, yA + 6) * B(xB + 6, yB + 2) + A(xA + 6, yA + 7) * B(xB + 7, yB + 2);
C(xC + 6, yC + 3) += A(xA + 6, yA + 0) * B(xB + 0, yB + 3) + A(xA + 6, yA + 1) * B(xB + 1, yB + 3) + A(xA + 6, yA + 2) * B(xB + 2, yB + 3) + A(xA + 6, yA + 3) * B(xB + 3, yB + 3) + A(xA + 6, yA + 4) * B(xB + 4, yB + 3) + A(xA + 6, yA + 5) * B(xB + 5, yB + 3) + A(xA + 6, yA + 6) * B(xB + 6, yB + 3) + A(xA + 6, yA + 7) * B(xB + 7, yB + 3);
C(xC + 6, yC + 4) += A(xA + 6, yA + 0) * B(xB + 0, yB + 4) + A(xA + 6, yA + 1) * B(xB + 1, yB + 4) + A(xA + 6, yA + 2) * B(xB + 2, yB + 4) + A(xA + 6, yA + 3) * B(xB + 3, yB + 4) + A(xA + 6, yA + 4) * B(xB + 4, yB + 4) + A(xA + 6, yA + 5) * B(xB + 5, yB + 4) + A(xA + 6, yA + 6) * B(xB + 6, yB + 4) + A(xA + 6, yA + 7) * B(xB + 7, yB + 4);
C(xC + 6, yC + 5) += A(xA + 6, yA + 0) * B(xB + 0, yB + 5) + A(xA + 6, yA + 1) * B(xB + 1, yB + 5) + A(xA + 6, yA + 2) * B(xB + 2, yB + 5) + A(xA + 6, yA + 3) * B(xB + 3, yB + 5) + A(xA + 6, yA + 4) * B(xB + 4, yB + 5) + A(xA + 6, yA + 5) * B(xB + 5, yB + 5) + A(xA + 6, yA + 6) * B(xB + 6, yB + 5) + A(xA + 6, yA + 7) * B(xB + 7, yB + 5);
C(xC + 6, yC + 6) += A(xA + 6, yA + 0) * B(xB + 0, yB + 6) + A(xA + 6, yA + 1) * B(xB + 1, yB + 6) + A(xA + 6, yA + 2) * B(xB + 2, yB + 6) + A(xA + 6, yA + 3) * B(xB + 3, yB + 6) + A(xA + 6, yA + 4) * B(xB + 4, yB + 6) + A(xA + 6, yA + 5) * B(xB + 5, yB + 6) + A(xA + 6, yA + 6) * B(xB + 6, yB + 6) + A(xA + 6, yA + 7) * B(xB + 7, yB + 6);
C(xC + 6, yC + 7) += A(xA + 6, yA + 0) * B(xB + 0, yB + 7) + A(xA + 6, yA + 1) * B(xB + 1, yB + 7) + A(xA + 6, yA + 2) * B(xB + 2, yB + 7) + A(xA + 6, yA + 3) * B(xB + 3, yB + 7) + A(xA + 6, yA + 4) * B(xB + 4, yB + 7) + A(xA + 6, yA + 5) * B(xB + 5, yB + 7) + A(xA + 6, yA + 6) * B(xB + 6, yB + 7) + A(xA + 6, yA + 7) * B(xB + 7, yB + 7);
C(xC + 7, yC + 0) += A(xA + 7, yA + 0) * B(xB + 0, yB + 0) + A(xA + 7, yA + 1) * B(xB + 1, yB + 0) + A(xA + 7, yA + 2) * B(xB + 2, yB + 0) + A(xA + 7, yA + 3) * B(xB + 3, yB + 0) + A(xA + 7, yA + 4) * B(xB + 4, yB + 0) + A(xA + 7, yA + 5) * B(xB + 5, yB + 0) + A(xA + 7, yA + 6) * B(xB + 6, yB + 0) + A(xA + 7, yA + 7) * B(xB + 7, yB + 0);
C(xC + 7, yC + 1) += A(xA + 7, yA + 0) * B(xB + 0, yB + 1) + A(xA + 7, yA + 1) * B(xB + 1, yB + 1) + A(xA + 7, yA + 2) * B(xB + 2, yB + 1) + A(xA + 7, yA + 3) * B(xB + 3, yB + 1) + A(xA + 7, yA + 4) * B(xB + 4, yB + 1) + A(xA + 7, yA + 5) * B(xB + 5, yB + 1) + A(xA + 7, yA + 6) * B(xB + 6, yB + 1) + A(xA + 7, yA + 7) * B(xB + 7, yB + 1);
C(xC + 7, yC + 2) += A(xA + 7, yA + 0) * B(xB + 0, yB + 2) + A(xA + 7, yA + 1) * B(xB + 1, yB + 2) + A(xA + 7, yA + 2) * B(xB + 2, yB + 2) + A(xA + 7, yA + 3) * B(xB + 3, yB + 2) + A(xA + 7, yA + 4) * B(xB + 4, yB + 2) + A(xA + 7, yA + 5) * B(xB + 5, yB + 2) + A(xA + 7, yA + 6) * B(xB + 6, yB + 2) + A(xA + 7, yA + 7) * B(xB + 7, yB + 2);
C(xC + 7, yC + 3) += A(xA + 7, yA + 0) * B(xB + 0, yB + 3) + A(xA + 7, yA + 1) * B(xB + 1, yB + 3) + A(xA + 7, yA + 2) * B(xB + 2, yB + 3) + A(xA + 7, yA + 3) * B(xB + 3, yB + 3) + A(xA + 7, yA + 4) * B(xB + 4, yB + 3) + A(xA + 7, yA + 5) * B(xB + 5, yB + 3) + A(xA + 7, yA + 6) * B(xB + 6, yB + 3) + A(xA + 7, yA + 7) * B(xB + 7, yB + 3);
C(xC + 7, yC + 4) += A(xA + 7, yA + 0) * B(xB + 0, yB + 4) + A(xA + 7, yA + 1) * B(xB + 1, yB + 4) + A(xA + 7, yA + 2) * B(xB + 2, yB + 4) + A(xA + 7, yA + 3) * B(xB + 3, yB + 4) + A(xA + 7, yA + 4) * B(xB + 4, yB + 4) + A(xA + 7, yA + 5) * B(xB + 5, yB + 4) + A(xA + 7, yA + 6) * B(xB + 6, yB + 4) + A(xA + 7, yA + 7) * B(xB + 7, yB + 4);
C(xC + 7, yC + 5) += A(xA + 7, yA + 0) * B(xB + 0, yB + 5) + A(xA + 7, yA + 1) * B(xB + 1, yB + 5) + A(xA + 7, yA + 2) * B(xB + 2, yB + 5) + A(xA + 7, yA + 3) * B(xB + 3, yB + 5) + A(xA + 7, yA + 4) * B(xB + 4, yB + 5) + A(xA + 7, yA + 5) * B(xB + 5, yB + 5) + A(xA + 7, yA + 6) * B(xB + 6, yB + 5) + A(xA + 7, yA + 7) * B(xB + 7, yB + 5);
C(xC + 7, yC + 6) += A(xA + 7, yA + 0) * B(xB + 0, yB + 6) + A(xA + 7, yA + 1) * B(xB + 1, yB + 6) + A(xA + 7, yA + 2) * B(xB + 2, yB + 6) + A(xA + 7, yA + 3) * B(xB + 3, yB + 6) + A(xA + 7, yA + 4) * B(xB + 4, yB + 6) + A(xA + 7, yA + 5) * B(xB + 5, yB + 6) + A(xA + 7, yA + 6) * B(xB + 6, yB + 6) + A(xA + 7, yA + 7) * B(xB + 7, yB + 6);
C(xC + 7, yC + 7) += A(xA + 7, yA + 0) * B(xB + 0, yB + 7) + A(xA + 7, yA + 1) * B(xB + 1, yB + 7) + A(xA + 7, yA + 2) * B(xB + 2, yB + 7) + A(xA + 7, yA + 3) * B(xB + 3, yB + 7) + A(xA + 7, yA + 4) * B(xB + 4, yB + 7) + A(xA + 7, yA + 5) * B(xB + 5, yB + 7) + A(xA + 7, yA + 6) * B(xB + 6, yB + 7) + A(xA + 7, yA + 7) * B(xB + 7, yB + 7);
}
template <class T>
inline void Matrix<T>::base_case4(const Matrix<T>& paddedA, const Matrix<T>& paddedB, Matrix<T>& paddedProd)
{
paddedProd(0, 0) = paddedA(0, 0) * paddedB(0, 0) + paddedA(0, 1) * paddedB(1, 0) + paddedA(0, 2) * paddedB(2, 0) + paddedA(0, 3) * paddedB(3, 0);
paddedProd(0, 1) = paddedA(0, 0) * paddedB(0, 1) + paddedA(0, 1) * paddedB(1, 1) + paddedA(0, 2) * paddedB(2, 1) + paddedA(0, 3) * paddedB(3, 1);
paddedProd(0, 2) = paddedA(0, 0) * paddedB(0, 2) + paddedA(0, 1) * paddedB(1, 2) + paddedA(0, 2) * paddedB(2, 2) + paddedA(0, 3) * paddedB(3, 2);
paddedProd(0, 3) = paddedA(0, 0) * paddedB(0, 3) + paddedA(0, 1) * paddedB(1, 3) + paddedA(0, 2) * paddedB(2, 3) + paddedA(0, 3) * paddedB(3, 3);
paddedProd(1, 0) = paddedA(1, 0) * paddedB(0, 0) + paddedA(1, 1) * paddedB(1, 0) + paddedA(1, 2) * paddedB(2, 0) + paddedA(1, 3) * paddedB(3, 0);
paddedProd(1, 1) = paddedA(1, 0) * paddedB(0, 1) + paddedA(1, 1) * paddedB(1, 1) + paddedA(1, 2) * paddedB(2, 1) + paddedA(1, 3) * paddedB(3, 1);
paddedProd(1, 2) = paddedA(1, 0) * paddedB(0, 2) + paddedA(1, 1) * paddedB(1, 2) + paddedA(1, 2) * paddedB(2, 2) + paddedA(1, 3) * paddedB(3, 2);
paddedProd(1, 3) = paddedA(1, 0) * paddedB(0, 3) + paddedA(1, 1) * paddedB(1, 3) + paddedA(1, 2) * paddedB(2, 3) + paddedA(1, 3) * paddedB(3, 3);
paddedProd(2, 0) = paddedA(2, 0) * paddedB(0, 0) + paddedA(2, 1) * paddedB(1, 0) + paddedA(2, 2) * paddedB(2, 0) + paddedA(2, 3) * paddedB(3, 0);
paddedProd(2, 1) = paddedA(2, 0) * paddedB(0, 1) + paddedA(2, 1) * paddedB(1, 1) + paddedA(2, 2) * paddedB(2, 1) + paddedA(2, 3) * paddedB(3, 1);
paddedProd(2, 2) = paddedA(2, 0) * paddedB(0, 2) + paddedA(2, 1) * paddedB(1, 2) + paddedA(2, 2) * paddedB(2, 2) + paddedA(2, 3) * paddedB(3, 2);
paddedProd(2, 3) = paddedA(2, 0) * paddedB(0, 3) + paddedA(2, 1) * paddedB(1, 3) + paddedA(2, 2) * paddedB(2, 3) + paddedA(2, 3) * paddedB(3, 3);
paddedProd(3, 0) = paddedA(3, 0) * paddedB(0, 0) + paddedA(3, 1) * paddedB(1, 0) + paddedA(3, 2) * paddedB(2, 0) + paddedA(3, 3) * paddedB(3, 0);
paddedProd(3, 1) = paddedA(3, 0) * paddedB(0, 1) + paddedA(3, 1) * paddedB(1, 1) + paddedA(3, 2) * paddedB(2, 1) + paddedA(3, 3) * paddedB(3, 1);
paddedProd(3, 2) = paddedA(3, 0) * paddedB(0, 2) + paddedA(3, 1) * paddedB(1, 2) + paddedA(3, 2) * paddedB(2, 2) + paddedA(3, 3) * paddedB(3, 2);
paddedProd(3, 3) = paddedA(3, 0) * paddedB(0, 3) + paddedA(3, 1) * paddedB(1, 3) + paddedA(3, 2) * paddedB(2, 3) + paddedA(3, 3) * paddedB(3, 3);
}
| true |
e029ace0720beb370961d08bb178c1849275fb92 | C++ | HeyAdesh/CPP-Codes-Basic- | /timepass.cpp | UTF-8 | 192 | 3.03125 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main()
{
int l,b,a;
cout<<"Enter the length and breadth\n";
cin>>l>>b;
a=l*b;
cout<<"The area of rectangle is\t"<<a;
return 0;
}
| true |
a1abe156120c9973c85d5dec70d20ca657b1466a | C++ | gracek333/FinancialApplication | /CommonUsedMethods.h | UTF-8 | 650 | 2.59375 | 3 | [] | no_license | #ifndef COMMONUSEDMETHODS_H
#define COMMONUSEDMETHODS_H
#include <sstream>
#include <iostream>
#include <vector>
#include <windows.h>
using namespace std;
class CommonUsedMethods
{
public:
static string getPhrase();
static char getChar();
static string convertIntToString(int number);
static int convertStringIntoInt(string numberInString);
static float getFloatFromUser();
static bool isNumberFromUserCorrect(string inputData);
static string replaceCommaWithDot(string inputData);
static float convertStringToFloat(string inputDataWithDot);
static string convertFloatToString(float numberInFloat);
};
#endif
| true |
98d343ebff03535ab13329e7b018b5a4dfeb476d | C++ | ai5/gpsfish | /osl/full/osl/state/historyState.cc | UTF-8 | 1,363 | 2.78125 | 3 | [] | no_license | /* historyState.cc
*/
#include "osl/state/historyState.h"
osl::state::HistoryState::HistoryState()
: dirty(false)
{
assert(current.isConsistent());
assert(initial_state.isConsistent());
}
osl::state::HistoryState::HistoryState(const SimpleState& initial)
: initial_state(initial), current(initial), dirty(false)
{
assert(current.isConsistent());
assert(initial_state.isConsistent());
}
osl::state::HistoryState::~HistoryState()
{
}
void osl::state::HistoryState::setRoot(const SimpleState& initial)
{
initial_state = current = NumEffectState(initial);
moves.clear();
dirty = false;
}
void osl::state::HistoryState::makeMove(Move move)
{
if (dirty)
update();
moves.push_back(move);
current.makeMove(move);
}
void osl::state::HistoryState::unmakeMove()
{
dirty = true;
moves.pop_back();
}
void osl::state::HistoryState::makeMovePass()
{
makeMove(Move::PASS(state().turn()));
}
void osl::state::HistoryState::unmakeMovePass()
{
assert(! moves.empty() && moves.back().isPass());
if (! dirty) {
moves.pop_back();
current.changeTurn();
return;
}
unmakeMove();
}
void osl::state::HistoryState::update() const
{
current = initial_state;
for (size_t i=0; i<moves.size(); ++i)
current.makeMove(moves[i]);
dirty = false;
}
// ;;; Local Variables:
// ;;; mode:c++
// ;;; c-basic-offset:2
// ;;; End:
| true |
9619e0937f6a51b38fba0124a528694cf695d281 | C++ | sxw106106/cpp-learning | /timer/TimerFunc/TimerFunc.cpp | UTF-8 | 2,030 | 2.953125 | 3 | [] | no_license | #include "TimerFunc.h"
My_Timer TimerFunc::my_timer[MAX_TIMER_COUNT]={0};
int TimerFunc::m_TimersCount=0;
int TimerFunc::ticker=0;
void TimerFunc::SetTimer(int ttime,int ifunction) //新建一个计时器
{
struct My_Timer a;
a.total_time = ttime;
a.left_time = ttime;
a.func = ifunction;
printf("\n index : %d ,total_timer : %d \n" ,m_TimersCount, a.total_time );
my_timer[m_TimersCount++] = a;
}
void TimerFunc::Timeout(int sigty) //判断定时器是否超时,以及超时时所要执行的动作
{
//printf("Signal: %d , Time ticker : %d\n", sigty, ticker++);
printf(" ticker : %d ", ticker++);
int j;
for( j = 0; j < m_TimersCount; j++ )
{
if(my_timer[j].left_time != 0 )
{
my_timer[j].left_time--;//continue the counter
}
else
{
switch(my_timer[j].func) //通过匹配my_timer[j].func,判断下一步选择哪种操作
{
case 1:
{
printf("doing\n");
}
}
// my_timer[j].left_time = my_timer[j].total_time; //循环计时
my_timer[j].left_time = 10; //循环计时
printf("\nmy_timer[%d].func : %d\n" ,j , my_timer[j].func );
printf("\ntotal_timer %d: %d\n" ,j , my_timer[j].total_time );
printf("Reset Timer to %d \n",my_timer[j].total_time);
}
}
}
//int main() //测试函数,定义三个定时器
int TimerFunc::StartTimer()
{
m_TimersCount = 0;
if(ticker>0 )
{
return 0;
printf("already StartTimer\n");
}
else
{
ticker = 0;
printf("start StartTimer\n");
}
pid_t pid;
if((pid = fork()) < 0)
{
return -1;
}
else if(pid == 0) //child
{
SetTimer(10,1);
// setTimer(4,2);
// setTimer(5,3);
signal(SIGALRM,Timeout); //接到SIGALRM信号,则执行timeout函数
while(1)
{
sleep(1); //每隔一秒发送一个SIGALRM
kill(getpid(),SIGALRM);//the same as raise(SIGALRM)
}
}
else
return 0;
}
| true |
ebb6eeb8c88361ffa1ac2785c56d57e90a3867a1 | C++ | michaelkatona/Shigako | /Shigako/EngineLayout.cpp | UTF-8 | 5,027 | 2.9375 | 3 | [] | no_license | #include "EngineLayout.h"
EngineLayout::EngineLayout(QWidget *parent, int margin /* = 0 */, int spacing /* = -1 */){
setMargin(margin);
setSpacing(spacing);
}
EngineLayout::~EngineLayout(){
for (auto& itr : m_items){
delete itr->item;
delete itr;
}
m_items.clear();
}
void EngineLayout::addItem(QLayoutItem *item){
add(item, West);
}
void EngineLayout::addWidget(QWidget *widget, Position position){
add(new QWidgetItem(widget), position);
}
bool EngineLayout::hasHeightForWidth() const{
return false;
}
int EngineLayout::count() const{
return m_items.size();
}
QLayoutItem * EngineLayout::itemAt(int index) const{
ItemWrapper *wrapper = m_items.value(index);
if (wrapper)
return wrapper->item;
else
return 0;
}
QSize EngineLayout::minimumSize() const{
return calculateSize(MinimumSize);
}
void EngineLayout::setGeometry(const QRect &rect){
ItemWrapper *center = 0;
int eastWidth = 0;
int westWidth = 0;
int northHeight = 0;
int southHeight = 0;
int centerHeight = 0;
int i;
QLayout::setGeometry(rect);
for (i = 0; i < m_items.size(); ++i) {
ItemWrapper* wrapper = m_items.at(i);
QLayoutItem* item = wrapper->item;
Position position = wrapper->position;
if (position == North) {
item->setGeometry(QRect(rect.x(), northHeight, rect.width(),
item->sizeHint().height()));
northHeight += item->geometry().height() + spacing();
}
else if (position == South) {
item->setGeometry(QRect(item->geometry().x(),
item->geometry().y(), rect.width(),
item->sizeHint().height()));
southHeight += item->geometry().height() + spacing();
item->setGeometry(QRect(rect.x(),
rect.y() + rect.height() - southHeight + spacing(),
item->geometry().width(),
item->geometry().height()));
}
else if (position == Center) {
center = wrapper;
}
}
centerHeight = rect.height() - northHeight - southHeight;
QList<QLayoutItem*> eastItems;
for (i = 0; i < m_items.size(); ++i) {
ItemWrapper *wrapper = m_items.at(i);
QLayoutItem *item = wrapper->item;
Position position = wrapper->position;
if (position == West) {
item->setGeometry(QRect(rect.x() + westWidth, northHeight,
item->sizeHint().width(), centerHeight));
westWidth += item->geometry().width() + spacing();
}
else if (position == East) {
if (item->sizeHint().width() > (eastWidth - spacing())){
eastWidth = item->sizeHint().width() + spacing();
}
eastItems.append(item);
}
}
int curHeight = 0;
if (eastItems.size() < 3){
std::printf("Not enough east items!");
}
for (i = 0; i < eastItems.size(); ++i){
QLayoutItem *item = eastItems.at(i);
switch (i){
case 0:
item->setGeometry(QRect(rect.width() - (eastWidth + spacing()), 0,
eastWidth, item->sizeHint().height()));
break;
case 1:
item->setGeometry(QRect(rect.width() - (eastWidth + spacing()), curHeight,
eastWidth, item->sizeHint().height()));
break;
case 2:
item->setGeometry(QRect(rect.width() - (eastWidth + spacing()), curHeight,
eastWidth, rect.height() - curHeight));
break;
default:
std::printf("Too many east items!");
break;
}
curHeight += item->sizeHint().height();
}
if (center){
center->item->setGeometry(QRect(westWidth, northHeight,
rect.width() - eastWidth - westWidth,
centerHeight));
}
}
QSize EngineLayout::sizeHint() const{
return calculateSize(SizeHint);
}
QLayoutItem* EngineLayout::takeAt(int index){
if (index >= 0 && index < m_items.size()) {
ItemWrapper *layoutStruct = m_items.takeAt(index);
return layoutStruct->item;
}
return 0;
}
void EngineLayout::add(QLayoutItem *item, Position position){
m_items.append(new ItemWrapper(item, position));
}
QSize EngineLayout::calculateSize(SizeType sizeType) const{
QSize totalSize;
for (int i = 0; i < m_items.size(); ++i) {
ItemWrapper *wrapper = m_items.at(i);
Position position = wrapper->position;
QSize itemSize;
if (sizeType == MinimumSize)
itemSize = wrapper->item->minimumSize();
else // (sizeType == SizeHint)
itemSize = wrapper->item->sizeHint();
if (position == North || position == South || position == Center)
totalSize.rheight() += itemSize.height();
if (position == West || position == East || position == Center)
totalSize.rwidth() += itemSize.width();
}
return totalSize;
} | true |
0d32afbfabb2017dc50a62ae7de7fd4b1d061de6 | C++ | Carlosnuji/Plantas | /tests/app.cpp | UTF-8 | 1,923 | 2.71875 | 3 | [
"MIT"
] | permissive | #include "app.h"
#include "doctest.h"
#include "db.h"
#include "../usuario.h"
#include "../planta.h"
#include "../token.h"
#include "../queja.h"
#include "../favorito.h"
#include "../json.hpp"
#include <QDebug>
using JSON = nlohmann::json;
App::App()
{
}
TEST_CASE("01 Test base datos")
{
/// Iniciar base datos
Db database;
CHECK(database.init() == true);
}
TEST_CASE("02 Usuario")
{
Usuario usuario("test", "test123", "test@gmail.com");
CHECK(usuario.save() == true);
CHECK(usuario.load(1) == true);
CHECK(usuario.getId() == 1);
CHECK(usuario.getNombre() == "test");
CHECK(usuario.getEmail() == "test@gmail.com");
CHECK(usuario.getStatus() == 0);
}
TEST_CASE("03 Planta")
{
Planta planta("Nombre", "Nombre científico", "Descripción");
CHECK(planta.save() == true);
CHECK(planta.load(1) == true);
CHECK(planta.getId() == 1);
CHECK(planta.getNombre() == "Nombre");
CHECK(planta.getNombreCientifico() == "Nombre científico");
CHECK(planta.getDescripcion() == "Descripción");
}
TEST_CASE("04 Token")
{
Token token;
QString tokenString{token.generateToken()};
int idUsuario{1};
CHECK(token.insert(tokenString, idUsuario) == true);
CHECK(token.checkToken(tokenString.toUtf8().constData()) == true);
}
TEST_CASE("05 Queja")
{
int idUsuario{1};
Queja queja(idUsuario, "Esto es una queja");
CHECK(queja.save() == true);
CHECK(queja.load(idUsuario) == true);
CHECK(queja.getId() == 1);
CHECK(queja.getIdUsuario() == 1);
}
TEST_CASE("06 Favorito")
{
int idUsuario{1};
int idPlanta{1};
Favorito favorito(idUsuario, idPlanta);
CHECK(favorito.check() == false);
CHECK(favorito.load(idUsuario, idPlanta) == true);
CHECK(favorito.getIdUsuario() == idUsuario);
CHECK(favorito.getIdPlanta() == idPlanta);
CHECK(favorito.check() == true);
}
| true |
d28a44ce89f76af8866dcb87fbb0b42c450aaca0 | C++ | lordeup/TAaFL | /LexerLib/TokenType.h | UTF-8 | 2,771 | 2.8125 | 3 | [] | no_license | #pragma once
#include <string>
namespace TokenType
{
const std::string ERROR = "ERROR";
const std::string ID = "ID";
const std::string INTEGER = "INTEGER";
const std::string FLOAT = "FLOAT";
const std::string DOUBLE = "DOUBLE";
const std::string CHAR = "CHAR";
const std::string STRING = "STRING";
const std::string ARRAY = "ARRAY";
const std::string BINARY = "BINARY";
const std::string OCTAL = "OCTAL";
const std::string HEXADECIMAL = "HEXADECIMAL";
const std::string OPERATOR_IF = "OPERATOR_IF";
const std::string OPERATOR_ELSE = "OPERATOR_ELSE";
const std::string OPERATOR_FOR = "OPERATOR_FOR";
const std::string OPERATOR_WHILE = "OPERATOR_WHILE";
const std::string OPERATOR_DO = "OPERATOR_DO";
const std::string OPERATOR_BREAK = "OPERATOR_BREAK";
const std::string OPERATOR_CONTINUE = "OPERATOR_CONTINUE";
const std::string OPERATOR_RETURN = "OPERATOR_RETURN";
const std::string OPERATOR_READ = "OPERATOR_READ";
const std::string OPERATOR_WRITE = "OPERATOR_WRITE";
const std::string OPERATOR_MAIN = "OPERATOR_MAIN";
const std::string OPERATOR_VOID = "OPERATOR_VOID";
const std::string OPERATOR_INT = "OPERATOR_INT";
const std::string OPERATOR_FLOAT = "OPERATOR_FLOAT";
const std::string OPERATOR_DOUBLE = "OPERATOR_DOUBLE";
const std::string OPERATOR_CHAR = "OPERATOR_CHAR";
const std::string OPERATOR_STRING = "OPERATOR_STRING";
const std::string OPERATOR_BOOL = "OPERATOR_BOOL";
const std::string PLUS = "PLUS";
const std::string MINUS = "MINUS";
const std::string MULTIPLICATION = "MULTIPLICATION";
const std::string DIVISION = "DIVISION";
const std::string ASSIGNMENT = "ASSIGNMENT";
const std::string MOD = "MOD";
const std::string LOGICAL_AND = "LOGICAL_AND";
const std::string LOGICAL_OR = "LOGICAL_OR";
const std::string LOGICAL_NOT = "LOGICAL_NOT";
const std::string COMMA = "COMMA";
const std::string SEMICOLON = "SEMICOLON";
const std::string COLON = "COLON";
const std::string BRACE_OPEN = "BRACE_OPEN";
const std::string BRACE_CLOSE = "BRACE_CLOSE";
const std::string BRACKET_OPEN = "BRACKET_OPEN";
const std::string BRACKET_CLOSE = "BRACKET_CLOSE";
const std::string BITWISE_AND = "BITWISE_AND";
const std::string BITWISE_OR = "BITWISE_OR";
const std::string BITWISE_NOT = "BITWISE_NOT";
const std::string BITWISE_XOR = "BITWISE_XOR";
const std::string BITWISE_RIGHT_SHIFT = "BITWISE_RIGHT_SHIFT";
const std::string BITWISE_LEFT_SHIFT = "BITWISE_LEFT_SHIFT";
const std::string MORE = "MORE";
const std::string LESS = "LESS";
const std::string EQUAL = "EQUAL";
const std::string NOT_EQUAL = "NOT_EQUAL";
const std::string MORE_OR_EQUAL = "MORE_OR_EQUAL";
const std::string LESS_OR_EQUAL = "LESS_OR_EQUAL";
const std::string COMMENT = "COMMENT";
const std::string END_OF_INPUT = "#";
}; | true |
2a9c733d0e02c6938fc1b14d1328c3b612d0c78e | C++ | IngwiePhoenix/stlplus3 | /tags/stlplus-03-06/containers/simple_ptr.tpp | UTF-8 | 9,117 | 3.109375 | 3 | [] | no_license | ////////////////////////////////////////////////////////////////////////////////
// Author: Daniel Milton
// Copyright: (c) Daniel Milton 2002 onwards
////////////////////////////////////////////////////////////////////////////////
namespace stlplus
{
////////////////////////////////////////////////////////////////////////////////
// simple_ptr_base class
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// constructors, assignments and destructors
// create a null pointer
template <typename T, typename C>
simple_ptr_base<T,C>::simple_ptr_base(void) :
m_pointer(0),
m_count(new unsigned(1))
{
}
// create a pointer containing a *copy* of the object pointer
template <typename T, typename C>
simple_ptr_base<T,C>::simple_ptr_base(const T& data) throw(illegal_copy) :
m_pointer(C()(data)),
m_count(new unsigned(1))
{
}
// create a pointer containing a dynamically created object
// Note: the object must be allocated *by the user* with new
// constructor form - must be called in the form simple_ptr<type> x(new type(args))
template <typename T, typename C>
simple_ptr_base<T,C>::simple_ptr_base(T* data) :
m_pointer(data),
m_count(new unsigned(1))
{
}
// copy constructor implements counted referencing - no copy is made
template <typename T, typename C>
simple_ptr_base<T,C>::simple_ptr_base(const simple_ptr_base<T,C>& r) :
m_pointer(r.m_pointer),
m_count(r.m_count)
{
increment();
}
// assignment operator - required, else the output of GCC suffers segmentation faults
template <typename T, typename C>
simple_ptr_base<T,C>& simple_ptr_base<T,C>::operator=(const simple_ptr_base<T,C>& r)
{
alias(r);
return *this;
}
// destructor decrements the reference count and delete only when the last reference is destroyed
template <typename T, typename C>
simple_ptr_base<T,C>::~simple_ptr_base(void)
{
if(decrement())
{
delete m_pointer;
delete m_count;
}
}
//////////////////////////////////////////////////////////////////////////////
// logical tests to see if there is anything contained in the pointer since it can be null
template <typename T, typename C>
bool simple_ptr_base<T,C>::null(void) const
{
return m_pointer==0;
}
template <typename T, typename C>
bool simple_ptr_base<T,C>::present(void) const
{
return m_pointer!=0;
}
template <typename T, typename C>
bool simple_ptr_base<T,C>::operator!(void) const
{
return m_pointer==0;
}
template <typename T, typename C>
simple_ptr_base<T,C>::operator bool(void) const
{
return m_pointer!=0;
}
//////////////////////////////////////////////////////////////////////////////
// dereference operators and functions
template <typename T, typename C>
T& simple_ptr_base<T,C>::operator*(void) throw(null_dereference)
{
if (!m_pointer) throw null_dereference("null pointer dereferenced in simple_ptr::operator*");
return *m_pointer;
}
template <typename T, typename C>
const T& simple_ptr_base<T,C>::operator*(void) const throw(null_dereference)
{
if (!m_pointer) throw null_dereference("null pointer dereferenced in simple_ptr::operator*");
return *m_pointer;
}
template <typename T, typename C>
T* simple_ptr_base<T,C>::operator->(void) throw(null_dereference)
{
if (!m_pointer) throw null_dereference("null pointer dereferenced in simple_ptr::operator->");
return m_pointer;
}
template <typename T, typename C>
const T* simple_ptr_base<T,C>::operator->(void) const throw(null_dereference)
{
if (!m_pointer) throw null_dereference("null pointer dereferenced in simple_ptr::operator->");
return m_pointer;
}
//////////////////////////////////////////////////////////////////////////////
// explicit function forms of the above assignment dereference operators
template <typename T, typename C>
void simple_ptr_base<T,C>::set_value(const T& data) throw(illegal_copy)
{
set(C()(data));
}
template <typename T, typename C>
T& simple_ptr_base<T,C>::value(void) throw(null_dereference)
{
if (!m_pointer) throw null_dereference("null pointer dereferenced in simple_ptr::value");
return *m_pointer;
}
template <typename T, typename C>
const T& simple_ptr_base<T,C>::value(void) const throw(null_dereference)
{
if (!m_pointer) throw null_dereference("null pointer dereferenced in simple_ptr::value");
return *m_pointer;
}
template <typename T, typename C>
void simple_ptr_base<T,C>::set(T* data)
{
unsigned& count = *m_count;
if (count<=1)
delete m_pointer;
else
{
--count;
m_count = new unsigned(1);
}
m_pointer = data;
}
template <typename T, typename C>
T* simple_ptr_base<T,C>::pointer(void)
{
return m_pointer;
}
template <typename T, typename C>
const T* simple_ptr_base<T,C>::pointer(void) const
{
return m_pointer;
}
////////////////////////////////////////////////////////////////////////////////
// functions to manage counted referencing
template <typename T, typename C>
void simple_ptr_base<T,C>::increment(void)
{
++(*m_count);
}
template <typename T, typename C>
bool simple_ptr_base<T,C>::decrement(void)
{
unsigned& count = *m_count;
--count;
return count == 0;
}
// make this an alias of the passed object
template <typename T, typename C>
void simple_ptr_base<T,C>::alias(const simple_ptr_base<T,C>& r)
{
// make it alias-copy safe - this means that I don't try to do the
// assignment if r is either the same object or an alias of it
if (m_pointer==r.m_pointer) return;
if(decrement()) {
delete m_pointer;
delete m_count;
}
m_pointer = r.m_pointer;
m_count = r.m_count;
increment();
}
template <typename T, typename C>
bool simple_ptr_base<T,C>::aliases(const simple_ptr_base<T,C>& r) const
{
return m_count == r.m_count;
}
template <typename T, typename C>
unsigned simple_ptr_base<T,C>::alias_count(void) const
{
return *m_count;
}
template <typename T, typename C>
void simple_ptr_base<T,C>::clear(void)
{
set(0);
}
template <typename T, typename C>
void simple_ptr_base<T,C>::clear_unique(void)
{
set(0); // no difference between clear and clear_unique with the simple_ptr
}
template <typename T, typename C>
void simple_ptr_base<T,C>::make_unique(void) throw(illegal_copy)
{
unsigned& count = *m_count;
if (count <= 1) return;
--count;
if (m_pointer) m_pointer = C()(*m_pointer);
m_count = new unsigned(1);
}
template <typename T, typename C>
void simple_ptr_base<T,C>::copy(const simple_ptr_base<T,C>& data) throw(illegal_copy)
{
alias(data);
make_unique();
}
#ifdef STLPLUS_MEMBER_TEMPLATES
// dynamic cast of underlying pointer to a derived/parent
template <typename T, typename C>
template <typename T2>
simple_ptr_base<T2,C> simple_ptr_base<T,C>::dyn_cast(void) const
{
simple_ptr_base<T2,C> rtn;
rtn.m_pointer = dynamic_cast<T2*>(m_pointer);
if (rtn.m_pointer) {
delete rtn.m_count;
rtn.m_count = m_count;
rtn.increment();
}
return rtn;
}
// static cast of underlying pointer to a derived/parent
template <typename T, typename C>
template <typename T2>
simple_ptr_base<T2,C> simple_ptr_base<T,C>::stat_cast(void) const
{
simple_ptr_base<T2,C> rtn;
rtn.m_pointer = static_cast<T2*>(m_pointer);
if (rtn.m_pointer) {
delete rtn.m_count;
rtn.m_count = m_count;
rtn.increment();
}
return rtn;
}
// cast of underlying pointer to a base - while keeping the same ref-counted object
template <typename T, typename C>
template <typename T2>
simple_ptr_base<T2,C> simple_ptr_base<T,C>::cast(void) const
{
simple_ptr_base<T2,C> rtn;
rtn.m_pointer = (T2*)m_pointer;
if (rtn.m_pointer) {
delete rtn.m_count;
rtn.m_count = m_count;
rtn.increment();
}
return rtn;
}
#endif
// internal function for distinguishing unique simple_ptr objects
// used for example in persistence routines
template <typename T, typename C>
unsigned* simple_ptr_base<T,C>::_count(void) const
{
return m_count;
}
template <typename T, typename C>
T* simple_ptr_base<T,C>::_pointer(void) const
{
return m_pointer;
}
template <typename T, typename C>
void simple_ptr_base<T,C>::_make_alias(T* pointer, unsigned* count)
{
// make it alias-copy safe - this means that I don't try to do the
// assignment if r is either the same object or an alias of it
if (m_count != count)
{
if(decrement())
{
delete m_pointer;
delete m_count;
}
m_pointer = pointer;
m_count = count;
increment();
}
}
////////////////////////////////////////////////////////////////////////////////
} // end namespace stlplus
| true |
4cebd106d4905845614c8bb058a329a5a34c76d6 | C++ | yuhenghuang/Leetcode | /1446_ConsecutiveCharacters.cpp | UTF-8 | 389 | 2.6875 | 3 | [] | no_license | #include "utils.hpp"
class Solution {
public:
int maxPower(string s) {
int n = s.size();
if (n<2) return n;
int res = 1, curr = 1;
for (int i=1; i<n; ++i) {
if (s[i-1]==s[i])
++curr;
else
curr = 1;
res = max(res, curr);
}
return res;
}
};
int main() {
UFUNC(Solution::maxPower);
return 0;
} | true |
864a38d4f07e9967e722d12516848eeec68cf390 | C++ | mluiselys/TP1-Puelles-Medina | /cVehiculo.h | UTF-8 | 1,321 | 2.671875 | 3 | [] | no_license | #pragma once
#include <iostream>
#include <string>
#include "cEnum.h"
using namespace std;
class cVehiculo
{
private:
//Atributos
int Cant_Pasajeros; //en el constructor se inicializa de una vez
float Precio_Base;
float Precio_Dia;
bool Estado;
bool Verificado;
string Patente;
Color color;
Tipo_Vehiculo tipo;
public:
//constructor
cVehiculo(Color color_, string patente, float precioDia, Tipo_Vehiculo tipo);
//Destructor
~cVehiculo();
//Verifica la seguridad del vehiculo
void VerificacionSeguridad();
//Informa que la seguridad de vehiculo esta pendiente
void VerificacionSeguridadPendiente();
//Verifica si el vehiculo est alquilado
bool VerificarAlquiler();
//setters y getters
void setestado(bool estado_) { Estado = estado_; }
int getCantPasajeros() { return Cant_Pasajeros; };
Color getcolor() { return color; };
bool getEstado() { return Estado; };
string getpatente() { return Patente; };
float getPreciobase() { return Precio_Base; };
float getpreciodia() { return Precio_Dia; };
Tipo_Vehiculo gettipo() { return tipo; };
bool getverificado() { return Verificado; };
//Se imprime
string To_String();
string To_string_Vehiculo();
string To_String_Color();
void imprimir();
};
| true |
bb73a559cd9b5e72198393050a61541807f67d90 | C++ | SeisSol/Meshing | /check_mesh/src/mesh.h | UTF-8 | 1,372 | 2.6875 | 3 | [] | no_license | #ifndef MESH_H_
#define MESH_H_
#include <array>
#include <map>
#include <sstream>
#include <string>
#include <vector>
#include "PUML/PUML.h"
class Mesh {
public:
explicit Mesh(std::string const& fileName);
~Mesh() = default;
[[nodiscard]] std::size_t numVertices() const { return puml.vertices().size(); }
[[nodiscard]] std::size_t numElements() const { return puml.cells().size(); }
[[nodiscard]] bool checkNeighbors() const;
private:
PUML::TETPUML puml;
enum class BCType {
internal, external, unknown
};
BCType bcToType(int id) const {
if (id == 0 || id == 3 || id > 64) {
return BCType::internal;
} else if (id == 1 || id == 2 || id == 5 || id == 6) {
return BCType::external;
} else {
return BCType::unknown;
}
}
std::string bcToString(int id) const {
if (id == 0) { return std::string("regular"); }
else if (id == 1) { return std::string("free surface"); }
else if (id == 2) { return std::string("free surface with gravity"); }
else if (id == 3) { return std::string("dynamic rupture"); }
else if (id == 5) { return std::string("absorbing"); }
else if (id == 6) { return std::string("periodic"); }
else if (id > 64) {
std::stringstream s;
s << "fault-tagging (" << id << ")";
return s.str();
} else {return std::string(""); }
}
};
#endif
| true |
05cc0b1a564392f7aa29191da818dddbf667d92e | C++ | FonzTech/SphereBall | /src/GameObject.cpp | UTF-8 | 2,854 | 2.671875 | 3 | [] | no_license | #include "GameObject.h"
#include "Camera.h"
const s32 GameObject::getCommonBasicMaterial(E_MATERIAL_TYPE basicMaterial)
{
// Create basic shader
BasicShaderCallback* bsc = new BasicShaderCallback(this);
IGPUProgrammingServices* gpu = driver->getGPUProgrammingServices();
s32 material = gpu->addHighLevelShaderMaterialFromFiles("shaders/standard.vs", "shaders/standard.fs", bsc, basicMaterial);
bsc->drop();
return material;
}
std::shared_ptr<GameObject> GameObject::createInstance(const nlohmann::json &jsonData)
{
return nullptr;
}
void GameObject::assignGameObjectCommonData(const nlohmann::json& commonData)
{
for (u8 i = 0; i < 3; ++i)
{
std::string key = i == 0 ? "position" : i == 1 ? "rotation" : "scale";
vector3df v;
const auto& iterator = commonData.find(key);
if (iterator == commonData.end())
{
v = i == 2 ? vector3df(1, 1, 1) : vector3df(0, 0, 0);
}
else
{
iterator->at("x").get_to(v.X);
iterator->at("y").get_to(v.Y);
iterator->at("z").get_to(v.Z);
}
if (i == 0)
{
this->position = v;
}
else if (this->models.size() > 0)
{
if (i == 1)
{
this->models.at(0)->rotation = v;
}
else
{
this->models.at(0)->scale = v;
}
}
}
}
GameObject::GameObject()
{
// Initialize vector for models
models = std::vector<std::shared_ptr<Model>>();
// Initialize variables
gameObjectIndex = 0;
destroy = false;
}
void GameObject::postUpdate()
{
}
aabbox3df GameObject::getBoundingBox()
{
return models.at(0)->mesh->getBoundingBox();
}
void GameObject::applyNormalMapping(IMaterialRendererServices* services, const std::shared_ptr<Model> model)
{
// Apply normal map if required
const bool useNormalMap = model->normalMapping.textureIndex > 0;
services->setVertexShaderConstant("useNormalMap", &useNormalMap, 1);
services->setPixelShaderConstant("useNormalMap", &useNormalMap, 1);
// Check for normal map existance
if (useNormalMap)
{
const vector3df p = Camera::singleton->getPosition();
services->setVertexShaderConstant("eyePos", &p.X, 3);
const vector3df lightDir(0, -1, 1);
services->setVertexShaderConstant("lightDir", &lightDir.X, 3);
const vector3df eyeDir = Camera::singleton->getLookAt() - p;
services->setVertexShaderConstant("eyeDir", &eyeDir.X, 3);
services->setPixelShaderConstant("lightPower", &model->normalMapping.lightPower, 1);
services->setPixelShaderConstant("normalMap", &model->normalMapping.textureIndex, 1);
}
}
GameObject::BasicShaderCallback::BasicShaderCallback(GameObject* go)
{
this->go = go;
}
void GameObject::BasicShaderCallback::OnSetConstants(IMaterialRendererServices* services, s32 userData)
{
// Execute parent method
ShaderCallback::OnSetConstants(services, userData);
// Apply normal mapping if required
if (go->models.size())
{
go->applyNormalMapping(services, go->models.at(0));
}
} | true |
6021efaa2a65a30661122ad698eae25feb5fbb48 | C++ | tarunluthra123/Competitive-Programming | /Hackerearth/Bitwise Manipulation/Bit flipping game.cpp | UTF-8 | 2,419 | 3.78125 | 4 | [] | no_license | /*
https://www.hackerearth.com/practice/basic-programming/bit-manipulation/basics-of-bit-manipulation/practice-problems/algorithm/bit-flippings-dd1f7ef1/
Bit Flipping Game
Two players A and B are playing a game.They are given binary numbers as input. Each binary number is represented as a string of
characters '0' or '1'. The string always ends at '1'. In one move each player decides a bit position . Then he visits all the
numbers and if their bit at that position is '1' then he changes it to '0'. It is mandatory to flip(change '1' to '0') bit of atleast one number in each move. The player who is unable to make a move loses. Player A begins the game.
Input
First line contains a number N as input. Next N lines contain a binary string each.
Output
Print A if player A wins , B otherwise. In the next line print the move number of the last move of the winning player.
Constraints
1<=N<=10^5
1<=|S|<=10^6 , |S| where is sum of length of all bit strings.
SAMPLE INPUT
2
01
001
SAMPLE OUTPUT
B
2
Explanation
First string in the input is 01 so its 0th bit is 0 and 1st bit is 1. Rest all the bits are zero
Second string in the input is 001 , its 0th bit is 0 , 1st bit is also 0 and second bit is 1. Rest all the bits are zero.
First move : Player A selects the bit position 1. So first string becomes 00 and second string is 001
Second move: Player B selects the bit position 2. So first string remains 00 and second becomes 000.
Now the turn is of player A but there are no numbers which have '1' in it's binary representation so A loses and B wins. Also the last move played by the player B is 2. Hence the move number is 2.
*/
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
long n, i, maxLength, l;
string s[100000];
cin >> n;
for (i = 0; i < n; i++)
{
cin >> s[i];
l = s[i].size();
maxLength = max (maxLength, l);
}
long count = 0;
for (unsigned long j = 0; j < maxLength; j++)
{
for (i = 0; i < n; i++)
{
if (j >= s[i].size() )
continue; //continue for i loop
if (s[i][j] == '1')
{
count++;
break; //continue for j loop
}
}
}
if (count & 1)
cout << 'A';
else
cout << 'B';
cout << endl << count;
return 0;
}
| true |
c3c9574788b347ded71e0c39cf5c206c0d0c4ff7 | C++ | mkostanbaeva/urlcounter | /main.cpp | UTF-8 | 9,533 | 3.046875 | 3 | [] | no_license | #include <iostream>
#include <map>
#include <string>
#include <algorithm>
#include <fstream>
#include <boost/asio.hpp>
#include <boost/asio/connect.hpp>
#include <boost/algorithm/string.hpp>
/*! \mainpage This programm counts the repeted words.
* To compile the program and the follow use you need to install the boost library.
*
* The file make.sh is using to compile this programm.
* Use the following expressin to run the programm: ./urlcounter <URL>
* Result of the programm will be displayed in the file output.txt.
* Logs of the programm will be displayed in the file trace.txt.
*/
using boost::asio::ip::tcp;
namespace asio = boost::asio;
using namespace std;
//std::ofstream trace;
//! Using the synchronous http client.
class HttpClient
{
public:
//! It's the defualt constructor.
/*!
It's creating a socket that is attached to the service.
*/
HttpClient() : socket(io_service)
{}
//! Reading contnent of the page.
/*!
There is a connection to host then sending request and after reading response.
\param host - ip-adress or domain name.
\return It's returning content of the page without header HTTP protocol.
*/
std::string ReadContent(const std::string& host)
{
Connect(host);
if (SendRequest(host))
return GetContentResponse();
return "";
}
private:
//! Connection to host.
/*!
There is creating an integrator by points connection to host and open the socket.
\param host - ip-adress or domain name.
*/
void Connect(const std::string& host)
{
try
{
if (host.empty())
return;
std::cout << "Conecting to " << host <<"\n"<< endl;
tcp::resolver resolver(io_service);
tcp::resolver::query query(host, "http");
tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
asio::connect(socket, endpoint_iterator);
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << "\n";
}
return;
}
//! Sending request.
/*!
A request with termination of connection after the server response received.
\param host - ip-adress or domain name.
\return It is return the value TRUE if the host name is not empty and unable to write request to the socket.
*/
bool SendRequest(const std::string& host)
{
try
{
if (host.empty())
return false;
std::cerr<<"Sending request\n"<<endl;
asio::streambuf request;
std::ostream request_stream(&request);
request_stream << "GET / HTTP/1.0\r\n";
request_stream << "Host: " << host << "\r\n";
request_stream << "Accept: */*\r\n";
request_stream << "Connection: close\r\n\r\n";
std::cerr<<"Write the socket"<< endl;
std::cerr<<"Write the request "<< endl;
boost::asio::write(socket, request);
return true;
}
catch (std::exception& e)
{
std::cout << "Exception: " << e.what() << "\n";
}
return false;
}
//! Reading the answer and returning content of the page.
/*!
There is reading and handling responses from the server. After removes the http protocol header.
\return It is return the page without http protocol header and return an empty string if an error occurs.
*/
std::string GetContentResponse()
{
try
{
asio::streambuf response;
asio::read_until(socket, response, "\r\n");
std::istream response_stream(&response);
std::string http_version;
response_stream >> http_version;
std::cerr<<"The HTTP version is "<<http_version<<"\n"<<endl;
unsigned int status_code;
response_stream >> status_code;
std::cerr<<"Status code is "<<status_code<<"\n"<<endl;
std::string status_message;
std::getline(response_stream, status_message);
if (!response_stream || http_version.substr(0, 5) != "HTTP/")
{
std::cout << "Invalid server response format\n";
return "";
}
if (status_code != 200)
{
std::cout << "The server returned an error code -" << status_code << "\n";
return "";
}
std::cerr<<"The response header is reading and then passing.\n"<<endl;
asio::read_until(socket, response, "\r\n\r\n");
std::string header;
while (std::getline(response_stream, header) && header != "\r")
{}
std::ostringstream stringbuf;
boost::system::error_code error;
while (boost::asio::read(socket, response,
boost::asio::transfer_at_least(1), error))
{
stringbuf << &response;
}
if (error != boost::asio::error::eof)
throw boost::system::system_error(error);
return stringbuf.str();
}
catch (std::exception& e)
{
std::cout << "Exception: " << e.what() << "\n";
}
return "";
}
private:
//! Service
asio::io_service io_service;
//! Socket
tcp::socket socket;
};
//! Data hendling and counts of the words from page.
/*!
It is a class for hendling html page and counts of the words on it.
There is delete HTML tag. Then there are counted the word, sorted by it popularity.
*/
class WordsCounter
{
//! A hash-array: key is the word, value is counts of the words on that page.
typedef std::map<std::string, int> string_map;
//! The massif pairs of words is the number of repetition.
typedef std::vector<std::pair<std::string, int>> string_vector;
public:
//! There is returns massif of words and number of it repetition from html page.
/*!
\param text - defualt text from html page.
\return There is returning massif pairs of words and number of it repetition sorted by descending.
*/
string_vector GetWordsSortedByCount(const std::string& text)
{
string_map map = CreateWordsMap(RemoveHtmlTags(text));
return SortMapByValue(map);
}
private:
//! From sourse code of the page removed all html tags.
/*!
A tags like this one "<...>" are deleting.
\param html - a defualt text from html page.
\return There is returning text without tags.
*/
static std::string RemoveHtmlTags(const std::string& html)
{
std::string result;
bool add=true;
for(char c : html)
{
if (c=='<')
add=false;
if (add)
result += c;
if (c=='>') {
add=true;
result+=' ';
}
}
return result;
}
//! A hash-array of words is creating with repetition counter.
/*!
As words separators are used next symbols: space , . : ; " ' ( ) [ ] { } ! ? / | \ -
Also the word can be separated by tabs and new line symbols.
\param text - text for the processing.
\return A hash-array contain next description: a key is the word, a value is number of counts thea words in the text.
*/
static string_map CreateWordsMap(const std::string& text)
{
std::vector<std::string> words;
boost::split(words, text, boost::is_any_of("\t\n ,.:;\"'()[]{}!?/|\\-"));
string_map words_map;
for(auto word : words)
if (!word.empty())
words_map[word]++;
return words_map;
}
//! For sorting data are compares pairs "word - amount".
static bool ComparePair(std::pair<std::string, int> p1, std::pair<std::string, int> p2)
{
return (p1.second>p2.second ||
(p1.second==p2.second && p1.first<p2.first));
}
//! A words are sorting by the number of repetition.
/*!
Containts of the hash-array is sorting in descending order of frequency of repetiton of words and lexicographical order.
\param map - a hash-array contain next description: a key is the word, a value is the number of counts the word in the text.
\return Then returns a sorted massif pairs "word - amoun" in descending order.
*/
static string_vector SortMapByValue(const string_map& map)
{
string_vector words_vector;
for(auto pair : map)
words_vector.push_back(pair);
std::sort(words_vector.begin(), words_vector.end(), ComparePair);
return words_vector;
}
};
int main(int argc, const char * argv[])
{
std::string host("www.yandex.ru");
if (argc > 1)
{
host = std::string(argv[1]);
std::cout<<"Download content from \""<<host<<"\"...\n";
}
else
{
std::cout<<"Download content from \"www.yandex.ru\"...\n"
<<"Usage: "<<argv[0]<<" [host_name] for download from \"host_name\".\n";
}
// trace.open ("trace.txt");
HttpClient client;
auto text_content = client.ReadContent(host);
WordsCounter counter;
auto words_counts = counter.GetWordsSortedByCount(text_content);
std::ofstream file;
file.open ("output.txt");
for(auto pair : words_counts)
file<< pair.first<<"\t"<<pair.second<<"\n";
file.close();
std::cout<<"Complete.\n";
// trace.close();
return 0;
}
| true |
c81a2bf4514179d11a2b6e91509ab0d2caed8823 | C++ | yxpandjay/kkshell | /common/config/config_manager.cpp | UTF-8 | 7,692 | 2.5625 | 3 | [] | no_license | //
// Created by min on 2020/8/6.
//
#include "config_manager.h"
#include <libgen.h>
#include <zconf.h>
#include <QFile>
ConfigManager *ConfigManager::instance = new ConfigManager();
static const char *configPath = "~/.config/kkshell/ini/settings.ini";
static bool isFleExist(const char *path) {
return (access(path, 0) != -1);
}
static std::string expand_user(std::string path) {
if (not path.empty() and path[0] == '~') {
char const *home = getenv("HOME");
if (home) {
path.replace(0, 1, home);
}
}
return path;
}
static std::string dirName(const char *path) {
char buffer[PATH_MAX];
strcpy(buffer, path);
char *name = dirname(buffer);
return std::string(name);
}
ConfigManager::ConfigManager() {
absConfigPath_ = expand_user(configPath);
absConfigDir_ = dirName(absConfigPath_.c_str());
mIni.SetUnicode();
mIni.SetMultiLine();
if (!loadDataFromDB()) {
loadDefaultConfig();
}
}
bool ConfigManager::loadDataFromDB() {
SI_Error ret = mIni.LoadFile(absConfigPath_.c_str());
if (SI_OK != ret) {
fprintf(stderr,"loadDataFromDB error, reload default config\n");
return false;
}
std::string version = getString("app", "version", "0");
if ("0" == version) {
fprintf(stderr,"loadDataFromDB error, reload default config\n");
return false;
}
return true;
}
void ConfigManager::loadDefaultConfig() {
QFile defaultSettings(":/ini/settings.ini");
defaultSettings.open(QIODevice::ReadOnly);
mIni.LoadData(defaultSettings.readAll().data());
if (!save()) {
fprintf(stderr, "save config error\n");
}
}
bool ConfigManager::getBool(const char *section, const char *key, bool defaultValue) {
return mIni.GetBoolValue(section, key, defaultValue);
}
static std::vector<bool> string2BooleanArray(const char *str) {
std::vector<bool> array;
char *p = const_cast<char *>(str);
while (*str != '\0') {
while (*str == ',' || isspace(static_cast<int>(*str))) str++;
p = const_cast<char *>(str);
while (*p != '\0' && *p != ',') p++;
char tmp[32] = {0};
if (p > str) {
strncpy(tmp, str, p - str);
if (!strcasecmp(tmp, "y")
|| !strcasecmp(tmp, "yes")
|| !strcasecmp(tmp, "true")
|| !strcasecmp(tmp, "1"))
array.push_back(true);
if (!strcasecmp(tmp, "n")
|| !strcasecmp(tmp, "no")
|| !strcasecmp(tmp, "false")
|| !strcasecmp(tmp, "0"))
array.push_back(false);
}
if (*p == '\0') break;
str = ++p;
}
return array;
}
std::vector<bool> ConfigManager::getBoolArray(const char *section, const char *key) {
std::vector<bool> result;
const char *str = mIni.GetValue(section, key, NULL);
if (str != NULL) {
result = string2BooleanArray(str);
}
return result;
}
int32_t ConfigManager::getInt(const char *section, const char *key, int32_t defaultValue) {
return (int32_t) mIni.GetLongValue(section, key, defaultValue);
}
std::vector<int32_t> string2IntArray(const char *str) {
std::vector<int32_t> array;
char *p = const_cast<char *>(str);
while (*str != '\0') {
while (*str == ',' || isspace(static_cast<int>(*str))) str++;
p = const_cast<char *>(str);
while (*p != '\0' && *p != ',') p++;
char tmp[32] = {0};
if (p > str) {
strncpy(tmp, str, p - str);
int32_t value;
if (!strncasecmp(tmp, "0x", 2)) {
if (EOF == sscanf(tmp, "%x", &value)) {
fprintf(stderr,"string2IntArray error: %s\n", str);
}
} else {
if (EOF == sscanf(tmp, "%d", &value)) {
fprintf(stderr, "string2IntArray error: %s\n", str);
}
}
array.push_back(value);
}
if (*p == '\0') break;
str = ++p;
}
return array;
}
std::vector<int32_t> ConfigManager::getIntArray(const char *section, const char *key) {
std::vector<int32_t> result;
const char *str = mIni.GetValue(section, key, NULL);
if (str != NULL) {
result = string2IntArray(str);
}
return result;
}
double ConfigManager::getDouble(const char *section, const char *key, double defaultValue) {
return mIni.GetDoubleValue(section, key, defaultValue);;
}
std::vector<double> string2DoubleArray(const char *str) {
std::vector<double> array;
char *p = const_cast<char *>(str);
while (*str != '\0') {
while (*str == ',' || isspace(static_cast<int>(*str))) str++;
p = const_cast<char *>(str);
while (*p != '\0' && *p != ',') p++;
char tmp[32] = {0};
if (p > str) {
strncpy(tmp, str, p - str);
double value;
if (EOF == sscanf(tmp, "%lf", &value)) {
fprintf(stderr,"string2DoubleArray error: %s\n", str);
}
array.push_back(value);
}
if (*p == '\0') break;
str = ++p;
}
return array;
}
std::vector<double> ConfigManager::getDoubleArray(const char *section, const char *key) {
std::vector<double> result;
const char *str = mIni.GetValue(section, key, NULL);
if (str != NULL) {
result = string2DoubleArray(str);
}
return result;
}
const char *ConfigManager::getCString(const char *section, const char *key, const char *defaultValue) {
return mIni.GetValue(section, key, defaultValue);
}
std::string ConfigManager::getString(const char *section, const char *key, const char *defaultValue) {
return mIni.GetValue(section, key, defaultValue);
}
void ConfigManager::setBool(const char *section, const char *key, bool value) {
mIni.SetBoolValue(section, key, value);
save();
}
void ConfigManager::setInt(const char *section, const char *key, int32_t value) {
mIni.SetLongValue(section, key, value);
save();
}
void ConfigManager::setDouble(const char *section, const char *key, double value) {
mIni.SetDoubleValue(section, key, value);
save();
}
void ConfigManager::setCString(const char *section, const char *key, const char *value) {
mIni.SetValue(section, key, value);
save();
}
bool ConfigManager::save() {
if (!isFleExist(absConfigDir_.c_str())) {
char cmd[256];
memset(cmd, 0, sizeof(cmd));
sprintf(cmd, "mkdir -p %s", absConfigDir_.c_str());
system(cmd);
system("sync");
}
SI_Error ret = mIni.SaveFile(absConfigPath_.c_str());
return ret == SI_OK;
}
std::vector<std::string> ConfigManager::getAllSections() {
CSimpleIniA::TNamesDepend sections;
mIni.GetAllSections(sections);
std::vector<std::string> sectionList;
for(CSimpleIniA::Entry const &entry : sections) {
sectionList.push_back(std::string(entry.pItem));
}
return sectionList;
}
std::vector<std::string> ConfigManager::getSectionKeys(const char *section) {
CSimpleIniA::TNamesDepend keys;
mIni.GetAllKeys(section, keys);
std::vector<std::string> keysList;
for(CSimpleIniA::Entry const &entry : keys) {
keysList.push_back(std::string(entry.pItem));
}
return keysList;
}
void ConfigManager::deleteSection(const char *section) {
std::vector<std::string> keys = getSectionKeys(section);
for (std::string key : keys) {
mIni.Delete(section, key.c_str(), true);
}
save();
}
void ConfigManager::deleteKey(const char *section, const char *key) {
mIni.Delete(section, key);
save();
}
| true |
b89ff5c7f19c128867fce884eed2379d06d8d1e2 | C++ | Gabsop/LP1 | /Aula 17/include/Agencia.hpp | UTF-8 | 368 | 2.6875 | 3 | [] | no_license | #include <string>
using namespace std;
class Agencia
{
private:
string nome;
int numero;
string cnpj;
public:
Agencia();
Agencia(string nome, int numero, string cnpj);
~Agencia();
string getNome();
void setNome(string nome);
int getNumero();
void setNumero(int numero);
string getCnpj();
void setCnpj(string cnpj);
}; | true |
ef178760832ce02d356a7c57c121ca3972f50449 | C++ | samarth-robo/deepnav_cvpr17 | /utils/src/search.cpp | UTF-8 | 4,740 | 3.15625 | 3 | [] | no_license | #include <search.h>
#include <climits>
#include <iostream>
#include <utility>
#include <boost/functional/hash.hpp>
using namespace std;
size_t NodeHash::operator()(Node::Ptr const &n) const {
size_t seed = 7;
boost::hash_combine(seed, n->id);
boost::hash_combine(seed, static_cast<size_t>(n->d));
return seed;
}
bool NodeEqual::operator()(Node::Ptr const &a, Node::Ptr const &b) const {
return (a->id == b->id) && (a->d == b->d);
}
bool PairCompare::operator()(pair<Node::Ptr, double> const &p1,
pair<Node::Ptr, double> const &p2) const {
return p1.second > p2.second; // > for reversed priority q (pop() gives element with lowest priority)
}
size_t Searcher::get_path_length() {
size_t len = 0;
for(int i = 0; i < path.size()-1; i++) {
if(!path[i]->equal(path[i+1])) len++;
}
return len;
}
// Exhaustive enumeration in the graph
// ignores start and end
bool ExhaustiveSearcher::search(Node::Ptr const &start,
Node::Ptr const &end) {
// check that graph has been set
if(!graph) {
cout << "set_graph() must be called before a_star_search()" << endl;
return false;
}
path.clear();
for(auto it = graph->cbegin(); it != graph->cend(); it++) {
Node::Ptr n = it->second;
path.push_back(n);
}
return true;
}
float AStarSearcher::a_star_heuristic(Node::Ptr const &s,
Node::Ptr const &t) const {
double dist;
geod.Inverse(float(s->lat), float(s->lng), float(t->lat), float(t->lng),
dist);
return static_cast<float>(dist);
}
// returns length of shortest path from start_node to destination
// assumes search() has been run before
float AStarSearcher::get_cost(Node::Ptr const &start,
Node::Ptr const &end) const {
auto got_start = g_score.find(start);
auto got_end = g_score.find(end);
if(got_start == g_score.end()) {
cout << "Could not find in g_score " << start << endl;
return -1.f;
} else if(got_end == g_score.end()) {
cout << "Could not find in g_score " << end << endl;
return -1.f;
} else {
float cost = got_end->second - got_start->second;
return cost;
}
}
// A* search in the graph
bool AStarSearcher::search(Node::Ptr const &s, Node::Ptr const &t) {
// cout << "A* start " << s << " end " << t << endl;
// check that start and end are valid nodes
Node::Ptr start = graph->get_node_ptr(s->id, s->d);
if(!start) {
cout << "Start node " << s << " is not a valid node" << endl;
return false;
}
Node::Ptr end = graph->get_node_ptr(t->id, t->d);
if(!end) {
cout << "End node " << t << " is not a valid node" << endl;
return false;
}
// check that graph has been set
if(!graph) {
cout << "set_graph() must be called before a_star_search()" << endl;
return false;
}
// clear book keeping data structures
while(!q.empty()) {q.pop();}
g_score.clear();
came_from.clear();
// init
q.push(make_pair(start, 0.f)); // priority does not matter for first element
// cout << "Pushed " << start << ", " << 0.0 << " to q" << endl;
g_score[start] = 0.0;
came_from[start] = start;
// search
bool found = false;
while(!q.empty()) {
pair<Node::Ptr, double> p = q.top();
q.pop();
Node::Ptr current = p.first;
// cout << "Popped " << current << " from q" << endl;
if(current->equald(end)) {
found = true;
break;
}
// process neighbors
// cout << "Has " << current->nbrs.size() << " neighbors" << endl;
for(int i = 0; i < current->nbrs.size(); i++) {
Node::Ptr nbr = current->nbrs[i];
double nbr_g_score = g_score[current] + current->distances[i];
// cout << "Considering Nbr " << nbr << ", with potential g_score = " << nbr_g_score << endl;
bool nbr_unexplored = true;
if(g_score.count(nbr)) {
nbr_unexplored = false;
// cout << nbr << " is previously explored, with a g_score of " << g_score[nbr] << endl;
} else {
// cout << nbr << " is unexplored" << endl;
}
if(nbr_unexplored || nbr_g_score < g_score[nbr]) {
g_score[nbr] = nbr_g_score;
double nbr_f_score = nbr_g_score + a_star_heuristic(nbr, end);
q.push(make_pair(nbr, nbr_f_score));
// cout << "Pushed " << nbr << ", " << nbr_f_score << " to q" << endl;
came_from[nbr] = current;
}
}
}
// get path
// cout << "Calculating path" << endl;
path.clear();
if(found) {
path.insert(path.begin(), end);
while(!path[0]->equald(start)) {
path.insert(path.begin(), came_from[path[0]]);
}
// cout << "Path calculated" << endl;
// cout << "Path is" << endl;
// for(int i = 0; i < path.size(); i++) cout << path[i] << endl;
} else {
cout << "Path not found" << endl;
}
return found;
}
| true |
a1bde86f0f937950905324dda53a0bcd3a142a97 | C++ | zdl1016-test/a | /test/signal_test/test.cpp | UTF-8 | 1,063 | 3 | 3 | [] | no_license | #include <stdio.h>
#include <signal.h>
#include <unistd.h>
static void sig_usr(int);
void RunWork();
int main(void)
{
RunWork();
#if 0
for(; ;)
pause();
#endif
}
void RunWork()
{
pid_t pid = fork();
if( pid == 0 )
{
printf( "enter child process ... \n" );
if(signal(SIGUSR1, sig_usr) == SIG_ERR)
printf("can't catch SIGUSR1\n");
if(signal(SIGUSR2, sig_usr) == SIG_ERR)
printf("can't catch SIGUSR2\n");
for(;;)
{
sleep(1);
}
printf( "will leave pid==0\n" );
}
if( pid > 0 )
{
printf( "continue parent process ... \n" );
printf( "will leave pid>0\n" );
}
printf( "exit RunWork.\n" );
}
static void sig_usr(int signo){
if(signo == SIGUSR1)
printf("received SIGUSR1\n");
else if(signo == SIGUSR2)
printf("received SIGUSR2\n");
else
printf("received signal %d\n", signo);
}
| true |
69e593b215f2168f727688486d392b257e0ba2a0 | C++ | HeRaNO/OI-ICPC-Codes | /Vijos/1419.cpp | UTF-8 | 942 | 2.765625 | 3 | [
"MIT"
] | permissive | #include <cstring>
#include <iostream>
#define MAXN 110
using namespace std;
int n, T = 1, w, pos;
string pass[MAXN * MAXN], word[MAXN];
string S;
char ch;
inline char uppercase(char a)
{
if (a >= 'a' && a <= 'z') a -= 32;
return a;
}
int check(string x, string y)
{
int t = 0;
for (int i = 0; i < x.length(); i++) if (uppercase(x[i]) != uppercase(y[i])) t++;
return t;
}
int main()
{
cin >> n;
getchar();
while (true)
{
ch = getchar();
if (ch == ' ')
{
T++;
continue;
}
if (ch == '!') break;
pass[T] += ch;
}
getchar();
for (int i = 1; i <= n; i++) cin >> word[i];
pass[1][0] += 32;
for (int i = 1; i <= T; i++)
for (int j = 1; j <= n; j++)
{
int t = check(pass[i], word[j]);
if (t <= 1)
{
pass[i] = word[j];
if (t == 1) w++;
break;
}
}
pass[1][0] -= 32;
cout << w << endl;
for (int i = 1; i < T; i++) cout << pass[i] << " ";
cout << pass[T] << '!' << endl;
return 0;
}
| true |
4e4ce8bae39fd444ada2dcdef9290f12cdef2239 | C++ | matrix-io/matrix-lite-nfc-py | /hal_nfc_wrapper/reader/read_values/pages.cpp | UTF-8 | 1,386 | 2.75 | 3 | [] | no_license | #include <pybind11/pybind11.h>
#include "./pages.h"
#include "../../nfc.h"
namespace py = pybind11;
// Python object for NFC Pages
void nfc_pages_values(py::module &m) {
py::class_<pages_data>(m, "pages_data")
.def_readonly("read_complete", &pages_data::read_complete)
.def_readonly("content", &pages_data::content)
.def_readonly("read_status", &pages_data::read_status)
.def("__repr__", &pages_data::toString);
}
// Populate with last scanned NFC tag
pages_data::pages_data() {
// If new tag scanned, populate struct
if (nfc_data.pages.recently_updated) {
read_complete = nfc_data.pages.read_complete;// ** Fix for C++ boolean conversion
content = nfc_data.pages.content;
}
// Else set struct as empty
else {
read_complete = false;
}
}
std::string pages_data::toString() const {
// Create string from 2D vector
std::string printed_content = "[\n";
for ( std::vector<uint8_t> &page : nfc_data.pages.content ) {
printed_content += "[ ";
for ( int x : page ) printed_content.append(std::to_string(x)+", ");
printed_content.append("], ");
}
printed_content += "]";
return
"pages {\n\tread_complete: "+std::to_string(read_complete)+
"\n\tcontent: "+printed_content+
"\n\tread_status: "+std::to_string(read_status)+
"\n}\n";
} | true |
3a50730f43cbba917a72932f9c8d2dc5a7a6ef7f | C++ | Omkarkale0002/Developer | /c++/01_arth.cpp | UTF-8 | 414 | 3.40625 | 3 | [] | no_license | /*Pre-increment postincrement of a value*/
#include<iostream>
using namespace std;
int main() //main
{
int a=10; //int a
cout<<"The original value is:"<<a; //value
a++;
cout<<"\nThe 1st increment is:"<<a;
a++; //first increment
cout<<"\n The 2nd increment is:"<<a;
++a; //second
a++;
cout<<"\n The 3rd incrementis:"<<a; //third
}
| true |
66d8cbb6034a92ba77f1711d494b9a4a0ee52382 | C++ | Aumoa/SC.Game | /SC.Game/Cursor.cpp | UTF-8 | 1,274 | 2.59375 | 3 | [] | no_license | using namespace SC;
using namespace SC::Game;
using namespace System;
using namespace System::Drawing;
CursorLockMode Cursor::LockState::get()
{
return mLockMode;
}
void Cursor::LockState::set( CursorLockMode value )
{
mLockMode = value;
switch ( mLockMode )
{
case CursorLockMode::Locked:
{
RECT rect;
GetClientRect( App::hWnd, &rect );
ClientToScreen( App::hWnd, ( POINT* )&rect );
ClientToScreen( App::hWnd, ( POINT* )&rect + 1 );
POINT point;
point.x = ( rect.left + rect.right ) / 2;
point.y = ( rect.top + rect.bottom ) / 2;
SetCursorPos( point.x, point.y );
ScreenToClient( App::hWnd, &point );
Input::mCursorPos = Point( point.x, point.y );
break;
}
case CursorLockMode::Confined:
{
RECT rect;
GetClientRect( App::hWnd, &rect );
ClientToScreen( App::hWnd, ( POINT* )&rect );
ClientToScreen( App::hWnd, ( POINT* )&rect + 1 );
ClipCursor( &rect );
break;
}
case CursorLockMode::None:
ClipCursor( nullptr );
break;
}
}
bool Cursor::Visible::get()
{
return mVisible;
}
void Cursor::Visible::set( bool value )
{
if ( value )
{
while ( mVisible <= 0 )
{
mVisible += 1;
ShowCursor( TRUE );
}
}
else if ( !value )
{
while ( mVisible >= 1 )
{
mVisible -= 1;
ShowCursor( FALSE );
}
}
} | true |
9076e737bd92ab7f0f18eb5e7aa934e3124a5de3 | C++ | lyh4967/MyAlgorithm | /MyAlgorithm/MyAlgorithm/BOJ/incomplete/[15949]Piet.cpp | WINDOWS-1252 | 7,914 | 2.828125 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
//ó dp: R, CC:L
struct Node {
int a; int b; char bl;
Node() {}
Node(int _a, int _b, char _bl) :a(_a), b(_b), bl(_bl) {}
};
int N, M;
char map[100][100];
bool visited[100][100];
//DP: R: 0, D:1 ~~
//CC: L:0, R:1
vector<Node> candi[4];
char curBlock;
int a, b;
int dirArr[4][2] = { { 0,1 },{ 1,0 },{ 0,-1 },{ -1,0 } };
bool compare_a(Node nodeA, Node nodeB) {
return nodeA.a < nodeB.a;
}
bool compare_b(Node nodeA, Node nodeB) {
return nodeA.b < nodeB.b;
}
bool isRanged(int a, int b) {
return 0 <= a && a < N && 0 <= b && b < M;
}
void selectCodel(int dp, int cc) {
//cout << " dp && cc: " << dp << "," << cc << endl;
/*if (dp == 0) {
if(cc == 0){
for (int j = M - 1; j >= 0; j--) {
for (int i = 0; i < N; i++) {
if (curBlock == map[i][j] && visited[i][j] == true) {
a = i; b = j;
return;
}
}
}
}
else if (cc == 1) {
for (int j = M - 1; j >= 0; j--) {
for (int i = N - 1; i >= 0; i--) {
if (curBlock == map[i][j] && visited[i][j] == true) {
a = i; b = j;
return;
}
}
}
}
}
else if (dp == 1) {
if (cc == 0) {
for (int i = N - 1; i >= 0; i--) {
for (int j = M - 1; j >= 0; j--) {
if (curBlock == map[i][j] && visited[i][j] == true) {
a = i; b = j;
return;
}
}
}
}
else if (cc == 1) {
for (int i = N - 1; i >= 0; i--) {
for (int j = 0; j < M; j++) {
if (curBlock == map[i][j] && visited[i][j] == true) {
a = i; b = j;
return;
}
}
}
}
}
else if (dp == 2) {
if (cc == 0) {
for (int j = 0; j < M; j++) {
for (int i = N - 1; i >= 0; i--) {
if (curBlock == map[i][j] && visited[i][j] == true) {
a = i; b = j;
return;
}
}
}
}
else if (cc == 1) {
for (int j = 0; j < M; j++) {
for (int i = 0; i < N; i++) {
if (curBlock == map[i][j] && visited[i][j] == true) {
a = i; b = j;
return;
}
}
}
}
}
else if (dp == 3) {
if (cc == 0) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
if (curBlock == map[i][j] && visited[i][j] == true) {
a = i; b = j;
return;
}
}
}
}
else if (cc == 1) {
for (int i = 0; i < N; i++) {
for (int j = M - 1; j >= 0; j--) {
if (curBlock == map[i][j] && visited[i][j] == true) {
a = i; b = j;
return;
}
}
}
}
}*/
int length = candi[dp].size();
if (dp == 0) {
if (cc == 0) {
a = candi[dp][0].a;
b = candi[dp][0].b;
}
else if (cc == 1) {
a = candi[dp][length - 1].a;
b = candi[dp][length - 1].b;
}
}
else if (dp == 1) {
/*cout << endl;
cout << "functiorn: " << dp << "," << cc << endl;
cout << "length: " << length << endl;*/
if (cc == 0) {
a = candi[dp][length - 1].a;
b = candi[dp][length - 1].b;
}
else if (cc == 1) {
a = candi[dp][0].a;
b = candi[dp][0].b;
}
}
else if (dp == 2) {
if (cc == 0) {
a = candi[dp][length - 1].a;
b = candi[dp][length - 1].b;
}
else if (cc == 1) {
a = candi[dp][0].a;
b = candi[dp][0].b;
}
}
else if (dp == 3) {
if (cc == 0) {
a = candi[dp][0].a;
b = candi[dp][0].b;
}
else if (cc == 1) {
a = candi[dp][length - 1].a;
b = candi[dp][length - 1].b;
}
}
}
void print() {
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
if (visited[i][j] == 1) {
cout << "";
}
else
cout << "";
}
cout << endl;
}
}
int main() {
ios_base::sync_with_stdio(false); cin.tie(NULL);
cin >> N >> M;
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
cin >> map[i][j];
}
}
int DP, CC;
for (int i = 0; i < N; i++)
fill(visited[i], visited[i] + M, false);
queue<Node> que;
vector<char> answer;
DP = 0; CC = 0;
curBlock = map[0][0];
a = 0; b = 0;
que.push(Node(a, b, curBlock));
answer.push_back(curBlock);
Node node;
while (!que.empty()) {
node = que.front(); que.pop();
int ta = node.a; int tb = node.b; int tbl = node.bl;
if (visited[ta][tb])
continue;
visited[ta][tb] = true;
for (int i = 0; i < 4; i++) {
int nA = ta + dirArr[i][0];
int nB = tb + dirArr[i][1];
if (isRanged(nA, nB) && !visited[nA][nB] && map[nA][nB] == tbl) {
node.a = nA; node.b = nB; node.bl = tbl;
que.push(node);
}
}
}
bool Tflag = false;
for (int j = M - 1; j >= 0; j--) {//R
for (int i = 0; i < N; i++) {
if (visited[i][j]) {
Tflag = true;
candi[0].push_back(Node(i, j, curBlock));
}
}
if (Tflag)
break;
}
Tflag = false;
for (int i = N - 1; i >= 0; i--) {//D
for (int j = 0; j < M; j++) {
if (visited[i][j]) {
Tflag = true;
candi[1].push_back(Node(i, j, curBlock));
}
}
if (Tflag)
break;
}
Tflag = false;
for (int j = 0; j < M; j++) {//L
for (int i = 0; i < N; i++) {
if (visited[i][j]) {
Tflag = true;
candi[2].push_back(Node(i, j, curBlock));
}
}
if (Tflag)
break;
}
Tflag = false;
for (int i = 0; i < N; i++) {//U
for (int j = 0; j < M; j++) {
if (visited[i][j]) {
Tflag = true;
candi[3].push_back(Node(i, j, curBlock));
}
}
if (Tflag)
break;
}
sort(candi[0].begin(), candi[0].end(), compare_a);
sort(candi[1].begin(), candi[1].end(), compare_b);
sort(candi[2].begin(), candi[2].end(), compare_a);
sort(candi[3].begin(), candi[3].end(), compare_b);
int cnt = 0;
bool flag = false;
while (true) {
if (cnt == 8)
break;
cnt++;
selectCodel(DP, CC);
int nA = a + dirArr[DP][0];
int nB = b + dirArr[DP][1];
/*cout << endl;
cout << "log: " << a << "," << b << "," << curBlock << endl;
cout << "DP,CC: " << DP << "," << CC << endl;
cout << "candi: " << endl;
for (int i = 0; i < 4; i++) {
cout << i << ": ";
for (int j = 0; j < candi[i].size(); j++) {
cout << candi[i][j].a << "," << candi[i][j].b<<" ";
}
cout << endl;
}
print();*/
if (isRanged(nA, nB) && map[nA][nB] != 'X') {
curBlock = map[nA][nB];
answer.push_back(curBlock);
a = nA; b = nB;
cnt = 0;
for (int i = 0; i < N; i++)
fill(visited[i], visited[i] + M, false);
node.a = a; node.b = b; node.bl = curBlock;
que.push(node);
for (int tmp = 0; tmp < 4; tmp++)
candi[tmp].clear();
while (!que.empty()) {//bfs
node = que.front(); que.pop();
int ta = node.a; int tb = node.b; int tbl = node.bl;
if (visited[ta][tb])
continue;
visited[ta][tb] = true;
for (int i = 0; i < 4; i++) {
int tnA = ta + dirArr[i][0];
int tnB = tb + dirArr[i][1];
if (isRanged(tnA, tnB) && !visited[tnA][tnB] && map[tnA][tnB] == tbl) {
node.a = tnA; node.b = tnB; node.bl = tbl;
que.push(node);
}
}
}
Tflag = false;
for (int j = M - 1; j >= 0; j--) {//R
for (int i = 0; i < N; i++) {
if (visited[i][j]) {
Tflag = true;
candi[0].push_back(Node(i, j, curBlock));
}
}
if (Tflag)
break;
}
Tflag = false;
for (int i = N - 1; i >= 0; i--) {//D
for (int j = 0; j < M; j++) {
if (visited[i][j]) {
Tflag = true;
candi[1].push_back(Node(i, j, curBlock));
}
}
if (Tflag)
break;
}
Tflag = false;
for (int j = 0; j < M; j++) {//L
for (int i = 0; i < N; i++) {
if (visited[i][j]) {
Tflag = true;
candi[2].push_back(Node(i, j, curBlock));
}
}
if (Tflag)
break;
}
Tflag = false;
for (int i = 0; i < N; i++) {//U
for (int j = 0; j < M; j++) {
if (visited[i][j]) {
Tflag = true;
candi[3].push_back(Node(i, j, curBlock));
}
}
if (Tflag)
break;
}
sort(candi[0].begin(), candi[0].end(), compare_a);
sort(candi[1].begin(), candi[1].end(), compare_b);
sort(candi[2].begin(), candi[2].end(), compare_a);
sort(candi[3].begin(), candi[3].end(), compare_b);
}
else {
if (flag == true) {
flag = false;
DP++;
DP %= 4;
}
else {
flag = true;
CC++;
CC %= 2;
}
}
}
int length = answer.size();
for (int i = 0; i < length; i++) {
cout << answer[i];
}
cout << endl;
return 0;
} | true |