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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
e3eb98e2e678fb98674f1090bbec696feef3240f | C++ | zylzjucn/Leetcode | /200~299/221. Maximal Square.cpp | UTF-8 | 752 | 2.671875 | 3 | [] | no_license | class Solution {
public:
int maximalSquare(vector<vector<char>>& v) {
if (v.empty())
return 0;
int m = v.size(), n = v[0].size(), i, j, l = 0;
vector<vector<int>> v1(m, vector<int>(n, 0));
for (i = 0; i < m; i++) {
v1[i][0] = v[i][0] - '0';
l = max(l, v1[i][0]);
}
for (j = 1; j < n; j++) {
v1[0][j] = v[0][j] - '0';
l = max(l, v1[0][j]);
}
for (i = 1; i < m; i++)
for (j = 1; j < n; j++)
{
if(v[i][j] == '1')
v1[i][j] = min(v1[i - 1][j - 1], min(v1[i][j - 1], v1[i - 1][j])) + 1;
l = max(l, v1[i][j]);
}
return l * l;
}
};
| true |
36a5a446a18584c69d1251e17f3c0f701ffb4d2e | C++ | nideng/Data_Structures | /chapter02/SeqList.h | UTF-8 | 4,626 | 3.328125 | 3 | [] | no_license | #ifndef SEQLIST_H
#define SEQLIST_H
#include<memory>
#include<functional>
#include<stdexcept>
#include<initializer_list>
#include<iostream>
using std::allocator;
using std::function;
using std::invalid_argument;
using std::initializer_list;
template<typename T>class SeqList;
template<typename T>
int LocateElem(const SeqList<T>& seq, const T& e, function<bool(T, T)>f);
template<typename T>class SeqList
{
friend int LocateElem<T>(const SeqList<T>& seq, const T& e, function<bool(T, T)>f);
public:
SeqList() :length(0), listsize(0), elem(nullptr) {}
SeqList(const initializer_list<T>& l):length(l.size()),listsize(l.size())
{
auto data = alloc.allocate(length);
std::uninitialized_copy_n(l.begin(), length, data);
elem = data;
}
SeqList(const SeqList<T>&);
SeqList& operator=(const SeqList<T>&);
T& operator[](int i) {
if (i >= 0 && i < length)return *(elem + i);
else throw invalid_argument("invalid_argument");
}
const T& operator[](int i) const {
if (i >= 0 && i < length)return *(elem + i);
else throw invalid_argument("invalid_argument");
}
~SeqList();
void ClearList();
int ListLength()const;
bool ListEmpty()const { return length == 0 ? true : false; }
void GetElem(int i, T* e);//获取顺序表中第i个元素,将其存储到e中。
void PriorElem(const T& cur_e, T* pre_e);
void NextElem(const T& cur_e, T* next_e);
void ListInsert(int i, T e);
void ListInsert(T e);//默认插在最后面
void ListDelete(int i, T* e);
void ListDelete();
private:
void chk_n_alloc()
{
if (length == listsize) reallocate();
}
void free();
void reallocate();
private:
T* elem;//基址
int length;//当前长度
int listsize;//当前存储量
allocator<T>alloc;//分配元素
};
template<typename T>
SeqList<T>::SeqList(const SeqList<T>&seq)
:length(seq.length),listsize(seq.length)
{
auto data = alloc.allocate(length);
std::uninitialized_copy_n(seq.elem, length, data);
elem = data;
}
template<typename T>
SeqList<T>& SeqList<T>::operator=(const SeqList<T>& seq)
{
auto data = alloc.allocate(seq.length);
free();
length =listsize= seq.length;
std::uninitialized_copy_n(seq.elem, length, data);
elem = data;
return *this;
}
template<typename T>
void SeqList<T>::free()
{
if (elem)
{
for (int i = length; i !=0; i--)
alloc.destroy((elem+i-1));
}
alloc.deallocate(elem, listsize);
}
template<typename T>
SeqList<T>::~SeqList()
{
free();
}
template<typename T>
void SeqList<T>::ClearList()
{
if (elem)
{
for (int i = length; i != 0; i--)
alloc.destroy((elem + i - 1));
}
}
template<typename T>
int SeqList<T>::ListLength()const
{
return length;
}
template<typename T>
void SeqList<T>::reallocate()
{
auto newListsize = ListLength() ? 2 * ListLength() : 1;
auto newdata = alloc.allocate(newListsize);
auto dest = newdata;
auto e = elem;
for (int i = 0; i != ListLength(); i++)
alloc.construct(dest++, std::move(*e++));
free();
elem = newdata;
length = dest - elem;
listsize = newListsize;
}
template<typename T>
void SeqList<T>::GetElem(int i, T* e)
{
e = &(this->operator[](i));
}
template<typename T>
int LocateElem<T>(const SeqList<T>& seq, const T& e, function<bool(T, T)>f)
{
auto p =seq.elem;
int i = 0;
while (i !=seq.length && !f(*p, e))
{
i++;
p++;
}
return i;//如果没找到,返回顺序表最后元素序号
}
template<typename T>
void SeqList<T>::ListInsert(int i, T el)
{
if (i<1 || i>length+1)
throw invalid_argument("invalid argument");
else if (i == length+1)
ListInsert(el);
else
{
if (listsize == length)
{
auto newListsize = ListLength() ? 2 * ListLength() : 1;
auto newdata = alloc.allocate(newListsize);
auto dest = newdata;
auto e = elem;
for (int j = 0; j != i-1; j++)
alloc.construct(dest++, std::move(*e++));
alloc.construct(dest++, el);
for (int j = i-1; j != length; j++)
alloc.construct(dest++, std::move(*e++));
free();
elem = newdata;
length = dest - elem;
listsize = newListsize;
}
}
}
template<typename T>
void SeqList<T>::ListInsert(T e)
{
chk_n_alloc();
alloc.construct(elem + length, e);
length++;
}
template<typename T>
void SeqList<T>::ListDelete(int i, T* e)
{
if(i<1||i>length)
throw invalid_argument("invalid argument");
else if (i == length)
{
*e = *(elem + (i - 1));
ListDelete();
}
else
{
*e = *(elem + (i - 1));
for (int j = i; i != length; i++)
{
auto p = elem + (i - 1);
auto q= elem + i;
*p = *q;
}
alloc.destroy(elem + (length - 1));
length--;
}
}
template<typename T>
void SeqList<T>::ListDelete()
{
if (elem)
alloc.destroy(elem +(length-1));
}
#endif // !SEQLIST_H
| true |
af360506c03ca924783bc5b28dc9c00c4c311596 | C++ | nik709/Stack | /Tparser.h | UTF-8 | 3,415 | 3.15625 | 3 | [] | no_license | #pragma once
#include "TStack.h"
using namespace std;
#define MaxLen 201
class TParser
{
private:
char inf[MaxLen];
char post[MaxLen];
Tstack <double> st_d;
Tstack <char> st_c;
public:
TParser(char *s = NULL) : st_d(100), st_c(100)
{
if (s == NULL)
inf[0] = '\0';
else strcpy_s(inf, s);
}
int Priority(char ch)
{
int n;
switch (ch)
{
case '(': n = 0;
case ')': n = 0; break;
case '+': n = 1;
case '-': n = 1; break;
case '*': n = 2;
case '/': n = 2; break;
case '^': n = 3; break;
default: n = -1;
}
return n;
}
bool IsNumber(char ch)
{
if (ch >= '0' && ch <= '9')
return true;
else return false;
}
bool IsOper(char ch)
{
if ((ch == '+') || (ch == '-') || (ch == '*') || (ch == '/') || (ch == '^'))
return true;
else return false;
}
double ExNumber(char *s, int &len)
{
int i = 0;
double tmp = atof(s);
while (IsNumber(s[i]) || s[i]=='.')
i++;
len = i;
return tmp;
}
double FullCalc()
{
st_d.clear();
st_c.clear();
st_c.Push('=');
int i = 0;
int len;
while (inf[i] != '\0')
{
if (IsNumber(inf[i]))
{
double tmp = ExNumber(&inf[i], len);
st_d.Push(tmp);
i += len - 1;
}
else if (inf[i] == '(')
st_c.Push(inf[i]);
else if (inf[i] == ')')
{
char tmpc = st_c.Pop();
while (tmpc != '(')
{
double op2 = st_d.Pop();
double op1 = st_d.Pop();
Operation(op1, op2, tmpc);
tmpc = st_c.Pop();
}
}
else if (IsOper(inf[i]))
{
char tmpc = st_c.Pop();
while (Priority(tmpc) >= Priority(inf[i]))
{
double op2 = st_d.Pop();
double op1 = st_d.Pop();
Operation(op1, op2, tmpc);
tmpc = st_c.Pop();
}
st_c.Push(tmpc);
st_c.Push(inf[i]);
}
i++;
} // } to main while
char tmpc = st_c.Pop();
while (tmpc != '=')
{
double op2 = st_d.Pop();
double op1 = st_d.Pop();
Operation(op1, op2, tmpc);
tmpc = st_c.Pop();
}
return st_d.Pop();
}
void Operation(double a, double b, char ch)
{
switch (ch)
{
case '+': st_d.Push(a + b); break;
case '-': st_d.Push(a - b); break;
case '*': st_d.Push(a * b); break;
case '/': st_d.Push(a / b); break;
case '^': st_d.Push(pow(a,b)); break;
}
}
void InfToPost()
{
int i = 0;
int j = 0;
st_c.Push('=');
while (inf[i] != '\0')
{
if (IsNumber(inf[i]))
{
post[j] = inf[i];
j++;
}
else if (inf[i] == '(')
st_c.Push(inf[i]);
else if (inf[i] == ')')
{
char tmp = st_c.Pop();
while (tmp != '(')
{
post[j] = tmp;
j++;
tmp = st_c.Pop();
}
}
else if (IsOper(inf[i]))
{
char tmp = st_c.Pop();
while (Priority(tmp) >= Priority(inf[i]))
{
post[j] = tmp;
j++;
tmp = st_c.Pop();
}
st_c.Push(tmp);
st_c.Push(inf[i]);
}
i++;
}
while (st_c.Top() != '=')
{
post[j] = st_c.Pop();
j++;
}
post[j] = '\0';
}
double CalcPost()
{
int i = 0;
st_d.clear();
while ((post[i] != '\0') & (post[i] != '='))
{
if (IsNumber(post[i]))
st_d.Push(post[i] - '0');
if (IsOper(post[i]))
{
double op1;
double op2;
op2 = st_d.Pop();
op1 = st_d.Pop();
Operation(op1, op2, post[i]);
}
i++;
}
return st_d.Pop();
}
friend ostream& operator <<(ostream &out, const TParser &P)
{
for (int i = 0; P.post[i] != '\0'; i++)
out << P.post[i] << ' ';
return out;
}
}; | true |
bf1296a00d983e6332755e7cf129f1e65eb563b7 | C++ | syed/tc | /bigburger-c++/BigBurgerTest.cpp | UTF-8 | 2,490 | 3.34375 | 3 | [] | no_license | #include "BigBurger.h"
#include <iostream>
#include <vector>
using std::cerr;
using std::cout;
using std::endl;
using std::vector;
class BigBurgerTest {
static void assertEquals(int testCase, const int& expected, const int& actual) {
if (expected == actual) {
cout << "Test case " << testCase << " PASSED!" << endl;
} else {
cout << "Test case " << testCase << " FAILED! Expected: <" << expected << "> but was: <" << actual << '>' << endl;
}
}
BigBurger solution;
void testCase0() {
int arrival_[] = {3, 3, 9};
vector<int> arrival(arrival_, arrival_ + (sizeof(arrival_) / sizeof(arrival_[0])));
int service_[] = {2, 15, 14};
vector<int> service(service_, service_ + (sizeof(service_) / sizeof(service_[0])));
int expected_ = 11;
assertEquals(0, expected_, solution.maxWait(arrival, service));
}
void testCase1() {
int arrival_[] = {182};
vector<int> arrival(arrival_, arrival_ + (sizeof(arrival_) / sizeof(arrival_[0])));
int service_[] = {11};
vector<int> service(service_, service_ + (sizeof(service_) / sizeof(service_[0])));
int expected_ = 0;
assertEquals(1, expected_, solution.maxWait(arrival, service));
}
void testCase2() {
int arrival_[] = {2, 10, 11};
vector<int> arrival(arrival_, arrival_ + (sizeof(arrival_) / sizeof(arrival_[0])));
int service_[] = {3, 4, 3};
vector<int> service(service_, service_ + (sizeof(service_) / sizeof(service_[0])));
int expected_ = 3;
assertEquals(2, expected_, solution.maxWait(arrival, service));
}
void testCase3() {
int arrival_[] = {2, 10, 12};
vector<int> arrival(arrival_, arrival_ + (sizeof(arrival_) / sizeof(arrival_[0])));
int service_[] = {15, 1, 15};
vector<int> service(service_, service_ + (sizeof(service_) / sizeof(service_[0])));
int expected_ = 7;
assertEquals(3, expected_, solution.maxWait(arrival, service));
}
public: void runTest(int testCase) {
switch (testCase) {
case (0): testCase0(); break;
case (1): testCase1(); break;
case (2): testCase2(); break;
case (3): testCase3(); break;
default: cerr << "No such test case: " << testCase << endl; break;
}
}
};
int main() {
for (int i = 0; i < 4; i++) {
BigBurgerTest test;
test.runTest(i);
}
}
| true |
dba137186ff48875307a81bd3ee39e33fe2c3642 | C++ | derbess/algos | /howmanysubstr.cpp | UTF-8 | 936 | 2.984375 | 3 | [] | no_license | #include<iostream>
using namespace std;
int isPalindrome(string str)
{
int cnt=0;
for(int i=0;i<str.size();i++)
{
if(str[i]==str[str.size()-i-1])
{
cnt++;
}
}
if(cnt==str.size())
{
return 1;
}
else return 0;
}
string getPalindrome(string str)
{
if(isPalindrome(str)==1)
{
return "Is_Palindrome";
}
else return "Not_Palindrome";
}
//void checkSubstringPalindrome(string subStr, string iStringData, string oStringData, int nrIOfileLines);
int howManySubstrings(string subStr, string str)
{
int ans = 0;
for(int i=0;i<str.size();i++)
{
if(str[i]==subStr[0])
{
int cnt=0;
for(int j=0;j<subStr.size();j++)
{
if(str[i+j]==subStr[j])
{
cnt++;
}
}
if(cnt==subStr.size())
{
ans++;
i+=subStr.size();
}
cnt=0;
}
}
return ans;
}
int main()
{
string ss,sb;
cin>>ss>>sb;
cout<<howManySubstrings(sb,ss)<<endl;
cout<<getPalindrome(ss);
return 0;
} | true |
ad80be0c3394c7b20ea8e483e599d713fad358ca | C++ | ZoranPandovski/al-go-rithms | /math/Matrix/C++/fast_matrix_exponentiation.cpp | UTF-8 | 1,037 | 2.96875 | 3 | [
"CC0-1.0"
] | permissive | #include <bits/stdc++.h>
using namespace std;
long long mod = (int)1e9 + 7;
#define matrix2D vector<vector<long long>>
matrix2D matrixMultiply(matrix2D &a, matrix2D &b)
{
matrix2D c(a.size(), vector<long long>(b[0].size()));
for (int i = 0; i < a.size(); i++)
{
for (int j = 0; j < b[0].size(); j++)
{
for (int k = 0; k < a[0].size(); k++)
{
c[i][j] = (c[i][j] + a[i][k] * b[k][j]) % mod;
}
}
}
return c;
}
matrix2D matrixPower(matrix2D &a, long long p)
{
matrix2D res = matrix2D(a.size(), vector<long long>(a.size()));
for (int i = 0; i < a.size(); i++)
res[i][i] = 1;
while (p)
{
if (p & 1)
res = matrixMultiply(a, res);
a = matrixMultiply(a, a);
p >>= 1;
}
return res;
}
int main()
{
matrix2D mat{{1, 1}, {1, 0}};
mat = matrixPower(mat, 12);
for (auto x : mat)
{
for (auto y : x)
cout << y << " ";
cout << "\n";
}
}
| true |
1bb0d84951239ecd39184e8fde39ea849c355c92 | C++ | andry-tino/coding-challenges | /white-rabbit-hole/WhiteRabbitHole/WhiteRabbitHole/Utils.cpp | UTF-8 | 773 | 2.984375 | 3 | [
"MIT"
] | permissive | // Utils.cpp
#include "Utils.h"
std::string challenge::whiterabbithole::disposition_to_string(const std::vector<unsigned int>& disposition)
{
if (disposition.size() == 0)
{
return std::string("''");
}
std::string s;
for (std::vector<unsigned int>::const_iterator it = disposition.begin(); it != disposition.end(); it++)
{
s = s + std::to_string((*it)) + ((it+1 == disposition.end()) ? "" : ",");
}
return s;
}
std::string challenge::whiterabbithole::phrase_to_string(const std::vector<std::string>& phrase)
{
if (phrase.size() == 0)
{
return std::string("''");
}
std::string s;
for (std::vector<std::string>::const_iterator it = phrase.begin(); it != phrase.end(); it++)
{
s = s + (*it) + ((it + 1 == phrase.end()) ? "" : ",");
}
return s;
}
| true |
3fc28caece564b37b63cd9b13301bcba7c0c1430 | C++ | Knabin/TBCppStudy | /Chapter2/Chapter2_09/main_chapter29.cpp | UTF-8 | 1,595 | 3.671875 | 4 | [] | no_license | #include <iostream>
#include "MY_CONSTANTS.h"
#define PRICE_PER_ITEM 30
// C++에서는 상수 대체용으로 매크로 사용 안 함!!
// 1. debugging 어려움
// 2. 적용 범위가 너무 넓음
using namespace std;
void printNumber(const int my_number)
{
// 입력으로 들어온 값을 바꾸지는 않기 때문에 파라미터에 const를 많이 붙임
// const int& 변수 형태로 많이 사용함
// my_number = 456; error!
int n = my_number; // 바꿔야 한다면 따로 복사하여 사용함
cout << my_number << endl;
}
int main()
{
// 변수값이 변경되지 않아야 하는 경우, const를 통해 변수를 고정함
// 주의! 선언과 동시에 초기화되어야 함
// 주의! 자료형과 const 순서에 따라 의미가 달라지는 경우가 있음
const double gravity{ 9.8 };
double const gravity2{ 9.8 }; // ����
// gravity = 1.2; error!
printNumber(123);
// compile time에 결정되는 상수
// constexpr: 컴파일 때 결정되는 상수를 구분하기 위함
const int my_const(123);
constexpr int my_const2(123);
int number;
cin >> number;
// 변수로 상수를 초기화
// runtime에 결정되는 상수
const int special_number(number);
// constexpr int special_number(number); error!
number = 123;
// special_number(123); error!
const int price_per_item = 30;
int num_item = 123;
//int price = num_item * PRICE_PER_ITEM;
int price = num_item * price_per_item;
// 헤더 파일 사용
double radius;
cin >> radius;
double circumference = 2.0 * radius * constants::moongravity;
return 0;
} | true |
fce4bf78306681e0d80ae6eae2150aad7f23f1da | C++ | vasmedvedev/yandex_cpp | /white_belt/week4/rational/interface/main.cpp | UTF-8 | 903 | 3.625 | 4 | [] | no_license | #include <iostream>
int gcd(int x, int y) {
do
{
int t = x % y;
x = y;
y = t;
} while (y);
return x;
}
class Rational {
public:
Rational() {
_numerator = 0;
_denominator = 1;
}
Rational(int numerator, int denominator) {
if (numerator == 0) {
_numerator = 0;
_denominator = 1;
return;
}
bool negative = denominator * numerator < 0;
int div = gcd(numerator, denominator);
int sign = negative ? -1 : 1;
_numerator = abs(numerator / div) * sign;
_denominator = abs(denominator / div);
}
int Numerator() const {
return _numerator;
}
int Denominator() const {
return _denominator;
}
private:
int _numerator;
int _denominator;
};
int main() {
std::cout << "OK" << std::endl;
return 0;
}
| true |
820c048acd35e5f565315b7c41f5356208f21b14 | C++ | walkccc/LeetCode | /solutions/1900. The Earliest and Latest Rounds Where Players Compete/1900.cpp | UTF-8 | 1,058 | 3.03125 | 3 | [
"MIT"
] | permissive | class Solution {
public:
vector<int> earliestAndLatest(int n, int firstPlayer, int secondPlayer) {
dp.resize(n + 1, vector<vector<P>>(n + 1, vector<P>(n + 1)));
const auto [a, b] = solve(firstPlayer, n - secondPlayer + 1, n);
return {a, b};
}
private:
typedef pair<int, int> P;
// dp[i][j][k] := (earliest, latest) pair w/ firstPlayer is i-th player from
// Front, secondPlayer is j-th player from end, and there're k people
vector<vector<vector<P>>> dp;
P solve(int l, int r, int k) {
if (l == r)
return {1, 1};
if (l > r)
swap(l, r);
if (dp[l][r][k] != pair<int, int>(0, 0))
return dp[l][r][k];
int a = INT_MAX;
int b = INT_MIN;
// Enumerate all possible positions
for (int i = 1; i <= l; ++i)
for (int j = l - i + 1; j <= r - i; ++j) {
if (i + j > (k + 1) / 2 || i + j < l + r - k / 2)
continue;
const auto [x, y] = solve(i, j, (k + 1) / 2);
a = min(a, x + 1);
b = max(b, y + 1);
}
return dp[l][r][k] = {a, b};
}
};
| true |
d27916f6ed862d195d5f079018fd769562b3d6cf | C++ | rahularya50/ioi_prep | /acm/2010/C.cpp | UTF-8 | 752 | 2.765625 | 3 | [] | no_license | #include "bits/stdc++.h"
using namespace std;
void go(long long n) {
auto besta = 4000;
auto bestb = 4000;
auto bestc = 4000;
for (long long a = 1; a < 4000; ++a) {
for (long long c = 1; a+c < 4000 && c <= a; ++c) {
auto cubesum = a*a*a + c*c*c;
if (cubesum % n != 0) continue;
auto bcube = cubesum / n;
auto b = round(pow(bcube, 1.0/3));
if (b*b*b != bcube) continue;
auto sum = a + 2*b + c;
if (sum < besta + 2*bestb + bestc) {
besta = a;
bestb = b;
bestc = c;
}
}
}
if (besta == 4000) {
cout << "No value.\n";
} else {
cout << "(" << besta << "/" << bestb << ")^3 + (" << bestc << "/" << bestb << ")^3 = " << n << "\n";
}
}
int main() {
int n;
for (cin >> n; n != 0; cin >> n) {
go(n);
}
} | true |
13822191690e537d40ba902797760c49b31c59cd | C++ | Debparna/ctci | /c++/Chapter 1/Arrays&String.cpp | UTF-8 | 12,270 | 3.984375 | 4 | [] | no_license | #include <deque>
#include <queue>
#include <stack>
#include <string>
#include <limits>
#include <vector>
#include <fstream>
#include <sstream>
#include <iostream>
#include <algorithm>
#include <climits>
#include<list>
using namespace std;
//Q1
//Implement an algorithm to determine if a string has all unique characters. What if you can not use additional data structures?
//Approach 1 – Brute Force technique: Run 2 loops with variable i and j. Compare str[i] and str[j]. If they become equal at any point, return false.
//Time Complexity: O(n2)
bool isUnique(string deb){
for(int i = 0; i < deb.length(); i++){
char temp;
temp = deb[i];
for(int j = 0; j < deb.length(); j++ ){
if( i != j){
if(temp == deb[j]){
return false;
}
}
}
}
return true;
}
/*
Other way of doing the same as above
bool isUnique(string str)
{
for (int i = 0; i < str.length(); i++) // If at any time we encounter 2 same characters, return false
for (int j = i + 1; j < str.length(); j++)
if (str[i] == str[j])
return false;
return true; // If no duplicate characters encountered, return true
}
*/
/*
Approach 2 - Based on ASCII values of characters
Without Extra Data Structure: The approach is valid for strings having alphabet as a-z. This approach is little tricky. Instead of maintaining a boolean array, we maintain an integer value called checker(32 bits). As we iterate over the string, we find the int value of the character with respect to ‘a’ with the statement int bitAtIndex = str.charAt(i) - ‘a’; Then the bit at that int value is set to 1 with the statement 1 << bitAtIndex. Now, if this bit is already set in the checker, the bit AND operation would make checker > 0. Return false in this case. Else Update checker to make the bit 1 at that index with the statement checker = checker | (1 << bitAtIndex);
Time Complexity: O(n)
*/
bool isUniqueChars(const string& str)
{
if (str.length() > 256) //then its not ASCII
{
return false;
}
unsigned int checker = 0; //create a checker var instead of array
for (int i = 0; i < str.length(); ++i)
{
int value = str[i] - 'a'; //finds the int value of the character with respect to ‘a’
if ((checker & (1 << value)) != 0) //the bit at that int value is set to 1
{
return false;
}
checker |= (1 << value); //if value not found elsewhere, make it one
}
return true;
}
/* IN THIS QUESTION WE ARE NOT ALLOWED TO USE ANOTHER DATA SRTUCTURE, BUT IF WE DO THEN
Approach 3 – Use of Extra Data Structure: This approach assumes ASCII char set(8 bits). The idea is to maintain a boolean array for the characters. The 256 indices represent 256 characters. All the array elements are initially set to false. As we iterate over the string, set true at the index equal to the int value of the character. If at any time, we encounter that the array value is already true, it means the character with that int value is repeated.
Time Complexity: O(n)
*/
bool isUniqueChars2(const string& str)
{
//To check if 1 byte = 8 bits, ascii char array 8 bits
if (str.length() > 256)
{
return false;
}
bool ascii_set[256] = { false }; //create an array
for (int i = 0; i < str.length(); ++i)
{
int value = str[i]; //stores the ASCII value of i in value
if (ascii_set[value] == true)
{
return false;
}
ascii_set[value] = true;
}
return true;
}
//Approach 2 – Sorting: Using sorting based on ASCII values of characters
//Time Complexity: O(n log n)
string result(bool value)
{
if (value)
{
return "True";
}
return "False";
}
//****************************************** Q2 *****************************************************//
//Q2
//Write code to reverse a C-Style String. (C-String means that “abcd” is represented as five characters, including the null character.)
//MY METHOD : swap
//Time Complexity: O(n)
void isReversed(string deb){
int size = deb.length();
char arr[size];
int j = 0;
for (int i = size - 1; i >= 0; i--) {
arr[j] = deb[i];
j++;
}
cout << arr;
return;
}
/* Function to reverse arr[] from start to end*/
// int arr[] = {1, 2, 3, 4, 5, 6};
void rvereseArray(int arr[], int start, int end)
{
int temp;
while (start < end)
{
temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}
// Recursive C program to reverse an array
void rvereseArray(int arr[], int start, int end)
{
int temp;
if (start >= end)
return;
temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
rvereseArray(arr, start+1, end-1);
}
//SECOND METHOD TO REVERSE IN PLACE, ACC TO CTCI
void reverse(char* str)
{
char *ptrEnd = str; //value of str in pointer ptrEnd
char temp;
if (str != NULL)
{
while (*ptrEnd != '\0')
{
ptrEnd++;
}
ptrEnd--; //ptrEnd to the end of string
while (str < ptrEnd) //WHAT???!?!?
{
temp = *str;
*str = *ptrEnd;
str++;
*ptrEnd = temp;
ptrEnd--;
}
}
}
/*
Anagram is "a word or phrase spelled by rearranging the letters of another word or phrase". So to be an anagram the arrangement of letters must make a word - that is, an anagram of a word must have a meaning, such as cinema, formed from iceman.
On the other hand, permutation is defined as "the act of changing the arrangement of a given number of elements". So a permutation of a word can be any random assortment of characters, not necessarily having a meaning in the original language.
So every anagram is a permutation of the word, but every permutation is not an anagram. To make it clearer 'cheaters' is an anagram of 'teachers' because both have the same letters, albeit in different positions, and both have some meaning in the English language. But 'eeahcrst' is merely a permutation of 'teachers' because 'eeahcrst' doesn't have any meaning associated with it in the English language.
*/
//Q3
//Find if a string is an anagram/permution of another
/*
Method 1 (Use Sorting) -
In the above implementation, quickSort is used which may be O(n^2) in worst case. If we use a O(nLogn) sorting algorithm like merge sort, then the complexity becomes O(nLogn)
1) Sort both strings
2) Compare the sorted strings
*/
void quickSort(char *arr, int si, int ei);
/* function to check whether two strings are anagram of each other */
bool anagram1(char *str1, char *str2)
{
// Get lenghts of both strings
int n1 = strlen(str1);
int n2 = strlen(str2);
// If length of both strings is not same, then they cannot be anagram
if (n1 != n2)
return false;
// Sort both strings
quickSort(str1, 0, n1 - 1);
quickSort(str2, 0, n2 - 1);
// Compare sorted strings
for (int i = 0; i < n1; i++)
if (str1[i] != str2[i])
return false;
return true;
}
// Following functions (exchange and partition are needed for quickSort)
void exchange(char *a, char *b)
{
char temp;
temp = *a;
*a = *b;
*b = temp;
}
int partition(char A[], int startIndex, int endIndex)
{
char x = A[endIndex];
int i = (startIndex - 1);
int j;
for (j = startIndex; j <= endIndex - 1; j++)
{
if(A[j] <= x)
{
i++;
exchange(&A[i], &A[j]);
}
}
exchange (&A[i + 1], &A[endIndex]);
return (i + 1);
}
/* Implementation of Quick Sort
A[] --> Array to be sorted
si --> Starting index
ei --> Ending index
*/
void quickSort(char A[], int startIndex, int endIndex)
{
int partitionIndex;
if(startIndex < endIndex)
{
partitionIndex = partition(A, startIndex, endIndex);
quickSort(A, startIndex, partitionIndex - 1);
quickSort(A, partitionIndex + 1, endIndex);
}
}
/*
Method 2 (Count characters)
This method assumes that the set of possible characters in both strings is small. In the following implementation, it is assumed that the characters are stored using 8 bit and there can be 256 possible characters.
1) Create count arrays of size 256 for both strings. Initialize all values in count arrays as 0.
2) Iterate through every character of both strings and increment the count of character in the corresponding count arrays.
3) Compare count arrays. If both count arrays are same, then return true.
*/
bool anagram2(char *str1, char *str2)
{
// Create 2 count arrays and initialize all values as 0
int count1[256] = {0};
int count2[256] = {0};
// For each character in input strings, increment count in the corresponding count array
int i;
for (i = 0; str1[i] && str2[i]; i++)
{
count1[str1[i]]++; //increments counts at the particular index for that ascii value, if 4 e's, 97 is incremented by 4
count2[str2[i]]++;
}
// If both strings are of different length. Removing this condition will make the program fail for strings like "aaca" and "aca"
if (str1[i] || str2[i])
return false;
// Compare count arrays
for (i = 0; i < 256; i++)
if (count1[i] != count2[i])
return false;
return true;
}
/*
Method 3 (Count characters)
This implementation can be further to use only one count array instead of two. We can increment the value in count array for characters in str1 and decrement for characters in str2. Finally, if all count values are 0, then the two strings are anagram of each other.
If the possible set of characters contains only English alphabets, then we can reduce the size of arrays to 52 and use str[i] – ‘A’ as an index for count arrays. This will further optimize this method.
Time Complexity: O(n)
*/
bool anagrams3(char *str1, char *str2)
{
int count[256] = {0}; // Create a count array and initialize all values as 0
int i;
for (i = 0; str1[i] && str2[i]; i++)//For each character in input strings, increment count in the corresponding count array
{
count[str1[i]]++; //increments counts at the particular index for that ascii value, if 4 e's, 97 is incremented by 4
count[str2[i]]--;
}
// If both strings are of different length. Removing this condition will make the program fail for strings like "aaca" and "aca"
if (str1[i] || str2[i])
return false;
for (i = 0; i < 256; i++) // See if there is any non-zero value in count array
if (count[i])
return false;
return true;
}
//Q4
//Write a method to replace all spaces in a string with ‘%20’.
void replaceSpaces(char str[], int length) //char str[]
{
int newLength, spaceCount = 0;
for (int i = 0; i < length; i++) //count the number of spaces in the given string.
{
if (str[i] == ' ')
{
spaceCount++;
}
}
newLength = length + spaceCount * 2; //calculate new string size.
str[newLength] = '\0';
for (int i = length - 1; i >= 0; i--) //copying the characters backwards and inserting %20
{
if (str[i] == ' ')
{
str[newLength - 1] = '0';
str[newLength - 2] = '2';
str[newLength - 3] = '%';
newLength -= 3;
}
else
{
str[newLength - 1] = str[i];
newLength--;
}
}
}
int main(){
//Q1
//string input = {"abkcde"};
//cout << input << " has unique characters: " << result(isUnique(input)) << endl;
//cout << input << " has unique characters: " << result(isUniqueChars(input)) << endl;
//cout << input << " has unique characters: " << result(isUniqueChars2(input)) << endl;
//Q2
//char input[10] = { "abcde"};
//isReversed(input);
//reverse(input);
//cout << "reverse of input string is " << input << endl;
//Q3
char str1[] = "geeksforgeeks";
char str2[] = "forgeeksgeeks";
if ( anagram2(str1, str2) ) //areAnagram(str1, str2) //areAnagrams(str1, str2)
printf("The two strings are anagram of each other");
else
printf("The two strings are not anagram of each other");
//Q4
/* // Increasing length of the string to meet question requirement of 'true' length by using char array. (Note: using a unique_ptr here)
auto newStr = make_unique<char[]>(str.length() + 3 * 2 + 1);
for (int i = 0; i < str.length(); i++)
{
newStr[i] = str[i];
}
cout << "Original string is " << str << endl;
replaceSpaces(newStr, str.length());
cout << "New string with %20 is " << newStr.get() << endl;
*/
return 0;
}
| true |
0d6c8f103ce5a20e474d8d85c6f8e03b34a95272 | C++ | zacbrannelly/SwinEngine | /Mouse.h | UTF-8 | 621 | 2.8125 | 3 | [] | no_license | #pragma once
#include <SDL.h>
#include <map>
#include <vector>
#include <string>
#include "glm\glm.hpp"
enum Button
{
Left = 1, Middle = 2, Right = 3
};
class Mouse
{
public:
static void GetStatesFromEvents(std::vector<SDL_Event>& events);
static bool IsButtonDown(Button btn);
static bool IsButtonUp(Button btn);
static bool WasButtonDown(Button btn);
static bool WasButtonUp(Button btn);
static glm::vec2 GetMousePosition();
static float GetMouseX();
static float GetMouseY();
private:
static std::map<Button, bool> _states;
static std::map<Button, bool> _prevStates;
static glm::vec2 _mousePosition;
}; | true |
e4c526b7bed7db928bfb8b0b7ca3c34a9b91d4cb | C++ | tstaples/Cat3D | /VGP336/Engine/EngineMath.cpp | UTF-8 | 9,534 | 2.828125 | 3 | [] | no_license | //====================================================================================================
// Filename: EngineMath.cpp
// Created by: Peter Chan
//====================================================================================================
//====================================================================================================
// Includes
//====================================================================================================
#include "Precompiled.h"
#include "EngineMath.h"
namespace Math
{
//====================================================================================================
// Constants
//====================================================================================================
const f32 kPi = 3.14159265358979f;
const f32 kTwoPi = 6.28318530717958f;
const f32 kPiByTwo = 1.57079632679489f;
const f32 kDegToRad = kPi / 180.0f;
const f32 kRadToDeg = 180.0f / kPi;
//====================================================================================================
// Function Definitions
//====================================================================================================
Matrix Matrix::RotationAxis(const Vector3& axis, f32 rad)
{
const Vector3 u = Normalize(axis);
const f32 x = u.x;
const f32 y = u.y;
const f32 z = u.z;
const f32 s = sin(rad);
const f32 c = cos(rad);
return Matrix
(
c + (x * x * (1.0f - c)),
x * y * (1.0f - c) + z * s,
x * z * (1.0f - c) - y * s,
0.0f,
x * y * (1.0f - c) - z * s,
c + (y * y * (1.0f - c)),
y * z * (1.0f - c) + x * s,
0.0f,
x * z * (1.0f - c) + y * s,
y * z * (1.0f - c) - x * s,
c + (z * z * (1.0f - c)),
0.0f,
0.0f,
0.0f,
0.0f,
1.0f
);
}
//----------------------------------------------------------------------------------------------------
bool Intersect(const Vector3& point, const AABB& aabb)
{
if (point.x > aabb.extend.x || point.x < -aabb.extend.x ||
point.y > aabb.extend.y || point.y < -aabb.extend.y ||
point.z > aabb.extend.z || point.z < -aabb.extend.z)
{
return false;
}
return true;
}
//----------------------------------------------------------------------------------------------------
bool Intersect(const Vector3& p, const OBB& obb)
{
// Build the transformation matrix to bring the point into the OBB's local space
Matrix matTrans = Matrix::Translation(obb.center);
Matrix matRot = Convert(obb.rot);
Matrix toLocal = Inverse(matRot * matTrans);
// Transform the point into the box's local space
Vector3 localPoint = TransformCoord(p, toLocal);
// We can just treat it as an AABB now since we're in the OBB's local space
AABB aabb(Vector3::Zero(), obb.extend);
return Intersect(localPoint, aabb);
}
//----------------------------------------------------------------------------------------------------
bool Intersect(const Ray& ray, const OBB& obb, f32& distance)
{
// Build transformation matrix to bring the ray into the OBB's local space
Matrix matTrans = Matrix::Translation(obb.center);
Matrix matRot = Convert(obb.rot);
Matrix toLocal = Inverse(matRot * matTrans);
// Bring the ray into OBB's local space
Vector3 localOrigin = TransformCoord(ray.org, toLocal);
Vector3 localDirection = TransformNormal(ray.dir, toLocal);
Ray localRay(localOrigin, localDirection);
// Do the intersect test with the ray and local OBB (AABB)
AABB aabb(Vector3::Zero(), obb.extend);
f32 dEntry = 0.0f, dExit = 0.0f;
bool rc = Intersect(localRay, aabb, dEntry, dExit);
distance = dExit - dEntry;
return rc;
}
//----------------------------------------------------------------------------------------------------
bool Intersect(const Ray& ray, const AABB& aabb, f32& distEntry, f32& distExit)
{
Vector3 boxMin = aabb.center - aabb.extend;
Vector3 boxMax = aabb.center + aabb.extend;
f32 txmin, txmax, tymin, tymax, tzmin, tzmax;
f32 divx = 1.0f / ray.dir.x;
f32 divy = 1.0f / ray.dir.y;
f32 divz = 1.0f / ray.dir.z;
if (divx >= 0.0f)
{
txmin = (boxMin.x - ray.org.x) * divx;
txmax = (boxMax.x - ray.org.x) * divx;
}
else
{
txmin = (boxMax.x - ray.org.x) * divx;
txmax = (boxMin.x - ray.org.x) * divx;
}
if (divy >= 0.0f)
{
tymin = (boxMin.y - ray.org.y) * divy;
tymax = (boxMax.y - ray.org.y) * divy;
}
else
{
tymin = (boxMax.y - ray.org.y) * divy;
tymax = (boxMin.y - ray.org.y) * divy;
}
if ((txmin > tymax) || (tymin > txmax))
{
return false;
}
if (tymin > txmin)
{
txmin = tymin;
}
if (tymax < txmax)
{
txmax = tymax;
}
if (divz >= 0.0f)
{
tzmin = (boxMin.z - ray.org.z) * divz;
tzmax = (boxMax.z - ray.org.z) * divz;
}
else
{
tzmin = (boxMax.z - ray.org.z) * divz;
tzmax = (boxMin.z - ray.org.z) * divz;
}
if ((txmin > tzmax) || (tzmin > txmax))
{
return false;
}
if (tzmin > txmin)
{
txmin = tzmin;
}
if (tzmax < txmax)
{
txmax = tzmax;
}
distEntry = txmin;
distExit = txmax;
return true;
}
//----------------------------------------------------------------------------------------------------
bool Intersect(const Ray& ray, const AABB& aabb)
{
f32 dEntry, dExit; // Do nothing with these
return Intersect(ray, aabb, dEntry, dExit);
}
//----------------------------------------------------------------------------------------------------
bool Intersect(const Ray& ray, const Plane& plane, f32& distance)
{
// Can't assume plane's normal is passed in normalized
const Vector3 n = Normalize(plane.n);
const f32 orgDotN = Dot(ray.org, n);
const f32 dirDotN = Dot(ray.dir, n);
// Check if the ray and plane are parallel
if (IsZero(dirDotN - plane.d))
{
// Check if the ray is on the plane
if (IsZero(orgDotN - plane.d))
{
distance = 0.0f;
return true;
}
return false;
}
distance = (plane.d - orgDotN) / dirDotN;
return true;
}
//----------------------------------------------------------------------------------------------------
bool GetIntersectPoint(const Ray& ray, const Plane& plane, Vector3& point)
{
f32 dist = 0;
if (Intersect(ray, plane, dist))
{
point = ray.org + (ray.dir * dist);
return true;
}
return false;
}
//----------------------------------------------------------------------------------------------------
// first pass check to see if point is intersecting
// second pass - ray box intersection test (ray in particle's direction)
// check against a 'slab'
// min/max x/y form a slab
// all 4 would be cross by the ray
// if you hit all the mins first, then the max's, you're intersecting
// get the point on the box where the intersection occurs
// get the normal of that face, then reflect the point over that normal
// hack: set old position to inverse of reflected vector to change direction point travels
bool GetContactPoint(const Ray& ray, const OBB& obb, Vector3& point, Vector3& normal)
{
// Build transformation matrix to bring the ray into the OBB's local space
Matrix matTrans = Matrix::Translation(obb.center);
Matrix matRot = Convert(obb.rot);
Matrix toWorld = matRot * matTrans;
Matrix toLocal = Inverse(toWorld);
Vector3 localOrg = TransformCoord(ray.org, toLocal);
Vector3 localDir = TransformNormal(ray.dir, toLocal);
Ray localRay(localOrg, localDir);
// Build the planes representing the OBB in local space
Plane planes[] =
{
Plane( 0.0f, 0.0f, -1.0f, obb.extend.z),
Plane( 0.0f, 0.0f, 1.0f, obb.extend.z),
Plane( 0.0f, -1.0f, 1.0f, obb.extend.y),
Plane( 0.0f, 1.0f, 1.0f, obb.extend.y),
Plane(-1.0f, 0.0f, 1.0f, obb.extend.x),
Plane( 1.0f, 0.0f, 1.0f, obb.extend.x)
};
const u32 numPlanes = 6;
u32 numIntersections = 0;
for (u32 i=0; i < numPlanes; ++i)
{
const Plane& plane = planes[i];
// Check the plane is the nearest ones
const f32 d = Dot(localOrg, plane.n);
if (d > plane.d)
{
f32 distance = 0.0f;
if (Intersect(localRay, plane, distance) && distance >= 0.0f)
{
Vector3 pt = localOrg + (localDir * distance);
// add small buffer to make sure the point is close enough to the box
if (fabs(pt.x) <= obb.extend.x + 0.01f &&
fabs(pt.y) <= obb.extend.y + 0.01f &&
fabs(pt.z) <= obb.extend.z + 0.01f)
{
point = pt;
normal = plane.n;
++numIntersections;
}
}
}
}
if (numIntersections == 0)
{
return false;
}
// Bring the point and normal back into world space
point = TransformCoord(point, toWorld);
normal = TransformNormal(point, toWorld);
return true;
}
} // namespace Math | true |
110bbf9d372ced6d746d7be3aeef3c59e1e9a671 | C++ | tonyxiong/stereosynth | /src/math/imageset.h | UTF-8 | 2,430 | 3.046875 | 3 | [
"MIT"
] | permissive | /*
* File: imageset.h
* Author: Alexandre Kaspar <akaspar@mit.edu>
*
* Created on December 5, 2014, 2:40 PM
*/
#ifndef IMAGESET_H
#define IMAGESET_H
#include "bilinear.h"
#include "mat.h"
#include "pointx.h"
#include <type_traits>
#include <boost/shared_array.hpp>
namespace pm {
struct ImageSet {
ImageSet() {}
explicit ImageSet(size_t n) : N(n) {
if(N > 0) {
stack.reset(new Mat[N]());
}
}
//! Element access
template <typename T>
inline const T & at(int y, int x, int index) const {
assert(index >= 0 && index < N && "Image index out of bounds");
return stack[index].at<T>(y, x);
}
template <typename T>
inline T & at(int y, int x, int index) {
assert(index >= 0 && index < N && "Image index out of bounds");
return stack[index].at<T>(y, x);
}
//! discrete access
template <typename T, typename S>
inline typename std::enable_if<std::is_integral<S>::value, T>::type &at(const IndexedPoint<S> &i) {
return at<T>(i.y, i.x, i.index);
}
template <typename T, typename S>
inline const typename std::enable_if<std::is_integral<S>::value, T>::type &at(const IndexedPoint<S> &i) const {
return at<T>(i.y, i.x, i.index);
}
//! continuous access
template <typename T, typename S>
inline typename std::enable_if<std::is_floating_point<S>::value, T>::type at(const IndexedPoint<S> &ip) const {
typedef typename IndexedPoint<S>::base BasePoint;
BasePoint p(ip); // without index
Point2i i(p); // integer version
if(p == BasePoint(i)){
// our version is equivalent to a integer one, no need to interpolate
return at<T>(i.x, i.y, ip.index);
}
// we need to interpolate
return bilinearLookup<T, S>(stack[ip.index], p);
}
inline Mat &operator[](size_t i){
assert(i >= 0 && i < N && "Image index out of bounds!");
return stack[i];
}
inline const Mat &operator[](size_t i) const {
assert(i >= 0 && i < N && "Image index out of bounds!");
return stack[i];
}
inline size_t size() const {
return N;
}
private:
boost::shared_array<Mat> stack;
size_t N;
};
}
#endif /* IMAGESET_H */
| true |
30d297cd3b50321dc413c17c3345028c2f0c1e97 | C++ | knakul853/ProgrammingContests | /OldStuff/SPOJ/new10/loner.cpp | UTF-8 | 1,659 | 2.953125 | 3 | [] | no_license | /*
Alfonso2 Peterssen (mukel)
SPOJ #140 "The Loner"
18 - 5 - 2009
*/
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
#define REP( i, n ) for ( int i = 0; i < (n); i++ )
#define REPD( i, n ) for ( int i = (n) - 1; i >= 0; i-- )
const int MAXN = 1 << 15;
int T, N;
char S[MAXN];
bool doit( char& a, char &b, char &c ) {
if ( a != '1' || b != '1' || c != '0' ) return 0;
a = '0'; b = '0'; c = '1';
return 1;
}
bool doit( char& a, char &b, char &c, char &d ) {
if ( a != '1' || b != '0' || c != '1' || d != '1' ) return 0;
a = '0'; b = '0'; c = '1'; d = '0';
return 1;
}
bool doit( char& a, char &b, char &c, char &d, char& e ) {
if ( a != '1' || b != '1' || c != '1' || d != '1' || e != '0' ) return 0;
a = '0'; b = '0'; c = '1'; d = '0'; e = '1';
return 1;
}
int main() {
scanf( "%d", &T );
while ( T-- ) {
scanf( "%d", &N );
scanf( "%s", &S );
REP( i, N )
if ( S[i] == '1' ) {
if ( i + 2 < N && doit( S[i], S[i + 1], S[i + 2] ) ) continue ;
if ( i + 3 < N && doit( S[i], S[i + 1], S[i + 2], S[i + 3] ) ) continue ;
if ( i + 4 < N && doit( S[i], S[i + 1], S[i + 2], S[i + 3], S[i + 4] ) ) continue ;
break ;
}
REPD( i, N )
if ( S[i] == '1' ) {
if ( i - 2 >= 0 && doit( S[i], S[i - 1], S[i - 2] ) ) continue ;
if ( i - 3 >= 0 && doit( S[i], S[i - 1], S[i - 2], S[i - 3] ) ) continue ;
if ( i - 4 >= 0 && doit( S[i], S[i - 1], S[i - 2], S[i - 3], S[i - 4] ) ) continue ;
break ;
}
if ( count( S, S + N, '1' ) == 1 )
printf( "yes\n" );
else
printf( "no\n" );
}
return 0;
}
| true |
2acc9d4aa89fd31b2dca84a7c1fb221c2013d971 | C++ | ZeikkuSSJ7/cpp | /file-io_args_classes/args.cpp | UTF-8 | 387 | 2.890625 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <stdio.h>
using namespace std;
int main(int argc, char const *argv[]) {
cout << argc << "\n";
cout << argv[1] << "\n";
ifstream i (argv[1]);
if (!i.is_open()) {
cout << "The file could not be opened!\n";
} else {
char x;
while(i.get(x)){
cout << x;
}
}
return 0;
}
| true |
2b96f51268f565087f2a7b96045bea9e73490609 | C++ | navidkpr/Competitive-Programming | /CodeForces/119/A[ Epic Game ].cpp | UTF-8 | 462 | 2.859375 | 3 | [] | no_license | #include <iostream>
using namespace std;
int a[2];
int gcd(int c, int b)
{
if (c < b)
swap(c, b);
if (b == 0)
return c;
return gcd(c % b, b);
}
int main()
{
int n;
cin >> a[0] >> a[1] >> n;
int turn = 0;
bool h = 0;
while (n > 0)
{
//cerr << a[turn] << ' ' << n << ' ' << gcd(a[turn], n) << endl;
h = 1;
n -= gcd(a[turn], n);
turn = 1 - turn;
}
if (h)
cout << 1 - turn << endl;
else
cout << 1 << endl;
return 0;
}
| true |
c01d04dbd4bc3a97d07581cadb371f8c8b664e7b | C++ | yzIAI/xxxt-homeworks | /hw3/solutions/q2.cpp | UTF-8 | 711 | 3.015625 | 3 | [] | no_license | /*
* [q2.cpp]
* 信息学堂2021 课后作业 Day 3 Question 2
*
* 信息学堂第三次的作业会带大家熟悉数组以及循环在数组的应用
* 请根据注释里的相应提示,完成 *TODO* 部分的作业内容
*
* © Tina J, 2021
* 作者:Tina Ji & Ziang Qiao
* 时间:03/07/2021
* 版本:1.0.0
*/
#include <iostream>
using namespace std;
int main(void) {
int i = 0, row = 10, col = 10, scalar = 3;
int matrix[row][col];
for (int j = 0; j < row; j++) {
for (int k = 0; k < col; k++) {
matrix[j][k] = 1;
}
}
for (int j = 0; j < row; j++) {
for (int k = 0; k < col; k++) {
matrix[j][k] *= scalar;
}
}
return 0;
} | true |
9cc5d752d9d01b8a780e1090be941ab62e880d96 | C++ | 66112/memory_pool | /TestCache.cpp | GB18030 | 4,421 | 3.265625 | 3 | [] | no_license | #include "ConcurrentAlloc.h"
#include <vector>
#include <Windows.h>
using std::vector;
using std::thread;
void BenchmarkMalloc(size_t ntimes, size_t nworks, size_t rounds)
{
vector<thread> vthread(nworks);
size_t malloc_costtime = 0;
size_t free_costtime = 0;
for (size_t k = 0; k < nworks; k++){
vthread[k] = std::thread([&]() {
std::vector<void*> v;
v.reserve(ntimes);
for (size_t j = 0; j < rounds; ++j)
{
size_t begin1 = clock();
for (size_t i = 0; i < ntimes; i++)
{
v.push_back(malloc(1025));
}
size_t end1 = clock();
size_t begin2 = clock();
for (size_t i = 0; i < ntimes; i++)
{
free(v[i]);
}
size_t end2 = clock();
v.clear();
malloc_costtime += end1 - begin1;
free_costtime += end2 - begin2;
}
});
}
for (auto& t : vthread)
{
t.join();
}
printf("%uִ̲߳%uִΣÿִBenchmarkMalloc alloc %u: ѣ%u ms\n",
nworks, rounds, ntimes, malloc_costtime);
printf("%uִ̲߳%uִΣÿִBenchmarkMalloc dealloc %u: ѣ%u ms\n",
nworks, rounds, ntimes, free_costtime);
printf("%u̲߳BenchmarkMalloc alloc&dealloc %uΣܼƻѣ%u ms\n",
nworks, nworks*rounds*ntimes, malloc_costtime + free_costtime);
}
void BenchmarkConcurrentMalloc(size_t ntimes, size_t nworks, size_t rounds)
{
std::vector<std::thread> vthread(nworks);
size_t malloc_costtime = 0;
size_t free_costtime = 0;
for (size_t k = 0; k < nworks; ++k)
{
//&ķʽж
vthread[k] = std::thread([&]() {
std::vector<void*> v;
v.reserve(ntimes);
for (size_t j = 0; j < rounds; ++j)
{
size_t begin1 = clock();
for (size_t i = 0; i < ntimes; i++)
{
v.push_back(ConcurrentAlloc(1025));
}
size_t end1 = clock();
size_t begin2 = clock();
for (size_t i = 0; i < ntimes; i++)
{
ConcurrentFree(v[i]);
}
size_t end2 = clock();
v.clear();
malloc_costtime += end1 - begin1;
free_costtime += end2 - begin2;
}
});
}
printf("%uִ̲߳%uִΣÿִconcurrent alloc %u: ѣ%u ms\n",
nworks, rounds, ntimes, malloc_costtime);
printf("%uִ̲߳%uִΣÿִconcurrent dealloc %u: ѣ%u ms\n",
nworks, rounds, ntimes, free_costtime);
printf("%u̲߳concurrent alloc&dealloc %uΣܼƻѣ%u ms\n",
nworks, nworks*rounds*ntimes, malloc_costtime + free_costtime);
for (auto& t : vthread)
{
t.join();
}
}
void TestConcurrentAlloc()
{
size_t n = 100000;
std::vector<void*> v;
for (size_t i = 0; i < n; ++i)
{
v.push_back(ConcurrentAlloc(10));
cout << v.back() << endl;
}
cout << endl << endl;
for (size_t i = 0; i < n; ++i)
{
ConcurrentFree(v[i]);
}
v.clear();
for (size_t i = 0; i < n; ++i)
{
v.push_back(ConcurrentAlloc(10));
//cout << v.back() << endl;
}
for (size_t i = 0; i < n; ++i)
{
ConcurrentFree(v[i]);
}
v.clear();
}
void TestThreadCache()
{
std::vector<void*> v;
for (size_t i = 0; i < 11; i++){
v.push_back(ConcurrentAlloc(12));
cout << v.back() << endl;
}
v.clear();
cout << endl;
for (size_t i = 0; i < 11; i++){
v.push_back(ConcurrentAlloc(12));
cout << v.back() << endl;
}
for (size_t i = 0; i < 10; i++){
ConcurrentFree(v[i]);
}
}
void TestPageCache()
{
//void* ptr = malloc((NPAGES - 1) << PAGE_SHIFT);
void* ptr = ConcurrentAlloc(129 << 12);
cout << ptr << endl;
if (ptr == nullptr)
{
throw std::bad_alloc();
}
ConcurrentFree(ptr);
PageID pageid = (PageID)ptr >> PAGE_SHIFT;
cout << pageid << endl;
void* shiftptr = (void*)(pageid << PAGE_SHIFT);
cout << shiftptr << endl;
}
void TestFree()
{
std::vector<void*> v;
for (size_t i = 0; i < 3; i++){
v.push_back(ConcurrentAlloc(4));
cout << v.back() << endl;
}
cout << endl;
for (size_t i = 0; i < 3; i++){
ConcurrentFree(v[i]);
}
v.clear();
cout << endl;
for (size_t i = 0; i < 10; i++){
v.push_back(ConcurrentAlloc(4));
cout << v.back() << endl;
}
}
int main()
{
//TestConcurrentAlloc();
//TestThreadCache();
//TestPageCache();
//TestFree();
cout << "==========================================================" << endl;
BenchmarkMalloc(10000, 10, 10);
cout << endl << endl;
BenchmarkConcurrentMalloc(10000, 10, 10);
cout << "==========================================================" << endl;
return 0;
}
//Lambdaʽ
| true |
2b64d5dc5a8df421dc1c4664522999a34a9db470 | C++ | janwilmans/nowindlibraries | /nwhost/BlockWrite.cc | UTF-8 | 6,909 | 2.53125 | 3 | [
"MIT"
] | permissive |
#include "BlockWrite.hh"
#include "DataBlockWrite.hh"
#include "NowindHostSupport.hh"
#include <cassert>
#define DBERR nwhSupport->debugMessage
// the BLOCKWRITE_SIZE is not hardcoded in ROM, the host requests the exact amount the msx should send.
static const unsigned BLOCKWRITE_SIZE = 240;
namespace nwhost {
// the blockWrite command transfers data from the MSX to the host (so it's 'writing' from the msx perspective)
// blocks of <sequencenr> <d0> .. <d239> <sequencenr> (total 242 bytes) are send, the sequence numbers are generated and checked by the host.
BlockWrite::BlockWrite()
{
}
void BlockWrite::copyData(std::vector<byte>& aDestinationData)
{
for (unsigned int i=0; i< mBuffer.size();i++)
{
aDestinationData[i] = mBuffer[i];
}
mBuffer.clear();
}
void BlockWrite::initialize(NowindHostSupport* aSupport)
{
nwhSupport = aSupport;
}
BlockWrite::~BlockWrite()
{
}
bool BlockWrite::isDone() const
{
return mDone;
}
void BlockWrite::init(unsigned int mMsTime, word aStartAddress, word aSize, std::vector<byte>* aReceiveBuffer, byte aReturnCode)
{
DBERR("BlockWrite::init(startAddress: 0x%04x, size: 0x%04x\n", aStartAddress, aSize);
mBlockSequenceNr = 0;
mReceiveIndex = 0;
mReceivedData = 0;
mRequestedData = 0;
mDone = false;
mDataBlockQueue.clear();
mBeginTime = mMsTime;
mStartAddress = aStartAddress;
// the nowind rom goes to Page23 mode immediately when the mStartAddress is in page 2/3 (>=0x8000)
if (mStartAddress >= TWOBANKLIMIT)
{
mTransferingToPage23 = true;
}
else
{
mTransferingToPage23 = false;
}
mTransferSize = aSize;
mDefaultReturnCode = aReturnCode;
mBuffer.clear();
mBuffer.resize(aSize);
mReceiveBuffer = aReceiveBuffer;
mReceiveBuffer->clear();
continueWithNextBlock();
continueWithNextBlock();
continueWithNextBlock();
continueWithNextBlock();
continueWithNextBlock();
continueWithNextBlock();
continueWithNextBlock();
continueWithNextBlock();
}
// todo:
// - add all blocks to receive from msx to a queue
// - send several 9-byte requests for data
// - receive blocks of 240+2 bytes, check the markers, request again
void BlockWrite::continueWithNextBlock()
{
if (getBytesLeft() == 0)
{
DBERR("BlockWrite DONE!\n");
nwhSupport->sendHeader();
nwhSupport->send(mDefaultReturnCode);
mDone = true;
return;
}
unsigned int startAddr = mStartAddress + mRequestedData;
//DBERR("BlockWrite::continueWithNextBlock, startAddress: 0x%04X, size: 0x%04X\n", startAddr, getBytesLeft());
// make sure the transfer does not cross the TWOBANKLIMIT
if (startAddr < TWOBANKLIMIT)
{
word endAddress = std::min(TWOBANKLIMIT-1, startAddr + getBytesLeft());
word transferSize = endAddress - startAddr;
requestBlock(startAddr, mTransferSize);
}
else
{
requestBlock(startAddr, getBytesLeft());
}
}
void BlockWrite::requestBlock(word aStartAddress, word aSize)
{
word lBlockSize = std::min(aSize, BLOCKWRITE_SIZE);
unsigned int endAddress = aStartAddress + aSize;
//DBERR("BlockWrite::requestBlock, address: 0x%04x, transferSize: 0x%04X \n", aStartAddress, lBlockSize);
if (mTransferingToPage23 == false && aStartAddress >= TWOBANKLIMIT)
{
// until now no Page23 blocks were send and the next block is a Page23 block
if (mDataBlockQueue.size() > 0)
{
// while not all Page01 blocks are received, dont start with Page23 blocks yet (because we cant switch back)
DBERR("BlockWrite::requestBlock, delaying page23 block until all page01 blocks are done.\n");
return;
}
else
{
//DBERR("BlockWrite::requestBlock, switching to page23 mode.\n");
nwhSupport->sendHeader();
nwhSupport->send(BLOCKWRITE_PAGE23_DATA);
mTransferingToPage23 = true;
}
}
// request the next block of data (consists of 3+1+2+2+1 = 9 bytes)
nwhSupport->sendHeader();
nwhSupport->send(0); // transfer not done
nwhSupport->send16(aStartAddress);
nwhSupport->send16(lBlockSize);
nwhSupport->send(mBlockSequenceNr);
DataBlockWrite* lData = new DataBlockWrite(mBlockSequenceNr, mRequestedData, aStartAddress, lBlockSize);
//DBERR("DataBlockWrite: mBlockSequenceNr: %u, aStartAddress: 0x%04X, lBlockSize: %u\n", mBlockSequenceNr, aStartAddress, lBlockSize);
mDataBlockQueue.push_back(lData);
mBlockSequenceNr = (mBlockSequenceNr+1) & 255;
mRequestedData += lBlockSize;
//todo: maybe write speed can be optimized by requesting multiple blocks at once,
// special care should taken to ensure the msx-receive buffer is does not overflow
// and that our garantees are still met?? I think this is not reliable!
// for example by making sure there are never more then 256/9 = 28 blocks out-standing.
}
void BlockWrite::receiveData(byte data)
{
// the datablock we expect to receive next
DataBlockWrite* lData = mDataBlockQueue.front();
//DBERR("BlockWrite::receiveData, receiveIndex: %u, currentBlockSize: %u\n", mReceiveIndex, lData->getSize());
if (mReceiveIndex == 0)
{
if (lData->getSequenceNr() != data)
{
// sequenceNrHeader is not the correct sequenceNr
// todo: maybe implement a retry mechanism,
// abort entire transfer for now
//DBERR("BLOCKWRITE_ERROR BlockWrite::receiveData, sequenceNrHeader: 0x%02X != 0x%02X\n", data, lData->getSequenceNr());
cancelWithCode(BLOCKWRITE_ERROR);
}
mReceiveIndex++;
}
else if (mReceiveIndex <= lData->getSize())
{
mBuffer[mReceivedData] = data;
mReceiveIndex++;
mReceivedData++;
}
else
{
if (lData->getSequenceNr() == data)
{
//DBERR("BlockWrite::receiveData, BLOCKEND [0x%02X] block OK\n", data);
delete lData;
mDataBlockQueue.pop_front();
mReceiveIndex = 0;
continueWithNextBlock();
}
else
{
DBERR("BlockWrite::receiveData, block ERROR!, sequenceNrTail: 0x%02X != 0x%02X\n", data, lData->getSequenceNr());
cancelWithCode(BLOCKWRITE_ERROR);
}
}
}
void BlockWrite::cancelWithCode(byte returnCode)
{
// nwhSupport->sendHeader();
// nwhSupport->send(returnCode); //todo: BlockWrite does not stop correctly on BLOCKWRITE_ERROR? (a timeout seems to be the only way to cause a 'disk offline'
mDone = true;
}
} // namespace nwhost
| true |
87c403f585e472af4f76fa25339abe52b2162543 | C++ | JackMcCallum/Portfolio | /Demos/Games/Tanks/Source/Game.h | UTF-8 | 1,614 | 2.6875 | 3 | [] | no_license | /************************************************************************/
/* @class Game
* @author Jack McCallum
*
* @description
* Class from where all the game is controlled, it is entered via TanksMain
* also controlls the score and win/lose condision
*
/************************************************************************/
#pragma once
#include "EventLoop.h"
class StandardMenu;
class FreeCam;
class CollisionManager;
class EffectsManager;
class HPDisplay;
class GameOver;
class Player;
class Game;
// This is a class for sending pointers to managers etc to our objects without making a huge mess
struct GameData
{
OgreMain* ogreMain;
CollisionManager* collisionManager;
EffectsManager* effectsManager;
Game* game;
// Effects manager etc...
};
class Game : public EventLoop
{
public:
Game(OgreMain* oMain);
virtual ~Game();
virtual void eventKeyboardKeyPressed(const JMKeyEvent &evt);
// Goto other event loops
void gotoPauseMenu();
void gotoGameOverWin();
void gotoGameOverLose();
// Generates a level with a given seed
void generateLevel(int seed);
// Updates
virtual void eventPreRender(const JMFrameEvent &evt);
// Creation and destruction of the scene
virtual void eventEnteringLoop(const JMFrameEvent &evt);
virtual void eventLeavingLoop(const JMFrameEvent &evt);
// Score control
void addScore(int val);
private:
// Game objects
StandardMenu* pauseMenu;
FreeCam* freeCam;
GameOver* gameOver;
Player* player;
// Pointers to be sent to other objects
GameData gameData;
// Interface
HPDisplay* hpDisplay;
Overlay* overlay;
// Score
int score;
};
| true |
74a61b1f6d902d6bff9a1d4231c9b1f386cd175b | C++ | DenisPushkin/randomizer | /gist.cpp | UTF-8 | 749 | 2.859375 | 3 | [] | no_license | #include "gist.h"
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
void gist (double* arr, int n, double left, double step, int length, int precision1, int precision2) {
vector < int > mas(length,0);
for (int i=0; i<n; ++i)
if (arr[i]>=left){
int j=0;
while (left+(j+1)*step<arr[i] && j<length) ++j;
if (j<length) ++mas[j];
}
for (int i=0; i<length; ++i) {
cout.precision(precision1);
cout << "[";
cout.width(precision1+3);
cout << left+i*step << ";";
cout.width(precision1+3);
cout << left+(i+1)*(step) << "] - ";
cout.precision(precision2);
cout << (double) mas[i]/n << endl;
}
}
| true |
04089bc1b96de3da7be03d7edac041f6ac117bd2 | C++ | JeremyBois/SimpleGL | /src/Components/PointLight.cpp | UTF-8 | 2,375 | 2.78125 | 3 | [] | no_license | #include "Components/PointLight.hpp"
#include "OpenGL/Shader.hpp"
#include "GameManager.hpp"
#include "Node.hpp"
#include <algorithm>
namespace simpleGL
{
std::vector<PointLight*> PointLight::PointLightContainer;
PointLight::PointLight()
// http://wiki.ogre3d.org/tiki-index.php?page=-Point+Light+Attenuation
: m_constCoef(1.0f), m_linearCoef(0.14f), m_quadraticCoef(0.07f)
{
m_color = glm::vec3(0.6f, 0.6f, 0.6f);
PointLightContainer.push_back(this);
}
PointLight::~PointLight()
{
// Has order does not matter reduce overhead using pop_back in place of removeAt
std::vector<PointLight*>::iterator it = std::find(PointLightContainer.begin(),
PointLightContainer.end(), this);
if (it != PointLightContainer.end())
{
// Swap current with last one then remove last
std::swap(*it, PointLightContainer.back());
PointLightContainer.pop_back();
}
}
/// Set light color and world position inside the shader
void PointLight::Use(const Shader& _shader, int _lightIndex) const
{
if (IsActive())
{
// Pass data to shader
_shader.Use();
// Pass color to shader
_shader.SetVec3("_pointLights_[" + std::to_string(_lightIndex) + "].color", m_color);
// Pass position
_shader.SetVec3("_pointLights_[" + std::to_string(_lightIndex) + "].worldPosition", GetTransform().GetPosition());
// Pass attenuation parameters
_shader.SetFloat("_pointLights_[" + std::to_string(_lightIndex) + "].constant", m_constCoef);
_shader.SetFloat("_pointLights_[" + std::to_string(_lightIndex) + "].linear", m_linearCoef);
_shader.SetFloat("_pointLights_[" + std::to_string(_lightIndex) + "].quadratic", m_quadraticCoef);
}
}
/// Loop over all light and pass their data to the shader
void PointLight::UseAll(const Shader& _shader)
{
unsigned int lightNumber = PointLightContainer.size();
for (unsigned int i = 0; i < lightNumber; ++i)
{
PointLightContainer[i]->Use(_shader, i);
}
// Pass number of point light to compute
_shader.SetInt("_PointLightCount_", lightNumber);
}
}
| true |
4dc6646f0279284da15b809bd09bc8a03378e7d9 | C++ | yous/acmicpc-net | /problem/9020/main.cpp | UTF-8 | 678 | 2.765625 | 3 | [] | no_license | #include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int T, N;
vector<bool> sieve(10001, true);
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cin >> T;
sieve[1] = false;
for (int i = 2; i * i <= 10000; i++) {
if (!sieve[i]) {
continue;
}
for (int j = i * i; j <= 10000; j += i) {
sieve[j] = false;
}
}
while (T-- > 0) {
cin >> N;
for (int i = N / 2; i >= 2; i--) {
if (sieve[i] && sieve[N - i]) {
cout << i << " " << N - i << "\n";
break;
}
}
}
return 0;
}
| true |
2a39fca94d7f4a5285a751ce45d3475383d84f39 | C++ | RikkaWZ/DSCode | /2LinearList/SqList/SqList.cpp | UTF-8 | 4,124 | 3.78125 | 4 | [] | no_license | #include "SqList.h"
/**
* 王道P17.1
* 删除具有最小值的元素,空出的位置由最后一个元素填补
*/
bool Del_Min(SqList &L, ElemType &value) {
if (L.length == 0)
return false;
value = L.data[0]; // 最小值先当作是第一个元素
int pos = 0;
for (int i = 1; i < L.length; i++)
if (L.data[i] < value) {
value = L.data[i];
pos = i;
}
L.data[pos] = L.data[L.length - 1];
L.length--;
return true;
}
/**
* 王道P17.2
* 设计高效算法逆置顺序表,时间复杂度 O(1)
*/
void Reverse(SqList &L) {
ElemType temp;
// 遍历表前半部分,与后半部分逐一交换顺序
for (int i = 0; i < L.length / 2; i++) {
temp = L.data[i];
L.data[i] = L.data[L.length - i - 1];
L.data[L.length - i - 1] = temp;
}
}
/**
* 王道P17.3
* 删除表中所有值为 x 的数据元素
* 时间复杂度 O(n),空间复杂度 O(1)
*/
void Del_x_1(SqList &L, ElemType x) {
// 解法1
int k = 0; // 记录值不为 x 的元素个数
for (int i = 0; i < L.length; i++)
// 边扫描边统计 k,并将不等于 x 的元素向前移动 k 个位置
if (L.data[i] != x) {
L.data[k] = L.data[i];
k++;
}
L.length = k; // 最后修改长度
}
void Del_x_2(SqList &L, ElemType x) {
// 解法2
int k = 0; // 记录值为 x 的元素个数
int i = 0;
while (i < L.length) {
// 边扫描边统计 k,并将不等于 x 的元素向前移动 k 个位置
if (L.data[i] == x)
k++;
else
L.data[i - k] = L.data[i];
i++;
}
L.length -= k; // 最后修改长度
}
/**
* 王道P17.5
* 删除顺序表表中所有值在给定值 s 与 t 之间的所有元素
*/
bool Del_x_t(SqList &L, ElemType s, ElemType t) {
if (s >= t || L.length == 0)
return false;
int k = 0; // 记录值在 s 与 t 之间的元素个数
for (int i = 0; i < L.length; i++) {
// 边扫描边统计 k,并将不等于 x 的元素向前移动 k 个位置
if (L.data[i] >= s && L.data[i] <= t)
k++;
else
L.data[i - k] = L.data[i];
}
L.length -= k; // 最后修改长度
return true;
}
/**
* 王道P17.4
* 删除*有序*顺序表表中所有值在给定值 s 与 t 之间的所有元素
*/
bool Del_x_t_2(SqList &L, ElemType s, ElemType t) {
int i;
int j;
if (s >= t || L.length == 0)
return false;
for (i = 0; i < L.length && L.data[i] < s; i++); // 寻找大于等于 s 的第一个元素
if (i >= L.length)
// 所有元素都小于 s
return false;
for (j = i; i < L.length && L.data[i] <= t; j++); // 寻找大于 t 的第一个元素
for (; j < L.length; i++, j++)
L.data[i] = L.data[j]; // 前移,填充被删元素位置
L.length = i;
return true;
}
/**
* 王道P17.6
* 有序顺序表删除所有值重复的元素,使表中元素均不同
*/
bool Del_Same(SqList &L) {
if (L.length == 0)
return false;
int i = 0; // 存储第一个不相同的元素指针
for (int j = 1; j < L.length; j++)
if (L.data[i] != L.data[j])
L.data[++i] = L.data[j];
L.length = i + 1;
return true;
}
/**
* 王道P17.7
* 两个有序表合成一个新的有序表
*/
bool Merge(SqList &A, SqList &B, SqList &C) {
if (A.length + B.length > MaxSize)
return false;
int k = 0;
int i = 0;
int j = 0;
while (i < A.length && j < B.length) {
if (A.data[i] <= B.data[j])
C.data[k++] = A.data[i++];
else
C.data[k++] = B.data[j++];
}
while (i < A.length)
C.data[k++] = A.data[i++];
while (j < B.length)
C.data[k++] = B.data[j++];
C.length = k;
return true;
}
int main() {
SqList L;
InitList(L);
// IncreaseSize(L, 5);
ListInsert(L, 1, 1);
ListInsert(L, 2, 2);
int d = 0;
ListDelete(L, 1, d);
ListInsert(L, 2, 9);
printf("%d", LocateElem(L, 9));
return 0;
}
| true |
6b9ba773d3a74d7043c36db6de562ff0cc582bc4 | C++ | google/perfetto | /include/perfetto/trace_processor/trace_blob_view.h | UTF-8 | 4,895 | 2.53125 | 3 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | /*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef INCLUDE_PERFETTO_TRACE_PROCESSOR_TRACE_BLOB_VIEW_H_
#define INCLUDE_PERFETTO_TRACE_PROCESSOR_TRACE_BLOB_VIEW_H_
#include <stddef.h>
#include <stdint.h>
#include <limits>
#include <memory>
#include "perfetto/base/logging.h"
#include "perfetto/trace_processor/ref_counted.h"
#include "perfetto/trace_processor/trace_blob.h"
namespace perfetto {
namespace trace_processor {
// A read-only view of a TraceBlob.
// This class is an equivalent of std::string_view for trace binary data, with
// a twist: it supports turning a TraceBlob into a refcounted reference. In this
// case the TraceBlobView acts directly as a shared_ptr, without requiring extra
// layers of indirection.
// The underlying TraceBlob will be freed once all the TraceBlobViews that refer
// to the same buffer have passed through the pipeline and been parsed.
// The overall idea is that a TraceBlob is passed around until it's written.
// When writing is done it transforms into a shared refcounted object which is
// held onto by one or more read-only TraceBlobView instances.
//
// In summary:
// - TraceBlob: writable, move-only, single-instance.
// - TraceBlobView: readable, copyable, multiple-instances can hold onto
// (different sub-slices of) the same refcounted TraceBlob.
class alignas(8) TraceBlobView {
public:
// Takes ownership of the passed |blob|.
static constexpr size_t kWholeBlob = std::numeric_limits<size_t>::max();
explicit TraceBlobView(TraceBlob blob,
size_t offset = 0,
size_t length = kWholeBlob) {
PERFETTO_DCHECK(offset <= std::numeric_limits<uint32_t>::max());
data_ = blob.data() + offset;
if (length == kWholeBlob) {
length_ = static_cast<uint32_t>(blob.size() - offset);
} else {
PERFETTO_DCHECK(length <= std::numeric_limits<uint32_t>::max());
PERFETTO_DCHECK(offset + length_ <= blob.size());
length_ = static_cast<uint32_t>(length);
}
blob_.reset(new TraceBlob(std::move(blob)));
}
TraceBlobView(RefPtr<TraceBlob> blob, size_t offset, uint32_t length)
: blob_(std::move(blob)), data_(blob_->data() + offset), length_(length) {
PERFETTO_DCHECK(offset + length_ <= blob_->size());
}
// Trivial empty ctor.
TraceBlobView() : data_(nullptr), length_(0) {}
~TraceBlobView() = default;
// Allow std::move().
TraceBlobView(TraceBlobView&& other) noexcept { *this = std::move(other); }
TraceBlobView& operator=(TraceBlobView&& other) noexcept {
data_ = other.data_;
length_ = other.length_;
blob_ = std::move(other.blob_);
return *this;
}
// Disable copy operators. Use x.Copy() to get a copy.
TraceBlobView(const TraceBlobView&) = delete;
TraceBlobView& operator=(const TraceBlobView&) = delete;
// [data, data+length] must be <= the current TraceBlobView.
TraceBlobView slice(const uint8_t* data, size_t length) const {
PERFETTO_DCHECK(data >= data_);
PERFETTO_DCHECK(data + length <= data_ + length_);
return TraceBlobView(blob_, data, static_cast<uint32_t>(length));
}
// Like slice() but takes an offset rather than a pointer as 1st argument.
TraceBlobView slice_off(size_t off, size_t length) const {
PERFETTO_DCHECK(off + length <= length_);
return TraceBlobView(blob_, data_ + off, static_cast<uint32_t>(length));
}
TraceBlobView copy() const { return slice(data_, length_); }
bool operator==(const TraceBlobView& rhs) const {
return (data_ == rhs.data_) && (length_ == rhs.length_) &&
(blob_ == rhs.blob_);
}
bool operator!=(const TraceBlobView& rhs) const { return !(*this == rhs); }
const uint8_t* data() const { return data_; }
size_t offset() const { return static_cast<size_t>(data_ - blob_->data()); }
size_t length() const { return length_; }
size_t size() const { return length_; }
RefPtr<TraceBlob> blob() const { return blob_; }
private:
TraceBlobView(RefPtr<TraceBlob> blob, const uint8_t* data, uint32_t length)
: blob_(std::move(blob)), data_(data), length_(length) {}
RefPtr<TraceBlob> blob_;
const uint8_t* data_ = nullptr;
uint32_t length_ = 0;
};
} // namespace trace_processor
} // namespace perfetto
#endif // INCLUDE_PERFETTO_TRACE_PROCESSOR_TRACE_BLOB_VIEW_H_
| true |
73a2f3cf2be163339a8004b0c3cde85b25e1d4c5 | C++ | Zeimd/crender-mt | /software-renderer/alg-test/uint8-float.cpp | UTF-8 | 10,556 | 2.734375 | 3 | [] | no_license | #include <ceng/datatypes/aligned-buffer.h>
#include "alg-test.h"
const float scale = 1.0f / 255.0f;
void uint8_to_normalized_float(const unsigned char* input, float* output, const int size)
{
for (int k = 0; k < size; ++k)
{
output[k] = float(input[k]) * scale;
}
}
void uint8_to_normalized_float_strip4(const unsigned char* input, float* output, const int size)
{
for (int k = 0; k < size; k += 4)
{
output[k] = float(input[k]) * scale;
output[k + 1] = float(input[k + 1]) * scale;
output[k + 2] = float(input[k + 2]) * scale;
output[k + 3] = float(input[k + 3]) * scale;
}
}
void uint8_to_normalized_float_strip8(const unsigned char* input, float* output, const int size)
{
for (int k = 0; k < size; k += 8)
{
output[k] = float(input[k]) * scale;
output[k + 1] = float(input[k + 1]) * scale;
output[k + 2] = float(input[k + 2]) * scale;
output[k + 3] = float(input[k + 3]) * scale;
output[k + 4] = float(input[k + 4]) * scale;
output[k + 5] = float(input[k + 5]) * scale;
output[k + 6] = float(input[k + 6]) * scale;
output[k + 7] = float(input[k + 7]) * scale;
}
}
void uint8_to_normalized_float_strip16(const unsigned char* input, float* output, const int size)
{
for (int k = 0; k < size; k += 16)
{
output[k] = float(input[k]) * scale;
output[k + 1] = float(input[k + 1]) * scale;
output[k + 2] = float(input[k + 2]) * scale;
output[k + 3] = float(input[k + 3]) * scale;
output[k + 4] = float(input[k + 4]) * scale;
output[k + 5] = float(input[k + 5]) * scale;
output[k + 6] = float(input[k + 6]) * scale;
output[k + 7] = float(input[k + 7]) * scale;
output[k + 8] = float(input[k + 8]) * scale;
output[k + 9] = float(input[k + 9]) * scale;
output[k + 10] = float(input[k + 10]) * scale;
output[k + 11] = float(input[k + 11]) * scale;
output[k + 12] = float(input[k + 12]) * scale;
output[k + 13] = float(input[k + 13]) * scale;
output[k + 14] = float(input[k + 14]) * scale;
output[k + 15] = float(input[k + 15]) * scale;
}
}
void uint8_to_normalized_float_sse(const unsigned char* input16, float* output16, const int size)
{
const _declspec(align(16)) float scaleVec[] = { scale, scale, scale, scale };
__asm
{
vpxor xmm7, xmm7, xmm7; // xmm7 = zero
vmovaps xmm6, scaleVec;
}
for (int k = 0; k < size; k += 16)
{
__asm
{
mov esi, input16;
mov eax, k;
vmovdqa xmm0, [esi + eax]; // xmm0 = byte {x15,x14,x13,...,x3,x2,x1,x0}
vpunpcklbw xmm1, xmm0, xmm7; // xmm1 = word {x7,x6,x5,x4,x3,x2,x1,x0}
vpunpckhbw xmm0, xmm0, xmm7; // xmm2 = word {x15,x14,x13,x12,x11,x10,x9,x8}
vpunpcklwd xmm2, xmm1, xmm7; // xmm3 = dword{ x3, x2, x1, x0 }
vpunpckhwd xmm3, xmm1, xmm7; // xmm4 = dword{ x7, x6, x5, x4 }
vpunpcklwd xmm4, xmm0, xmm7; // xmm5 = dword{ x11, x10, x9, x8 }
vpunpckhwd xmm5, xmm0, xmm7; // xmm6 = dword{ x15, x14, x13, x12 }
// Convert to float
vcvtdq2ps xmm2, xmm2;
vcvtdq2ps xmm3, xmm3;
vcvtdq2ps xmm4, xmm4;
vcvtdq2ps xmm5, xmm5;
// Scale correctly
vmulps xmm2, xmm2, xmm6;
vmulps xmm3, xmm3, xmm6;
vmulps xmm4, xmm4, xmm6;
vmulps xmm5, xmm5, xmm6;
// Store
mov edi, output16;
mov eax, k;
shl eax, 2;
vmovaps[edi + eax], xmm2;
vmovaps[edi + eax + 16], xmm3;
vmovaps[edi + eax + 32], xmm4;
vmovaps[edi + eax + 48], xmm5;
}
}
}
void uint8_to_normalized_float_optimized_sse(const unsigned char* input16, float* output16, const int size)
{
const float floatVal = float(1 << 15);
const _declspec(align(16)) float floatBits[] = { floatVal, floatVal, floatVal, floatVal };
for (int k = 0; k < size; k += 16)
{
__asm
{
mov esi, input16;
mov eax, k;
vmovdqa xmm0, [esi + eax]; // xmm0 = byte {x15,x14,x13,...,x3,x2,x1,x0}
vpxor xmm7, xmm7, xmm7; // xmm7 = zero
vpunpcklbw xmm1, xmm0, xmm7; // xmm1 = word {x7,x6,x5,x4,x3,x2,x1,x0}
vpunpckhbw xmm2, xmm0, xmm7; // xmm2 = word {x15,x14,x13,x12,x11,x10,x9,x8}
// Scale so that 255 -> 1.0
vpsrlw xmm3, xmm1, 7;
vpaddusw xmm1, xmm1, xmm3;
vpsrlw xmm4, xmm2, 7;
vpaddusw xmm2, xmm2, xmm4;
vpunpcklwd xmm3, xmm1, xmm7; // xmm3 = dword{ x3, x2, x1, x0 }
vpunpckhwd xmm4, xmm1, xmm7; // xmm4 = dword{ x7, x6, x5, x4 }
vpunpcklwd xmm5, xmm2, xmm7; // xmm5 = dword{ x11, x10, x9, x8 }
vpunpckhwd xmm6, xmm2, xmm7; // xmm6 = dword{ x15, x14, x13, x12 }
// Convert to float
vmovdqa xmm7, floatBits;
vpor xmm3, xmm3, xmm7;
vpor xmm4, xmm4, xmm7;
vpor xmm5, xmm5, xmm7;
vpor xmm6, xmm6, xmm7;
vsubps xmm3, xmm3, xmm7;
vsubps xmm4, xmm4, xmm7;
vsubps xmm5, xmm5, xmm7;
vsubps xmm6, xmm6, xmm7;
// Store
mov edi, output16;
mov eax, k;
shl eax, 2;
vmovaps[edi + eax], xmm3;
vmovaps[edi + eax + 16], xmm4;
vmovaps[edi + eax + 32], xmm5;
vmovaps[edi + eax + 48], xmm6;
}
}
}
void uint8_to_normalized_float_sse_v3(const unsigned char* input16, float* output16, const int size)
{
const _declspec(align(16)) float scaleVec[] = { scale, scale, scale, scale };
__asm
{
vmovaps xmm7, scaleVec;
}
for (int k = 0; k < size; k += 16)
{
__asm
{
mov esi, input16;
mov eax, k;
vpmovzxbd xmm3, [esi + eax];
vpmovzxbd xmm4, [esi + eax + 4];
vpmovzxbd xmm5, [esi + eax + 8];
vpmovzxbd xmm6, [esi + eax + 12];
// Convert to float
vcvtdq2ps xmm3, xmm3;
vcvtdq2ps xmm4, xmm4;
vcvtdq2ps xmm5, xmm5;
vcvtdq2ps xmm6, xmm6;
// Scale
vmulps xmm3, xmm3, xmm7;
vmulps xmm4, xmm4, xmm7;
vmulps xmm5, xmm5, xmm7;
vmulps xmm6, xmm6, xmm7;
// Store
mov edi, output16;
//mov eax, k;
shl eax, 2;
vmovaps[edi + eax], xmm3;
vmovaps[edi + eax + 16], xmm4;
vmovaps[edi + eax + 32], xmm5;
vmovaps[edi + eax + 48], xmm6;
}
}
}
void uint8_to_normalized_float_avx(const unsigned char* input, float* output, const int size)
{
const _declspec(align(32)) float scaleVec[] = { scale, scale, scale, scale, scale, scale, scale, scale };
__asm
{
vmovaps ymm7, scaleVec;
}
for (int k = 0; k < size; k += 16)
{
__asm
{
mov esi, input;
mov eax, k;
vpmovzxbd xmm3, [esi + eax];
vpmovzxbd xmm4, [esi + eax + 4];
vpmovzxbd xmm5, [esi + eax + 8];
vpmovzxbd xmm6, [esi + eax + 12];
vperm2f128 ymm3, ymm3, ymm4, 00100000b;
vperm2f128 ymm4, ymm5, ymm6, 00100000b;
// Convert to float
vcvtdq2ps ymm3, ymm3;
vcvtdq2ps ymm4, ymm4;
// Scale
vmulps ymm3, ymm3, ymm7;
vmulps ymm4, ymm4, ymm7;
// Store
mov edi, output;
//mov eax, k;
shl eax, 2;
vmovaps[edi + eax], ymm3;
vmovaps[edi + eax + 32], ymm4;
}
}
}
void normalized_float_to_uint8(const float* input, unsigned char* output, const int size)
{
for (int k = 0; k < size; ++k)
{
output[k] = Ceng::CE_FloatToInt(input[k] * 255.0f);
//output[k] = unsigned char(input[k] * 255.0f);
}
}
void normalized_float_to_uint8_sse(const float* input, unsigned char* output, const int size)
{
const float fxScale = 255.0f;
const _declspec(align(16)) float scaleVec[] = { fxScale, fxScale, fxScale, fxScale };
const _declspec(align(16)) unsigned char shuffle_mask[] = { 0, 4, 8, 12, 1, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15 };
__asm
{
vmovdqa xmm7, scaleVec;
vmovdqa xmm6, shuffle_mask;
}
for (int k = 0; k < size; k += 16)
{
__asm
{
mov esi, input;
mov eax, k;
shl eax, 2;
vmovaps xmm0, [esi + eax];
vmovaps xmm1, [esi + eax + 16];
vmovaps xmm2, [esi + eax + 32];
vmovaps xmm3, [esi + eax + 48];
vmulps xmm0, xmm0, xmm7;
vmulps xmm1, xmm1, xmm7;
vmulps xmm2, xmm2, xmm7;
vmulps xmm3, xmm3, xmm7;
vminps xmm0, xmm0, xmm7;
vminps xmm1, xmm1, xmm7;
vminps xmm2, xmm2, xmm7;
vminps xmm3, xmm3, xmm7;
vcvttps2dq xmm0, xmm0;
vcvttps2dq xmm1, xmm1;
vcvttps2dq xmm2, xmm2;
vcvttps2dq xmm3, xmm3;
vpslld xmm1, xmm1, 8;
vpslld xmm2, xmm2, 16;
vpslld xmm3, xmm3, 24;
vpor xmm0, xmm0, xmm1;
vpor xmm2, xmm2, xmm3;
vpor xmm0, xmm0, xmm2;
vpshufb xmm0, xmm0, xmm6;
mov edi, output;
mov eax, k;
vmovdqa[edi + eax], xmm0;
}
}
}
void normalized_float_to_uint8_optimized_sse(const float* input, unsigned char* output, const int size)
{
const float clamp = 1.0f - 1.0f / 256.0f;
const _declspec(align(16)) float clampVec[] = { clamp, clamp, clamp, clamp };
const float fxScale = float(1 << 15);
const _declspec(align(16)) float scaleVec[] = { fxScale, fxScale, fxScale, fxScale };
const _declspec(align(16)) unsigned char shuffle_mask[] = { 0, 4, 8, 12, 1, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15 };
__asm
{
vmovaps xmm7, clampVec;
vmovaps xmm6, scaleVec;
}
for (int k = 0; k < size; k += 16)
{
__asm
{
mov esi, input;
mov eax, k;
shl eax, 2;
vmovdqa xmm0, [esi + eax];
vmovdqa xmm1, [esi + eax + 16];
vmovdqa xmm2, [esi + eax + 32];
vmovdqa xmm3, [esi + eax + 48];
vpminud xmm0, xmm0, xmm7;
vpminud xmm1, xmm1, xmm7;
vpminud xmm2, xmm2, xmm7;
vpminud xmm3, xmm3, xmm7;
vaddps xmm0, xmm0, xmm6;
vaddps xmm1, xmm1, xmm6;
vaddps xmm2, xmm2, xmm6;
vaddps xmm3, xmm3, xmm6;
vpslld xmm1, xmm1, 8;
vpor xmm0, xmm0, xmm1;
vpslld xmm3, xmm3, 8;
vpor xmm2, xmm2, xmm3;
vpslld xmm2, xmm2, 16;
vpblendw xmm0, xmm0, xmm2, 10101010b;
vpshufb xmm0, xmm0, shuffle_mask;
mov edi, output;
mov eax, k;
vmovdqa[edi + eax], xmm0;
}
}
}
void normalized_float_to_uint8_avx(const float* input, unsigned char* output, const int size)
{
const float fxScale = 255.0f;
const _declspec(align(32)) float scaleVec[] = { fxScale, fxScale, fxScale, fxScale, fxScale, fxScale, fxScale, fxScale };
const _declspec(align(16)) unsigned char shuffle_mask[] = { 0, 4, 8, 12, 1, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15 };
__asm
{
vmovaps ymm7, scaleVec;
vmovdqa xmm6, shuffle_mask;
}
for (int k = 0; k < size; k += 16)
{
__asm
{
mov esi, input;
mov eax, k;
shl eax, 2;
vmovaps ymm0, [esi + eax];
vmovaps ymm1, [esi + eax + 32];
vmulps ymm0, ymm0, ymm7;
vmulps ymm1, ymm1, ymm7;
vminps ymm0, ymm0, ymm7;
vminps ymm1, ymm1, ymm7;
vcvttps2dq ymm0, ymm0;
vcvttps2dq ymm1, ymm1;
vmovaps ymm2, ymm1; // lower half to ymm2
vperm2f128 ymm3, ymm1, ymm1, 00000001b; // upper half to ymm3
vperm2f128 ymm1, ymm0, ymm0, 00000001b; // upper half to ymm1
vpslld xmm1, xmm1, 8;
vpslld xmm2, xmm2, 16;
vpslld xmm3, xmm3, 24;
vpor xmm0, xmm0, xmm1;
vpor xmm2, xmm2, xmm3;
vpor xmm0, xmm0, xmm2;
vpshufb xmm0, xmm0, xmm6;
mov edi, output;
mov eax, k;
vmovdqa[edi + eax], xmm0;
}
}
}
| true |
6b4e7f6ccd64bfe700000daabf4b83be256b3065 | C++ | Matlock42/Jeopardy | /jgameClass.h | UTF-8 | 953 | 2.703125 | 3 | [
"Unlicense",
"LicenseRef-scancode-public-domain"
] | permissive | /**********************************
* Jeopardy Game v. 3.0
*
* Complete rewrite of version 2.0
@author: Joel Cranmer <42.joel.cranmer@gmail.com>
@created: 2013/06/23
@modified:
@version: 3
*
**********************************/
#ifndef jgame_H
#define jgame_H
class Question;
class Game
{
public:
bool playing(void);
Game(int);
~Game();
int showBoard(void);
int showScore(void);
int updateStatus(void);
private:
int loadQuestions(void); // load questions from xml files in ./Data
bool showQuestion(int prompt); // display the question and answer prompt
int clearScreen(void); // clear the screen of text
std::vector <std::string> findXML ( const char *path ); // return vector of all .xml files in the given directory
bool mPlaying; // True-game goes on; False-No more questions
int mScore; // Current score
int mSize; // size of the game board
Question*** mQuestionSet; // 5x5 board size
};
#endif
| true |
07a757d7eead2fb3d67dced646e3bbd060af9814 | C++ | evanbradley6/BradleyEvan_CIS5_40739 | /Project/Project 1/Craps_Project_1_Complete/main.cpp | UTF-8 | 13,981 | 3.609375 | 4 | [] | no_license | /*
* File: main.cpp
* Author: Evan Bradley
* Created on February 6, 2020, 8:47 AM
* Purpose: Craps game with Preset Bets and 5 rounds Version 1,
* Version 2 will have input bets, and unlimited rounds
*/
//System Libraries
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
//User Libraries
//Global Constants - No Global Variables
//Only Universal Constants, Math, Physics, Conversions, Higher Dimensions
//Function Prototypes
//Execution Begins Here
int main(int argc, char** argv) {
//Declare Variable Data Types and Constant
char initalRoll, reRoll; // so user can press enter to roll the dice
int choice, point, round = 0; // User Bet Choice and User's point, and round initializer
short total = 10; // User initial total amount is $10
const int MAX = 6;// for maximum dots on a die side
const int MIN = 1;// for minimum dots on a die side
int die1;
int die2;
int sum;
//Prompt User of the game
cout << "Game of Craps" << endl
<< "Start with $10 and select a bet amount" << endl
<< "Win = Get your bet back plus double your bet!" << endl
<< "Lose = Lose your bet!" << endl;
//Set Random Number seed and put in a while loop so that program runs 5 times
while(round < 5){
//Obtain Each First roll number at the beginning of each round
unsigned seed = time(0);
srand(seed);
die1 = (rand() % (MAX - MIN + 1)) + 1;
die2 = (rand() % (MAX - MIN + 1)) + 1;
sum = die1 + die2;
//Get User's Bet choice
cout << "Choose your bet amount:" << endl
<< "1. $2" << endl
<< "2. $5" << endl
<< "3. $10" << endl;
//User Selects Bet
cin >> choice;
cin.ignore(1,'\n'); // Allows user to press enter, and enter not be stored in keyboard for next cin.get() call.
//Input Validation to make sure they chose a correct bet number, allows user to reinput bet choice
while(choice < 1 || choice > 3){
cout << "Please enter a valid option for betting amounts:" << endl;
cin >> choice;
cin.ignore(1,'\n');
}
//Check choice variable for User bet choice and proceed to appropriate case
switch(choice){
case 1: cout << "Press Enter to roll the dice!" << endl;
// User may press enter to output each roll
cin.get(initalRoll);
//Assigns the point to sum, so the program may compare the point to future re-rolls
point = sum;
cout << sum << endl;
//Checks if user wins on first roll
if(sum == 7 || sum == 11){
cout << "You rolled Lucky " << sum << "! You Win!!" << endl << endl;
total = total + 4;
cout << "Your total now is: $" << total << endl;
}
//Checks if USer loses on first roll
else if(sum == 2 || sum == 12){
cout << "Bad Luck, you rolled " << sum << " on your first roll! You lose!" << endl << endl;
total = total - 2;
cout << "Your total now is: $ " << total << endl;
}
else{
//Sends point to output, so user know which reroll may score
cout << "Your point is: " << point << endl;
//Re-roll and check if you get point
cout << "Press Enter to Re-roll." << endl;;
cin.get(reRoll);
die1 = rand()%(6 - 1) + 1;
die2 = rand()%(6 - 1) + 1;
sum = die1 + die2;
// Check to see if reroll sum is point, then win
if(sum == point){
cout << "You rolled " << point << ", which is" << endl
<< "Your point. You Win!" << endl << endl;
total = total + 4;
cout << "Your total is now: $" << total << endl;
}
//Check if reroll sum is 7, then lose
else if(sum == 7){
cout << "Bad Luck, you rolled " << sum << endl
<< "on your point roll. You lose!" << endl << endl;
total = total - 2;
cout << "Your Total is now: $" << total << endl;
}
else{
//Do-while loop b/c it must roll again b/c current roll is not win point or lose point
do{
cout << "You rolled: " << sum << endl;
cout << "Press Enter to Re-roll." << endl;;
cin.get(reRoll);
die1 = rand()%(6 - 1) + 1;
die2 = rand()%(6 - 1) + 1;
sum = die1 + die2;
}
//Want loop to run while the roll is neither the win point nor the lose point, then move on
while(sum != point && sum != 7);
//Check roll to see if not lose point, then win, b/c you took out all other possibilities with previous loop
if (sum != 7){
cout << "You rolled " << point << ", which is" << endl
<< "Your point. You Win!" << endl << endl;
total = total + 4;
cout << "Your total is now: $" << total << endl;
}
//Anything else is 7, which loses.
else{
cout << "Bad Luck, you rolled " << sum << endl
<< "on your point roll. You lose!" << endl << endl;
total = total - 2;
cout << "Your Total is now: $" << total << endl;
}
}
}
break;
case 2: cout << "Press Enter to roll the dice!" << endl;
cin.get(initalRoll);
point = sum;
cout << sum << endl;
if(sum == 7 || sum == 11){
cout << "You rolled Lucky " << sum << "! You Win!!" << endl << endl;
total = total + 10;
cout << "Your total now is: $" << total << endl;
}
else if(sum == 2 || sum == 12){
cout << "Bad Luck, you rolled " << sum << " on your first roll! You lose!" << endl << endl;
total = total - 5;
cout << "Your total now is: $ " << total << endl;
}
else{
cout << "Your point is: " << point << endl;
//Re-roll and check if you get point
cout << "Press Enter to Re-roll." << endl;;
cin.get(reRoll);
die1 = rand()%(6 - 1) + 1;
die2 = rand()%(6 - 1) + 1;
sum = die1 + die2;
// Check the point rolls to check if point then win, if 7 then love, if neither then re-roll
if(sum == point){
cout << "You rolled " << point << ", which is" << endl
<< "Your point. You Win!" << endl << endl;
total = total + 10;
cout << "Your total is now: $" << total << endl;
}
else if(sum == 7){
cout << "Bad Luck, you rolled " << sum << endl
<< "on your point roll. You lose!" << endl << endl;
total = total - 5;
cout << "Your Total is now: $" << total << endl;
}
else{
do{
cout << "You rolled: " << sum << endl;
cout << "Press Enter to Re-roll." << endl;;
cin.get(reRoll);
die1 = rand()%(6 - 1) + 1;
die2 = rand()%(6 - 1) + 1;
sum = die1 + die2;
}
while(sum != point && sum != 7);
if (sum != 7){
cout << "You rolled " << point << ", which is" << endl
<< "Your point. You Win!" << endl << endl;
total = total + 10;
cout << "Your total is now: $" << total << endl;
}
else{
cout << "Bad Luck, you rolled " << sum << endl
<< "on your point roll. You lose!" << endl << endl;
total = total - 5;
cout << "Your Total is now: $" << total << endl;
}
}
}
break;
case 3: cout << "Press Enter to roll the dice!" << endl;
cin.get(initalRoll);
point = sum;
cout << sum << endl;
if(sum == 7 || sum == 11){
cout << "You rolled Lucky " << sum << "! You Win!!" << endl << endl;
total = total + 20;
cout << "Your total now is: $" << total << endl;
}
else if(sum == 2 || sum == 12){
cout << "Bad Luck, you rolled " << sum << " on your first roll! You lose!" << endl << endl;
total = total - 10;
cout << "Your total now is: $" << total << endl;
}
else{
cout << "Your point is: " << point << endl;
//Re-roll and check if you get point
cout << "Press Enter to Re-roll." << endl;;
cin.get(reRoll);
die1 = rand()%(6 - 1) + 1;
die2 = rand()%(6 - 1) + 1;
sum = die1 + die2;
// Check the point rolls to check if point then win, if 7 then love, if neither then re-roll
if(sum == point){
cout << "You rolled " << point << ", which is" << endl
<< "Your point. You Win!" << endl << endl;
total = total + 20;
cout << "Your total is now: $" << total << endl;
}
else if(sum == 7){
cout << "Bad Luck, you rolled " << sum << endl
<< "on your point roll. You lose!" << endl << endl;
total = total - 10;
cout << "Your Total is now: $" << total << endl;
}
else{
do{
cout << "You rolled: " << sum << endl;
cout << "Press Enter to Re-roll." << endl;;
cin.get(reRoll);
die1 = rand()%(6 - 1) + 1;
die2 = rand()%(6 - 1) + 1;
sum = die1 + die2;
}
while(sum != point && sum != 7);
if (sum != 7){
cout << "You rolled " << point << ", which is" << endl
<< "Your point. You Win!" << endl << endl;
total = total + 20;
cout << "Your total is now: $" << total << endl;
}
else{
cout << "Bad Luck, you rolled " << sum << endl
<< "on your point roll. You lose!" << endl << endl;
total = total - 10;
cout << "Your Total is now: $" << total << endl;
}
}
}
break;
}
//Each iteration will show each round number to the User, so they know how much money they have going into each round.
if(round == 0)
cout << "That was round 1!" << endl << endl;
else if(round == 1)
cout << "That was round 2!" << endl << endl;
else if(round == 2)
cout << "That was round 3!" << endl << endl;
else if(round == 3)
cout << "That was round 4!" << endl << endl;
else{
cout << "That was round 5, the last round!" << endl
<< endl << "Your total earnings are: $" << total;
}
//Increment rounds so loop doesn't go infinite.
round++;
}
//Initialize Variables
//Display Outputs
//Exit stage right!
return 0;
} | true |
fc2c917faa0e3b35e44828bd1f15e2463e50c778 | C++ | cycasmi/proyectos-VS | /Sexto Semestre Graficas (Infograhie)/Travailles pratiques/DoubleW/DoubleW/main.cpp | ISO-8859-1 | 8,761 | 2.625 | 3 | [] | no_license | // Prnoms, noms et matricule des membres de l'quipe:
// - Cynthia Castillo (1878153)
#include <iostream>
#include "inf2705.h"
#pragma warning(disable:4996)
// variables pour l'utilisation des nuanceurs
//Defining ints using GLu-int with the purpouse of being more crossplatform
GLuint progBase; // le programme de nuanceurs de base
GLint locVertex = -1;
GLint locColor = -1;
GLint locmatrModel = -1;
GLint locmatrVisu = -1;
GLint locmatrProj = -1;
// matrices de du pipeline graphique
MatricePipeline matrModel;
MatricePipeline matrVisu;
MatricePipeline matrProj;
bool afficheAxes = false; // indique si on affiche les axes
GLenum modePolygone = GL_FILL; // comment afficher les polygones
#if 1
// pour un W
float p1[3] = { -4.0, 2.0, 0.0 };
float p2[3] = { -3.0, -3.0, 0.0 };
float p3[3] = { -1.0, -3.0, 0.0 };
float p4[3] = { 0.0, 0.0, 0.0 };
float p5[3] = { 1.0, -3.0, 0.0 };
float p6[3] = { 3.0, -3.0, 0.0 };
float p7[3] = { 4.0, 2.0, 0.0 };
#else
// pour une flche (Voir apprentissage supplmentaire)
float p1[3] = { -3.0, 1.0, 0.0 };
float p2[3] = { -3.0, -1.0, 0.0 };
float p3[3] = { 0.0, -1.0, 0.0 };
float p4[3] = { -0.5, -2.5, 0.0 };
float p5[3] = { 3.0, 0.0, 0.0 };
float p6[3] = { -0.5, 2.5, 0.0 };
float p7[3] = { 0.0, 1.0, 0.0 };
#endif
void chargerNuanceurs()
{
// charger le nuanceur de base
{
// crer le programme
progBase = glCreateProgram();
// attacher le nuanceur de sommets
{
GLuint nuanceurObj = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(nuanceurObj, 1, &ProgNuanceur::chainesSommetsMinimal, NULL);
glCompileShader(nuanceurObj);
glAttachShader(progBase, nuanceurObj);
ProgNuanceur::afficherLogCompile(nuanceurObj);
}
// attacher le nuanceur de fragments
{
GLuint nuanceurObj = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(nuanceurObj, 1, &ProgNuanceur::chainesFragmentsMinimal, NULL);
glCompileShader(nuanceurObj);
glAttachShader(progBase, nuanceurObj);
ProgNuanceur::afficherLogCompile(nuanceurObj);
}
// faire l'dition des liens du programme
glLinkProgram(progBase);
ProgNuanceur::afficherLogLink(progBase);
// demander la "Location" des variables
if ((locVertex = glGetAttribLocation(progBase, "Vertex")) == -1) std::cerr << "!!! pas trouv la \"Location\" de Vertex" << std::endl;
if ((locColor = glGetAttribLocation(progBase, "Color")) == -1) std::cerr << "!!! pas trouv la \"Location\" de Color" << std::endl;
if ((locmatrModel = glGetUniformLocation(progBase, "matrModel")) == -1) std::cerr << "!!! pas trouv la \"Location\" de matrModel" << std::endl;
if ((locmatrVisu = glGetUniformLocation(progBase, "matrVisu")) == -1) std::cerr << "!!! pas trouv la \"Location\" de matrVisu" << std::endl;
if ((locmatrProj = glGetUniformLocation(progBase, "matrProj")) == -1) std::cerr << "!!! pas trouv la \"Location\" de matrProj" << std::endl;
}
}
void initialiser()
{
// donner la couleur de fond
glClearColor(0.0, 0.0, 0.0, 1.0);
// activer le mlange de couleur pour bien voir les possibles plis l'affichage
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
// charger les nuanceurs
chargerNuanceurs();
glPointSize(3.0);
}
void conclure()
{
}
void FenetreTP::afficherScene()
{
glPolygonMode(GL_FRONT_AND_BACK, modePolygone);
// effacer l'ecran et le tampon de profondeur
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
#if 0
// dfinir le pipeline graphique
// VERSION OpenGL 2.1
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-12, 12, -8, 8, -10, 10); // la taille de la fentre
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
#else
// dfinir le pipeline graphique
// VERSION OpenGL 4.x
glUseProgram(progBase);
// dfinir le pipeline graphique
matrProj.Ortho(-12, 12, -8, 8, -10, 10); // la taille de la fentre
glUniformMatrix4fv(locmatrProj, 1, GL_FALSE, matrProj);
matrVisu.LoadIdentity();
glUniformMatrix4fv(locmatrVisu, 1, GL_FALSE, matrVisu);
matrModel.LoadIdentity();
glUniformMatrix4fv(locmatrModel, 1, GL_FALSE, matrModel);
// Attention: Redfinir "glTranslatef()" ici afin de ne rien changer ensuite
#define glTranslatef( X, Y, Z )
{
//matrModel.Translate((X), (Y), (Z));
glUniformMatrix4fv(locmatrModel, 1, GL_FALSE, matrModel);
}
#endif
// afficher les axes
if (afficheAxes) FenetreTP::afficherAxes();
// ...
// exemple: utiliser du rouge opaque
glColor3f(1, 0, 0);
// mieux encore: utiliser du rouge, mais avec un alpha de 0.8 plutt que 1.0 pour bien voir les possibles plis l'affichage
glColor4f(1, 0, 0, 0.8);
// la fentre varie en X de -12 12 et en Y de -8 8
glColor3f(1, 1, 1);
// modifier ...
//Divisions
glTranslatef(0.0, 0.0, 0.0);//for start drawing from the center of the canvas
glBegin(GL_LINES);
{
//Horizontal lines
glVertex3f(-12.0, 0.0, 0.0);
glVertex3f(12.0, 0.0, 0.0);
//Vertical lines
glVertex3f(-4.0, 8.0, 0.0);
glVertex3f(-4.0, -8.0, 0.0);
glVertex3f(4.0, 8.0, 0.0);
glVertex3f(4.0, -8.0, 0.0);
}
glEnd();
//Starting to draw the W's
glTranslatef(0.0, 0.0, 0.0);
glTranslatef(0.0, 4.0, 0.0);
//Pantalon vert
glColor3f(0.0, 1.0, 0.0);
glBegin(GL_TRIANGLES);
{ //Needs three coordinates to draw each triangle
glVertex3fv(p1);
glVertex3fv(p2);
glVertex3fv(p3);
glVertex3fv(p1);
glVertex3fv(p3);
glVertex3fv(p4);
glVertex3fv(p1);
glVertex3fv(p4);
glVertex3fv(p7);
glVertex3fv(p4);
glVertex3fv(p5);
glVertex3fv(p7);
glVertex3fv(p5);
glVertex3fv(p6);
glVertex3fv(p7);
}
glEnd();
//Pantalon rouge
glTranslatef(-8.0, 0.0, 0.0);
glColor3f(1.0, 0.0, 0.0);
glBegin(GL_QUADS);
{//draws four sided figures individualy for each 4 points
glVertex3fv(p1);
glVertex3fv(p2);
glVertex3fv(p3);
glVertex3fv(p4);
glVertex3fv(p1);
glVertex3fv(p4);
glVertex3fv(p7);
glVertex3fv(p1);
glVertex3fv(p4);
glVertex3fv(p5);
glVertex3fv(p6);
glVertex3fv(p7);
}
glEnd();
//Pantalon bleu
glTranslatef(16.0, 0.0, 0.0);
glColor3f(0.0, 0.0, 1.0);
glBegin(GL_QUAD_STRIP);
{//links every two points given to start forming quards
glVertex3fv(p2);
glVertex3fv(p3);//this will draw nothing because doenst forms a quad
glVertex3fv(p1);
glVertex3fv(p4);
glVertex3fv(p4);
glVertex3fv(p7);
glVertex3fv(p5);
glVertex3fv(p6);
}
glEnd();
//Pantalon jaune
glTranslatef(0.0, -8.0, 0.0);
glColor3f(1.0, 1.0, 0.0);
glBegin(GL_TRIANGLE_STRIP);
{//after a inicial triangle, each aditional point will form a triangle using the last two used
glVertex3fv(p4);
glVertex3fv(p5);
glVertex3fv(p6);
glVertex3fv(p7);
glVertex3fv(p4);
glVertex3fv(p1);
glVertex3fv(p3);
glVertex3fv(p2);
}
glEnd();
//Pantalon mauve
glTranslatef(-8.0, 0.0, 0.0);
glColor4f(1.0, 0.0, 1.0, 0.8);
glBegin(GL_POLYGON);
{
glVertex3fv(p4);
glVertex3fv(p1);
glVertex3fv(p2);
glVertex3fv(p3);
glVertex3fv(p4);
glVertex3fv(p5);
glVertex3fv(p6);
glVertex3fv(p7);
glVertex3fv(p7);
glVertex3fv(p1);
glVertex3fv(p2);
glVertex3fv(p4);
}
glEnd();
glTranslatef(-8.0, 0.0, 0.0);
//Pantalon cyan
glColor3f(0.0, 1.0, 1.0);
glBegin(GL_TRIANGLE_FAN);
{
glVertex3fv(p4);
glVertex3fv(p5);
glVertex3fv(p6);
glVertex3fv(p7);
glVertex3fv(p1);
glVertex3fv(p2);
glVertex3fv(p3);
}
glEnd();
}
void FenetreTP::redimensionner(GLsizei w, GLsizei h)
{
glViewport(0, 0, w, h);
}
void FenetreTP::clavier(TP_touche touche)
{
switch (touche)
{
case TP_ECHAP:
case TP_q: // Quitter l'application
quit();
break;
case TP_x: // Activer/dsactiver l'affichage des axes
afficheAxes = !afficheAxes;
std::cout << "// Affichage des axes ? " << (afficheAxes ? "OUI" : "NON") << std::endl;
break;
case TP_v: // Recharger les fichiers des nuanceurs et recrer le programme
chargerNuanceurs();
std::cout << "// Recharger nuanceurs" << std::endl;
break;
case TP_g: // Permuter l'affichage en fil de fer ou plein
modePolygone = (modePolygone == GL_FILL) ? GL_LINE : GL_FILL;
break;
default:
std::cout << " touche inconnue : " << (char)touche << std::endl;
imprimerTouches();
break;
}
}
void FenetreTP::sourisClic(int button, int state, int x, int y)
{
}
void FenetreTP::sourisWheel(int x, int y)
{
}
void FenetreTP::sourisMouvement(int x, int y)
{
}
int main(int argc, char *argv[])
{
// crer une fentre
FenetreTP fenetre("INF2705 TP0");
// allouer des ressources et dfinir le contexte OpenGL
initialiser();
bool boucler = true;
while (boucler)
{
// affichage
fenetre.afficherScene();
fenetre.swap();
// rcuprer les vnements et appeler la fonction de rappel
boucler = fenetre.gererEvenement();
}
// dtruire les ressources OpenGL alloues
conclure();
return 0;
} | true |
a7e7b3144ecf62d0aca3e57d49dac56247e44bd4 | C++ | ibradam/voronoi | /include/voronoi/point.hpp | UTF-8 | 7,384 | 2.6875 | 3 | [] | no_license | /**********************************************************************
* PACKAGE : geometrix
* COPYRIGHT: (C) 2015, Bernard Mourrain, Inria
**********************************************************************/
#pragma once
#ifndef POINT_HPP
#define POINT_HPP
#include <cmath>
#define TMPL template<class C, int N>
#define SELF point<C,N>
#define Viewer viewer<axel,W>
#define Ostream std::ostream
#undef Scalar
//====================================================================
namespace mmx {
//--------------------------------------------------------------------
template<class C, int N= 3>
class point
{
public:
typedef C Scalar;
point(void) ;
point(Scalar x, Scalar y=0, Scalar z= 0) ;
point(const SELF & p) ;
inline Scalar x(void) const { return m_coord[0] ; }
inline Scalar& x(void) { return m_coord[0] ; }
inline Scalar y(void) const { if (N>1) return m_coord[1] ; else return 0; }
inline Scalar& y(void) { if (N>1) return m_coord[1] ; else return *new Scalar(0); }
inline Scalar z(void) const { if (N>2) return m_coord[2] ; else return 0; }
inline Scalar& z(void) { if (N>2) return m_coord[2] ; else return *new Scalar(0); }
Scalar operator [] (const int & i) const { return m_coord[i] ; }
Scalar & operator [] (const int & i) { return m_coord[i] ; }
Scalar at (const int & i) const { return m_coord[i] ; }
Scalar & at (const int & i) { return m_coord[i] ; }
inline void setx(Scalar x) { this->m_coord[0] = x ; }
inline void sety(Scalar y) { if (N>1) this->m_coord[1] = y ; }
inline void setz(Scalar z) { if (N>2) this->m_coord[2] = z ; }
bool operator == (const point & other) const ;
bool operator != (const point & other) const ;
bool operator < (const point & other) const ;
SELF & operator = (const point & other) ;
// Linear Algebra operations
point operator+(const point &v)const; //Addition
point operator-(const point &v)const; //Substraction
point operator*(const Scalar&k)const; //Multiplication by Scalar
//Division by Scalar
point operator/(const Scalar&k)const { return *this*( Scalar(1)/k); }; //Division by Scalar
point operator*(const point &v)const; //Coordinate-wise Product
point& operator+=(const point &v) //Addition
{ for(unsigned i=0;i<N;i++) this->at(i)+=v.at(i); return *this; }
point& operator-=(const point &v) //Substraction
{ for(unsigned i=0;i<N;i++) this->at(i)-=v.at(i); return *this; }
point& operator*=(const Scalar&k) //Multiplication by Scalar
{ for(unsigned i=0;i<N;i++) this->at(i)*=k; return *this; }
point& operator/=(const Scalar&k) //Division by Scalar
{ for(unsigned i=0;i<N;i++) this->at(i)/=k; return *this; }
point operator*=(const point &v)const //Coordinate-wise Product
{ for(unsigned i=0;i<N;i++) this->at(i)*=v.at(i); return *this; }
point operator-()const; //Negative of a point
point cross(const point &v) const; //Cross Product
Scalar dot(point v2)const; //Dot Product
Scalar dist2(point v2)const; //Distance Product
Scalar norm() const; //L2 Norm
private:
Scalar m_coord[N] ;
//Scalar m_coord[1] ;
//Scalar m_coord[2] ;
};
TMPL
SELF::point(void)
{
for(unsigned i=0;i<N;i++) this->m_coord[i] = (Scalar)0 ;
//this->m_coord[1] = (Scalar)0 ;
//this->m_coord[2] = (Scalar)0 ;
}
TMPL
SELF::point(Scalar x, Scalar y, Scalar z)
{
this->m_coord[0] = x ;
this->m_coord[1] = y ;
this->m_coord[2] = z ;
}
TMPL
SELF::point(const SELF & other)
{
for(unsigned i=0;i<N;i++)
this->m_coord[i] = other[i] ;
}
TMPL
SELF & SELF::operator = (const SELF & other)
{
if(this == &other)
return *this ;
for(unsigned i=0;i<N;i++)
this->m_coord[i] = other[i] ;
return * this ;
}
TMPL bool
SELF::operator == (const SELF & other) const {
bool res = true;
for(unsigned i=0;i<N && res; i++)
res = (m_coord[i]==other[i]);
return res;
}
TMPL bool
SELF::operator != (const SELF & other) const {
return !((*this)==other);
}
TMPL bool
SELF::operator < (const SELF & other) const {
return ((this->x() < other.x())
|| ((this->x() == other.x()) && (this->y() < other.y()))
|| ((this->x() == other.x()) && (this->y() == other.y()) && (this->z() < other.z()))) ;
}
TMPL
SELF SELF::operator +(const SELF &v)const //Addition
{
SELF res;
for(unsigned i=0;i<N;i++ )
res[i] = m_coord[i] + v[i];
return res;
}
TMPL
SELF SELF::operator -(const SELF &v)const //Subtraction
{
SELF res;
for(unsigned i=0;i<N;i++ )
res[i] = m_coord[i] - v[i];
return res;
}
TMPL
SELF SELF::operator *(const Scalar &k)const //Multiplication By Scalar
{
SELF res;
for(unsigned i=0;i<N;i++ )
res[i] = m_coord[i] *k;
return res;
}
TMPL
SELF operator *(typename SELF::Scalar k,const SELF &v) //Left multiplication By Scalar
{
return v * k;
}
TMPL
SELF SELF::operator -()const //Negative Of a point
{
SELF res;
for(unsigned i=0;i<N;i++ )
res[i] = -m_coord[i];
return res;
}
TMPL
SELF SELF::operator *(const SELF &v)const // Coordinate-wise Product
{
SELF res;
for(unsigned i=0;i<N;i++ )
res[i] = m_coord[i] * v[i];
return res;
}
TMPL
SELF SELF::cross(const SELF &v)const //Cross Product
{
SELF res;
res.x() = (this->y() * v.z()) - (this->z() * v.y());
res.y() = (this->z() * v.x()) - (this->x() * v.z());
res.z() = (this->x() * v.y()) - (this->y() * v.x());
return res;
}
TMPL
SELF cross(const SELF v1, const SELF v2) //Cross Product of 2 points
{
return v1.cross(v2);
}
TMPL
typename SELF::Scalar SELF::dot(const SELF v2) const //Dot product
{
Scalar res=0;
for(unsigned i=0;i<N;i++) res += m_coord[i] * v2[i];
return res;
}
TMPL
typename SELF::Scalar SELF::dist2(const SELF v2) const //Dot product
{
Scalar res=0;
for(unsigned i=0;i<N;i++) res+=(m_coord[i] - v2[i])*(m_coord[i] - v2[i]);
return res;
}
TMPL
typename SELF::Scalar dot(const SELF v1, const SELF v2) //Dot product of 2 points
{
return v1.dot(v2);
}
TMPL
typename SELF::Scalar SELF::norm() const //Norm
{
return std::sqrt( this->dot(*this) );
}
TMPL inline typename SELF::Scalar read (const SELF& v, unsigned i) {
return v[i];
}
TMPL inline typename SELF::Scalar distance (const SELF& p1, const SELF& p2) {
return std::sqrt(p1.dist2(p2));
}
//--------------------------------------------------------------------
TMPL Ostream&
operator<<(Ostream& os, const SELF& p) {
os <<(char *)"[";
for(unsigned i=0;i<N;i++){
if(i>0) os <<(char *)" ";
os <<p[i];
}
os <<(char *)"]";
return os;
}
//--------------------------------------------------------------------
template<class VIEWER, class C, class V, int N>
VIEWER&
operator<<(VIEWER& os, const SELF& p) {
os<<"<point color=\""<<(int)(255*os.color.r)<<" "<<(int)(255*os.color.g)<<" "<<(int)(255*os.color.b)<<"\">"
<<p.x()<<" "<<p.y()<<" "<<p.z()
<<"</point>\n";
return os;
}
//--------------------------------------------------------------------
} /* namespace mmx */
//====================================================================
#undef TMPL
#undef SELF
#undef Scalar
#undef Viewer
#undef Ostream
#endif
| true |
8e6606f60077b628ab88d34b2347005a8a53dba0 | C++ | olihewi/NetScape | /src/MouseTracker.cpp | UTF-8 | 2,355 | 2.65625 | 3 | [] | no_license | //
// Created by hewis on 15/04/2021.
//
#include "ASGEGameLib/Utilities/MouseTracker.h"
MouseTracker::MouseTracker(ASGE::Input* _input) :
input(_input),
click_callback_id(input->addCallbackFnc(ASGE::E_MOUSE_CLICK, &MouseTracker::mouseInput, this)),
move_callback_id(input->addCallbackFnc(ASGE::E_MOUSE_MOVE, &MouseTracker::mouseInput, this)),
scroll_callback_id(input->addCallbackFnc(ASGE::E_MOUSE_SCROLL, &MouseTracker::mouseInput, this))
{
}
MouseTracker::~MouseTracker()
{
input->unregisterCallback(static_cast<unsigned int>(click_callback_id));
input->unregisterCallback(static_cast<unsigned int>(move_callback_id));
input->unregisterCallback(static_cast<unsigned int>(scroll_callback_id));
}
void MouseTracker::mouseInput(ASGE::SharedEventData data)
{
queue.emplace_back(data);
}
void MouseTracker::updateInput()
{
old_mouse_pos = new_mouse_pos;
old_click_state = new_click_state;
scroll_state = ASGE::Point2D();
for (auto& data : queue)
{
const auto* mouse = dynamic_cast<const ASGE::MoveEvent*>(data.get());
if (mouse != nullptr)
{
new_mouse_pos =
ASGE::Point2D(static_cast<float>(mouse->xpos), static_cast<float>(mouse->ypos));
continue;
}
const auto* click = dynamic_cast<const ASGE::ClickEvent*>(data.get());
if (click != nullptr)
{
if (click->action != ASGE::KEYS::KEY_REPEATED)
{
new_click_state[click->button] = click->action == ASGE::KEYS::KEY_PRESSED;
}
continue;
}
const auto* scroll = dynamic_cast<const ASGE::ScrollEvent*>(data.get());
if (scroll != nullptr)
{
scroll_state =
ASGE::Point2D(static_cast<float>(scroll->xoffset), static_cast<float>(scroll->yoffset));
continue;
}
}
queue.clear();
}
bool MouseTracker::getButton(int _index)
{
return new_click_state[_index];
}
bool MouseTracker::getButtonDown(int _index)
{
return new_click_state[_index] && !old_click_state[_index];
}
bool MouseTracker::getButtonUp(int _index)
{
return !new_click_state[_index] && old_click_state[_index];
}
ASGE::Point2D MouseTracker::getMousePos()
{
return new_mouse_pos;
}
ASGE::Point2D MouseTracker::getMouseDelta() const
{
return ASGE::Point2D(new_mouse_pos.x - old_mouse_pos.x, new_mouse_pos.y - old_mouse_pos.y);
}
ASGE::Point2D MouseTracker::getScroll()
{
return scroll_state;
}
| true |
1d5399e6328f545a9a257e6cbf8515dc1766dcdd | C++ | wdeyes/Note_c_jiajia | /PinDuoDuo/no3.cpp | UTF-8 | 2,894 | 3.1875 | 3 | [] | no_license | // n长度的数字,满足递增数列,求和为s的数列有多少种。
// n=3 s=10 输出4种,说明:有127,136,145,235。
// n=4,s=18,输出15种
#include<iostream>
#include <vector>
#include <cmath>
using namespace std;
// 参考 https://blog.csdn.net/h2453532874/article/details/99250644
// 动态规划
// 递推关系和放苹果问题类似
// dp[n][s]分为两种情况,第一位是1和第一位不是1的,
// 是1的:全部拿走1,情况种类和n-1位和为s-n的一样;
// 不是1的:全部拿走1,情况种类和n位,和为s-n的一样;
// dp[n][s] = dp[n-1][s-n] + dp[n][s-n]
int main(int argc, char const *argv[])
{
int n;
while(cin>>n){
int s;
cin >> s;
vector< vector<int> > dp(n+1, vector<int> (s+1));
//初始化
for(int i=1; i<=s; ++i)
dp[1][i]=1;
for(int i=2; i<=n; ++i){
//和的最小值
int s_min=(1+i)*i/2;
for(int j=s_min; j<=s; ++j){
dp[i][j]=dp[i-1][j-i]+dp[i][j-i];
}
}
cout << dp[n][s] << endl;
}
return 0;
}
// //自己考虑的动态规划,有问题,失败,no3_1.cpp改用递归
// int main(){
// int n;
// while(cin >> n){
// int s;
// cin >> s;
// //dp[i][j]表示i位,和为j,有多少种
// vector< vector<int> > dp(n+1, vector<int> (s+1));
// //dp初始化
// for(int i=1; i<=s; ++i)
// dp[1][i]=1;
// for(int i=2; i<=n; ++i){
// //构成i位数字的最小 s 为 s_min
// int s_min = (1+i)*i/2;
// for(int j=s_min; j<=s; ++j){
// //分析:n位递增数列,去掉最后一位就是n-1位的递增数列,且它们和的差为最后一位的这个数
// // dp[i][j]表示i位,和为j有多少种
// //递推关系为:dp[i][j]=dp[i-1][k1]+dp[i-1][k2]+...+dp[i-1][k_up]
// //比如:dp[3][10]=dp[2][3]+dp[2][4]+dp[2][5]
// // 下限3就是构成2位的最小和,所以i-1位的最小和为(1+i-1)*(i-1)/2;
// // 上限5,dp[2][6]不满足,数列24,对应244不满足递增,数列15(对应154)更不满足。
// // i-1位和为k,则第i位是j-k, 递增需要k/2+1<j-k,这里有问题
// int down = (i-1)*i/2;
// double up = 2.0*(j-1)/3.0;
// int k=down;
// do {
// dp[i][j] += dp[i-1][k];
// ++k;
// }
// while(k<up);
// }
// }
// for(auto &nums : dp){
// for(auto &val:nums)
// cout << val << " ";
// cout << endl;
// }
// cout << dp[n][s] << endl;
// }
// return 0;
// } | true |
e74ab217bd8bd8cbf7110fc5769e234d7cc1526f | C++ | sakib-personal/practiced-codes-in-data-structure | /FINAL/list_tree.h | UTF-8 | 2,095 | 3.75 | 4 | [] | no_license | #include<iostream>
using namespace std;
//template<class T>
struct node{
int item;
node* left;
node* right;
node(int item){
this->item = item;
this->left = NULL;
this->right = NULL;
}
};
class list{
node* root;
int count;
public:
list(){
root = NULL;
count = 0;
}
void insert(int item){
node* n = new node(item);
if(root==NULL){
root = n;
}
else{
node* tmp = root;
while(item){
if(tmp->item > item){
if(tmp->left == NULL){
tmp->left = n;
break;
}
else{
tmp = tmp->left;
}
}
else{
if(tmp->right == NULL){
tmp->right = n;
break;
}
else{
tmp = tmp->right;
}
}
}
}
count++;
}
bool search(int item){
node* search = root;
if(search->item == item){
return true;
}
else if(search->item != item){
while(item){
if(search->item > item){
if(search->left->item == item){
return true;
}
else{
search = search->left;
}
}
else if(search->item < item){
if(search->right->item == item){
return true;
}
else{
search = search->right;
}
}
else{
return false;
}
}
}
}
int size(){
return count;
}
};
| true |
40baf9430c9a1850cf149f61e7ab6869c759a4a6 | C++ | sfb901c1/TEA | /peer/trusted/structs/aad_tuple.h | UTF-8 | 2,344 | 3.03125 | 3 | [] | no_license | /**
* Author: Alexander S.
*/
#ifndef AAD_TUPLE_H
#define AAD_TUPLE_H
#include <utility>
#include "../../../include/config.h"
#include "../overlay_structure_scheme.h"
#include "../../../include/serialization.h"
#include "../../../include/message_structs.h"
namespace c1::peer {
/**
* Structure used to store the additional authenticated data (sent via an untrusted path)
*/
struct AadTuple : public Serializable {
PeerInformation sender;
PeerInformation receiver;
round_t round;
std::vector<OverlayStructureSchemeMessage> p_structure;
AadTuple(PeerInformation sender,
PeerInformation receiver,
round_t round,
std::vector<OverlayStructureSchemeMessage> p_structure)
: sender(std::move(sender)), receiver(std::move(receiver)), round(round), p_structure(std::move(p_structure)) {}
void serialize(std::vector<uint8_t> &working_vec) const override {
//std::vector<uint8_t> aad;
sender.serialize(working_vec);
receiver.serialize(working_vec);
serialize_number(working_vec, round);
serialize_vec(working_vec, p_structure);
}
size_t estimate_size() const override {
return sender.estimate_size() + receiver.estimate_size() + sizeof(round) + estimate_vec_size(p_structure);
}
static AadTuple deserialize(const std::vector<uint8_t> &working_vec, size_t &cur) {
auto sender = PeerInformation::deserialize(working_vec, cur);
auto receiver = PeerInformation::deserialize(working_vec, cur);
auto round = deserialize_number<round_t>(working_vec, cur);
auto structure_msg = deserialize_vec<OverlayStructureSchemeMessage>(working_vec, cur);
return AadTuple{sender, receiver, round, structure_msg};
}
bool operator==(const AadTuple &rhs) const {
return std::tie(sender, receiver, round, p_structure)
== std::tie(rhs.sender, rhs.receiver, rhs.round, rhs.p_structure);
}
bool operator!=(const AadTuple &rhs) const {
return !(rhs == *this);
}
inline operator std::string() const {
std::string result = "Aad_Tuple: ";
result += "Sender: " + std::string(sender) + ", ";
result += "Receiver: " + std::string(receiver) + ", ";
result += "Round: " + std::to_string(round) + ", ";
result += "p_structure.size(): " + std::to_string(p_structure.size()) + "\n";
return result;
}
};
}
#endif //AAD_TUPLE_H
| true |
24c27b0c80bfac792e9c3377c9c45452e6aaf755 | C++ | PavelMolchan/cpp | /dz25.1/dz25.1/dz25.1.cpp | UTF-8 | 1,498 | 3.78125 | 4 | [] | no_license | #include <iostream>
using namespace std;
class Complex
{
public:
Complex()
{
real = 0;
imag = 0;
}
Complex(int _real, int _imag) :real(_real), imag(_imag){}
Complex(const Complex& num2)
{
real = num2.real;
imag = num2.imag;
}
void Print()
{
cout << real;
if (imag > 0)
cout << "+i" << imag << endl;
else if (imag < 0)
cout << "-i" << -1 * imag << endl;
else
cout << endl;
}
Complex operator= (const Complex& num2)
{
if (this == &num2){
return *this;
}
else
{
real = num2.real;
imag = num2.imag;
return *this;
}
}
Complex operator+(const Complex& num2)
{
Complex Res;
Res.real = real + num2.real;
Res.imag = imag + num2.imag;
return Res;
}
Complex operator-(const Complex& num2)
{
Complex Res;
Res.real = real - num2.real;
Res.imag = imag - num2.imag;
return Res;
}
Complex operator*(const Complex& num2)
{
Complex Res;
Res.real = real*num2.real - imag*num2.imag;
Res.imag = imag*num2.real + real*num2.imag;
return Res;
}
Complex operator/(const Complex& num2)
{
Complex Res;
Res.real = (real*num2.real + imag*num2.imag) / (num2.real*num2.real + num2.imag*num2.imag);
Res.imag = (real*num2.real - imag*num2.imag) / (num2.real*num2.real + num2.imag*num2.imag);
return Res;
}
private:
float real;
float imag;
};
int main()
{
Complex A(3, 6);
A.Print();
Complex B(5, 4);
B.Print();
Complex C;
C = A + B;
C.Print();
C = C - B;
C.Print();
C = A*B;
C.Print();
C = A / B;
C.Print();
} | true |
63ded4320c01e8e7f7db898428908b8d79df43e7 | C++ | guijiangheng/pro-tbb | /src/main.cpp | UTF-8 | 3,196 | 2.890625 | 3 | [] | no_license | #include <iostream>
#include <tbb/tbb.h>
#include <pstl/algorithm>
#include <pstl/execution>
#include <protbb/fractal.h>
using namespace protbb;
using ImagePtr = std::shared_ptr<Image>;
ImagePtr applyGamma(const ImagePtr& image, double gamma) {
auto width = image->width;
auto height = image->height;
auto outImage = std::make_shared<Image>(image->name + "_gamma", width, height);
tbb::parallel_for(0, height, [&image, &outImage, width, height, gamma](int i) {
auto begSrc = &image->data[0] + width * i;
auto begDest = &outImage->data[0] + width * i;
std::transform(pstl::execution::unseq, begSrc, begSrc + width, begDest, [gamma](const Image::Pixel& p) {
auto v = 0.3 * p.bgra[2] + 0.59 * p.bgra[1] + 0.11 * p.bgra[0];
auto res = std::pow(v, gamma);
return Image::Pixel(res, res, res);
});
});
return outImage;
}
ImagePtr applyTint(const ImagePtr& image, const double *tints) {
auto width = image->width;
auto height = image->height;
auto outImage = std::make_shared<Image>(image->name + "_tinted", width, height);
tbb::parallel_for(0, height, [&image, &outImage, width, height, tints](int i) {
auto begSrc = &image->data[0] + width * i;
auto begDest = &outImage->data[0] + width * i;
std::transform(pstl::execution::unseq, begSrc, begSrc + width, begDest, [tints](const Image::Pixel& p) {
auto b = (std::uint8_t)(p.bgra[0] + (255 - p.bgra[0]) * tints[0]);
auto g = (std::uint8_t)(p.bgra[1] + (255 - p.bgra[1]) * tints[1]);
auto r = (std::uint8_t)(p.bgra[2] + (255 - p.bgra[2]) * tints[2]);
return Image::Pixel(b, g, r);
});
});
return outImage;
}
void writeImage(const ImagePtr& image) {
image->write((image->name + ".bmp").c_str());
}
void fig_1_7(const std::vector<ImagePtr>& images) {
const double tints[] = { 0.75, 0, 0 };
for (auto& image : images) {
writeImage(applyTint(applyGamma(image, 1.4), tints));
}
}
void fig_1_10(const std::vector<ImagePtr>& images) {
const double tints[] = { 0.75, 0, 0 };
int i = 0;
tbb::flow::graph g;
tbb::flow::source_node<ImagePtr> src(g, [&i, &images](ImagePtr& out) {
if (i < images.size()) {
out = images[i++];
return true;
}
return false;
}, false);
tbb::flow::function_node<ImagePtr, ImagePtr> gamma(g,
tbb::flow::unlimited,
[](const ImagePtr& img) -> ImagePtr {
return applyGamma(img, 1.4);
}
);
tbb::flow::function_node<ImagePtr, ImagePtr> tint(g,
tbb::flow::unlimited,
[tints](const ImagePtr& img) -> ImagePtr {
return applyTint(img, tints);
}
);
tbb::flow::function_node<ImagePtr> write(g,
tbb::flow::unlimited,
[](const ImagePtr& img) {
writeImage(img);
}
);
tbb::flow::make_edge(src, gamma);
tbb::flow::make_edge(gamma, tint);
tbb::flow::make_edge(tint, write);
src.activate();
g.wait_for_all();
}
int main() {
std::vector<ImagePtr> images;
for (auto i = 2000; i < 20000000; i *= 10)
images.push_back(makeFractalImage(800, 800, i));
auto now = tbb::tick_count::now();
fig_1_10(images);
std::cout << "Time: " << (tbb::tick_count::now() - now).seconds() << " seconds" << std::endl;
return 0;
}
| true |
f72060aede67f4d6e0db07d788236e60dd743f8d | C++ | shubhampathak09/codejam | /30 days training for beginners/Problem_Bank_adhoc/topoder-trying to underatand bs.cpp | UTF-8 | 1,034 | 2.859375 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
//
//
//int solve(int low,int high,int a[],int k)
//{
// int n=sizeof(a)/sizeof(a[0]);
//
// int sum=0;
//
// int count=0;
//
// for(int i=0;i<n;i++)
// sum+=a[i];
// // 450
// while(low<high)
// {
//
// int mid=(low+high)/2; //225
//
//
//
// if(mid>sum)
// {
// high=mid-1; //450
// count++;
// }
// else if(mid<sum)
// {
// low=mid+1;
// count++;
// }
//
// if(count==k)
// return mid;
// }
//
// return -1;
//}
//
//int main()
//{
//
// int a[]={10,20,30,40,50,60,70,80,90};
//
// int n=sizeof(a)/sizeof(a[0]);
//
// int high=450;
//
// int low=1;
//
// int k=3;
//
//cout<<solve(low,high,a,k);
//
//}
//
//
int solve(int a[],int low,int high,int k)
{
int low=1;
int high=INT_MAX;
int max_capacity=450 // k=1
// 10 20 30 40 50 60 70 80 90
while(low<=high)
{
int mid=(low+high)/2;
if(mid>max_capacity)
continue
else if(mid<max_capacity)
{
max_capacity=mid;
k--;
}
}
}
| true |
411161f6ad54a3db3c5be93f4ce57427b60fa594 | C++ | the-paulus/old-skool-code | /C++/E19-1.cpp | UTF-8 | 1,499 | 3.703125 | 4 | [] | no_license | //Paul Lyon
//Exercise 19-1
//E19-1.cpp
// compiler directives
#include<iostream.h>
#include<fstream.h>
#define PRINT_IT ofstream prn("PRN")
PRINT_IT;
// function prototypes
void selection_sort(int input_array[], int input_size);
void display_array(int input_array[], int input_size);
int main()
{
//int nums[5] = {20, 31, 17, 47, 14};
int nums[5] = { 0, -31, 19, 104, 19};
int nums_length = 5;
cout << "Unsorted Array:\n";
prn << "Unsorted Array:\n";
display_array(nums, nums_length);
selection_sort(nums, nums_length);
cout << "Sorted Array:\n";
prn << "Sorted Array:\n";
display_array(nums, nums_length);
return 0;
}
// Selection sort procedure. Sorts an array of ints in descending order.
void selection_sort(int input_array[], int input_size)
{
int i, j;
int small, temp;
for (i = input_size - 1; i > 0; i--)
{
small = 0; // Initialize small to first element.
// Find the smallest element between the positions 1 and i.
for (j = 1; j <= i; j++)
{
if (input_array[j] < input_array[small])
{
small = j;
}
}
// Swap the smallest element found with element in position i.
temp = input_array[small];
input_array[small] = input_array[i];
input_array[i] = temp;
}
}
// Function that simply displays each element of input_array.
void display_array(int input_array[], int input_size)
{
int i;
for (i = 0; i < input_size; i++)
{
cout << input_array[i] << ' ';
prn << input_array[i] << ' ';
}
cout << "\n\n";
prn << "\n\n";
}
| true |
9def6a01abef1fa28faaac78b4dbc6c45c391ce6 | C++ | marvins/MapServerConnector | /src/apps/msc-viewer/gui/AddServiceWidget.cpp | UTF-8 | 5,216 | 2.78125 | 3 | [] | no_license | /**
* @file AddServiceWidget.cpp
* @author Marvin Smith
* @date 3/16/2016
*/
#include "AddServiceWidget.hpp"
/*********************************/
/* Constructor */
/*********************************/
AddServiceWidget::AddServiceWidget( Options::ptr_t options,
QWidget* parent )
: QWidget(parent),
m_options(options)
{
// Create the main layout
m_main_layout = new QVBoxLayout();
m_main_layout->setAlignment(Qt::AlignTop);
// Create the Title Widget
Build_Title_Widget();
// Create the selector widget
Build_Selector_Widget();
// Set the Layout
setLayout(m_main_layout);
}
/****************************************************/
/* Change the Current Method Widget */
/****************************************************/
void AddServiceWidget::Change_Current_Method_Widget( const int& method_id )
{
// Set the Selector
m_stack_widget->setCurrentIndex(method_id);
}
/****************************************/
/* Build the Title Widget */
/****************************************/
void AddServiceWidget::Build_Title_Widget()
{
// Create title widget
m_title_widget = new QWidget(this);
// Create title widget layout
m_title_layout = new QHBoxLayout();
m_title_layout->setAlignment( Qt::AlignLeft );
// Create the label
m_title_label = new QLabel("Add Map Service", m_title_widget );
m_title_layout->addWidget(m_title_label);
// Add to title widget
m_title_widget->setLayout(m_title_layout);
// Add to main layout
m_main_layout->addWidget(m_title_widget);
}
/**********************************************/
/* Build the Selector Widget */
/**********************************************/
void AddServiceWidget::Build_Selector_Widget()
{
// Create the Main Widget
m_selector_widget = new QWidget(this);
// Create the layout
m_selector_layout = new QHBoxLayout();
m_selector_layout->setAlignment(Qt::AlignLeft);
// Set the label
m_selector_label = new QLabel("Method", m_selector_widget );
m_selector_layout->addWidget(m_selector_label);
// Set the Combo
m_selector_combo = new QComboBox( m_selector_widget );
m_selector_combo->addItem("Import Service File");
m_selector_combo->addItem("Define Service Parameters");
m_selector_layout->addWidget(m_selector_combo);
connect( m_selector_combo, SIGNAL(currentIndexChanged(int)),
this, SLOT(Change_Current_Method_Widget(const int&)));
// Set the layout
m_selector_widget->setLayout(m_selector_layout);
// Add to main widget
m_main_layout->addWidget(m_selector_widget);
// Create the Stack Widget
m_stack_widget = new QStackedWidget();
// Build the Import Widget
Build_Import_Widget();
// Add the Define Widget
m_define_widget = new QWidget();
m_define_layout = new QVBoxLayout();
m_define_title_widget = new QWidget(m_define_widget);
m_define_title_layout = new QHBoxLayout();
m_define_title_widget->setLayout(m_define_title_layout);
m_define_title_label = new QLabel("Define Map Service Parameters");
m_define_title_layout->addWidget(m_define_title_label);
m_define_layout->addWidget(m_define_title_widget);
m_define_widget->setLayout(m_define_layout);
m_stack_widget->addWidget(m_define_widget);
// add to main layout
m_main_layout->addWidget( m_stack_widget );
}
/*********************************************/
/* Build the Import Widget */
/*********************************************/
void AddServiceWidget::Build_Import_Widget()
{
// Add the Import Widget
m_import_widget = new QWidget();
// Add the Import Layout
m_import_layout = new QVBoxLayout();
m_import_layout->setAlignment( Qt::AlignTop );
// Create the title widget
m_import_title_widget = new QWidget(m_import_widget);
m_import_title_layout = new QHBoxLayout();
m_import_title_layout->setAlignment(Qt::AlignLeft);
m_import_title_widget->setLayout(m_import_title_layout);
m_import_layout->addWidget(m_import_title_widget);
m_import_title_label = new QLabel("Import Map Service File.");
m_import_title_layout->addWidget(m_import_title_label);
// Create the Path Widget
QWidget* import_path_widget = new QWidget(m_import_widget);
QHBoxLayout* import_path_layout = new QHBoxLayout();
import_path_layout->setAlignment(Qt::AlignLeft);
QLabel* import_path_label = new QLabel("Path", import_path_widget);
import_path_layout->addWidget(import_path_label);
QLineEdit* import_path_edit = new QLineEdit(import_path_widget);
import_path_layout->addWidget(import_path_edit);
QPushButton* import_path_button = new QPushButton("Select", import_path_widget);
import_path_layout->addWidget(import_path_button);
import_path_widget->setLayout(import_path_layout);
m_import_layout->addWidget(import_path_widget);
// Set the Main Layout
m_import_widget->setLayout(m_import_layout);
// Add to the Stack Widget
m_stack_widget->addWidget(m_import_widget);
}
| true |
ee011da2b3d7b9e6b14da39654acbf4578c44ff5 | C++ | etip00123/ETIPproject | /Share/seeds/rbd.cpp | UTF-8 | 8,222 | 3.0625 | 3 | [] | no_license | pragma solidity ^0.4.21;
contract IMigrationContract {
function migrate(address addr, uint256 nas) returns (bool success);
}
/* 灵感来自于NAS coin*/
contract SafeMath {
function safeAdd(uint256 x, uint256 y) internal returns(uint256) {
uint256 z = x + y;
assert((z >= x) && (z >= y));
return z;
}
function safeSubtract(uint256 x, uint256 y) internal returns(uint256) {
assert(x >= y);
uint256 z = x - y;
return z;
}
function safeMult(uint256 x, uint256 y) internal returns(uint256) {
uint256 z = x * y;
assert((x == 0)||(z/x == y));
return z;
}
}
contract Token {
uint256 public totalSupply;
function balanceOf(address _owner) constant returns (uint256 balance);
function transfer(address _to, uint256 _value) returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) returns (bool success);
function approve(address _spender, uint256 _value) returns (bool success);
function allowance(address _owner, address _spender) constant returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
/* ERC 20 token */
contract StandardToken is Token {
function transfer(address _to, uint256 _value) returns (bool success) {
if (balances[msg.sender] >= _value && _value > 0) {
balances[msg.sender] -= _value;
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
return true;
} else {
return false;
}
}
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) {
balances[_to] += _value;
balances[_from] -= _value;
allowed[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
} else {
return false;
}
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
}
contract ChinaToken is StandardToken, SafeMath {
// metadata
string public constant name = "China";
string public constant symbol = "ChinaCoin";
uint256 public constant decimals = 18;
string public version = "1.0";
// contracts
address public ethFundDeposit; // ETH存放地址
address public newContractAddr; // token更新地址
// crowdsale parameters
bool public isFunding; // 状态切换到true
uint256 public fundingStartBlock;
uint256 public fundingStopBlock;
uint256 public currentSupply; // 正在售卖中的tokens数量
uint256 public tokenRaised = 0; // 总的售卖数量token
uint256 public tokenMigrated = 0; // 总的已经交易的 token
uint256 public tokenExchangeRate = 1000; // 1000 兑换 1 ETH
// events
event AllocateToken(address indexed _to, uint256 _value); // 分配的私有交易token;
event IssueToken(address indexed _to, uint256 _value); // 公开发行售卖的token;
event IncreaseSupply(uint256 _value);
event DecreaseSupply(uint256 _value);
event Migrate(address indexed _to, uint256 _value);
// 转换
function formatDecimals(uint256 _value) internal returns (uint256 ) {
return _value * 10 ** decimals;
}
// constructor
function ChinaToken(
address _ethFundDeposit,
uint256 _currentSupply)
{
ethFundDeposit = _ethFundDeposit;
isFunding = false; //通过控制预CrowdS ale状态
fundingStartBlock = 0;
fundingStopBlock = 0;
currentSupply = formatDecimals(_currentSupply);
totalSupply = formatDecimals(100000);
balances[msg.sender] = totalSupply;
if(currentSupply > totalSupply) throw;
}
modifier isOwner() { require(msg.sender == ethFundDeposit); _; }
/// 设置token汇率
function setTokenExchangeRate(uint256 _tokenExchangeRate) isOwner external {
if (_tokenExchangeRate == 0) throw;
if (_tokenExchangeRate == tokenExchangeRate) throw;
tokenExchangeRate = _tokenExchangeRate;
}
/// @dev 超发token处理
function increaseSupply (uint256 _value) isOwner external {
uint256 value = formatDecimals(_value);
if (value + currentSupply > totalSupply) throw;
currentSupply = safeAdd(currentSupply, value);
IncreaseSupply(value);
}
/// @dev 被盗token处理
function decreaseSupply (uint256 _value) isOwner external {
uint256 value = formatDecimals(_value);
if (value + tokenRaised > currentSupply) throw;
currentSupply = safeSubtract(currentSupply, value);
DecreaseSupply(value);
}
/// 启动区块检测 异常的处理
function startFunding (uint256 _fundingStartBlock, uint256 _fundingStopBlock) isOwner external {
if (isFunding) throw;
if (_fundingStartBlock >= _fundingStopBlock) throw;
if (block.number >= _fundingStartBlock) throw;
fundingStartBlock = _fundingStartBlock;
fundingStopBlock = _fundingStopBlock;
isFunding = true;
}
/// 关闭区块异常处理
function stopFunding() isOwner external {
if (!isFunding) throw;
isFunding = false;
}
/// 开发了一个新的合同来接收token(或者更新token)
function setMigrateContract(address _newContractAddr) isOwner external {
if (_newContractAddr == newContractAddr) throw;
newContractAddr = _newContractAddr;
}
/// 设置新的所有者地址
function changeOwner(address _newFundDeposit) isOwner() external {
if (_newFundDeposit == address(0x0)) throw;
ethFundDeposit = _newFundDeposit;
}
///转移token到新的合约
function migrate() external {
if(isFunding) throw;
if(newContractAddr == address(0x0)) throw;
uint256 tokens = balances[msg.sender];
if (tokens == 0) throw;
balances[msg.sender] = 0;
tokenMigrated = safeAdd(tokenMigrated, tokens);
IMigrationContract newContract = IMigrationContract(newContractAddr);
if (!newContract.migrate(msg.sender, tokens)) throw;
Migrate(msg.sender, tokens); // log it
}
/// 转账ETH 到ChinaI团队
function transferETH() isOwner external {
if (this.balance == 0) throw;
if (!ethFundDeposit.send(this.balance)) throw;
}
/// 将BILIBILI token分配到预处理地址。
function allocateToken (address _addr, uint256 _eth) isOwner external {
if (_eth == 0) throw;
if (_addr == address(0x0)) throw;
uint256 tokens = safeMult(formatDecimals(_eth), tokenExchangeRate);
if (tokens + tokenRaised > currentSupply) throw;
tokenRaised = safeAdd(tokenRaised, tokens);
balances[_addr] += tokens;
AllocateToken(_addr, tokens); // 记录token日志
}
/// 购买token
function () payable {
if (!isFunding) throw;
if (msg.value == 0) throw;
if (block.number < fundingStartBlock) throw;
if (block.number > fundingStopBlock) throw;
uint256 tokens = safeMult(msg.value, tokenExchangeRate);
if (tokens + tokenRaised > currentSupply) throw;
tokenRaised = safeAdd(tokenRaised, tokens);
balances[msg.sender] += tokens;
IssueToken(msg.sender, tokens); //记录日志
}
}
| true |
afc0e6f08a2f55179cbc56027a73578f03af5484 | C++ | martin-varbanov96/fmi--summer16 | /Dafi/Kontrolno_teoriq_2/02/main.cpp | WINDOWS-1251 | 1,298 | 3.109375 | 3 | [] | no_license | #include <iostream>
using namespace std;
class PoweredDevice{
public:
PoweredDevice(int nPower){
cout << "PoweredDevice" << nPower << endl;
}
};
class Scanner: virtual public PoweredDevice{
public:
Scanner(int nScanner, int nPower)
:PoweredDevice(nPower){
cout << "Scanner" << nScanner << endl;
}
};
class Printer : virtual public PoweredDevice{
public:
Printer(int nPrinter, int nPower)
:PoweredDevice(nPower){
cout << "Printer: " << nPrinter << endl;
}
};
class Copier : public Scanner, public Printer{
public:
Copier(int nScanner, int nPrinter, int nPower)
:Scanner(nScanner, nPower),
Printer(nPrinter, nPower),
PoweredDevice(nPower){
}
};
int main()
{
Copier hable(1, 2, 3);
return 0;
}
/*
PoweredDevice3
Scanner1
Printer: 2
ideqta na zadachata e, che kogato imame nasledqvane v poveche ot edin class,
suzdavame instanciq na klasa Copier s argumenti 1, 2, 3. Copier
PoweredDevice(nPower), Powered Device 3. Scanner,
*/
| true |
c2d7973bebe44f446f2ee84b81d98ba7ae625407 | C++ | santosli/experiment_datamining | /dataminning/test.cpp | UTF-8 | 2,265 | 3.046875 | 3 | [] | no_license | #include <iostream>
#include "KahanSum.hpp"
#include "Median.hpp"
#include "Vector.hpp"
#include "DataIO.hpp"
#include "Vector_function.hpp"
using namespace std;
int n;
int main()
{
cout << "Please enter the size of vector N :" <<endl;
cin >> n;
KahanSum ks;
Median md;
Vector vc1,vc2,vc3;
//for (int i = 1;i<=1000;i++)
//{
//ks.add(i);
//md.add(i);
//}
//cout << "KahanSum : " << ks.get_sum() << endl;
//cout << (1 + 1000) * 1000 /2 <<endl;
//cout << "Median of 1-1000 : " << md.get_median() << endl;
// vc1.fill(1);
// cout << "This is vc1 : " << endl;
// vc1.print();
// vc1.set(1,99);
// cout << "The value of index 1 is : " << vc1.get(1) << endl;
// cout << "This is vc1 : " << endl;
// vc1.print();
// vc2.fill(2);
// cout << "This is vc2 : " << endl;
// vc2.print();
// vc1.add(vc2);
// cout << "This is vc1 after add v2: " << endl;
// vc1.print();
// vc1.sub(vc2);
// cout << "This is vc1 after sub v2: " << endl;
// vc1.print();
// vc1.mul(2);
// cout << "This is vc1 after mul 2 : " << endl;
// vc1.print();
// vc1.inc_mul(vc2,2);
// cout << "This is vc1 after inc_mul v2,2 : " << endl;
// vc1.print();
// cout << "The dot of vc1 * vc2 is : " << vc1.dot(vc2) << endl;
// cout << "The square norm of vc1 is : " << vc1.square_norm() <<endl;
// cout << "The norm of vc1 is : " << vc1.norm() << endl;
// cout << "The sum of vc1 is : " << vc1.sum() << endl;
// cout << "The min of vc1 is : " << vc1.min() << endl;
// cout << "The max of vc1 is : " << vc1.max() << endl;
list<Vector> lv;
vc1.fill(1.1);
vc2.fill(2.2);
vc3.fill(3.5);
lv.push_back(vc1);
lv.push_back(vc2);
lv.push_back(vc3);
string inPath = "a.txt";
//write_data(inPath,lv);
list<Vector> lv2;
//read_data(inPath,lv2);
// list<Vector>::iterator it;
// for (it = lv2.begin(); it != lv2.end(); it++)
// {
// for (int j = 0; j < it->get_size(); j++)
// {
// if (j != it->get_size() - 1)
// {
// cout << it->get(j) << ", ";
// }
// else
// {
// cout << it->get(j) << endl;
// }
// }
// }
Vector vc4;
vc4 = vector_mean(lv);
cout << "The mean of vectors is : " << endl;
vc4.print();
vc4 = vector_median(lv);
cout << "The median of vectors is :" << endl;
vc4.print();
system("pause");
} | true |
1c7c098e2cd702f316d8695cb8e609cb4c99631a | C++ | omerorhun/game_server | /inc/GameService.h | UTF-8 | 965 | 2.53125 | 3 | [] | no_license | #ifndef _GAME_SERVICE_H_
#define _GAME_SERVICE_H_
#include "Game.h"
#include "errors.h"
#include <list>
#include <ev.h>
#include <thread>
#include <string>
#include <mutex>
class GameService {
public:
GameService();
static GameService *get_instance();
Game *create_game(Rivals rivals);
ErrorCodes accept_game(int game_id, uint64_t uid);
ErrorCodes start_game(int game_id);
ErrorCodes finish_game_with_uid(uint64_t uid);
ErrorCodes finish_game(Game *game, std::string results);
ErrorCodes remove_game(int game_id);
Game *lookup_by_uid(uint64_t uid);
Game *lookup(int game_id);
int get_game_id(uint64_t uid);
private:
static GameService *_ps_instance;
int _game_id_offset;
std::list<Game> _games;
std::mutex _mtx_add;
void watchdog(); // for removing finished games
};
#endif // _GAME_SERVICE_H_ | true |
f495770487b3af09536e254a7319e86d780f960e | C++ | Kaffeine/qml2html | /main.cpp | UTF-8 | 5,049 | 2.703125 | 3 | [] | no_license | #include <QCoreApplication>
#include <QQmlEngine>
#include <QQmlComponent>
#include <QDebug>
#include <QFile>
#include <iostream>
#if QT_VERSION < QT_VERSION_CHECK(5, 14, 0)
#define GENERATOR_ENDL endl
#else
#define GENERATOR_ENDL Qt::endl
#endif
namespace Html {
class HtmlNode : public QObject
{
Q_OBJECT
Q_CLASSINFO("DefaultProperty", "data")
Q_PROPERTY(QQmlListProperty<QObject> data READ data DESIGNABLE false)
public:
QQmlListProperty<QObject> data();
virtual QString getHtml() const;
virtual QString tag() const { return QString(); }
QString openTag() const;
QString closeTag() const;
private:
// data property
static void data_append(QQmlListProperty<QObject> *, QObject *);
static int data_count(QQmlListProperty<QObject> *);
static QObject *data_at(QQmlListProperty<QObject> *, int);
static void data_clear(QQmlListProperty<QObject> *);
QList<HtmlNode*> m_nodes;
};
class Page : public HtmlNode
{
Q_OBJECT
Q_PROPERTY(QString title MEMBER m_title)
public:
QString getHtml() const override;
QString tag() const override { return QLatin1String("html"); }
protected:
QString m_title;
};
class Text : public HtmlNode
{
Q_OBJECT
Q_PROPERTY(QString text MEMBER m_text)
public:
QString getHtml() const override;
protected:
QString m_text;
};
class Heading : public Text
{
Q_OBJECT
Q_PROPERTY(int level MEMBER m_level)
public:
QString tag() const override
{
return QStringLiteral("h%1").arg(m_level);
}
protected:
int m_level = 1;
};
class Paragraph : public Text
{
Q_OBJECT
public:
QString tag() const override { return QLatin1String("p"); }
};
class Button : public Text
{
Q_OBJECT
public:
QString tag() const override { return QLatin1String("button"); }
};
QQmlListProperty<QObject> HtmlNode::data()
{
return QQmlListProperty<QObject>(this, nullptr,
data_append,
data_count,
data_at,
data_clear);
}
QString HtmlNode::getHtml() const
{
QString html;
for (const HtmlNode *node : m_nodes) {
html += node->getHtml() + QLatin1Char('\n');
}
return html;
}
QString HtmlNode::openTag() const
{
return QLatin1Char('<') + tag() + QLatin1Char('>');
}
QString HtmlNode::closeTag() const
{
return QLatin1String("</") + tag() + QLatin1Char('>');
}
void HtmlNode::data_append(QQmlListProperty<QObject> *prop, QObject *o)
{
if (!o) {
return;
}
HtmlNode *that = static_cast<HtmlNode *>(prop->object);
HtmlNode *newNode = qobject_cast<HtmlNode *>(o);
that->m_nodes.append(newNode);
}
int HtmlNode::data_count(QQmlListProperty<QObject> *prop)
{
HtmlNode *that = static_cast<HtmlNode *>(prop->object);
return that->m_nodes.count();
}
QObject *HtmlNode::data_at(QQmlListProperty<QObject> *prop, int index)
{
HtmlNode *that = static_cast<HtmlNode *>(prop->object);
return that->m_nodes.at(index);
}
void HtmlNode::data_clear(QQmlListProperty<QObject> *prop)
{
HtmlNode *that = static_cast<HtmlNode *>(prop->object);
that->m_nodes.clear();
}
QString Page::getHtml() const
{
QString result;
QTextStream stream(&result);
stream << openTag() << GENERATOR_ENDL;
stream << "<head>" << GENERATOR_ENDL;
stream << "<title>" << m_title << "</title>" << GENERATOR_ENDL;
stream << "</head>" << GENERATOR_ENDL;
stream << "<body>" << GENERATOR_ENDL;
stream << HtmlNode::getHtml();
stream << "</body>" << GENERATOR_ENDL;
stream << closeTag() << GENERATOR_ENDL;
return result;
}
QString Text::getHtml() const
{
QString result;
QTextStream stream(&result);
stream << openTag();
stream << m_text;
stream << closeTag();
return result;
}
} // Html namespace
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
qmlRegisterType<Html::Page>("HTML", 1, 0, "Page");
qmlRegisterType<Html::Heading>("HTML", 1, 0, "Heading");
qmlRegisterType<Html::Paragraph>("HTML", 1, 0, "Paragraph");
qmlRegisterType<Html::Button>("HTML", 1, 0, "Button");
const QString input = a.arguments().count() > 1 ? a.arguments().at(1) : QLatin1String(":/index.qml");
QQmlEngine engine;
QQmlComponent *rootComponent = new QQmlComponent(&engine);
rootComponent->loadUrl(QUrl::fromLocalFile(input), QQmlComponent::PreferSynchronous);
if (rootComponent->isError()) {
const QList<QQmlError> errorList = rootComponent->errors();
for (const QQmlError &error : errorList) {
QMessageLogger(error.url().toString().toLatin1().constData(),
error.line(), nullptr).warning()
<< error;
}
return -1;
}
QObject *rootObject = rootComponent->create();
Html::Page *page = qobject_cast<Html::Page*> (rootObject);
std::cout << page->getHtml().toUtf8().constData();
return 0;
}
#include "main.moc"
| true |
22a7a59f3d6898f6ee24dbb5545c5b59b934ab74 | C++ | KingBobb/Mytiny_dnn | /Mytiny_dnn/network.h | UTF-8 | 2,033 | 2.578125 | 3 | [] | no_license | #ifndef NETWORK_H
#define NETWORK_H
#include<iostream>
#include<stdexcept>
#include<algorithm>
#include<iomanip>
#include<iterator>
#include<map>
#include<set>
#include<vector>
#include<string>
#include"nodes.h"
#include"util/util.h"
#include"lossfunctions\loss_function.h"
#include"activations\activation_function.h"
namespace mytiny_dnn
{
enum class content_type{
weights, ///< save/load the weights
model, ///< save/load the network architecture
weights_and_model ///< save/load both the weights and the architecture
};
enum class file_format {
binary,
json
};
struct result{
int num_success;
int num_total;
//map<
result() :num_success(0), num_total(0){}
float_t accuracy()const{
return float_t(num_success*100.0 / num_total);
}
template <typename Char,typename CharTraits>
void print_summary(std::basic_ostream<Char, CharTraits>& os)const{
os << "accuracy:" << accuracy()
<< "% (" << num_success << "/"
<< num_total << ")" << std::endl;
}
template <typename Char, typename CharTraits>
void print_detail(std::basic_ofstream<Char, CharTraits>& os){
print_summary(os);
auto all_labels = labels();
os << std::setw(5) << "*" << " ";
for (auto c : all_labels)
os << std::setw(5) << c << " ";
os << std::endl;
for (auto r : all_labels) {
os << std::setw(5) << r << " ";
for (auto c : all_labels)
os << std::setw(5) << confusion_matrix[r][c] << " ";
os << std::endl;
}
}
std::set<label_t> labels()const{
std::set<label_t>all_labels;
for (auto r : confusion_matrix)
{
all_labels.insert(r.first);
for (auto c : r.second)
all_labels.insert(c.first);
}
return all_labels;
}
std::map<label_t, std::map<label_t, int>>confusion_matrix;
};
enum grad_check_mode{
GRAD_CHECK_ALL, ///< check all elements of weights
GRAD_CHEVK_RANDOM ///< check 10 randomly selected weights
};
template<typename NetType>
class network;
template<typename Layer>
}
#endif // !NETWORK_H
| true |
d7c3fc895c00ff63c6ee22e29619b5d716dcc84e | C++ | sandeep-07/DSA_ALL | /HasCycle.cpp | UTF-8 | 1,589 | 3.4375 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
template<typename T>
class Graph{
map<T,list<T>> l;
public:
void addEdge(int x,int y){
l[x].push_back(y);
l[y].push_back(x);
}
void dfs_helper(T src,map<T,bool>& visited){
cout<<src<<" ";
visited[src]=true;
// go to all nbrs of that node
for(T nbr:l[src]){
if(!visited[nbr]){
// visited[nbr]=true;
dfs_helper(nbr,visited);
}
// dfs_helper(src,visited);
}
}
void dfs(T src){
map<T,bool> visited;
// mark all the nodes as not visited in the beginning
for(auto p:l){
T node=p.first;
visited[node]=false;
}
dfs_helper(src,visited);
}
bool cycle_helper(int node,bool vis[],int par){
// if(vis[node])
// return true;
vis[node] = true;
for(int x:l[node])
{
if(!vis[x])
{
return cycle_helper(x,vis,node);
}
else{
if(x!=par)
return true;
}
}
return false;
}
bool contains_cycle(){
int V = l.size();
bool visited[V];
for (int i = 0; i < V;i++){
visited[i] = false;
}
return cycle_helper(0, visited,-1);
}
};
int main(){
Graph<int> g;
g.addEdge(0,1);
g.addEdge(1,2);
g.addEdge(2,3);
g.addEdge(3,0);
cout << g.contains_cycle();
return 0;
} | true |
c5733dee2c295ce9fc22c8129ed21dde200bdac2 | C++ | AndyGaming/Andrew_Repo | /CSE_CSUSB/cse520/lab_1/draw.cpp | UTF-8 | 2,131 | 3.109375 | 3 | [] | no_license | //draw.cpp : demo program for drawing 3 dots, two lines, ploylines, rectangles
#include <GL/glut.h>
//initialization
void init( void )
{
glClearColor( 1.0, 1.0, 1.0, 0.0 ); //get white background color
glColor3f( 0.0f, 0.0f, 0.0f ); //set drawing color
glPointSize( 4.0 ); //a dot is 4x4
glMatrixMode( GL_PROJECTION );
glLoadIdentity(); //replace current matrix with identity matrix
gluOrtho2D( 0.0, 500.0, 0.0, 500.0 );
}
void display( void )
{
glClear( GL_COLOR_BUFFER_BIT ); //clear screen
glBegin( GL_POINTS ); //draw points
glVertex2i( 100, 50 ); //draw a point
glVertex2i( 100, 150 ); //draw a point
glVertex2i( 200, 200 ); //draw a point
glEnd();
glBegin( GL_LINES ); //draw lines
glVertex2i( 20, 20 ); //horizontal line
glVertex2i( 400, 20 );
glVertex2i( 20, 10 ); //vertical line
glVertex2i( 20, 400 );
glEnd();
glBegin( GL_LINE_STRIP ); //draw polyline
glVertex2i( 200, 100 );
glVertex2i( 300, 100 );
glVertex2i( 450, 200 );
glVertex2i( 200, 100 );
glEnd();
glColor3f( 0.6, 0.6, 0.6 ); //bright grey
glRecti( 400, 400, 450, 480 );
glColor3f( 1.0, 0.0, 0.0 ); //red
glRecti( 350, 350, 380, 390 );
glFlush(); //send all output to screen
}
//------------------------------------------------------------------------------
//draw_main.cpp: main loop of drawing program
#include <GL/glut.h>
#include <math.h>
#include <stdlib.h>
#include <stdio.h>
//initialization
void init(void);
//does the drawing
void display(void);
/* Main Loop
* Open window with initial window size, title bar,
* RGBA display mode, depth buffer.
*/
int main(int argc, char** argv)
{
glutInit(&argc, argv); //initialize toolkit
glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB ); //set display mode: single bufferring, RGBA model
glutInitWindowSize(500, 500); //set window size on screen
glutInitWindowPosition( 100, 150 ); //set window position on screen
glutCreateWindow(argv[0]); //open screen window
init();
glutDisplayFunc (display); //points to display function
glutMainLoop(); //go into perpetual loop
return 0;
}
| true |
cf323ba8ce4e84e888dd7b3badb84e1dfc923562 | C++ | cdsc-github/Fluid-Registration | /C++Source/DoubleArray1D.h | UTF-8 | 12,372 | 3.15625 | 3 | [] | no_license | #ifndef __DoubleArray1D__
#define __DoubleArray1D__
#include <iostream>
#include <iomanip>
using namespace std;
#ifdef _DEBUG
#include <stdio.h>
#endif
//
//####################################################################
// DoubleArray1D.h
//####################################################################
/**
Provides a "light weight" one dimensional array structure
with initialization capabilities, array operations, and
optional bounds checking.
<pre>
The beginning index default is 0 : (C convention)
Access using (*), e.g. A(i) for ith element. : (Not C convention)
</pre>
The copy constructor creates a duplicate instance. Deleting the copy
will not delete the data of the original.<p>
Created for use in Math 270E and 270C<p>
***Fixes***
Fixed assignment operator so that indexing information is not
overwritten. Made dot const correct. CRA 01/21/03 <p>
Added ostream support. CRA 01/21/03 <p>
<i>Source</i>:
<A HREF="../DoubleArray1D.h">DoubleArray1D.h</A><p>
@author Chris Anderson (C) UCLA
@version May 25, 2000
*/
//#####################################################################
// Chris Anderson (C) UCLA April 2, 2000
//#####################################################################
//
class DoubleArray1D
{
public :
//
//###################################################################
// Constructors/Initialization
//###################################################################
//
DoubleArray1D()
{
dataPtr = 0;
index1Size = 0;
index1Begin = 0;
index1End = 0;
}
DoubleArray1D(long m)
{
dataPtr = 0;
index1Size = 0;
index1Begin = 0;
index1End = 0;
initialize(m);
};
DoubleArray1D(double* d, long m)
{
dataPtr = 0;
index1Size = 0;
index1Begin = 0;
index1End = 0;
initialize(d,m);
};
DoubleArray1D(const DoubleArray1D& D)
{
index1Size = D.index1Size;
index1Begin = D.index1Begin;
index1End = D.index1End;
dataPtr = new double[index1Size];
long i;
for(i = 0; i < index1Size; i++){dataPtr[i] = D.dataPtr[i];}
}; ///<p>
virtual ~DoubleArray1D()
{
if( dataPtr != 0) delete [] dataPtr;
}
void initialize(long m)
{
if(index1Size != m)
{
delete [] dataPtr;
dataPtr = new double[m];
}
index1Size = m;
index1Begin = 0;
index1End = index1Begin + (index1Size - 1);
long i;
for(i = 0; i < index1Size; i++)
{dataPtr[i] = 0.0;}
}; ///<p>
void initialize(double* d, long m)
{
initialize(m);
long i;
for(i = 0; i < index1Size; i++)
{dataPtr[i] = d[i];}
};
//
//###################################################################
// Element Access
//###################################################################
//
#ifdef _DEBUG
double& operator()(long i1)
{
boundsCheck(i1, index1Begin, index1End,1);
return *(dataPtr + (i1 - index1Begin));
};
const double& operator()(long i1) const
{
boundsCheck(i1, index1Begin, index1End,1);
return *(dataPtr + (i1 - index1Begin));
};
#else
inline double& operator()(long i1)
{
return *(dataPtr + (i1 - index1Begin));
}; ///<p>
inline const double& operator()(long i1) const
{
return *(dataPtr + (i1 - index1Begin));
};
#endif
//
//###################################################################
// Array Structure Access Functions
//###################################################################
//
///<p>
double* getDataPointer(){return dataPtr;};
void setIndex1Begin(long i)
{index1Begin = i; index1End = index1Begin + (index1Size - 1);};
long getIndex1Begin() const {return index1Begin;}
long getIndex1End() const {return index1End;}
long getIndex1Size() const {return index1Size;}
//
// Get/Set specifically for one dimensional arrays
//
void setIndexBegin(long i)
{index1Begin = i; index1End = index1Begin + (index1Size - 1);};
long getIndexBegin() const {return index1Begin;}
long getIndexEnd() const {return index1End;}
long getSize() const {return index1Size;} ///<p>
//
// Resizes array to exactly newSize
//
void resize(long newSize)
{
long i;
double* newDataPtr = new double[newSize];
double* tmpDataPtr;
if(newSize > index1Size)
{
for(i = 0; i < index1Size; i++) newDataPtr[i] = dataPtr[i];
}
else
{
for(i = 0; i < newSize; i++) newDataPtr[i] = dataPtr[i];
}
index1Size = newSize;
tmpDataPtr = dataPtr;
dataPtr = newDataPtr;
if(tmpDataPtr != 0) delete [] tmpDataPtr;
index1End = index1Begin + (index1Size - 1);
}
//
//###################################################################
// Array Operators
//###################################################################
//
DoubleArray1D operator+(const DoubleArray1D& D)
{
#ifdef _DEBUG
sizeCheck(this->index1Size,D.index1Size);
#endif
DoubleArray1D R(*this);
long i;
for(i = 0; i < index1Size; i++)
{
R.dataPtr[i] += D.dataPtr[i];
}
return R;
}
DoubleArray1D operator-(const DoubleArray1D& D)
{
#ifdef _DEBUG
sizeCheck(this->index1Size,D.index1Size);
#endif
DoubleArray1D R(*this);
long i;
for(i = 0; i < index1Size; i++)
{
R.dataPtr[i] -= D.dataPtr[i];
}
return R;
}
DoubleArray1D operator*(double alpha)
{
DoubleArray1D R(*this);
long i;
for(i = 0; i < index1Size; i++)
{
R.dataPtr[i] *= alpha;
}
return R;
}
friend DoubleArray1D operator*(double alpha, const DoubleArray1D& D)
{
DoubleArray1D R(D);
long i;
for(i = 0; i < D.index1Size; i++)
{
R.dataPtr[i] *= alpha;
}
return R;
}
///<p>
DoubleArray1D operator/(double alpha)
{
DoubleArray1D R(*this);
long i;
for(i = 0; i < index1Size; i++)
{
R.dataPtr[i] /= alpha;
}
return R;
}
//
//###################################################################
//
//###################################################################
//
void operator=(const DoubleArray1D& D)
{
#ifdef _DEBUG
if(index1Size != 0)
{
sizeCheck(this->index1Size,D.index1Size);
}
#endif
//
// If null instance, then initialize and acquire indexing
// from right hand side.
//
if(index1Size == 0)
{
initialize(D.index1Size);
index1Size = D.index1Size;
index1Begin = D.index1Begin;
index1End = D.index1End;
}
//
// copy over the data
//
long i;
for(i = 0; i < D.index1Size; i++)
{dataPtr[i] = D.dataPtr[i];}
}
void operator*=(double alpha)
{
long i;
for(i = 0; i < index1Size; i++)
{dataPtr[i] *= alpha;}
}
void operator+=(const DoubleArray1D& D)
{
#ifdef _DEBUG
if(index1Size != 0)
{
sizeCheck(this->index1Size,D.index1Size);
}
#endif
long i;
for(i = 0; i < D.index1Size; i++)
{dataPtr[i] += D.dataPtr[i];}
} ///<p>
void operator-=(const DoubleArray1D& D)
{
#ifdef _DEBUG
if(index1Size != 0)
{
sizeCheck(this->index1Size,D.index1Size);
}
#endif
long i;
for(i = 0; i < D.index1Size; i++)
{dataPtr[i] -= D.dataPtr[i];}
}
void setToValue(double d)
{
long i;
for(i = 0; i < index1Size; i++)
{
dataPtr[i] = d;
}
}
double dot(const DoubleArray1D& B) const
{
#ifdef _DEBUG
sizeCheck(this->index1Size,B.index1Size);
#endif
double R;
R = 0;
long i;
for(i = 0; i < index1Size; i++)
{R += dataPtr[i]*B.dataPtr[i];}
return R;
}
//
// Output
//
friend ostream& operator<<(ostream& outStream, const DoubleArray1D& V)
{
long i;
for(i = 0; i < V.index1Size; i++)
{
outStream << setw(5) << V.dataPtr[i] << " ";
outStream << endl;
}
return outStream;
}
//
//###################################################################
// Class Data Members
//###################################################################
//
protected :
double* dataPtr; // data pointer
long index1Begin; // coordinate 1 starting index
long index1End; // coordinate 1 ending index
long index1Size; // coordinate 1 size
//
//###################################################################
// Bounds Checking
//###################################################################
//
#ifdef _DEBUG
static void boundsCheck(long i, long begin, long end, int coordinate)
{
if((i < begin)||(i > end))
{
printf("Array index %d out of bounds \n",coordinate);
printf("Offending index value %d : Acceptable Range [%d, %d] \n",i, begin, end);
}
}
#else
static void boundsCheck(long, long, long, int){}
#endif
#ifdef _DEBUG
static void sizeCheck(long size1, long size2)
{
if(size1 != size2)
{
printf("Array Sizes Are Incompatable %d != %d \n", size1, size2);
}
}
#else
static void sizeCheck(long, long){}
#endif
};
#endif
| true |
5f47f41e1feef3f6a74bbab5756eb4f815f207fd | C++ | alistair-singh/cpp-misc | /malloc.cc | UTF-8 | 451 | 3.453125 | 3 | [] | no_license |
#include <algorithm>
#include <cstdlib>
#include <iostream>
#include <memory>
int main() {
const int SIZE = 1024;
char *ptr1 = static_cast<char *>(::malloc(sizeof(char) * SIZE));
auto ptr2 = new char[SIZE];
std::fill(ptr1, ptr1 + SIZE, '1');
std::fill(ptr2, ptr2 + SIZE, '2');
std::cout << std::hex << static_cast<void *>(ptr1) << '\n'
<< static_cast<void *>(ptr2) << '\n';
::free(ptr1);
delete[] ptr2;
return 0;
}
| true |
bc920cc4e9ad9c528b3a3bc018f5f292794e83f5 | C++ | dipty13/Competitive-Programming-Codes | /HackerRank/Restaurant.cpp | UTF-8 | 268 | 2.546875 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int main()
{
int t, l, b,gcd, x, y;
cin >> t;
while(t--)
{
cin >> l >> b;
gcd = __gcd(l, b);
x = l / gcd;
y = b / gcd;
cout << x * y << endl;
}
return 0;
}
| true |
34288967a56941df36bf407d960c83bded4ef11a | C++ | cba96/Data-Structure | /HeapSort/heapSort.cpp | UTF-8 | 2,521 | 3.40625 | 3 | [] | no_license | // test heap sort
#pragma
#include <iostream>
#include <algorithm>
#include <iterator>
#include <ctime>
#include "heapSort.h"
using namespace std;
#define NUMBER_OF_DATASET 10000000
#define MAX_NUMBER_TO_SHOW 50
template <class T>
void initializeArray(T nArr[], int n)
{
srand((unsigned) time(NULL));
for (int i = 1; i <= n; i++)
{
nArr[i] = rand() % n;
}
}
int main(void)
{
cout << "Heap sort example: " << endl;
cout << "# of dataset: " << NUMBER_OF_DATASET << endl << endl;
// use an array from a[1] to a[10]
// int a[NUMBER_OF_DATASET + 1];
int *a = new int[NUMBER_OF_DATASET + 1];
// initialize dataset randomly
initializeArray(a, NUMBER_OF_DATASET);
// input data
// for discarding a[0], we use a + 1...
if (NUMBER_OF_DATASET <= MAX_NUMBER_TO_SHOW)
{
cout << "Input data:" << endl;
copy(a + 1, a + NUMBER_OF_DATASET + 1, ostream_iterator<int>(cout, " "));
cout << endl << endl;
}
else
{
cout << "Input data:" << endl;
copy(a + 1, a + MAX_NUMBER_TO_SHOW + 1, ostream_iterator<int>(cout, " "));
cout << "... omitted" << endl << endl;
}
/*
Timing in C++ (slide: 9)
100 ticks
*/
double clocksPerMillis = double (CLOCKS_PER_SEC) / 1000;
clock_t startTime = clock();
// code to be timed comes here...
heapSort(a, NUMBER_OF_DATASET);
double elapsedMillis = (clock() - startTime) / clocksPerMillis;
// output sorted data
if (NUMBER_OF_DATASET < MAX_NUMBER_TO_SHOW)
{
cout << "Output sorted data:" << endl;
copy(a + 1, a + NUMBER_OF_DATASET + 1, ostream_iterator<int>(cout, " "));
cout << endl << endl;
}
else
{
cout << "Output sorted data:" << endl;
copy(a + 1, a + MAX_NUMBER_TO_SHOW + 1, ostream_iterator<int>(cout, " "));
cout << "... omitted" << endl << endl;
}
cout << "ElapsedMillis ( 100 ticks): " << elapsedMillis << " ms" << endl;
/*
The Fix (slide: 16)
1000 ticks
*/
startTime = clock();
long numberOfRepetitions = 0;
do
{
numberOfRepetitions++;
// put code to initialize a[] here...
initializeArray(a, NUMBER_OF_DATASET);
// code to be timed comes here...
heapSort(a, NUMBER_OF_DATASET);
} while (clock() - startTime < 1000);
elapsedMillis = (clock() - startTime) / clocksPerMillis;
// repeat the same routine for 1 sec,
// and then divide the elapsed time by the number of repetitions
double timeForCode = elapsedMillis / numberOfRepetitions;
cout << "ElapsedMillis (1000 ticks): " << timeForCode << " ms"
<< " (# of Repetitions: " << numberOfRepetitions << ")"
<< endl;
delete a;
return 0;
}
| true |
9ee5e5d3a74f0dfca3ce0337090fe65d1961fa9e | C++ | JunzheCS2/FirstRepo12 | /Assignment 13-2/13-2.cpp | UTF-8 | 341 | 3.203125 | 3 | [] | no_license | #include "Numbers.hpp"
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
Number n(5);
n.setElement();
n.printOut();
cout << "Sum " << n.getSum() << endl;
cout << "Size " << n.getSize() << endl;
Number N(10);
for( int i=0;i<10; i++)
{
N.setElement(i,i*10);
}
N.printOut();
} | true |
6762c695fa9083dc70e2d73886ad3ef85df2ef05 | C++ | abouchie/TicTacToe-using-Classes | /Driver.cpp | UTF-8 | 389 | 3.015625 | 3 | [] | no_license | /*
* Adrienne Bouchie
* Driver.cpp
*
*/
#include "TicTacToe.h"
main() {
char playerAnswer;
TicTacToe TTT;
cout << "Would you like to play a game of Tic-Tac-Toe? (y/n)" << endl;
cin >> playerAnswer;
if ( playerAnswer == 'y' || playerAnswer == 'Y' ) {
TTT.setPlayerInfo();
TTT.displayBoard();
TTT.makeMove();
}
else
cout << "Okay you're no fun! Bye!" << endl;
}
| true |
a8e2b25cd8787f67e03f2fc1be81841776e5f20e | C++ | joe-nano/ljus | /ljus/hash/Hash.h | UTF-8 | 1,830 | 2.859375 | 3 | [
"MIT",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause"
] | permissive | //
// Created by cents on 24/08/17.
//
#ifndef HASH_H
#define HASH_H
#include <string>
extern "C" {
#include <argon2.h>
};
#include <fcntl.h>
#include <unistd.h>
#include <sstream>
#include <cstring>
#include "../exceptions/ZeroEntropyError.h"
#define HASH_LENGTH 32
#define SALT_LENGTH 16
#define T_COST 5
#define PARALLELISM 3
#define M_COST 48000
using namespace std;
namespace Ljus {
class Hash {
public:
/**
* Securely hash a plain text value, using the argon2 ref spec implementation
* @param value the plain text value. Please don't store this.
* @return the argon2 hashed and salted string
*/
static string make( string value );
/**
* Check if the plain value and hashed value are at their core, equivalent.
* @param plain the plain text value
* @param hashed the stored hashed and salted string
* @return equivalency
*/
static bool check( string plain, string hashed );
/**
* Check if a hash needs to be rehashed. This is generally a check as to if the work factor has increased since the last time this was run.
* We recommend running this every time a user logs in, checking for equivalency, and if the user entered the correct password, hashing their input with the new work factor.
* Most often, this will happen because you updated your copy of Ljus and the standards have changed. Updating the work factor is not considered a breaking change, however, failure to check for rehashing in your authentication approach may cause loss of security and breaking effects.
* @param hashed the hashed value
* @return if a value needs to be rehashed
*/
static bool needs_rehash( string hashed );
};
}
#endif //HASH_H
| true |
5a533f4fd05fe30e0c878e93a67f0fdf829cc796 | C++ | cyclone472/SDSpractice | /Day6/Day6/P2458.cpp | UHC | 1,271 | 3.171875 | 3 | [] | no_license | #include <iostream>
#include <cstring>
#include <vector>
using namespace std;
vector<int> graph[501];
vector<int> revGraph[501];
bool visited[501];
int n, m;
void getInput();
void dfs(int, vector<int>*);
int main() {
getInput();
//cout << "n : " << n << " m : " << m << '\n';
int ans = 0;
for (int i = 1; i <= n; i++) {
// i ؼ dfs ٸ Ž
visited[i] = true;
dfs(i, graph);
dfs(i, revGraph);
// visit
bool isAns = true;
for (int j = 1; j <= n; j++) {
if (!visited[j]) {
isAns = false;
break;
}
}
if (isAns)
ans++;
memset(visited, 0, sizeof(visited));
}
cout << ans << '\n';
return 0;
}
void getInput(void) {
ios_base::sync_with_stdio(false);
cin.tie(0);
memset(visited, 0, sizeof(visited));
cin >> n >> m;
for (int i = 0; i < m; i++) {
int start, end;
cin >> start >> end;
graph[start].push_back(end);
}
// ݴ
for (int start = 1; start <= n; start++) {
for (int x : graph[start]) {
revGraph[x].push_back(start);
}
}
}
void dfs(int cnt, vector<int>* g) {
for (int x : g[cnt]) {
if (!visited[x]) {
visited[x] = true;
dfs(x, g);
}
}
} | true |
ba259350919982debacda01c284938116bf9397a | C++ | Lethe0616/practice | /20200115/0115.cpp | UTF-8 | 208 | 2.53125 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
int n,m,i;
double sum=0;
scanf("%d %d",&n,&m);
for(i=n;i<=m;i++)
{sum=sum+1/pow(i,2.0);}
printf("%.5lf",sum);
return 0;
}
| true |
9d0caf19dfdf86ec1a9fb6ef07bda6cfe8a17755 | C++ | TarsisJordao/ArquivosVerificar | /teste_serial2.0.ino | UTF-8 | 850 | 2.796875 | 3 | [] | no_license | char charRead;
void setup()
{
Serial.begin(115200);
}
void inicio()
{
Serial.println("TESTE DE COMANDOS NA SERIAL");
Serial.println();
}
void loop()
{
while(Serial.available() > 0)
{
charRead=Serial.read();
Serial.println(charRead);
switch(charRead)
{
case '1':
{
Serial.println("GPIO4");
Serial.println();
break;
}
case '2':
{
Serial.println("GPIO5");
Serial.println();
break;
}
case '3':
{
Serial.println("GPIO12");
Serial.println();
break;
}
case '4':
{
Serial.println("GPIO13");
Serial.println();
break;
}
default:
{
Serial.println("Opcao invalida");
Serial.println();
}
}
}
}
| true |
6fe0f72982ce8a83e82785e739b89421f9ac4f91 | C++ | mcdavis17/Hashing | /Src/hashing.cpp | UTF-8 | 1,118 | 3.078125 | 3 | [] | no_license | //
// hashing.cpp
// Hashing
//
//
//
//CLASS TO CREATE HASHNODE OBJECTS TO STORE THE NECESSARY VALUES OF EACH NODE
class HashNode {
public:
int key;
std::string value;
std::string lineNumbers;
HashNode* next;
HashNode() { key = -1; }
HashNode(int k, std::string v, int lineNumber) {
key = k;
value = v;
lineNumbers += std::to_string(lineNumber);
}
};
//DJB2 HASH FUNCTION (http://www.cse.yorku.ca/~oz/hash.html)
unsigned long hash(char *str) {
unsigned long hash = 5381;
int c;
while ( (c = *str++) ) {
hash = ( (hash << 5) + hash) + c;
}
return hash;
}
//HANDLES COLLISIONS WHEN INSERTING & SEARCHING
int handleCollision(int currIndex, std::string word, std::string probeMethod, int i, int dhash) {
if (probeMethod == "lp") {
currIndex += i;
}
if (probeMethod == "qp") {
currIndex = currIndex + (i * i);
}
if (probeMethod == "dh") {
currIndex = ( (dhash - (currIndex % dhash)) * i ) + currIndex;
}
return currIndex;
}
| true |
1e01ff585d83309e1892f5846efcead1b420969d | C++ | Edwardyeoh1810/evt | /libraries/chain/include/evt/chain/apply_context.hpp | UTF-8 | 1,864 | 2.53125 | 3 | [
"BSL-1.0",
"Apache-2.0",
"BSD-2-Clause",
"BSD-3-Clause",
"MIT"
] | permissive | /**
* @file
* @copyright defined in evt/LICENSE.txt
*/
#pragma once
#include <algorithm>
#include <sstream>
#include <boost/noncopyable.hpp>
#include <fc/utility.hpp>
#include <evt/chain/controller.hpp>
namespace chainbase {
class database;
}
namespace evt { namespace chain {
struct action_trace;
class transaction_context;
class apply_context : boost::noncopyable {
public:
apply_context(controller& con, transaction_context& trx_ctx, const action& action)
: control(con)
, db(con.db())
, token_db(con.token_db())
, trx_context(trx_ctx)
, act(action) {
reset_console();
}
public:
void exec(action_trace& trace);
void exec_one(action_trace& trace);
public:
uint64_t next_global_sequence();
bool has_authorized(const domain_name& domain, const domain_key& key) const;
void finalize_trace( action_trace& trace, const fc::time_point& start );
public:
void reset_console();
std::ostringstream&
get_console_stream() {
return _pending_console_output;
}
const std::ostringstream&
get_console_stream() const {
return _pending_console_output;
}
template <typename T>
void
console_append(T val) {
_pending_console_output << val;
}
template <typename T, typename... Ts>
void
console_append(T val, Ts... rest) {
console_append(val);
console_append(rest...);
};
inline void
console_append_formatted(const string& fmt, const variant_object& vo) {
console_append(fc::format_string(fmt, vo));
}
public:
controller& control;
chainbase::database& db;
token_database& token_db;
transaction_context& trx_context;
const action& act;
private:
std::ostringstream _pending_console_output;
};
}} // namespace evt::chain
| true |
4ae6a48dea8f833e17715f6a4d4bde19fd0a87a2 | C++ | GarimaAhuja/IRE | /CodeBase/RomilAdityaSirs/naiveClustering.cpp | UTF-8 | 1,089 | 2.90625 | 3 | [] | no_license | #include<iostream>
#include<fstream>
#include<vector>
#include<algorithm>
#include<map>
using namespace std;
int main()
{
ifstream entityFile("entities.txt");
string line;
vector<vector<string> > entities;
map< string,vector<int> > clusters;
while(getline(entityFile,line))
{
vector<string> curr;
while(line.size()>0)
{
string temp=line.substr(0,line.find(","));
if(find(curr.begin(),curr.end(),temp)==curr.end())
{
curr.push_back(temp);
}
line=line.substr(line.find(",")+1);
}
entities.push_back(curr);
}
for(int i=0;i<100000;i++)
{
for(int j=0;j<entities[i].size();j++)
{
if(clusters.find(entities[i][j])==clusters.end())
{
vector<int> curr;
curr.push_back(i+1);
clusters.insert(std::pair<string, vector<int> >(entities[i][j],curr));
}
else
{
clusters[entities[i][j]].push_back(i+1);
}
}
}
for(map<string,vector<int> >::iterator it=clusters.begin();it!=clusters.end();it++)
{
cout<<it->first<<":";
for(int i=0;i<it->second.size();i++)
cout<<it->second[i]<<",";
cout<<endl;
}
return 0;
}
| true |
cfb72a8a00043c173cf4daee164ce584e07f0d8f | C++ | mukoedo1993/CPP_advanced | /effective_modern_CPP/item7/variadic.cc | UTF-8 | 820 | 3 | 3 | [] | no_license | #include<iostream>
#include<vector>
#include<memory>
template<typename T,
typename... Ts>
void doSomeWork(Ts&&... params)
{
//create local T object from params...
T localObject(std::forward<Ts>(params)...);
std::cout<<localObject.size()<<"\n";//13
T localObject1{std::forward<Ts>(params)...};
std::cout<<localObject1.size();//2
}
int main()
{
std::vector<int>vi={1,2,3,4};
doSomeWork<std::vector<int>>(13,5);
auto u_p=std::make_unique<std::vector<int>>(13,5);//13
auto s_p=std::make_shared<std::vector<int>>(13,5);//13
std::cout<<'\n'<<u_p->size()<<" "<<s_p->size();//
//auto u_p1=std::make_unique<std::vector<int>>{13,5};//error
//auto s_p1=std::make_shared<std::vector<int>>{13,5};//error
//std::cout<<'\n'<<u_p1->size()<<" "<<s_p1->size();//
} | true |
442d0b45785948633b4fa1953ee5925635e7550a | C++ | aaronlimwk/tunnelman | /Actor.cpp | UTF-8 | 19,861 | 2.5625 | 3 | [] | no_license | #include "Actor.h"
#include "GameConstants.h"
#include "GraphObject.h"
#include "StudentWorld.h"
#include <algorithm>
#include <vector>
using namespace std;
// Students: Add code to this file (if you wish), Actor.h, StudentWorld.h, and StudentWorld.cpp
///////////////////////////////////
// Boulder Class Implementations //
///////////////////////////////////
void Boulder::doSomething()
{
if (!isAlive())
{
return;
}
if (getState() == stable)
{
if (!(getWorld()->checkEarthBelow(getX(), (getY() - 1))))
{
setState(waiting);
return;
}
}
if (getState() == waiting)
{
if (getTicks() == 30)
{
setState(falling);
getWorld()->playSound(SOUND_FALLING_ROCK);
return;
}
else
{
addTicks();
}
}
if (getState() == falling)
{
if (getWorld()->noOverlap(getX(), (getY() - 1), this))
{
moveTo(getX(), (getY() - 1));
}
else
{
setDead();
return;
}
Tunnelman* player = getWorld()->searchForTunnelman(this, 3.0);
if (player != nullptr)
{
player->annoy(100);
return;
}
getWorld()->hitProtesters(this);
}
return;
}
//////////////////////////////////
// Squirt Class Implementations //
//////////////////////////////////
void Squirt::doSomething()
{
if (!isAlive())
{
return;
}
if (getTravel() <= 0)
{
setDead();
return;
}
if (getWorld()->squirtProtesters(this))
{
setDead();
return;
}
switch (getDirection())
{
case up:
if (getWorld()->noOverlap(getX(), (getY() + 1), this))
{
moveTo(getX(), (getY() + 1));
}
else
{
setDead();
return;
}
break;
case down:
if (getWorld()->noOverlap(getX(), (getY() - 1), this))
{
moveTo(getX(), (getY() - 1));
}
else
{
setDead();
return;
}
break;
case right:
if (getWorld()->noOverlap((getX() + 1), getY(), this))
{
moveTo((getX() + 1), getY());
}
else
{
setDead();
return;
}
break;
case left:
if (getWorld()->noOverlap((getX() - 1), getY(), this))
{
moveTo((getX() - 1), getY());
}
else
{
setDead();
return;
}
break;
}
reduceTravel();
return;
}
////////////////////////////////
// Item Class Implementations //
////////////////////////////////
void Item::doSomething()
{
if (!isAlive())
{
return;
}
doDifferentiatedStuff();
if (getState() == temporary)
{
if (getLifetime() == 0)
{
setDead();
}
reduceLifetime();
}
return;
}
///////////////////////////////
// Oil Class Implementations //
///////////////////////////////
void Oil::doDifferentiatedStuff()
{
if (!isVisible() && getWorld()->withinRadiusOfTunnelman(getX(), getY(), 4.0))
{
isDiscovered();
return;
}
if (isVisible())
{
if (getWorld()->withinRadiusOfTunnelman(getX(), getY(), 3.0))
{
setDead();
getWorld()->playSound(SOUND_FOUND_OIL);
getWorld()->increaseScore(1000);
getWorld()->reduceOil();
}
}
return;
}
////////////////////////////////
// Gold Class Implementations //
////////////////////////////////
void Gold::doDifferentiatedStuff()
{
if (!isVisible() && getWorld()->withinRadiusOfTunnelman(getX(), getY(), 4.0))
{
isDiscovered();
return;
}
if (isVisible() && getState() == permanent)
{
Tunnelman* player = getWorld()->searchForTunnelman(this, 3.0);
if (player != nullptr)
{
setDead();
getWorld()->playSound(SOUND_GOT_GOODIE);
getWorld()->increaseScore(10);
player->addGold();
return;
}
}
if (isVisible() && getState() == temporary)
{
if (getWorld()->searchForProtester(this))
{
setDead();
}
}
return;
}
/////////////////////////////////
// Sonar Class Implementations //
/////////////////////////////////
// Mutator(s)
void Sonar::doDifferentiatedStuff()
{
Tunnelman* player = getWorld()->searchForTunnelman(this, 3.0);
if (player != nullptr)
{
setDead();
getWorld()->playSound(SOUND_GOT_GOODIE);
getWorld()->increaseScore(75);
player->addSonar();
}
return;
}
/////////////////////////////////
// Water Class Implementations //
/////////////////////////////////
// Mutator(s)
void Water::doDifferentiatedStuff()
{
Tunnelman* player = getWorld()->searchForTunnelman(this, 3.0);
if (player != nullptr)
{
setDead();
getWorld()->playSound(SOUND_GOT_GOODIE);
getWorld()->increaseScore(100);
player->addSquirt();
}
return;
}
/////////////////////////////////////
// Tunnelman Class Implementations //
/////////////////////////////////////
void Tunnelman::doSomething()
{
if (!isAlive())
{
return;
}
int ch;
if (getWorld()->getKey(ch) == true)
{
switch (ch)
{
case KEY_PRESS_UP:
if (getDirection() != up)
{
setDirection(up);
}
else
{
if (getWorld()->noOverlap(getX(), (getY() + 1), this))
{
moveTo(getX(), (getY() + 1));
getWorld()->clearEarth(getX(), getY(), getType());
}
}
moveTo(getX(), getY());
break;
case KEY_PRESS_DOWN:
if (getDirection() != down)
{
setDirection(down);
}
else
{
if (getWorld()->noOverlap(getX(), (getY() - 1), this))
{
moveTo(getX(), (getY() - 1));
getWorld()->clearEarth(getX(), getY(), getType());
}
}
moveTo(getX(), getY());
break;
case KEY_PRESS_RIGHT:
if (getDirection() != right)
{
setDirection(right);
}
else
{
if (getWorld()->noOverlap((getX() + 1), getY(), this))
{
moveTo((getX() + 1), getY());
getWorld()->clearEarth(getX(), getY(), getType());
}
}
moveTo(getX(), getY());
break;
case KEY_PRESS_LEFT:
if (getDirection() != left)
{
setDirection(left);
}
else
{
if (getWorld()->noOverlap((getX() - 1), getY(), this))
{
moveTo((getX() - 1), getY());
getWorld()->clearEarth(getX(), getY(), getType());
}
}
moveTo(getX(), getY());
break;
case KEY_PRESS_ESCAPE:
setDead();
break;
case KEY_PRESS_TAB:
if (getGold() > 0)
{
if (getWorld()->dropGold())
{
reduceGold();
}
}
break;
case 'Z':
case 'z':
if (getSonar() > 0)
{
getWorld()->playSound(SOUND_SONAR);
getWorld()->reveal();
reduceSonar();
}
break;
case KEY_PRESS_SPACE:
if (getSquirt() > 0)
{
getWorld()->playSound(SOUND_PLAYER_SQUIRT);
reduceSquirt();
switch (getDirection())
{
case up:
getWorld()->createSquirt(getX(), (getY() + 4), getDirection());
break;
case down:
getWorld()->createSquirt(getX(), (getY() - 4), getDirection());
break;
case right:
getWorld()->createSquirt((getX() + 4), getY(), getDirection());
break;
case left:
getWorld()->createSquirt((getX() - 4), getY(), getDirection());
break;
}
}
break;
}
}
return;
}
void Tunnelman::annoy(int damage)
{
reduceHealth(damage);
if (getHealth() <= 0)
{
getWorld()->playSound(SOUND_PLAYER_GIVE_UP);
setDead();
}
}
/////////////////////////////////////
// Protester Class Implementations //
/////////////////////////////////////
void Protester::doSomething()
{
// Check if protester is currently alive
if (!isAlive())
{
return;
}
// If protester is "resting" during the current tick, do nothing
if (getRestingTicks() > 0)
{
reduceRestingTicks();
return;
}
else
{
setRestingTicks(getTicksToWaitBetweenMoves());
}
// If protester is leaving the oil field, it must find its way back to the exit point
if (getState() == leaving)
{
if (getX() == 60 && getY() == 60)
{
setDead();
getWorld()->reduceNumProtesters();
}
else
{
int up = getWorld()->shortestPath(this, getX(), getY() + 1, 60, 60);
int down = getWorld()->shortestPath(this, getX(), getY() - 1, 60, 60);
int right = getWorld()->shortestPath(this, getX() + 1, getY(), 60, 60);
int left = getWorld()->shortestPath(this, getX() - 1, getY(), 60, 60);
vector<int> shortest = { up, down, right, left };
sort(shortest.begin(), shortest.end());
if (shortest[0] == up)
{
setDirection(GraphObject::up);
moveTo(getX(), getY() + 1);
}
else if (shortest[0] == down)
{
setDirection(GraphObject::down);
moveTo(getX(), getY() - 1);
}
else if (shortest[0] == right)
{
setDirection(GraphObject::right);
moveTo(getX() + 1, getY());
}
else
{
setDirection(GraphObject::left);
moveTo(getX() - 1, getY());
}
}
return;
}
// Checks to see if Tunnelman is within a distance of 4 units of the Tunnelman
Tunnelman* player = getWorld()->searchForTunnelman(this, 4.0);
if (player != nullptr)
{
bool facingTunnelman = false;
// Checks to see if protester is currently facing the Tunnelman
switch (getDirection())
{
case up:
if (getY() < player->getY())
{
facingTunnelman = true;
}
break;
case down:
if (getY() > player->getY())
{
facingTunnelman = true;
}
break;
case right:
if (getX() < player->getX())
{
facingTunnelman = true;
}
break;
case left:
if (getX() > player->getX())
{
facingTunnelman = true;
}
break;
}
// If both cases mentioned above are satisfied, yell at the Tunnelman
if (getShoutingTicks() <= 0 && facingTunnelman == true)
{
getWorld()->playSound(SOUND_PROTESTER_YELL);
player->annoy(2);
setShoutingTicks(15);
reducePerpendicularTicks();
return;
}
else if (getWorld()->withinLineOfSight(this) != none && facingTunnelman == true) // If the protester is directly facing the tunnelman, stay at its position (do nothing)
{
reduceShoutingTicks();
reducePerpendicularTicks();
moveTo(getX(), getY());
return;
}
else if (facingTunnelman == true) // If the protester is not directly facing the tunnelman, move towards the protester's position
{
switch (getDirection())
{
case up:
if (getY() < player->getY())
{
moveTo(getX(), (getY() + 1));
}
break;
case down:
if (getY() > player->getY())
{
moveTo(getX(), (getY() - 1));
}
break;
case right:
if (getX() < player->getX())
{
moveTo((getX() + 1), getY());
}
break;
case left:
if (getX() > player->getX())
{
moveTo((getX() - 1), getY());
}
break;
}
reduceShoutingTicks();
reducePerpendicularTicks();
return;
}
else // If the protester is in a straight horizontal or vertical line of sight to the Tunnelman, change its direction to face in the direction of the Tunnelman
{
Direction dir = getWorld()->withinLineOfSight(this);
if (dir != none)
{
setDirection(dir);
reduceShoutingTicks();
reducePerpendicularTicks();
moveTo(getX(), getY());
return;
}
}
}
// Otherwise if the protester is more than 4 units away from the Tunnelman
if (!(getWorld()->withinRadiusOfTunnelman(getX(), getY(), 4.0)))
{
if (doDifferentiatedStuff())
{
reduceShoutingTicks();
reducePerpendicularTicks();
if (getShoutingTicks() <= -100)
{
setShoutingTicks(0);
}
if (getPerpendicularTicks() <= -100)
{
setPerpendicularTicks(0);
}
return;
}
// Checks to see if protester is in a straight horizontal or vertical line of sight to the Tunnelman
// AND could actually move the entire way to the Tunnelman with no Earth or Boulders blocking its path
Direction dir = getWorld()->withinLineOfSight(this);
if (dir != none)
{
// change its direction to face in the direction of the Tunnelman
// AND then take one step toward him
setDirection(dir);
switch (dir)
{
case up:
moveTo(getX(), (getY() + 1));
break;
case down:
moveTo(getX(), (getY() - 1));
break;
case right:
moveTo((getX() + 1), getY());
break;
case left:
moveTo((getX() - 1), getY());
break;
}
resetNumSquaresToMove();
reduceShoutingTicks();
reducePerpendicularTicks();
return;
}
}
reduceNumSquaresToMove();
// If the protester has finished walking numSquaresToMove steps in its currently-selected direction
if (getNumSquaresToMove() <= 0)
{
// Protester will pick a random new direction to move
// IF the random direction is blocked either by Earth or a Boulder such that it can't take even a single step
// THEN select a different direction and check it for blockage
// The protester will then change its direction to this new chosen direction
bool isPossible = true;
do
{
isPossible = true;
int randomDir = rand() % 4;
switch (randomDir)
{
case 0: // UP
if (getWorld()->noOverlap(getX(), (getY() + 1), this))
{
setDirection(up);
}
else
{
isPossible = false;
}
break;
case 1: // DOWN
if (getWorld()->noOverlap(getX(), (getY() - 1), this))
{
setDirection(down);
}
else
{
isPossible = false;
}
break;
case 2: // RIGHT
if (getWorld()->noOverlap((getX() + 1), getY(), this))
{
setDirection(right);
}
else
{
isPossible = false;
}
break;
case 3: // LEFT
if (getWorld()->noOverlap((getX() - 1), getY(), this))
{
setDirection(left);
}
else
{
isPossible = false;
}
break;
}
} while (isPossible == false);
randomizeNumSquaresToMove();
}
else if (getPerpendicularTicks() <= 0) // Checks to see if the protester has not made a perpendicular turn in the last 200 non-resting ticks
{
bool changingDirection = true;
// Checks to see if a protester is sitting at an intersection where it could turn
// AND move at least one square in a perpendicular direction from its currently facing direction
switch (getDirection()) // Pick a viable perpendicular direction. If both perpendicular directions are viable, then pick one of the two choices randomly
{
case up:
case down:
if ((getWorld()->noOverlap((getX() + 1), getY(), this)) && (getWorld()->noOverlap((getX() - 1), getY(), this)))
{
int randomDir = rand() % 2;
if (randomDir == 0)
{
setDirection(right); // Sets its direction to the selected perpendicular direction
}
else
{
setDirection(left); // Sets its direction to the selected perpendicular direction
}
}
else if (getWorld()->noOverlap((getX() + 1), getY(), this))
{
setDirection(right); // Sets its direction to the selected perpendicular direction
}
else if (getWorld()->noOverlap((getX() - 1), getY(), this))
{
setDirection(left); // Sets its direction to the selected perpendicular direction
}
else
{
changingDirection = false;
}
break;
case right:
case left:
if ((getWorld()->noOverlap(getX(), (getY() + 1), this)) && (getWorld()->noOverlap(getX(), (getY() - 1), this)))
{
int randomDir = rand() % 2;
if (randomDir == 0)
{
setDirection(up); // Sets its direction to the selected perpendicular direction
}
else
{
setDirection(down); // Sets its direction to the selected perpendicular direction
}
}
else if (getWorld()->noOverlap(getX(), (getY() + 1), this))
{
setDirection(up); // Sets its direction to the selected perpendicular direction
}
else if (getWorld()->noOverlap(getX(), (getY() - 1), this))
{
setDirection(down); // Sets its direction to the selected perpendicular direction
}
else
{
changingDirection = false;
}
break;
}
if (changingDirection)
{
randomizeNumSquaresToMove(); // Pick a new value for numSquaresToMove
setPerpendicularTicks(200);
}
}
bool canMoveHere = false;
// Protester will then attempt to take one step in its currently facing direction
switch (getDirection())
{
case up:
if (getWorld()->noOverlap(getX(), (getY() + 1), this))
{
moveTo(getX(), (getY() + 1));
canMoveHere = true;
}
break;
case down:
if (getWorld()->noOverlap(getX(), (getY() - 1), this))
{
moveTo(getX(), (getY() - 1));
canMoveHere = true;
}
break;
case right:
if (getWorld()->noOverlap((getX() + 1), getY(), this))
{
moveTo((getX() + 1), getY());
canMoveHere = true;
}
break;
case left:
if (getWorld()->noOverlap((getX() - 1), getY(), this))
{
moveTo((getX() - 1), getY());
canMoveHere = true;
}
break;
}
// If the protester is for some reason blocked from taking a step in its currently direction
// It will set numSquaresToMove to zero, resulting in a new direction being chosing during the protester's next non-resting tick
if (!canMoveHere)
{
resetNumSquaresToMove();
}
reduceShoutingTicks();
reducePerpendicularTicks();
if (getShoutingTicks() <= -10000)
{
setShoutingTicks(0);
}
if (getPerpendicularTicks() <= -10000)
{
setPerpendicularTicks(0);
}
return;
}
void Protester::annoy(int damage)
{
reduceHealth(damage);
if (getHealth() > 0)
{
getWorld()->playSound(SOUND_PROTESTER_ANNOYED);
int N = max(50, 100 - static_cast<int>(getWorld()->getLevel()) * 10);
setRestingTicks(N);
}
else
{
setState(leaving);
getWorld()->playSound(SOUND_PROTESTER_GIVE_UP);
setRestingTicks(0);
getPoints(damage);
}
}
void Protester::getPoints(int damage)
{
if (damage == 100)
{
getWorld()->increaseScore(500);
}
else
{
getWorld()->increaseScore(100);
}
}
void Protester::pickGold()
{
getWorld()->playSound(SOUND_PROTESTER_FOUND_GOLD);
getWorld()->increaseScore(25);
setState(leaving);
}
//////////////////////////////////////////////
// Hardcore Protester Class Implementations //
//////////////////////////////////////////////
bool HardcoreProtester::doDifferentiatedStuff()
{
int M = 16 + static_cast<int>(getWorld()->getLevel()) * 2;
int up = getWorld()->shortestPath(this, getX(), getY() + 1, getWorld()->tunnelmanGetX(), getWorld()->tunnelmanGetY());
int down = getWorld()->shortestPath(this, getX(), getY() - 1, getWorld()->tunnelmanGetX(), getWorld()->tunnelmanGetY());
int right = getWorld()->shortestPath(this, getX() + 1, getY(), getWorld()->tunnelmanGetX(), getWorld()->tunnelmanGetY());
int left = getWorld()->shortestPath(this, getX() - 1, getY(), getWorld()->tunnelmanGetX(), getWorld()->tunnelmanGetY());
vector<int> shortest = { up, down, right, left };
sort(shortest.begin(), shortest.end());
if (shortest[0] <= M)
{
if (shortest[0] == up)
{
setDirection(GraphObject::up);
moveTo(getX(), getY() + 1);
}
else if (shortest[0] == down)
{
setDirection(GraphObject::down);
moveTo(getX(), getY() - 1);
}
else if (shortest[0] == right)
{
setDirection(GraphObject::right);
moveTo(getX() + 1, getY());
}
else
{
setDirection(GraphObject::left);
moveTo(getX() - 1, getY());
}
return true;
}
return false;
}
void HardcoreProtester::getPoints(int damage)
{
if (damage == 100)
{
getWorld()->increaseScore(500);
}
else
{
getWorld()->increaseScore(250);
}
}
void HardcoreProtester::pickGold()
{
getWorld()->playSound(SOUND_PROTESTER_FOUND_GOLD);
getWorld()->increaseScore(50);
int ticks_to_stare = max(50, 100 - static_cast<int>(getWorld()->getLevel()) * 10);
setRestingTicks(ticks_to_stare);
} | true |
4ca2790cb54c6c65d05bf650ac23622173528d4f | C++ | Cpasjuste/pscrap | /include/p_search.h | UTF-8 | 1,496 | 2.609375 | 3 | [] | no_license | //
// Created by cpasjuste on 29/03/19.
//
#ifndef PSCRAP_P_SEARCH_H
#define PSCRAP_P_SEARCH_H
#include <vector>
#include <json-c/json.h>
#include "p_movie.h"
namespace pscrap {
class Search {
public:
// TODO: handle tv shows
enum class Type {
Movie,
TvShow
};
/// empty search, to be loaded from file with "load"
Search() = default;
/// search for a movie, using curl and json
explicit Search(const std::string &api_key, const std::string &name,
const std::string &language = "en-US", Type type = Type::Movie);
/// proceed the search
/// return 0 on success, curl error code on error
int get(int *http_code = nullptr);
/// load a saved search from a file
int load(const std::string &srcPath);
/// save a search to a file
int save(const std::string &dstPath);
int page = 0;
int total_results = 0;
int total_pages = 0;
std::vector<Movie> movies;
private:
void parseMovieRoot(const std::string &jsonData);
void parseMovie(json_object *obj);
static bool sortByTitleDistance(const Movie &movie1, const Movie &movie2, const std::string &title);
std::string url;
std::string data;
std::string search;
std::string search_escaped;
std::string api_key;
std::string language;
};
}
#endif //PSCRAP_P_SEARCH_H
| true |
9e2e6e422888f72fc47bb1bcdbf5126bb3fc1d2a | C++ | sander-skjulsvik/IN1910 | /lectures/2019.10.01/throw.cpp | UTF-8 | 863 | 3.328125 | 3 | [] | no_license | #include <iostream>
#include <cmath>
#include <vector>
// using forward euler to solve ode
using namespace std;
struct Sulution
{
vector<double> t;
vector<double> v;
vector<double> y;
};
Sulution vertical_throw(double v0, double y0, double dt, double T, double m, double D){
Sulution sol;
double g = 9.81;
double t = 0;
double v = v0;
double y = y0;
sol.t = {t};
sol.y = {y0};
sol.v = {v0};
while (t < T){
v += dt * (-m * g - D * abs(v) * v);
y += dt*v;
t += dt;
sol.v.push_back(v);
sol.y.push_back(y);
sol.t.push_back(t);
}
return sol;
}
int main(){
double v0 = 1.0;
double y0 =1.0;
double dt = 0.001;
double T = 1.0;
double m = 1.0;
double D = 1.0;
Sulution sol = vertical_throw(v0, y0, dt, T, m, D);
return 0;
} | true |
25788e2b17852cc5e1a1b19c0028ff3e6f3d732c | C++ | sysidos/fuchsia | /src/developer/shell/console/command.cc | UTF-8 | 6,022 | 2.515625 | 3 | [
"BSD-3-Clause"
] | permissive | // Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/developer/shell/console/command.h"
#include <stdlib.h>
#include <regex>
#include <string_view>
#include <vector>
namespace shell::console {
Command::Command() = default;
Command::~Command() = default;
namespace {
// Temporary parser. Delete when we have something good.
bool IsIdentifierChar(char ch) { return isalnum(ch) || ch == '_'; }
class Marker {
public:
Marker(const std::string& str) : source_(str) {}
Marker(const Marker& m, size_t offset) : source_(m.source_.data() + offset) {}
Marker MatchNextIdentifier(const std::string& keyword);
Marker MatchAnyIdentifier(std::string* identifier);
Marker MatchSpecial(const std::string& special);
Marker MatchIntegerLiteral(int64_t* val);
const char* data() { return source_.data(); }
bool operator==(const Marker& other) { return other.source_.data() == source_.data(); }
private:
std::string_view source_;
};
Marker Marker::MatchNextIdentifier(const std::string& keyword) {
size_t pos = 0;
while (std::isspace(source_[pos])) {
pos++;
}
if (source_.find(keyword, pos) == pos &&
(pos == source_.length() || !IsIdentifierChar(source_[pos + keyword.length()]))) {
return Marker(*this, pos + keyword.length());
}
return *this;
}
Marker Marker::MatchAnyIdentifier(std::string* identifier) {
size_t pos = 0;
while (std::isspace(source_[pos])) {
pos++;
}
if (isdigit(source_[pos] || !IsIdentifierChar(source_[pos]))) {
return *this;
}
while (IsIdentifierChar(source_[pos])) {
identifier->push_back(source_[pos]);
pos++;
}
return Marker(*this, pos);
}
Marker Marker::MatchSpecial(const std::string& special) {
size_t pos = 0;
while (std::isspace(source_[pos])) {
pos++;
}
if (source_.find(special, pos) != pos) {
return *this;
}
return Marker(*this, pos + special.length());
}
Marker Marker::MatchIntegerLiteral(int64_t* val) {
size_t pos = 0;
while (std::isspace(source_[pos])) {
pos++;
}
std::string number;
const char* begin = source_.data() + pos;
const char* curr = begin;
while (isdigit(*curr)) {
number += *curr;
curr++;
}
if (*curr == '_') {
if (curr - begin > 3) {
return *this;
}
do {
++curr;
for (int i = 0; i < 3; i++) {
if (!isdigit(*curr)) {
return *this;
}
number += *curr;
curr++;
}
} while (*curr == '_');
}
if (curr == begin) {
return *this;
}
size_t idx;
*val = std::stoll(number, &idx, 10);
if (errno == ERANGE || idx == source_.length()) {
return *this;
}
return Marker(*this, idx);
}
// The result of a parsing step. Contains an updated position (marker()), the node_id of the
// topmost node (node_id()), the type of that node (type()), and whether there was an error
// (result()).
class ParseResult {
public:
ParseResult(const Marker& marker, const Err& err, llcpp::fuchsia::shell::ShellType&& type,
uint64_t node_id)
: marker_(marker), err_(err), type_(std::move(type)), node_id_(node_id) {}
Marker marker() { return marker_; }
Err result() { return err_; }
llcpp::fuchsia::shell::ShellType type() { return std::move(type_); }
uint64_t node_id() { return node_id_; }
private:
Marker marker_;
Err err_;
llcpp::fuchsia::shell::ShellType type_;
uint64_t node_id_;
};
class Parser {
public:
Parser(AstBuilder* builder) : builder_(builder) {}
ParseResult ParseValue(Marker m) {
// int64 Integer literals for now.
int64_t i;
Marker after_int = m.MatchIntegerLiteral(&i);
if (after_int == m) {
return ParseResult(m, Err(kBadParse, "Integer not found"), builder_->undef(), 0);
}
uint64_t node_id = builder_->AddIntegerLiteral(i);
llcpp::fuchsia::shell::BuiltinType type = llcpp::fuchsia::shell::BuiltinType::INTEGER;
llcpp::fuchsia::shell::BuiltinType* type_ptr = builder_->ManageCopyOf(&type);
return ParseResult(after_int, Err(),
llcpp::fuchsia::shell::ShellType::WithBuiltinType(fidl::unowned(type_ptr)),
node_id);
}
ParseResult ParseSimpleExpression(Marker m) {
// Skip some levels for now
return ParseValue(m);
}
ParseResult ParseExpression(Marker m) { return ParseSimpleExpression(m); }
ParseResult ParseVariableDecl(Marker m) {
bool is_const = false;
Marker end_var = m.MatchNextIdentifier("var");
if (end_var == m) {
end_var = m.MatchNextIdentifier("const");
if (end_var == m) {
return ParseResult(m, Err(kBadParse, "Keyword var or const not found"), builder_->undef(),
0);
}
is_const = true;
}
std::string identifier;
Marker end_ident = end_var.MatchAnyIdentifier(&identifier);
if (end_ident == end_var) {
return ParseResult(m, Err(kBadParse, "Identifier not found"), builder_->undef(), 0);
}
Marker end_equals = end_ident.MatchSpecial("=");
if (end_equals == end_ident) {
return ParseResult(m, Err(kBadParse, "'=' not found"), builder_->undef(), 0);
}
ParseResult result = ParseExpression(end_equals);
if (!result.result().ok()) {
return result;
}
uint64_t node_id =
builder_->AddVariableDeclaration(identifier, result.type(), result.node_id(), is_const);
return ParseResult(result.marker(), Err(), builder_->undef(), node_id);
}
private:
AstBuilder* builder_;
};
} // namespace
bool Command::Parse(const std::string& line) {
if (line.empty()) {
return true;
}
Marker marker(line);
AstBuilder builder;
Parser p(&builder);
ParseResult result = p.ParseVariableDecl(marker);
builder.SetRoot(result.node_id());
parse_error_ = result.result();
if (parse_error_.ok()) {
accumulated_nodes_ = std::move(builder);
return true;
}
return false;
}
} // namespace shell::console
| true |
029d19ef2ff42bc94cddc1dbb8cacd09cb280bc0 | C++ | hu2di/c-hust | /Sort/merger.cpp | UTF-8 | 529 | 2.953125 | 3 | [] | no_license | void merge(int a[], int a1, int a2, int a3){
int i, j, k, t;
int temp[10];
i = a1;
j = a2;
k = a1;
while (i < a2 && j <= a3){
if (a[i] < a[j]){
temp[k] = a[i];
i++;
}
else{
temp[k] = a[j];
j++;
}
k++;
}
if (i >= a2)
for (t = j; t <= a3; t++){
temp[k] = a[t];
k++;
}
else
for (t = i; t <= a2; t++){
temp[k] = a[t];
k++;
}
for (k = a1; k <= a3; k++)
a[k] = temp[k];
}
void merge_sort(int a[], int k1, int k3){
int k2;
if (k1 < k3){
k2 = int((k1 + k3)/2);
merge_sort(a, k1, k2);
merge_sort(a, k2 + 1, k3);
merge(a, k1, k2, k3);
}
}
| true |
f4e71cdc058626e521dca9169ac4af67ce4deabb | C++ | tommybutler/mlearnpy2 | /home--tommy--mypy/mypy/lib/python2.7/site-packages/pystan/stan/lib/stan_math/test/unit/math/prim/mat/meta/get_test.cpp | UTF-8 | 523 | 2.5625 | 3 | [
"Unlicense",
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | #include <stan/math/prim/mat.hpp>
#include <gtest/gtest.h>
TEST(MetaTraits, get) {
using stan::get;
Eigen::Matrix<double,Eigen::Dynamic,Eigen::Dynamic> m(2,3);
m << 1, 3, 5,
2, 4, 6;
EXPECT_EQ(1.0, get(m,0));
EXPECT_EQ(3.0, get(m,2));
EXPECT_EQ(6.0, get(m,5));
Eigen::Matrix<double,Eigen::Dynamic,1> rv(2);
rv << 1, 2;
EXPECT_EQ(1.0, get(rv,0));
EXPECT_EQ(2.0, get(rv,1));
Eigen::Matrix<double,1,Eigen::Dynamic> v(2);
v << 1, 2;
EXPECT_EQ(1.0, get(v,0));
EXPECT_EQ(2.0, get(v,1));
}
| true |
b7542857519884d3c37f2a97cb5a50439bfcd641 | C++ | janniklaskeck/studyCpp | /AdvancedCpp/Uebung4/Freespace.cpp | UTF-8 | 299 | 2.609375 | 3 | [] | no_license | #include "Freespace.h"
Freespace::Freespace(Vector2D pos)
{
this->pos = pos;
displayChar = '0';
}
Freespace::~Freespace()
{
}
bool Freespace::isBlocking()
{
return false;
}
bool Freespace::isGoal()
{
return false;
}
void Freespace::render(std::ostream& stream)
{
stream << displayChar;
}
| true |
d8dea138be93a7b709e1fb9378271b61f52ba9fb | C++ | daveRQ/Grafica | /GLFW_GLAD_GLUT_GLEW_cmake_project/src/Tutorial_01/clases.h | UTF-8 | 29,029 | 3.40625 | 3 | [] | no_license | #include <cmath>
#include <vector>
#include <iostream>
using namespace std;
void rotate_x_y(float* arr, float incremento, float x) {
// float incremento = 0.01;
float center = 1.5;
for (int i = 0; i < 2592; i += 8) {
arr[i + 0] = center + (arr[i] - center) * cos(incremento) - (arr[i + 1] - center) * sin(incremento);
arr[i + 1] = center + (arr[i] - center) * sin(incremento) + (arr[i + 1] - center) * cos(incremento);
}
}
void rotate_x_z(float* arr, float incremento, float x) {
// float incremento = 0.01;
float center = 1.5;
for (int i = 0; i < 2592; i += 8) {
arr[i + 0] = center + (arr[i] - center) * cos(incremento) - (arr[i + 2] - center) * sin(incremento);
arr[i + 2] = center + (arr[i] - center) * sin(incremento) + (arr[i + 2] - center) * cos(incremento);
}
}
void rotate_y_z(float* arr, float incremento, float x) {
// float incremento = 0.01;
float center = 1.5;
for (int i = 0; i < 2592; i += 8) {
arr[i + 1] = center + (arr[i + 1] - center) * cos(incremento) - (arr[i + 2] - center) * sin(incremento);
arr[i + 2] = center + (arr[i + 1] - center) * sin(incremento) + (arr[i + 2] - center) * cos(incremento);
}
}
class Vertice {
public:
float pos_x, pos_y, pos_z;
float col_x, col_y, col_z;
float tex_x, tex_y;
Vertice(float px, float py, float pz) {
pos_x = px; pos_y = py; pos_z = pz;
col_x = 0; col_y = 0; col_z = 0;
tex_x = 1; tex_y = 1;
}
void setPosicion(float px, float py, float pz) {
pos_x = px; pos_y = py; pos_z = pz;
}
void setColor(float cx, float cy, float cz) {
col_x = cx; col_y = cy; col_z = cz;
}
void setTextura(float tx, float ty) {
tex_x = tx; tex_y = ty;
}
};
class Cara {
public:
Vertice* v1; Vertice* v2; Vertice* v3; Vertice* v4;
// triangule1: v1, v2, v3
// triangule2: v2, v3, v4
Cara(float v1_x, float v1_y, float v1_z,
float v2_x, float v2_y, float v2_z,
float v3_x, float v3_y, float v3_z,
float v4_x, float v4_y, float v4_z) {
v1 = new Vertice(v1_x, v1_y, v1_z);
v2 = new Vertice(v2_x, v2_y, v2_z);
v3 = new Vertice(v3_x, v3_y, v3_z);
v4 = new Vertice(v4_x, v4_y, v4_z);
v1->setTextura(1.0f, 0.0f);
v2->setTextura(0.0f, 0.0f);
v3->setTextura(1.0f, 1.0f);
v4->setTextura(0.0f, 1.0f);
}
void blanco() {
v1->setColor(1.0, 1.0, 1.0);
v2->setColor(1.0, 1.0, 1.0);
v3->setColor(1.0, 1.0, 1.0);
v4->setColor(1.0, 1.0, 1.0);
}
void rojo() {
v1->setColor(1.0, 0.0, 0.0);
v2->setColor(1.0, 0.0, 0.0);
v3->setColor(1.0, 0.0, 0.0);
v4->setColor(1.0, 0.0, 0.0);
}
void azul() {
v1->setColor(0.0, 0.0, 1.0);
v2->setColor(0.0, 0.0, 1.0);
v3->setColor(0.0, 0.0, 1.0);
v4->setColor(0.0, 0.0, 1.0);
}
void naranja() {
v1->setColor(1.0, 0.5, 0.0);
v2->setColor(1.0, 0.5, 0.0);
v3->setColor(1.0, 0.5, 0.0);
v4->setColor(1.0, 0.5, 0.0);
}
void verde() {
v1->setColor(0.0, 1.0, 0.0);
v2->setColor(0.0, 1.0, 0.0);
v3->setColor(0.0, 1.0, 0.0);
v4->setColor(0.0, 1.0, 0.0);
}
void amarillo() {
v1->setColor(1.0, 1.0, 0.0);
v2->setColor(1.0, 1.0, 0.0);
v3->setColor(1.0, 1.0, 0.0);
v4->setColor(1.0, 1.0, 0.0);
}
void copy_color_cara(Cara* copy) {
v1->setColor(copy->v1->col_x, copy->v1->col_y, copy->v1->col_z);
v2->setColor(copy->v1->col_x, copy->v1->col_y, copy->v1->col_z);
v3->setColor(copy->v1->col_x, copy->v1->col_y, copy->v1->col_z);
v4->setColor(copy->v1->col_x, copy->v1->col_y, copy->v1->col_z);
}
char color() {
if (v1->col_x == 1.0 && v1->col_y == 1.0 && v1->col_z == 1.0)
return 'w';
if (v1->col_x == 1.0 && v1->col_y == 0.0 && v1->col_z == 0.0)
return 'r';
if (v1->col_x == 0.0 && v1->col_y == 0.0 && v1->col_z == 1.0)
return 'b';
if (v1->col_x == 1.0 && v1->col_y == 0.5 && v1->col_z == 0.0)
return 'o';
if (v1->col_x == 0.0 && v1->col_y == 1.0 && v1->col_z == 0.0)
return 'g';
if (v1->col_x == 1.0 && v1->col_y == 1.0 && v1->col_z == 0.0)
return 'y';
}
void modificar(float x, float y, float z) {
v1->pos_x += x; v2->pos_x += x; v3->pos_x += x; v4->pos_x += x;
v1->pos_y += y; v2->pos_y += y; v3->pos_y += y; v4->pos_y += y;
v1->pos_z += z; v2->pos_z += z; v3->pos_z += z; v4->pos_z += z;
}
};
class Cubo {
public:
Cara* cara1; Cara* cara2; Cara* cara3;
Cara* cara4; Cara* cara5; Cara* cara6;
Vertice* v1; Vertice* v2; Vertice* v3; Vertice* v4;
Vertice* v5; Vertice* v6; Vertice* v7; Vertice* v8;
string tipo_cubo;
// las caras formas " Z "
Cubo(float v1_x, float v1_y, float v1_z,
float v2_x, float v2_y, float v2_z,
float v3_x, float v3_y, float v3_z,
float v4_x, float v4_y, float v4_z,
float v5_x, float v5_y, float v5_z,
float v6_x, float v6_y, float v6_z,
float v7_x, float v7_y, float v7_z,
float v8_x, float v8_y, float v8_z,
string _tipo_cubo, float x) {
tipo_cubo = _tipo_cubo;
float value = 0.02;
v1_x += value; v2_x += value; v3_x += value; v4_x += value; v5_x -= value; v6_x -= value; v7_x -= value; v8_x -= value;
v1_y += value; v2_y -= value; v3_y += value; v4_y -= value; v5_y += value; v6_y -= value; v7_y += value; v8_y -= value;
v1_z -= value; v2_z -= value; v3_z += value; v4_z += value; v5_z -= value; v6_z -= value; v7_z += value; v8_z += value;
v1_x += x;
v2_x += x;
v3_x += x;
v4_x += x;
v5_x += x;
v6_x += x;
v7_x += x;
v8_x += x;
v1 = new Vertice(v1_x, v1_y, v1_z); v2 = new Vertice(v2_x, v2_y, v2_z); v3 = new Vertice(v3_x, v3_y, v3_z);
v4 = new Vertice(v4_x, v4_y, v4_z); v5 = new Vertice(v5_x, v5_y, v5_z); v6 = new Vertice(v6_x, v6_y, v6_z);
v7 = new Vertice(v7_x, v7_y, v7_z); v8 = new Vertice(v8_x, v8_y, v8_z);
this->cara1 = new Cara(v1_x, v1_y, v1_z, v2_x, v2_y, v2_z, v3_x, v3_y, v3_z, v4_x, v4_y, v4_z);
this->cara2 = new Cara(v5_x, v5_y, v5_z, v6_x, v6_y, v6_z, v7_x, v7_y, v7_z, v8_x, v8_y, v8_z);
this->cara3 = new Cara(v5_x, v5_y, v5_z, v1_x, v1_y, v1_z, v7_x, v7_y, v7_z, v3_x, v3_y, v3_z);
this->cara4 = new Cara(v6_x, v6_y, v6_z, v2_x, v2_y, v2_z, v8_x, v8_y, v8_z, v4_x, v4_y, v4_z);
this->cara5 = new Cara(v1_x, v1_y, v1_z, v2_x, v2_y, v2_z, v5_x, v5_y, v5_z, v6_x, v6_y, v6_z);
this->cara6 = new Cara(v3_x, v3_y, v3_z, v4_x, v4_y, v4_z, v7_x, v7_y, v7_z, v8_x, v8_y, v8_z);
}
// siempre ocupa 288 posiciones
void add_valores(float* vertices, int ini) {
add_cara1(vertices, ini + (48 * 0));
add_cara2(vertices, ini + (48 * 1));
add_cara3(vertices, ini + (48 * 2));
add_cara4(vertices, ini + (48 * 3));
add_cara5(vertices, ini + (48 * 4));
add_cara6(vertices, ini + (48 * 5));
}
// siempre agrega 48
void add_cara1(float* vertices, int ini) {
// Caras tienen 2 triangulos - 1 2 3 y 2 3 4
*(vertices + ini + 0) = cara1->v1->pos_x;
*(vertices + ini + 1) = cara1->v1->pos_y;
*(vertices + ini + 2) = cara1->v1->pos_z;
*(vertices + ini + 3) = cara1->v1->col_x;
*(vertices + ini + 4) = cara1->v1->col_y;
*(vertices + ini + 5) = cara1->v1->col_z;
*(vertices + ini + 6) = cara1->v1->tex_x;
*(vertices + ini + 7) = cara1->v1->tex_y;
*(vertices + ini + 8) = cara1->v2->pos_x;
*(vertices + ini + 9) = cara1->v2->pos_y;
*(vertices + ini + 10) = cara1->v2->pos_z;
*(vertices + ini + 11) = cara1->v2->col_x;
*(vertices + ini + 12) = cara1->v2->col_y;
*(vertices + ini + 13) = cara1->v2->col_z;
*(vertices + ini + 14) = cara1->v2->tex_x;
*(vertices + ini + 15) = cara1->v2->tex_y;
*(vertices + ini + 16) = cara1->v3->pos_x;
*(vertices + ini + 17) = cara1->v3->pos_y;
*(vertices + ini + 18) = cara1->v3->pos_z;
*(vertices + ini + 19) = cara1->v3->col_x;
*(vertices + ini + 20) = cara1->v3->col_y;
*(vertices + ini + 21) = cara1->v3->col_z;
*(vertices + ini + 22) = cara1->v3->tex_x;
*(vertices + ini + 23) = cara1->v3->tex_y;
// 2da cara (vertex 2 3 4)
*(vertices + ini + 24) = cara1->v2->pos_x;
*(vertices + ini + 25) = cara1->v2->pos_y;
*(vertices + ini + 26) = cara1->v2->pos_z;
*(vertices + ini + 27) = cara1->v2->col_x;
*(vertices + ini + 28) = cara1->v2->col_y;
*(vertices + ini + 29) = cara1->v2->col_z;
*(vertices + ini + 30) = cara1->v2->tex_x;
*(vertices + ini + 31) = cara1->v2->tex_y;
*(vertices + ini + 32) = cara1->v3->pos_x;
*(vertices + ini + 33) = cara1->v3->pos_y;
*(vertices + ini + 34) = cara1->v3->pos_z;
*(vertices + ini + 35) = cara1->v3->col_x;
*(vertices + ini + 36) = cara1->v3->col_y;
*(vertices + ini + 37) = cara1->v3->col_z;
*(vertices + ini + 38) = cara1->v3->tex_x;
*(vertices + ini + 39) = cara1->v3->tex_y;
*(vertices + ini + 40) = cara1->v4->pos_x;
*(vertices + ini + 41) = cara1->v4->pos_y;
*(vertices + ini + 42) = cara1->v4->pos_z;
*(vertices + ini + 43) = cara1->v4->col_x;
*(vertices + ini + 44) = cara1->v4->col_y;
*(vertices + ini + 45) = cara1->v4->col_z;
*(vertices + ini + 46) = cara1->v4->tex_x;
*(vertices + ini + 47) = cara1->v4->tex_y;
}
void add_cara2(float* vertices, int ini) {
// Caras tienen 2 triangulos - 1 2 3 y 2 3 4
*(vertices + ini + 0) = cara2->v1->pos_x;
*(vertices + ini + 1) = cara2->v1->pos_y;
*(vertices + ini + 2) = cara2->v1->pos_z;
*(vertices + ini + 3) = cara2->v1->col_x;
*(vertices + ini + 4) = cara2->v1->col_y;
*(vertices + ini + 5) = cara2->v1->col_z;
*(vertices + ini + 6) = cara2->v1->tex_x;
*(vertices + ini + 7) = cara2->v1->tex_y;
*(vertices + ini + 8) = cara2->v2->pos_x;
*(vertices + ini + 9) = cara2->v2->pos_y;
*(vertices + ini + 10) = cara2->v2->pos_z;
*(vertices + ini + 11) = cara2->v2->col_x;
*(vertices + ini + 12) = cara2->v2->col_y;
*(vertices + ini + 13) = cara2->v2->col_z;
*(vertices + ini + 14) = cara2->v2->tex_x;
*(vertices + ini + 15) = cara2->v2->tex_y;
*(vertices + ini + 16) = cara2->v3->pos_x;
*(vertices + ini + 17) = cara2->v3->pos_y;
*(vertices + ini + 18) = cara2->v3->pos_z;
*(vertices + ini + 19) = cara2->v3->col_x;
*(vertices + ini + 20) = cara2->v3->col_y;
*(vertices + ini + 21) = cara2->v3->col_z;
*(vertices + ini + 22) = cara2->v3->tex_x;
*(vertices + ini + 23) = cara2->v3->tex_y;
// 2da cara (vertex 2 3 4)
*(vertices + ini + 24) = cara2->v2->pos_x;
*(vertices + ini + 25) = cara2->v2->pos_y;
*(vertices + ini + 26) = cara2->v2->pos_z;
*(vertices + ini + 27) = cara2->v2->col_x;
*(vertices + ini + 28) = cara2->v2->col_y;
*(vertices + ini + 29) = cara2->v2->col_z;
*(vertices + ini + 30) = cara2->v2->tex_x;
*(vertices + ini + 31) = cara2->v2->tex_y;
*(vertices + ini + 32) = cara2->v3->pos_x;
*(vertices + ini + 33) = cara2->v3->pos_y;
*(vertices + ini + 34) = cara2->v3->pos_z;
*(vertices + ini + 35) = cara2->v3->col_x;
*(vertices + ini + 36) = cara2->v3->col_y;
*(vertices + ini + 37) = cara2->v3->col_z;
*(vertices + ini + 38) = cara2->v3->tex_x;
*(vertices + ini + 39) = cara2->v3->tex_y;
*(vertices + ini + 40) = cara2->v4->pos_x;
*(vertices + ini + 41) = cara2->v4->pos_y;
*(vertices + ini + 42) = cara2->v4->pos_z;
*(vertices + ini + 43) = cara2->v4->col_x;
*(vertices + ini + 44) = cara2->v4->col_y;
*(vertices + ini + 45) = cara2->v4->col_z;
*(vertices + ini + 46) = cara2->v4->tex_x;
*(vertices + ini + 47) = cara2->v4->tex_y;
}
void add_cara3(float* vertices, int ini) {
// Caras tienen 2 triangulos - 1 2 3 y 2 3 4
*(vertices + ini + 0) = cara3->v1->pos_x;
*(vertices + ini + 1) = cara3->v1->pos_y;
*(vertices + ini + 2) = cara3->v1->pos_z;
*(vertices + ini + 3) = cara3->v1->col_x;
*(vertices + ini + 4) = cara3->v1->col_y;
*(vertices + ini + 5) = cara3->v1->col_z;
*(vertices + ini + 6) = cara3->v1->tex_x;
*(vertices + ini + 7) = cara3->v1->tex_y;
*(vertices + ini + 8) = cara3->v2->pos_x;
*(vertices + ini + 9) = cara3->v2->pos_y;
*(vertices + ini + 10) = cara3->v2->pos_z;
*(vertices + ini + 11) = cara3->v2->col_x;
*(vertices + ini + 12) = cara3->v2->col_y;
*(vertices + ini + 13) = cara3->v2->col_z;
*(vertices + ini + 14) = cara3->v2->tex_x;
*(vertices + ini + 15) = cara3->v2->tex_y;
*(vertices + ini + 16) = cara3->v3->pos_x;
*(vertices + ini + 17) = cara3->v3->pos_y;
*(vertices + ini + 18) = cara3->v3->pos_z;
*(vertices + ini + 19) = cara3->v3->col_x;
*(vertices + ini + 20) = cara3->v3->col_y;
*(vertices + ini + 21) = cara3->v3->col_z;
*(vertices + ini + 22) = cara3->v3->tex_x;
*(vertices + ini + 23) = cara3->v3->tex_y;
// 2da cara (vertex 2 3 4)
*(vertices + ini + 24) = cara3->v2->pos_x;
*(vertices + ini + 25) = cara3->v2->pos_y;
*(vertices + ini + 26) = cara3->v2->pos_z;
*(vertices + ini + 27) = cara3->v2->col_x;
*(vertices + ini + 28) = cara3->v2->col_y;
*(vertices + ini + 29) = cara3->v2->col_z;
*(vertices + ini + 30) = cara3->v2->tex_x;
*(vertices + ini + 31) = cara3->v2->tex_y;
*(vertices + ini + 32) = cara3->v3->pos_x;
*(vertices + ini + 33) = cara3->v3->pos_y;
*(vertices + ini + 34) = cara3->v3->pos_z;
*(vertices + ini + 35) = cara3->v3->col_x;
*(vertices + ini + 36) = cara3->v3->col_y;
*(vertices + ini + 37) = cara3->v3->col_z;
*(vertices + ini + 38) = cara3->v3->tex_x;
*(vertices + ini + 39) = cara3->v3->tex_y;
*(vertices + ini + 40) = cara3->v4->pos_x;
*(vertices + ini + 41) = cara3->v4->pos_y;
*(vertices + ini + 42) = cara3->v4->pos_z;
*(vertices + ini + 43) = cara3->v4->col_x;
*(vertices + ini + 44) = cara3->v4->col_y;
*(vertices + ini + 45) = cara3->v4->col_z;
*(vertices + ini + 46) = cara3->v4->tex_x;
*(vertices + ini + 47) = cara3->v4->tex_y;
}
void add_cara4(float* vertices, int ini) {
// Caras tienen 2 triangulos - 1 2 3 y 2 3 4
*(vertices + ini + 0) = cara4->v1->pos_x;
*(vertices + ini + 1) = cara4->v1->pos_y;
*(vertices + ini + 2) = cara4->v1->pos_z;
*(vertices + ini + 3) = cara4->v1->col_x;
*(vertices + ini + 4) = cara4->v1->col_y;
*(vertices + ini + 5) = cara4->v1->col_z;
*(vertices + ini + 6) = cara4->v1->tex_x;
*(vertices + ini + 7) = cara4->v1->tex_y;
*(vertices + ini + 8) = cara4->v2->pos_x;
*(vertices + ini + 9) = cara4->v2->pos_y;
*(vertices + ini + 10) = cara4->v2->pos_z;
*(vertices + ini + 11) = cara4->v2->col_x;
*(vertices + ini + 12) = cara4->v2->col_y;
*(vertices + ini + 13) = cara4->v2->col_z;
*(vertices + ini + 14) = cara4->v2->tex_x;
*(vertices + ini + 15) = cara4->v2->tex_y;
*(vertices + ini + 16) = cara4->v3->pos_x;
*(vertices + ini + 17) = cara4->v3->pos_y;
*(vertices + ini + 18) = cara4->v3->pos_z;
*(vertices + ini + 19) = cara4->v3->col_x;
*(vertices + ini + 20) = cara4->v3->col_y;
*(vertices + ini + 21) = cara4->v3->col_z;
*(vertices + ini + 22) = cara4->v3->tex_x;
*(vertices + ini + 23) = cara4->v3->tex_y;
// 2da cara (vertex 2 3 4)
*(vertices + ini + 24) = cara4->v2->pos_x;
*(vertices + ini + 25) = cara4->v2->pos_y;
*(vertices + ini + 26) = cara4->v2->pos_z;
*(vertices + ini + 27) = cara4->v2->col_x;
*(vertices + ini + 28) = cara4->v2->col_y;
*(vertices + ini + 29) = cara4->v2->col_z;
*(vertices + ini + 30) = cara4->v2->tex_x;
*(vertices + ini + 31) = cara4->v2->tex_y;
*(vertices + ini + 32) = cara4->v3->pos_x;
*(vertices + ini + 33) = cara4->v3->pos_y;
*(vertices + ini + 34) = cara4->v3->pos_z;
*(vertices + ini + 35) = cara4->v3->col_x;
*(vertices + ini + 36) = cara4->v3->col_y;
*(vertices + ini + 37) = cara4->v3->col_z;
*(vertices + ini + 38) = cara4->v3->tex_x;
*(vertices + ini + 39) = cara4->v3->tex_y;
*(vertices + ini + 40) = cara4->v4->pos_x;
*(vertices + ini + 41) = cara4->v4->pos_y;
*(vertices + ini + 42) = cara4->v4->pos_z;
*(vertices + ini + 43) = cara4->v4->col_x;
*(vertices + ini + 44) = cara4->v4->col_y;
*(vertices + ini + 45) = cara4->v4->col_z;
*(vertices + ini + 46) = cara4->v4->tex_x;
*(vertices + ini + 47) = cara4->v4->tex_y;
}
void add_cara5(float* vertices, int ini) {
// Caras tienen 2 triangulos - 1 2 3 y 2 3 4
*(vertices + ini + 0) = cara5->v1->pos_x;
*(vertices + ini + 1) = cara5->v1->pos_y;
*(vertices + ini + 2) = cara5->v1->pos_z;
*(vertices + ini + 3) = cara5->v1->col_x;
*(vertices + ini + 4) = cara5->v1->col_y;
*(vertices + ini + 5) = cara5->v1->col_z;
*(vertices + ini + 6) = cara5->v1->tex_x;
*(vertices + ini + 7) = cara5->v1->tex_y;
*(vertices + ini + 8) = cara5->v2->pos_x;
*(vertices + ini + 9) = cara5->v2->pos_y;
*(vertices + ini + 10) = cara5->v2->pos_z;
*(vertices + ini + 11) = cara5->v2->col_x;
*(vertices + ini + 12) = cara5->v2->col_y;
*(vertices + ini + 13) = cara5->v2->col_z;
*(vertices + ini + 14) = cara5->v2->tex_x;
*(vertices + ini + 15) = cara5->v2->tex_y;
*(vertices + ini + 16) = cara5->v3->pos_x;
*(vertices + ini + 17) = cara5->v3->pos_y;
*(vertices + ini + 18) = cara5->v3->pos_z;
*(vertices + ini + 19) = cara5->v3->col_x;
*(vertices + ini + 20) = cara5->v3->col_y;
*(vertices + ini + 21) = cara5->v3->col_z;
*(vertices + ini + 22) = cara5->v3->tex_x;
*(vertices + ini + 23) = cara5->v3->tex_y;
// 2da cara (vertex 2 3 4)
*(vertices + ini + 24) = cara5->v2->pos_x;
*(vertices + ini + 25) = cara5->v2->pos_y;
*(vertices + ini + 26) = cara5->v2->pos_z;
*(vertices + ini + 27) = cara5->v2->col_x;
*(vertices + ini + 28) = cara5->v2->col_y;
*(vertices + ini + 29) = cara5->v2->col_z;
*(vertices + ini + 30) = cara5->v2->tex_x;
*(vertices + ini + 31) = cara5->v2->tex_y;
*(vertices + ini + 32) = cara5->v3->pos_x;
*(vertices + ini + 33) = cara5->v3->pos_y;
*(vertices + ini + 34) = cara5->v3->pos_z;
*(vertices + ini + 35) = cara5->v3->col_x;
*(vertices + ini + 36) = cara5->v3->col_y;
*(vertices + ini + 37) = cara5->v3->col_z;
*(vertices + ini + 38) = cara5->v3->tex_x;
*(vertices + ini + 39) = cara5->v3->tex_y;
*(vertices + ini + 40) = cara5->v4->pos_x;
*(vertices + ini + 41) = cara5->v4->pos_y;
*(vertices + ini + 42) = cara5->v4->pos_z;
*(vertices + ini + 43) = cara5->v4->col_x;
*(vertices + ini + 44) = cara5->v4->col_y;
*(vertices + ini + 45) = cara5->v4->col_z;
*(vertices + ini + 46) = cara5->v4->tex_x;
*(vertices + ini + 47) = cara5->v4->tex_y;
}
void add_cara6(float* vertices, int ini) {
// Caras tienen 2 triangulos - 1 2 3 y 2 3 4
*(vertices + ini + 0) = cara6->v1->pos_x;
*(vertices + ini + 1) = cara6->v1->pos_y;
*(vertices + ini + 2) = cara6->v1->pos_z;
*(vertices + ini + 3) = cara6->v1->col_x;
*(vertices + ini + 4) = cara6->v1->col_y;
*(vertices + ini + 5) = cara6->v1->col_z;
*(vertices + ini + 6) = cara6->v1->tex_x;
*(vertices + ini + 7) = cara6->v1->tex_y;
*(vertices + ini + 8) = cara6->v2->pos_x;
*(vertices + ini + 9) = cara6->v2->pos_y;
*(vertices + ini + 10) = cara6->v2->pos_z;
*(vertices + ini + 11) = cara6->v2->col_x;
*(vertices + ini + 12) = cara6->v2->col_y;
*(vertices + ini + 13) = cara6->v2->col_z;
*(vertices + ini + 14) = cara6->v2->tex_x;
*(vertices + ini + 15) = cara6->v2->tex_y;
*(vertices + ini + 16) = cara6->v3->pos_x;
*(vertices + ini + 17) = cara6->v3->pos_y;
*(vertices + ini + 18) = cara6->v3->pos_z;
*(vertices + ini + 19) = cara6->v3->col_x;
*(vertices + ini + 20) = cara6->v3->col_y;
*(vertices + ini + 21) = cara6->v3->col_z;
*(vertices + ini + 22) = cara6->v3->tex_x;
*(vertices + ini + 23) = cara6->v3->tex_y;
// 2da cara (vertex 2 3 4)
*(vertices + ini + 24) = cara6->v2->pos_x;
*(vertices + ini + 25) = cara6->v2->pos_y;
*(vertices + ini + 26) = cara6->v2->pos_z;
*(vertices + ini + 27) = cara6->v2->col_x;
*(vertices + ini + 28) = cara6->v2->col_y;
*(vertices + ini + 29) = cara6->v2->col_z;
*(vertices + ini + 30) = cara6->v2->tex_x;
*(vertices + ini + 31) = cara6->v2->tex_y;
*(vertices + ini + 32) = cara6->v3->pos_x;
*(vertices + ini + 33) = cara6->v3->pos_y;
*(vertices + ini + 34) = cara6->v3->pos_z;
*(vertices + ini + 35) = cara6->v3->col_x;
*(vertices + ini + 36) = cara6->v3->col_y;
*(vertices + ini + 37) = cara6->v3->col_z;
*(vertices + ini + 38) = cara6->v3->tex_x;
*(vertices + ini + 39) = cara6->v3->tex_y;
*(vertices + ini + 40) = cara6->v4->pos_x;
*(vertices + ini + 41) = cara6->v4->pos_y;
*(vertices + ini + 42) = cara6->v4->pos_z;
*(vertices + ini + 43) = cara6->v4->col_x;
*(vertices + ini + 44) = cara6->v4->col_y;
*(vertices + ini + 45) = cara6->v4->col_z;
*(vertices + ini + 46) = cara6->v4->tex_x;
*(vertices + ini + 47) = cara6->v4->tex_y;
}
Cubo* copy_cubo2() {
Cubo* cub = new Cubo(
v1->pos_x, v1->pos_y, v1->pos_z,
v2->pos_x, v2->pos_y, v2->pos_z,
v3->pos_x, v3->pos_y, v3->pos_z,
v4->pos_x, v4->pos_y, v4->pos_z,
v5->pos_x, v5->pos_y, v5->pos_z,
v6->pos_x, v6->pos_y, v6->pos_z,
v7->pos_x, v7->pos_y, v7->pos_z,
v8->pos_x, v8->pos_y, v8->pos_z,
tipo_cubo, 0
);
cub->cara1->v1->col_x = cara1->v1->col_x;
cub->cara1->v1->col_y = cara1->v1->col_y;
cub->cara1->v1->col_z = cara1->v1->col_z;
cub->cara1->v2->col_x = cara1->v2->col_x;
cub->cara1->v2->col_y = cara1->v2->col_y;
cub->cara1->v2->col_z = cara1->v2->col_z;
cub->cara1->v3->col_x = cara1->v3->col_x;
cub->cara1->v3->col_y = cara1->v3->col_y;
cub->cara1->v3->col_z = cara1->v3->col_z;
cub->cara1->v4->col_x = cara1->v4->col_x;
cub->cara1->v4->col_y = cara1->v4->col_y;
cub->cara1->v4->col_z = cara1->v4->col_z;
cub->cara2->v1->col_x = cara2->v1->col_x;
cub->cara2->v1->col_y = cara2->v1->col_y;
cub->cara2->v1->col_z = cara2->v1->col_z;
cub->cara2->v2->col_x = cara2->v2->col_x;
cub->cara2->v2->col_y = cara2->v2->col_y;
cub->cara2->v2->col_z = cara2->v2->col_z;
cub->cara2->v3->col_x = cara2->v3->col_x;
cub->cara2->v3->col_y = cara2->v3->col_y;
cub->cara2->v3->col_z = cara2->v3->col_z;
cub->cara2->v4->col_x = cara2->v4->col_x;
cub->cara2->v4->col_y = cara2->v4->col_y;
cub->cara2->v4->col_z = cara2->v4->col_z;
cub->cara3->v1->col_x = cara3->v1->col_x;
cub->cara3->v1->col_y = cara3->v1->col_y;
cub->cara3->v1->col_z = cara3->v1->col_z;
cub->cara3->v2->col_x = cara3->v2->col_x;
cub->cara3->v2->col_y = cara3->v2->col_y;
cub->cara3->v2->col_z = cara3->v2->col_z;
cub->cara3->v3->col_x = cara3->v3->col_x;
cub->cara3->v3->col_y = cara3->v3->col_y;
cub->cara3->v3->col_z = cara3->v3->col_z;
cub->cara3->v4->col_x = cara3->v4->col_x;
cub->cara3->v4->col_y = cara3->v4->col_y;
cub->cara3->v4->col_z = cara3->v4->col_z;
cub->cara4->v1->col_x = cara4->v1->col_x;
cub->cara4->v1->col_y = cara4->v1->col_y;
cub->cara4->v1->col_z = cara4->v1->col_z;
cub->cara4->v2->col_x = cara4->v2->col_x;
cub->cara4->v2->col_y = cara4->v2->col_y;
cub->cara4->v2->col_z = cara4->v2->col_z;
cub->cara4->v3->col_x = cara4->v3->col_x;
cub->cara4->v3->col_y = cara4->v3->col_y;
cub->cara4->v3->col_z = cara4->v3->col_z;
cub->cara4->v4->col_x = cara4->v4->col_x;
cub->cara4->v4->col_y = cara4->v4->col_y;
cub->cara4->v4->col_z = cara4->v4->col_z;
cub->cara5->v1->col_x = cara5->v1->col_x;
cub->cara5->v1->col_y = cara5->v1->col_y;
cub->cara5->v1->col_z = cara5->v1->col_z;
cub->cara5->v2->col_x = cara5->v2->col_x;
cub->cara5->v2->col_y = cara5->v2->col_y;
cub->cara5->v2->col_z = cara5->v2->col_z;
cub->cara5->v3->col_x = cara5->v3->col_x;
cub->cara5->v3->col_y = cara5->v3->col_y;
cub->cara5->v3->col_z = cara5->v3->col_z;
cub->cara5->v4->col_x = cara5->v4->col_x;
cub->cara5->v4->col_y = cara5->v4->col_y;
cub->cara5->v4->col_z = cara5->v4->col_z;
cub->cara6->v1->col_x = cara6->v1->col_x;
cub->cara6->v1->col_y = cara6->v1->col_y;
cub->cara6->v1->col_z = cara6->v1->col_z;
cub->cara6->v2->col_x = cara6->v2->col_x;
cub->cara6->v2->col_y = cara6->v2->col_y;
cub->cara6->v2->col_z = cara6->v2->col_z;
cub->cara6->v3->col_x = cara6->v3->col_x;
cub->cara6->v3->col_y = cara6->v3->col_y;
cub->cara6->v3->col_z = cara6->v3->col_z;
cub->cara6->v4->col_x = cara6->v4->col_x;
cub->cara6->v4->col_y = cara6->v4->col_y;
cub->cara6->v4->col_z = cara6->v4->col_z;
return cub;
}
void add_value(Cubo* t) {
cara1->copy_color_cara(t->cara1);
cara2->copy_color_cara(t->cara2);
cara3->copy_color_cara(t->cara3);
cara4->copy_color_cara(t->cara4);
cara5->copy_color_cara(t->cara5);
cara6->copy_color_cara(t->cara6);
}
void modificar(float x, float y, float z) {
cara1->v1->pos_x += x; cara1->v2->pos_x += x; cara1->v3->pos_x += x; cara1->v4->pos_x += x; cara2->v1->pos_x += x;
cara2->v2->pos_x += x; cara2->v3->pos_x += x; cara2->v4->pos_x += x; cara3->v1->pos_x += x; cara3->v2->pos_x += x;
cara3->v3->pos_x += x; cara3->v4->pos_x += x; cara4->v1->pos_x += x; cara4->v2->pos_x += x; cara4->v3->pos_x += x;
cara4->v4->pos_x += x; cara5->v1->pos_x += x; cara5->v2->pos_x += x; cara5->v3->pos_x += x; cara5->v4->pos_x += x;
cara6->v1->pos_x += x; cara6->v2->pos_x += x; cara6->v3->pos_x += x; cara6->v4->pos_x += x;
cara1->v1->pos_y += y; cara1->v2->pos_y += y; cara1->v3->pos_y += y; cara1->v4->pos_y += y; cara2->v1->pos_y += y;
cara2->v2->pos_y += y; cara2->v3->pos_y += y; cara2->v4->pos_y += y; cara3->v1->pos_y += y; cara3->v2->pos_y += y;
cara3->v3->pos_y += y; cara3->v4->pos_y += y; cara4->v1->pos_y += y; cara4->v2->pos_y += y; cara4->v3->pos_y += y;
cara4->v4->pos_y += y; cara5->v1->pos_y += y; cara5->v2->pos_y += y; cara5->v3->pos_y += y; cara5->v4->pos_y += y;
cara6->v1->pos_y += y; cara6->v2->pos_y += y; cara6->v3->pos_y += y; cara6->v4->pos_y += y;
cara1->v1->pos_z += z; cara1->v2->pos_z += z; cara1->v3->pos_z += z; cara1->v4->pos_z += z; cara2->v1->pos_z += z;
cara2->v2->pos_z += z; cara2->v3->pos_z += z; cara2->v4->pos_z += z; cara3->v1->pos_z += z; cara3->v2->pos_z += z;
cara3->v3->pos_z += z; cara3->v4->pos_z += z; cara4->v1->pos_z += z; cara4->v2->pos_z += z; cara4->v3->pos_z += z;
cara4->v4->pos_z += z; cara5->v1->pos_z += z; cara5->v2->pos_z += z; cara5->v3->pos_z += z; cara5->v4->pos_z += z;
cara6->v1->pos_z += z; cara6->v2->pos_z += z; cara6->v3->pos_z += z; cara6->v4->pos_z += z;
}
};
| true |
28e67ab45473b21522cee4f54de041e15891f338 | C++ | Riverside-City-College-Computer-Science/CSC5_Winter_2014_40375 | /cr2439879/Home Rate/main.cpp | UTF-8 | 694 | 3.296875 | 3 | [] | no_license | /*
* File: main.cpp
* Author: Cody Rudd
* Created on January 13, 2014, 11:32 AM
* Cheaper To Buy Or Rent
*/
//System Libraries
#include <iostream>
#include <cmath>
//Global Constants
//Function Prototypes
//Execution Begins Here
using namespace std;
int main(int argc, char** argv) {
//Declare Variables
float l,r,t,p;
//Input Loan, Rate, and time
cout<<"What is the loan taken?"<<endl;
cin>>l;
cout<<"What is the rate % ?"<<endl;
cin>>r;
cout<<"How many payment in a year?"<<endl;
cin>>t;
//Calculate cost
float temp=pow(1+r,t);
p=r*temp*l/(temp-1);
//Output Payment
cout<<"Payment per month = $"<<p/12<<endl;
return 0;
}
| true |
dd1d3bf1ba7c4eb92b9c5a022948466fb2d31ce6 | C++ | EngravedMemories/guo_jiacheng | /郭佳承 3-6 第六章作业1/6.28/main.cpp | UTF-8 | 285 | 2.765625 | 3 | [] | no_license | #include <iostream>
using namespace std;
int isperfect()
{
int a=0,i=1,f=0;
for(a=2;a<=1000;a++)
{
f=0;
for(i=1;i<a;i++)
{
if(a%i==0)
f+=i;
}
if(f==a)
cout<<a<<endl;
}
return a;
}
int main()
{
isperfect();
return 0;
}
| true |
4fe2d39a64f8be7eb25d128c3a3a180cc82cc2d4 | C++ | Magnuskodd/TDT4102 | /Øving5/Øving5/Blackjack.cpp | UTF-8 | 1,356 | 3.25 | 3 | [] | no_license | #include "std_lib_facilities.h"
#include "Card.h"
#include<string>
#include<locale>
vector<int> getSum(vector<Card> summer) {
int sum = 0;
int sumWithAce = 0;
bool canBlackjack = false;
for (auto card : summer) {
switch(card.getRank()) {
case Rank::ace:
sum += 1;
sumWithAce += 11;
break;
case Rank::king:
sum += 10;
sumWithAce += 10;
break;
case Rank::queen:
sum += 10;
sumWithAce += 10;
break;
case Rank::jack:
sum += 10;
sumWithAce += 10;
break;
default:
int adder = static_cast<int>(card.getRank()) + 2;
sum += adder;
sumWithAce += adder;
break;
}
}
vector<int> sumsVector{ sum, sumWithAce };
return sumsVector;
}
bool blackjack(vector<Card> user) {
bool isBlackjack = false;
if (user.size() == 2) {
if (user[0].getRank() == Rank::ace) {
if (static_cast<int>(user[1].getRank()) <= 11 && static_cast<int>(user[1].getRank()) >= 8) {
isBlackjack = true;
}
}
else if (static_cast<int>(user[0].getRank()) <= 11 && static_cast<int>(user[0].getRank()) >= 8) {
if (user[1].getRank() == Rank::ace) {
isBlackjack = true;
}
}
}
return isBlackjack;
}
int getMax(vector<int> summer) {
int max = 0;
if (summer[1] > 21) {
max = summer[0];
}
else {
max = summer[1];
}
return max;
} | true |
bb78d4aa1b04b2aee014f85e15c98de6c68c0732 | C++ | lineCode/ArchiveGit | /Clients/Powerhouse/Autorun/Autorun (generic)/Autorun.cpp | UTF-8 | 22,983 | 2.546875 | 3 | [] | no_license | // INI search values for the APP's path
#define INI_FILENAME "pinoc.ini"
#define INI_SECTION "Options"
#define INI_KEY "Path"
// Define the application
#define APP_EXE "pinoc.exe"
#define APP_ARGS ""
#define APP_CD_LABEL ""
#define APP_CLASS "pinoc"
// If the app is not found...
#define SETUP_EXE "setup.exe"
#define SETUP_CD_LABEL "Introduction"
// What about us?
#define AUTORUN_CLASS "autorun"
#define AUTORUN_TITLE "The Adventures of Pinocchio"
// Button names
#define IDS_CONTINUE "Play"
#define IDS_INSTALL "Setup"
#define IDS_EXIT "Cancel"
// Header files
#include <windows.h>
#include <windowsx.h>
#include <memory.h>
#include "autorun.h"
#ifndef WIN32
#define DRIVE_UNKNOWN 0
#define DRIVE_NO_ROOT_DIR 1
#define DRIVE_REMOVABLE 2
#define DRIVE_FIXED 3
#define DRIVE_REMOTE 4
#define DRIVE_CDROM 5
#define DRIVE_RAMDISK 6
#endif WIN32
// Global Variables:
static HINSTANCE g_hInst; // current instance
static char g_szAppPath[_MAX_PATH];
static HPALETTE g_hpal;
static HBITMAP g_hbmAutoRun;
// Foward declarations of functions included in this code module:
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);
int OnCreate(HWND hWnd);
//************************************************************************
LPSTR FixPath( LPSTR lpPath )
//************************************************************************
{
int length;
if ( !(length = lstrlen(lpPath)) )
return( lpPath );
while ( length && (lpPath[length-1] == '\n' || lpPath[length-1] == '\r') )
lpPath[--length] = '\0';
if ( !length )
return( lpPath );
if ( lpPath[length-1] != '\\' )
lstrcat( lpPath, "\\" );
return( lpPath );
}
#ifndef WIN32
//************************************************************************/
BOOL IsCDROM(WORD DriveNumber)
//************************************************************************/
{
BOOL bCDfound = FALSE;
_asm mov ax,01500h
_asm xor bx,bx
_asm int 02Fh
_asm or bx,bx
_asm jz Done
_asm mov ax,0150bh
_asm mov cx,DriveNumber
_asm int 02Fh
_asm or ax,ax
_asm jz Done
bCDfound = TRUE;
Done:
return bCDfound;
}
#endif WIN32
//************************************************************************/
UINT GetExtendedDriveType(int i)
//************************************************************************/
{
char szPath[256];
szPath[0] = i + 'a';
szPath[1] = ':';
szPath[2] = '\\';
szPath[3] = '\0';
UINT DriveType = GetDriveType( szPath );
#ifndef WIN32
switch (DriveType)
{
case DRIVE_REMOTE:
if (IsCDROM(i))
DriveType = DRIVE_CDROM;
break;
}
#endif WIN32
return DriveType;
}
/***********************************************************************/
int Print( LPSTR lpFormat, ... )
/***********************************************************************/
{
// Put up a modal message box with arguments specified exactly like printf
LPSTR lpArguments = (LPSTR)&lpFormat + sizeof(lpFormat);
char szBuffer[512];
wvsprintf( szBuffer, lpFormat, (LPSTR)lpArguments );
HWND hFocusWindow = GetFocus();
// Load app name resource
int retc = MessageBox( hFocusWindow/*MessageParent*/, szBuffer, AUTORUN_TITLE, MB_OK );
SetFocus( hFocusWindow );
return( retc );
}
/***********************************************************************/
int PrintOKCancel( LPSTR lpFormat, ... )
/***********************************************************************/
{
// Put up a modal message box with arguments specified exactly like printf
LPSTR lpArguments = (LPSTR)&lpFormat + sizeof(lpFormat);
char szBuffer[512];
wvsprintf( szBuffer, lpFormat, (LPSTR)lpArguments );
HWND hFocusWindow = GetFocus();
// Load app name resource
int retc = MessageBox( hFocusWindow/*MessageParent*/, szBuffer, AUTORUN_TITLE, MB_OKCANCEL );
SetFocus( hFocusWindow );
return( retc );
}
/************************************************************************/
BOOL FileExists( LPSTR lpFileName, LPSTR lpCDLabel )
/************************************************************************/
{
UINT errmode = SetErrorMode(SEM_FAILCRITICALERRORS);
// see if installed path is cool
OFSTRUCT of;
if ( OpenFile( lpFileName, &of, OF_EXIST ) != HFILE_ERROR )
{
SetErrorMode(errmode);
return( TRUE );
}
if ( !lpCDLabel || !lstrlen(lpCDLabel) )
{
SetErrorMode(errmode);
return( FALSE );
}
// keep trying to we get it or user gives up
while (TRUE)
{
// see if there is a CDROM drive that exists with our program on it.
for (int drive = 0; drive < 26; ++drive)
{
UINT type = GetExtendedDriveType(drive);
if (type == DRIVE_CDROM)
{
lpFileName[0] = drive + 'a';
if ( OpenFile( lpFileName, &of, OF_EXIST ) != HFILE_ERROR )
break;
}
else
if (type == 1)
{
drive = 26;
break;
}
}
// see if we found the file somewhere
if (drive < 26)
break; // file was found
// ask user to insert CD into cdrom drive
if (PrintOKCancel("Please insert the '%s' disk to continue.", (LPSTR)lpCDLabel) == IDCANCEL)
{
SetErrorMode(errmode);
return( FALSE );
}
// keep trying
}
SetErrorMode(errmode);
return( TRUE );
}
/************************************************************************/
BOOL IsInstalled()
/************************************************************************/
{
g_szAppPath[0] = '\0';
GetPrivateProfileString(INI_SECTION, INI_KEY, "", g_szAppPath, sizeof(g_szAppPath), INI_FILENAME);
FixPath(g_szAppPath);
lstrcat(g_szAppPath, APP_EXE);
if (lstrlen(g_szAppPath))
return(FileExists(g_szAppPath, APP_CD_LABEL));
else
return FALSE;
}
//************************************************************************
LPCSTR FileName( LPCSTR lpPath )
//************************************************************************
{
LPCSTR lp = lpPath + lstrlen( lpPath );
while( *lp != '\\' && *lp != ':' )
{
if ( (--lp) < lpPath )
return( lpPath + lstrlen(lpPath) ); // null string
}
lp++;
return( lp ); // the file name
}
//************************************************************************
LPSTR StripFile( LPSTR lpPath )
//************************************************************************
{
LPSTR lp;
if ( lp = (LPSTR)FileName( lpPath ) )
*lp = '\0';
return( lpPath );
}
//************************************************************************
BOOL ActivateApp()
//************************************************************************
{
HWND hwnd = FindWindow(AUTORUN_CLASS, NULL);
if (!hwnd)
return FALSE;
// We found another version of ourself. Lets defer to it:
if (IsIconic(hwnd))
ShowWindow(hwnd, SW_RESTORE);
#ifdef WIN32
SetForegroundWindow(GetLastActivePopup(hwnd));
#else
SetActiveWindow(GetLastActivePopup(hwnd));
#endif
// If this app actually had any functionality, we would
// also want to communicate any action that our 'twin'
// should now perform based on how the user tried to
// execute us.
return TRUE;
}
/************************************************************************/
BOOL InitApplication(HINSTANCE hInstance)
/************************************************************************/
{
// Win32 will always set hPrevInstance to NULL, so lets check
// things a little closer. This is because we only want a single
// version of this app to run at a time
#ifdef WIN32
if (ActivateApp())
return FALSE;
#endif
// Fill in window class structure with parameters that describe
// the main window.
WNDCLASS wc;
wc.lpszClassName = AUTORUN_CLASS;
wc.style = CS_HREDRAW | CS_VREDRAW;
wc.lpfnWndProc = WndProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = hInstance;
wc.lpszMenuName = NULL;
wc.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(-1));
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
return RegisterClass(&wc);
}
/************************************************************************/
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
/************************************************************************/
{
HWND hWnd = CreateWindow(AUTORUN_CLASS, AUTORUN_TITLE,
WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU, 0, 0, 0, 0,
NULL, NULL, hInstance, NULL);
if (!hWnd)
return FALSE;
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
return TRUE;
}
/************************************************************************/
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
/************************************************************************/
{
// Store instance handle in our global variable
g_hInst = hInstance;
// see if application we launch is already running
if (FindWindow(APP_CLASS, NULL))
return FALSE;
if (!hPrevInstance)
{ // Will always be TRUE on Windows 95
// Perform instance initialization:
if (!InitApplication(hInstance))
return FALSE;
}
else
{
ActivateApp();
return FALSE;
}
// Perform application initialization:
if (!InitInstance(hInstance, nCmdShow))
return FALSE;
HACCEL hAccelTable = LoadAccelerators(hInstance, AUTORUN_CLASS);
// Main message loop:
MSG msg;
while (GetMessage(&msg, NULL, 0, 0))
{
if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
return (msg.wParam);
lpCmdLine; // This will prevent 'unused formal parameter' warnings
}
/************************************************************************/
BOOL LaunchApplication(void)
/************************************************************************/
{
char szImagePath[_MAX_PATH];
lstrcpy(szImagePath, g_szAppPath);
lstrcat(szImagePath, " ");
lstrcat(szImagePath, APP_ARGS);
if ( !FileExists(szImagePath, APP_CD_LABEL ) )
return( FALSE );
#ifdef WIN32
STARTUPINFO si;
PROCESS_INFORMATION pi;
si.cb = sizeof(STARTUPINFO);
// Yeah, this could be done with a 'memset', but this is more illustrative:
si.lpReserved = NULL;
si.lpDesktop = NULL;
si.lpTitle = NULL;
si.dwX = NULL;
si.dwY = NULL;
si.dwXSize = NULL;
si.dwYSize = NULL;
si.dwXCountChars = NULL;
si.dwYCountChars = NULL;
si.dwFillAttribute = NULL;
si.dwFlags = NULL;
si.wShowWindow = NULL;
si.cbReserved2 = NULL;
si.lpReserved2 = NULL;
si.hStdInput = NULL;
si.hStdOutput = NULL;
si.hStdError = NULL;
return CreateProcess(NULL, szImagePath, NULL, NULL, FALSE,
CREATE_NEW_PROCESS_GROUP, NULL, NULL, &si, &pi);
#else
UINT err = WinExec(szImagePath, SW_SHOW);
return (err >= 32);
#endif
}
/************************************************************************/
BOOL LaunchSetup(void)
/************************************************************************/
{
char szImagePath[_MAX_PATH];
GetModuleFileName(g_hInst, szImagePath, sizeof(szImagePath));
StripFile(szImagePath);
lstrcat(szImagePath, SETUP_EXE);
if ( !FileExists(szImagePath, SETUP_CD_LABEL ) )
return( FALSE );
#ifdef WIN32
STARTUPINFO si;
PROCESS_INFORMATION pi;
si.cb = sizeof(STARTUPINFO);
// Yeah, this could be done with a 'memset', but this is more illustrative:
si.lpReserved = NULL;
si.lpDesktop = NULL;
si.lpTitle = NULL;
si.dwX = NULL;
si.dwY = NULL;
si.dwXSize = NULL;
si.dwYSize = NULL;
si.dwXCountChars = NULL;
si.dwYCountChars = NULL;
si.dwFillAttribute = NULL;
si.dwFlags = NULL;
si.wShowWindow = NULL;
si.cbReserved2 = NULL;
si.lpReserved2 = NULL;
si.hStdInput = NULL;
si.hStdOutput = NULL;
si.hStdError = NULL;
return CreateProcess(NULL, szImagePath, NULL, NULL, FALSE,
CREATE_NEW_PROCESS_GROUP, NULL, NULL, &si, &pi);
#else
UINT err = WinExec(szImagePath, SW_SHOW);
return (err >= 32);
#endif
}
/************************************************************************/
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
/************************************************************************/
{
int wmId, wmEvent;
switch (message)
{
case WM_CREATE:
{
return OnCreate(hWnd);
}
case WM_PALETTECHANGED:
{
if ((HWND)wParam == hWnd)
break;
}
// fall through to WM_QUERYNEWPALETTE
case WM_QUERYNEWPALETTE:
{
HDC hdc = GetDC(hWnd);
if (g_hpal)
SelectPalette(hdc, g_hpal, FALSE);
UINT uMappedColors = RealizePalette(hdc);
ReleaseDC(hWnd,hdc);
if (uMappedColors>0)
{
InvalidateRect(hWnd,NULL,TRUE);
return TRUE;
}
else
return FALSE;
break;
}
case WM_COMMAND:
{
wmId = LOWORD(wParam); // Remember, these are...
wmEvent = HIWORD(wParam); // ...different for Win32!
switch (wmId)
{
case IDM_CONTINUE:
if (!LaunchApplication())
{
// failed to launch your application, you need
// to decide what to do in this case and add code
// to do that here. You can use GetLastError() to
// determine the cause of this failure.
// Print( "Can't find '%ls'", (LPSTR)APP_EXE );
}
else
PostMessage(hWnd, WM_CLOSE, 0, 0);
break;
case IDM_INSTALL:
if (!LaunchSetup())
{
// failed to launch your application, you need
// to decide what to do in this case and add code
// to do that here. You can use GetLastError() to
// determine the cause of this failure.
// Print( "Can't find '%ls'", (LPSTR)SETUP_EXE );
}
else
PostMessage(hWnd, WM_CLOSE, 0, 0);
break;
case IDM_EXIT:
DestroyWindow(hWnd);
break;
default:
return (DefWindowProc(hWnd, message, wParam, lParam));
}
break;
}
case WM_PAINT:
{
RECT rect; // Used in WM_PAINT
HDC hdcSrc; // Used in WM_PAINT
HBITMAP hbmOld; // Used in WM_PAINT
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hWnd, &ps);
SelectPalette(hdc, g_hpal, FALSE);
RealizePalette(hdc);
GetClientRect(hWnd, &rect);
hdcSrc = CreateCompatibleDC(hdc);
hbmOld = (HBITMAP)SelectObject(hdcSrc, g_hbmAutoRun);
SelectPalette(hdcSrc, g_hpal, FALSE);
RealizePalette(hdcSrc);
// Get the bitmap data
BITMAP bm;
GetObject(g_hbmAutoRun, sizeof(BITMAP), &bm);
if (!BitBlt(hdc, 0, 0, bm.bmWidth, bm.bmHeight, hdcSrc, 0, 0, SRCCOPY))
MessageBeep(0);
SelectObject(hdcSrc, hbmOld);
DeleteDC(hdcSrc);
EndPaint(hWnd, &ps);
break;
}
case WM_DESTROY:
{
// Tell WinHelp we don't need it any more...
WinHelp(hWnd, "autorun.hlp", HELP_QUIT,(DWORD)0);
DeleteObject(g_hpal);
DeleteObject(g_hbmAutoRun);
PostQuitMessage(0);
break;
}
default:
return (DefWindowProc(hWnd, message, wParam, lParam));
}
return (0);
}
// This is a 'utility' function I find usefull. It will center one
// window over another. It also makes sure that the placement is within
// the 'working area', meaning that it is both within the display limits
// of the screen, -and- not obscured by the tray or other frameing
// elements of the desktop.
/************************************************************************/
BOOL CenterWindow(HWND hwndChild, HWND hwndParent)
/************************************************************************/
{
RECT rChild, rParent, rWorkArea = {0,0,0,0};
int wChild, hChild, wParent, hParent;
int wScreen, hScreen, xScreen, yScreen, xNew, yNew;
// Get the Height and Width of the child window
GetWindowRect(hwndChild, &rChild);
wChild = rChild.right - rChild.left;
hChild = rChild.bottom - rChild.top;
// Get the Height and Width of the parent window
GetWindowRect(hwndParent, &rParent);
wParent = rParent.right - rParent.left;
hParent = rParent.bottom - rParent.top;
// Get the limits of the 'workarea'
#ifdef WIN32
#if !defined(SPI_GETWORKAREA)
#define SPI_GETWORKAREA 48
#endif
BOOL bResult = SystemParametersInfo(
SPI_GETWORKAREA, // system parameter to query or set
sizeof(RECT), // depends on action to be taken
&rWorkArea, // depends on action to be taken
0);
wScreen = rWorkArea.right - rWorkArea.left;
hScreen = rWorkArea.bottom - rWorkArea.top;
xScreen = rWorkArea.left;
yScreen = rWorkArea.top;
#else
wScreen = hScreen = xScreen = yScreen = 0;
#endif
// On Windows NT, the above metrics aren't valid (yet), so they all return
// '0'. Lets deal with that situation properly:
if (wScreen==0 && hScreen==0)
{
wScreen = GetSystemMetrics(SM_CXSCREEN);
hScreen = GetSystemMetrics(SM_CYSCREEN);
xScreen = 0; // These values should already be '0', but just in case
yScreen = 0;
}
// Calculate new X position, then adjust for screen
xNew = rParent.left + ((wParent - wChild) /2);
if (xNew < xScreen)
xNew = xScreen;
else
if ((xNew+wChild) > wScreen)
xNew = (xScreen + wScreen) - wChild;
// Calculate new Y position, then adjust for screen
yNew = rParent.top + ((hParent - hChild) /2);
if (yNew < yScreen)
yNew = yScreen;
else
if ((yNew+hChild) > hScreen)
yNew = (yScreen + hScreen) - hChild;
// Set it, and return
return SetWindowPos(hwndChild, NULL, xNew, yNew, 0, 0, SWP_NOSIZE | SWP_NOZORDER);
}
/************************************************************************/
LPBITMAPFILEHEADER ReadBitmap(LPSTR lpFileName)
/************************************************************************/
{
OFSTRUCT of;
HFILE fh;
if ( (fh = OpenFile(lpFileName, &of, OF_READ)) < 0 )
return(NULL);
DWORD dwSize = _llseek(fh, 0, 2);
_llseek(fh, 0, 0);
LPBITMAPFILEHEADER lp = (LPBITMAPFILEHEADER)GlobalAllocPtr(GPTR, dwSize);
if (!lp)
return(NULL);
// read in the bits
_hread( fh, lp, dwSize );
_lclose( fh );
return(lp);
}
// This function will be called when the WM_CREATE message is processed
// by our application. This is where we will load the bitmap to be
// displayed, create a palette for the image, resize the window to fit
// the bitmap, and put in our control buttons that will allow the user
// to tell us how to proceed.
/************************************************************************/
int OnCreate(HWND hWnd)
/************************************************************************/
{
HDC hdc = GetDC(hWnd);
if ( !hdc )
{
Print( "Can't get DC" );
return(-1);
}
g_hpal = NULL;
char szFileName[_MAX_PATH];
GetModuleFileName(g_hInst, szFileName, sizeof(szFileName));
StripFile(szFileName);
lstrcat(szFileName, "title.bmp");
LPBITMAPFILEHEADER lpbfh = ReadBitmap(szFileName);
if (!lpbfh)
{
Print( "Can't find 'title.bmp'" );
return(-1);
}
LPBITMAPINFO lpbmi = (LPBITMAPINFO)((LPSTR)lpbfh + sizeof(BITMAPFILEHEADER));
// How many colors does it use?:
int cColors = (int)lpbmi->bmiHeader.biClrUsed;
if (cColors == 0)
cColors = (1 << (int)(lpbmi)->bmiHeader.biBitCount);
// Use that to determine where the actual bitmap image starts:
LPVOID pimage = &(lpbmi->bmiColors[cColors]);
// Now lets create a palette based on the image we loaded:
LPLOGPALETTE plgpl = (LPLOGPALETTE )GlobalAllocPtr(GPTR, sizeof(LOGPALETTE) + (cColors-1)*sizeof(PALETTEENTRY));
if (!plgpl)
{
Print( "Can't allocate palette memory" );
return -1; // failure
}
plgpl->palVersion = 0x300;
plgpl->palNumEntries = cColors;
for (int i=0; i<cColors; i++)
{
plgpl->palPalEntry[i].peRed = lpbmi->bmiColors[i].rgbRed;
plgpl->palPalEntry[i].peGreen = lpbmi->bmiColors[i].rgbGreen;
plgpl->palPalEntry[i].peBlue = lpbmi->bmiColors[i].rgbBlue;
//plgpl->palPalEntry[i].peFlags = PC_NOCOLLAPSE; // is this needed?
}
g_hpal = CreatePalette(plgpl);
// And free up the memory we allocated:
GlobalFreePtr(plgpl);
if (!g_hpal)
{
Print( "Can't create a palette" );
return -1; // Fail on no palette
}
// Now create a true DIBitmap from all of this:
// First assign the palette to the DC:
SelectPalette(hdc, g_hpal, FALSE);
RealizePalette(hdc);
// Now create a DIB based off the the DC with the bitmap image from the resource:
g_hbmAutoRun = CreateDIBitmap(hdc, (BITMAPINFOHEADER FAR *)lpbmi,
CBM_INIT, pimage, lpbmi, DIB_RGB_COLORS);
GlobalFreePtr(lpbfh);
if (!g_hbmAutoRun)
{
Print( "Can't create a dib" );
return(-1);
}
// Get the bitmap data
BITMAP bm;
GetObject(g_hbmAutoRun, sizeof(BITMAP), &bm);
SetWindowPos(hWnd, NULL, 0, 0, bm.bmWidth, bm.bmHeight,
SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE);
// Since what we really want to do is size the 'Client' window,
// Lets find out how far off we were, adjust our values, and
// try it again...
RECT rect;
GetClientRect(hWnd, &rect);
int x = bm.bmWidth - (rect.right-rect.left);
int y = bm.bmHeight - (rect.bottom-rect.top);
SetWindowPos(hWnd, NULL, 0, 0, bm.bmWidth+x,
bm.bmHeight+y, SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE);
CenterWindow(hWnd, GetDesktopWindow());
// Ok, our image is loaded, and our window properly sized
// Lets add in some controls: The text to use for these
// buttons is coming out of the resource of this app
int id;
char szString[20];
if (IsInstalled())
{
id = IDM_CONTINUE;
lstrcpy( szString, IDS_CONTINUE );
}
else
{
id = IDM_INSTALL;
lstrcpy( szString, IDS_INSTALL );
}
HWND hwndBtnOk = CreateWindow("BUTTON", szString,
WS_CHILD | WS_CLIPSIBLINGS | WS_VISIBLE | BS_DEFPUSHBUTTON,
0, 0, 0, 0,
hWnd, (HMENU)id, g_hInst, NULL);
lstrcpy( szString, IDS_EXIT );
HWND hwndBtnExit = CreateWindow("BUTTON", szString,
WS_CHILD | WS_CLIPSIBLINGS | WS_VISIBLE | BS_PUSHBUTTON,
0, 0, 0, 0,
hWnd, (HMENU)IDM_EXIT, g_hInst, NULL);
HFONT hfontBtn = (HFONT)GetStockObject(ANSI_VAR_FONT);
SendMessage(hwndBtnOk, WM_SETFONT, (WPARAM)hfontBtn,(LPARAM)TRUE);
SendMessage(hwndBtnExit, WM_SETFONT, (WPARAM)hfontBtn, (LPARAM)TRUE);
SelectObject(hdc, hfontBtn);
TEXTMETRIC tm;
GetTextMetrics(hdc, &tm);
int iHeight = (tm.tmHeight + tm.tmExternalLeading) * 2;
int iWidth = (bm.bmWidth / 2) - (iHeight * 2);
x = ((bm.bmWidth/2) / 2) - (iWidth/2);
y = bm.bmHeight - iHeight - (iHeight/2);
SetWindowPos(hwndBtnOk, NULL, x, y, iWidth, iHeight,
SWP_NOZORDER | SWP_NOACTIVATE);
x += bm.bmWidth/2;
SetWindowPos(hwndBtnExit, NULL, x, y, iWidth, iHeight,
SWP_NOZORDER | SWP_NOACTIVATE);
ShowWindow(hWnd, SW_SHOW);
ReleaseDC(hWnd, hdc);
return 0; // Sucess
}
| true |
5bfd9732566dc206120b035df589f2ffc8e2cf90 | C++ | Althis974/PiscineCPP | /day05/ex04/srcs/main.cpp | UTF-8 | 3,572 | 2.703125 | 3 | [] | no_license | /* ************************************************************************** */
/* LE - / */
/* / */
/* main.cpp .:: .:/ . .:: */
/* +:+:+ +: +: +:+:+ */
/* By: rlossy <rlossy@student.le-101.fr> +:+ +: +: +:+ */
/* #+# #+ #+ #+# */
/* Created: 2019/12/17 10:58:11 by rlossy #+# ## ## #+# */
/* Updated: 2019/12/17 10:58:11 by rlossy ### #+. /#+ ###.fr */
/* / */
/* / */
/* ************************************************************************** */
#include "../includes/Bureaucrat.hpp"
#include "../includes/Intern.hpp"
#include "../includes/OfficeBlock.hpp"
#include <iostream>
#include <stdexcept>
int main()
{
std::cout << "\n----- Presentation -----\n" << std::endl;
Intern idiotOne;
Bureaucrat hermes = Bureaucrat("Hermes Conrad", 37);
Bureaucrat bob = Bureaucrat("Bobby Bobson", 123);
OfficeBlock ob;
std::cout << hermes << std::endl;
std::cout << bob << std::endl;
std::cout << "\n----- Try to work without employees -----\n" << std::endl;
try
{
ob.doBureaucracy("RobotomyRequest", "Clappy");
}
catch (std::exception &e)
{
std::cout << e.what() << std::endl;
}
ob.setIntern(&idiotOne);
std::cout << "\n----- Try to work with intern only -----\n" << std::endl;
try
{
ob.doBureaucracy("RobotomyRequest", "Clappy");
}
catch (std::exception &e)
{
std::cout << e.what() << std::endl;
}
ob.setSigner(&bob);
std::cout << "\n----- Try to work with intern and signer -----\n"
<< std::endl;
try
{
ob.doBureaucracy("RobotomyRequest", "Clappy");
}
catch (std::exception &e)
{
std::cout << e.what() << std::endl;
}
ob.setExecutor(&bob);
std::cout << "\n----- Try to work with full team -----\n" << std::endl;
try
{
ob.doBureaucracy("RobotomyRequest", "Clappy");
}
catch (std::exception &e)
{
std::cout << e.what() << std::endl;
}
ob.setSigner(&hermes);
std::cout << "\n----- Try to switch bob with hermes as signer -----\n"
<< std::endl;
try
{
ob.doBureaucracy("RobotomyRequest", "Clappy");
}
catch (std::exception &e)
{
std::cout << e.what() << std::endl;
}
ob.setExecutor(&hermes);
std::cout << "\n----- Finally bob is useless -----\n" << std::endl;
try
{
ob.doBureaucracy("RobotomyRequest", "Clappy");
}
catch (std::exception &e)
{
std::cout << e.what() << std::endl;
}
Bureaucrat armando = Bureaucrat("Armando", 50);
Bureaucrat lucca = Bureaucrat("Lucca", 115);
std::cout << "\n----- Ritals try to make us compete -----\n" << std::endl;
try
{
OfficeBlock ritals(nullptr, &lucca, &armando);
}
catch (std::exception &e)
{
std::cout << e.what() << std::endl;
}
Intern pedro;
OfficeBlock ritals(&pedro, &lucca, &armando);
std::cout << "\n----- They are persistent -----\n" << std::endl;
try
{
ritals.doBureaucracy("", "peaky");
}
catch (std::exception &e)
{
std::cout << e.what() << std::endl;
}
std::cout << "\n----- Wow they finally did something that works -----\n"
<< std::endl;
try
{
ritals.doBureaucracy("ShrubberyCreation", "Hall");
}
catch (std::exception &e)
{
std::cout << e.what() << std::endl;
}
return (0);
} | true |
88adf9b655c5bc9d917ee1880555e0938fed3bf2 | C++ | rongyi/lintcode | /src/binary-representation.cc | UTF-8 | 2,231 | 3.296875 | 3 | [] | no_license | // http://www.lintcode.com/zh-cn/problem/binary-representation
#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
#include <unordered_set>
#include <vector>
using std::vector;
using std::cout;
using std::endl;
using std::string;
using std::unordered_set;
class Solution {
public:
/**
*@param n: Given a decimal number that is passed in as a string
*@return: A string
*/
string binaryRepresentation(string n) {
std::stringstream ss;
string interger_part;
string decimal_part;
if (n.find_first_of('.', 0) == std::string::npos) {
interger_part = n;
} else {
interger_part = n.substr(0, n.find_first_of('.'));
decimal_part = n.substr(n.find_first_of('.') + 1);
}
// cout << interger_part << endl;
// cout << decimal_part << endl;
// integer part
string binary_int;
int i = std::stoi(interger_part);
bool is_negtive = i < 0;
if (i == std::numeric_limits<int>::min()) {
for (unsigned j = 0; j < sizeof(int); j++) {
ss << "1";
}
} else if (i == 0) {
binary_int = "0";
} else {
i = std::abs(i);
while (i != 0) {
ss << (i & 0x1);
i >>= 1;
}
binary_int = ss.str();
// for decimal part
ss.clear();
std::reverse(binary_int.begin(), binary_int.end());
}
// integer part done
unordered_set<double> decimal_set;
string binary_dec;
if (decimal_part != "" && std::stoll(decimal_part) != 0) {
double d = std::stod("0." + decimal_part);
while (d > 0) {
if (binary_dec.size() > 32 ||
decimal_set.find(d) != decimal_set.end()) {
return "ERROR";
}
decimal_set.insert(d);
d *= 2;
if (d >= 1) {
binary_dec += "1";
d -= 1;
} else {
binary_dec += "0";
}
}
}
string ret;
if (binary_dec != "") {
ret = binary_int + "." + binary_dec;
} else {
ret = binary_int;
}
if (is_negtive) {
ret.insert(0, "-");
}
return ret;
}
};
int main() {
Solution so;
auto ret = so.binaryRepresentation("28187281.128121212121");
cout << ret << endl;
return 0;
}
| true |
3c1e023d684df25303851ac4c2c873fac13df61b | C++ | RyoIwanaga/civ | /Console/Console.h | UTF-8 | 1,596 | 2.796875 | 3 | [] | no_license | #ifndef _Console_h_
#define _Console_h_
#include <cassert>
#include "../World.h"
#include "../Util.h"
//#include "Window.h"
namespace Console {
#include <curses.h>
enum class Color : short {
Player1 = 10,
Player2,
Player3,
Player4,
Player5,
Player6,
Player7,
Player8,
};
short makeColorPlayer(ushort player)
{
return player + 10;
}
void initialize()
{
// The very first thing to do: Before you use any other curses routines, the initscr() routine must be called first.
// If your program is going to write to several terminals, you should call newterm instead, which is another story.
initscr();
// One-character-a-time. To disable the buffering of typed characters by the TTY driver and get a character-at-a-time input, you need to call
cbreak();
// No echo. To suppress the automatic echoing of typed characters, you need to call
noecho();
// Special keys. In order to capture special keystrokes like Backspace, Delete and the four arrow keys by getch(), you need to call
keypad(stdscr, TRUE);
start_color();
init_pair(1, COLOR_WHITE, COLOR_BLACK);
init_pair(2, COLOR_WHITE, COLOR_GREEN);
init_pair(3, COLOR_WHITE, COLOR_BLUE);
init_pair(static_cast<int>(Color::Player1), COLOR_WHITE, COLOR_BLUE);
init_pair(static_cast<int>(Color::Player2), COLOR_WHITE, COLOR_RED);
init_pair(static_cast<int>(Color::Player3), COLOR_WHITE, COLOR_YELLOW);
}
void finalize ()
{
// Before exiting. Before the program is terminated, endwin() must be called to restore the terminal settings.
endwin();
}
} // end of namespace Console
#endif // _Console_h_
| true |
8ed7c06900d847d39b022dc77b3a2b310ffbd3c0 | C++ | ROKAF-CV/Homework_JB | /chapter/chapter3/algorithm3.cpp | UHC | 1,710 | 2.8125 | 3 | [] | no_license | #include "Edge.h"
void edge() {
Mat origin = imread("Lenna.jpg", 0);
Edge edge(origin);
Mat out(origin.size(), origin.type());
Mat out2(origin.size(), origin.type());
edge.gaussian_blur(origin, out, 0.5);
GaussianBlur(origin, out2, Size(7, 7), 1.0);
imshow("out", out);
imshow("out2", out2);
waitKey();
}
void sobel() {
Mat origin = imread("Lenna.jpg", 0);
Edge edge(origin);
Mat out(origin.size(), CV_32F);
Mat out_x ,out_y;
edge.sobelOp(origin, out, 'y');
//edge.sobelOp(origin, out, 'x');
Sobel(origin, out_x, CV_32F, 1,0);
Sobel(origin, out_y, CV_32F, 0,1);
imshow("out", out);
imshow("x", out_x);
imshow("y", out_y);
waitKey();
}
void LOG() {
Mat origin = imread("Lenna.jpg", 0);
Edge edge(origin);
Mat out(origin.size(), origin.type());
edge.zerocrossing_detection(origin, out, 0.7, 1.0);
imshow("out", out);
waitKey();
}
void canny() {
Mat origin = imread("example.jpg", 0);
imshow("origin11", origin);
Edge edge(origin);
Mat out;
Mat out2(origin.size(), origin.type());
std::chrono::system_clock::time_point start = std::chrono::system_clock::now();
edge.canny_edge(origin, out, 60.0, 20.0);
std::chrono::duration<double> sec = std::chrono::system_clock::now() - start;
std::cout << "Test() Լ ϴ ɸ ð() : " << sec.count() << " seconds" << std::endl;
start = std::chrono::system_clock::now();
Canny(origin, out2, 20, 60);
sec = std::chrono::system_clock::now() - start;
std::cout << "Test() Լ ϴ ɸ ð() : " << sec.count() << " seconds" << std::endl;
imshow("origin", origin);
imshow("out", out);
imshow("out2", out2);
waitKey();
}
int main() {
//sobel();
//canny();
LOG();
return 0;
} | true |
d7e696f169c97d00039a6d2c829bb5485175ebed | C++ | bisqwit/crt-filter | /blur.hh | UTF-8 | 2,957 | 3.25 | 3 | [] | no_license | #include <cmath>
/* blur(): Really fast O(n) gaussian blur algorithm (gaussBlur_4)
* By Ivan Kuckir with ideas from Wojciech Jarosz
* Adapted from http://blog.ivank.net/fastest-gaussian-blur.html
*
* input: The two-dimensional array of input signal. Must contain w*h elements.
* output: Where the two-dimensional array of blurred signal will be written
* temp: Another array, for temporary use. Same size as input and output.
* w: Width of array
* h: Height of array.
* sigma: Blurring kernel size. Must be smaller than w and h.
* n_boxes: Controls the blurring quality. 1 = box filter. 3 = pretty good filter.
* Higher number = diminishingly better results, but linearly slower.
* elem_t: Type of elements. Should be integer type.
*/
template<unsigned n_boxes, typename elem_t>
void blur(const elem_t* input, elem_t* output, elem_t* temp,
unsigned w,unsigned h,float sigma)
{
auto wIdeal = std::sqrt((12*sigma*sigma/n_boxes)+1); // Ideal averaging filter width
unsigned wl = wIdeal; if(wl%2==0) --wl;
unsigned wu = wl+2;
auto mIdeal = (12*sigma*sigma - n_boxes*wl*wl - 4*n_boxes*wl - 3*n_boxes)/(-4.*wl - 4);
unsigned m = std::round(mIdeal);
const elem_t* data = input;
for(unsigned n=0; n<n_boxes; ++n)
{
unsigned r = ((n<m ? wl : wu) - 1)/2; // IDK should this be float?
// boxBlur_4:
float iarr = 1.f / (r+r+1);
// boxBlurH_4 (blur horizontally for each row):
const elem_t* scl = data; elem_t* tcl = temp;
for(unsigned i=0; i<h; ++i)
{
auto ti = i*w, li = ti, ri = ti+r;
auto fv = scl[ti], lv = scl[ti+w-1]; int val = 0;
#pragma omp simd reduction(+:val)
for(unsigned j=0; j<r; j++) val += scl[ti+j];
val += (r+1)*fv;
for(unsigned j=0 ; j<=r ; j++) { val += scl[ri++] - fv ; tcl[ti++] = std::round(val*iarr); }
for(unsigned j=r+1; j<w-r; j++) { val += scl[ri++] - scl[li++]; tcl[ti++] = std::round(val*iarr); }
for(unsigned j=w-r; j<w ; j++) { val += lv - scl[li++]; tcl[ti++] = std::round(val*iarr); }
}
// boxBlurT_4 (blur vertically for each column)
scl = temp; tcl = output;
for(unsigned i=0; i<w; ++i)
{
auto ti = i, li = ti, ri = ti+r*w;
auto fv = scl[ti], lv = scl[ti+w*(h-1)]; int val = 0;
#pragma omp simd reduction(+:val)
for(unsigned j=0; j<r; ++j) val += scl[ti + j*w];
val += (r+1)*fv;
for(unsigned j=0; j<=r; ++j) { val += scl[ri] - fv ; tcl[ti] = std::round(val*iarr); ri+=w; ti+=w; }
for(unsigned j=r+1; j<h-r; ++j) { val += scl[ri] - scl[li]; tcl[ti] = std::round(val*iarr); li+=w; ri+=w; ti+=w; }
for(unsigned j=h-r; j<h; ++j) { val += lv - scl[li]; tcl[ti] = std::round(val*iarr); li+=w; ti+=w; }
}
data = output;
}
}
| true |
221de2cb2e7057578fea34a1bd5ae656b2276910 | C++ | tonnas/uva_online_judge | /cpp/573.cpp | UTF-8 | 595 | 3.28125 | 3 | [] | no_license |
#include <iostream>
using namespace std;
int main()
{
int count;
double height, night, day, percent, h;
bool success;
while (cin >> height >> day >> night >> percent)
{
if (height == 0) break;
count = 0;
h = 0;
percent = day * percent / 100;
while (1)
{
count++;
h += day;
day -= percent;
if (day < 0) day = 0;
if (h > height)
{
success = true;
break;
}
h -= night;
if (h < 0)
{
success = false;
break;
}
}
if (success) cout << "success";
else cout << "failure";
cout << " on day " << count << endl;
}
return 0;
}
| true |
c62653200e2efa21e8795d73d1d7acf241f1e9e6 | C++ | ShaunNaude/COS214_GP | /include/Planets/Planet.h | UTF-8 | 1,375 | 2.6875 | 3 | [] | no_license | //
// Created by danienel21 on 2019/10/19.
//
#ifndef COS214_GP_PLANET_H
#define COS214_GP_PLANET_H
#include <vector>
#include <string>
class Spaceships;
class Route;
class Critter;
using namespace std;
class Planet {
private:
string planetName;
int relationship;
int resources;
private:
int threatLevel;
vector<Critter*> crittersPlanet;
vector<Spaceships*> friendlyShips;
protected:
bool discovered;
bool habitable;
string status;
public:
Planet(string name , int resources);
void addFriendlyShip(Spaceships* s);
void removeFriendlyShip(Spaceships* s);
////////////////////////////////////////
///// getters & setters
////////////////////////////////////////
int getResources();
bool isHabitable() const;
void setHabitable(bool habitable);
bool isDiscovered() const;
void setDiscovered(bool discovered);
string getPlanetName();
const string &getStatus() const;
void setStatus(const string &status);
void setRelationship(int num);
void incRelationship();
void decRelationship();
int getRelationship();
const vector<Critter *> &getCrittersPlanet() const;
void addBasicCritters(int num);
int getThreatLevel();
void setResources(int resources);
void addResources(int resources);
void attackPlanet();
};
#endif //COS214_GP_PLANET_H
| true |
0f38df6a19e2a8e565a5df9e4185644ffadce437 | C++ | mikeyb1337/RomanCalc | /RomanCalculatorStarter/RomanNumber.hpp | UTF-8 | 2,144 | 3.078125 | 3 | [] | no_license | //
// Created by HOME on 10/19/2021.
//
#ifndef ROMANCALCULATORSTARTER_ROMANNUMBER_H
#define ROMANCALCULATORSTARTER_ROMANNUMBER_H
#include <vector>
#include <string>
#include "Token.hpp"
#include "InfixToPostfix.hpp"
#include "Tokenizer.hpp"
class RomanNumber {
public:
void print(){
std::cout << _decimalValue << std::endl;
std::cout << _romanNumber << std::endl;
}
RomanNumber() {}
RomanNumber(int n){ _decimalValue = n; _romanNumber = decimalToRoman( n ); }
RomanNumber( std::string s){ _romanNumber = s; _decimalValue = romanToDecimal( s ); }
RomanNumber operator+ (const RomanNumber& c) const
{
RomanNumber result;
result._decimalValue = this->_decimalValue + c._decimalValue;
return result;
}
void operator= (const int c) {
this->setDecimalValue( c );
}
RomanNumber operator- (const RomanNumber& c) const
{
RomanNumber result;
result._decimalValue = this->_decimalValue - c._decimalValue;
return result;
}
RomanNumber operator* (const RomanNumber& c) const
{
RomanNumber result;
result._decimalValue = this->_decimalValue * c._decimalValue;
return result;
}
RomanNumber operator/ (const RomanNumber& c) const
{
RomanNumber result;
result._decimalValue = this->_decimalValue / c._decimalValue;
return result;
}
RomanNumber operator% (const RomanNumber& c) const
{
RomanNumber result;
result._decimalValue = this->_decimalValue % c._decimalValue;
return result;
}
int romanToDecimal( std::string );
std::string decimalToRoman( int n );
void setRomanNumber( std::string s );
void setDecimalValue( int n );
int getDecimalValue() { return _decimalValue;}
std::string getRomanNumber() { return _romanNumber;}
private:
bool isAValidRomanNumber( std::string _romanNumber );
std::string _romanNumber;
int _decimalValue;
};
#endif //ROMANCALCULATORSTARTER_ROMANNUMBER_H
| true |
f9e85d12fc87594737730d22a1d861ee511f4913 | C++ | naresh569/shs-server | /Sessions.hpp | UTF-8 | 2,955 | 3.390625 | 3 | [] | no_license |
#pragma once
#include "Config.hpp"
class Session {
public:
int _id;
int userId;
char* token;
char* timeOfStart;
Session(int);
~Session();
void generateToken();
char* getToken();
static int total;
static Session* createSession(int);
static void display();
static int getUserId(char*);
} *sessions[MAXUSERS];
int Session :: total = 0;
Session :: Session(int puserId) {
_id = total + 1;
userId = puserId;
token = "";
generateToken();
timeOfStart = "";
total++;
}
Session :: ~Session() {
total--;
}
void Session :: generateToken() {
token = new char[SIZENORMAL];
token[0] = 0;
long randInt;
for (int i = 0; i < LENGTHTOKEN; i++) {
long randInt = random(97, 123);
concat(token, (char) randInt);
}
// Serial.print(" > Generated token: ");
// Serial.println(token);
}
char* Session :: getToken() {
return token;
}
Session* Session :: createSession(int puserId) {
int index = -1;
for (int i = 0; i < MAXUSERS; i++) {
// By default, place the session in the first available position
if (sessions[i] == NULL) {
// Serial.println(" > Session NULL");
if (index == -1)
index = i;
continue;
}
// If session for the user already exists, release that session
// create new session in that place
if (sessions[i]->userId == puserId) {
index = i;
delete sessions[index];
}
}
if (index == -1) {
Serial.println(" > ERROR: Limit for max sessions reached..");
return NULL;
}
// Serial.print(" > Placing position for the session: ");
// Serial.println(index);
sessions[index] = new Session(puserId);
return sessions[index];
}
void Session :: display() {
int t = total;
Serial.println();
Serial.print(" > Total sessions: ");
Serial.println(t);
if (!t)
return;
Serial.println(" # SESSIONS\nSNo\tUserID\tToken");
short int count = 0;
for(int i = 0; i < MAXUSERS; i++) {
if (sessions[i] == NULL)
continue;
count++;
Serial.print(count);
Serial.print("\t");
Serial.print(sessions[i]->userId);
Serial.print("\t");
Serial.println(sessions[i]->token);
}
Serial.println();
}
int Session :: getUserId(char* tk) {
if (!tk) {
Serial.println(" > ERROR: Given token is invalid!");
return 0;
}
int t = total;
if (!t) {
Serial.println(" > ERROR: No sessions available!");
return 0;
}
int userId = 0;
for(int i = 0; i < MAXUSERS; i++) {
if (sessions[i] == NULL)
continue;
if (equals(sessions[i]->token, tk, true)) {
userId = sessions[i]->userId;
break;
}
}
return userId;
}
| true |
74b7aa68ecb79640a9a9a7f00ecdd56c138acf53 | C++ | ZhiyLiu/optim | /Correspondence_Oct7/Pablo2_Oct7/lib/m3d/include/M3DFigurePredictor.h | UTF-8 | 2,134 | 2.796875 | 3 | [] | no_license | #ifndef M3D_FIGUREE_PREDICTOR_H
#define M3D_FIGUREE_PREDICTOR_H
#include "M3DFigure.h"
struct SimilarityTransform
{
Vector3D COR; // center of rotation, defaulted as the COG
Matrix cov; // covariance matrix
Matrix rotM; // rotation matrix
Quat rotQ; // rotation quaternion
double scale; // scale
Vector3D trans; // translation
Vector3D transTemp;
};
class M3DFigurePredictor
{
public:
// Either the newFigure or the newPrimitives hold the predicting "link"
// atoms specified by linkCount and linkIds[].
// Note: the predicted figure will be stored back in *figure, instead
// of *newFigure
M3DFigurePredictor(int linkCount, int *linkIds, M3DFigure *figure,
M3DFigure *newFigure);
M3DFigurePredictor(int linkCount, int *linkIds, M3DFigure *figure,
M3DPrimitive **newPrimitives);
// Predict the arbitrarily cut end of the bones by the rest of the atoms.
// Only the "link" atoms specified by realLinkCoiunt/realLinkIds are
// used inthe estimation of the similarity transformation.
M3DFigurePredictor(int linkCount, int *linkIds, int realLinkCount,
int *realLinkIds, M3DFigure *figure, M3DFigure *newFigure);
~M3DFigurePredictor() {}
const SimilarityTransform * bestTransform() { return &bestSim; }
private:
// Estimate the best similarity transformation given two sets of points
// []x and []y.
void estimateSimilarityTransformation(int n, Vector3D *x, Vector3D *y,
SimilarityTransform *sTrans, Vector3D *COG=NULL);
// Main prediction function
// linkCount/linkIds the # and indices of the "link" atoms
// figure the entire figure, with the atoms before transformation
// newLinkAtoms all the "link" atoms after the transformation
// the predicted figure will be stored back to *figure
void predictFigureByLinkAtoms(int linkCount, int *linkIds, M3DFigure *figure,
M3DPrimitive **newLinkAtoms);
// Prediction function for the arbitrarily cut end of the bones
void predictFigureByLinkAtoms(int linkCount, int *linkIds, int realLinkCount,
int *realLinkIds, M3DFigure *figure, M3DPrimitive **newLinkAtoms);
SimilarityTransform bestSim;
};
#endif
| true |
3357221a5ba9c55bc181853eaa139be2330227c3 | C++ | 15831944/Cpp_SQL | /2020_08_07/멀리뛰기/멀리뛰기/Source1.cpp | UTF-8 | 371 | 2.578125 | 3 | [] | no_license | #include <string>
#include <vector>
using namespace std;
int dp[2001];
long long solution(int n) {
long long answer = 0;
dp[1] = 1; //1,2,3,5,
dp[2] = 2;
for (int i = 3; i <= n; i++)
//dp[i] = (dp[i - 1] + dp[i - 2]) % 1234567;
dp[i] = (dp[i - 1] + dp[i - 2]) ;
answer = dp[n];
return answer;
}
int main()
{
solution(4);
return 0;
} | true |
751ddcfab14f366d585eb328cefc3d2f184f15c3 | C++ | Alon-Regev/Interpreter | /Interpreter/Node.cpp | UTF-8 | 1,512 | 3.34375 | 3 | [] | no_license | #include "Node.h"
Node::Node() : _value(""), _left(nullptr), _right(nullptr), _parentheses(0), _lineNumber(DEFAULT_LINE_NUMBER)
{
}
Node::Node(const std::string& value) : _value(value), _left(nullptr), _right(nullptr), _parentheses(0), _lineNumber(DEFAULT_LINE_NUMBER)
{
}
Node::Node(const std::string& value, int lineNumber) : _value(value), _left(nullptr), _right(nullptr), _parentheses(0), _lineNumber(lineNumber)
{
}
Node::~Node()
{
// delete subtrees
delete this->_left;
this->_left = nullptr;
delete this->_right;
this->_right = nullptr;
}
bool Node::isLeaf()
{
return this->_left == nullptr && this->_right == nullptr;
}
// deep copy operator
Node& Node::operator=(const Node& other)
{
// copy values
this->_value = other._value;
this->_parentheses = other._parentheses;
this->_lineNumber = other._lineNumber;
// copy left subtree if it exists
if (other._left != nullptr)
{
this->_left = new Node();
*this->_left = *other._left;
}
else
{
this->_left = other._left;
}
// copy right subtree if it exists
if (other._right != nullptr)
{
this->_right = new Node();
*this->_right = *other._right;
}
else
{
this->_right = other._right;
}
return *this;
}
Node* Node::copy()
{
// copy to new node by assignment
Node* newCopy = new Node();
*newCopy = *this;
return newCopy;
}
char Node::getParentheses()
{
return this->_parentheses;
}
void Node::setParentheses(const char c)
{
this->_parentheses = c;
}
int Node::getLineNumber()
{
return this->_lineNumber;
}
| true |
36961cca6b484d7a46c49ebe680af3403068e355 | C++ | SeizeTheMoment/Solution-to-Algorithm-Excercise | /leetcode/周赛/20200802/3.排布二进制网格的最少交换次数(中等).cpp | UTF-8 | 1,034 | 2.765625 | 3 | [] | no_license | class Solution {
public:
int minSwaps(vector<vector<int>>& grid) {
int N = grid.size();
vector<int> zerocnt;
zerocnt.resize(N);
for(int i=0;i<N;i++)
{
int k = 0;
for(int j=N-1;j>=0;j--)
{
if(grid[i][j] == 0)
k++;
else
break;
}
zerocnt[i] = k;
}
int ans = 0;
for(int i=0; i<N-1; i++)
{
if(zerocnt[i]>=N-i-1)
continue;
int j;
for(j=i+1;j<N;j++)
{
if(zerocnt[j]>=N-i-1)
{
break;
}
}
if(j==N)
return -1;
while(j>i)
{
int temp = zerocnt[j-1];
zerocnt[j-1] = zerocnt[j];
zerocnt[j] = temp;
j--;
ans++;
}
}
return ans;
}
};
| true |
ece0a245f030caab58705ec589bddd457de712ca | C++ | rainlee/leetcode-jecklee | /SudokuSolver.cpp | GB18030 | 1,648 | 3.59375 | 4 | [] | no_license | /***
* ݹ
* б'.' ö9
* Ϸݹ鴦
***/
const int N = 9;
class Solution {
public:
void solveSudoku(vector<vector<char> > &board) {
doSudoku(board);
}
private:
static bool doSudoku(vector<vector<char> > &board) {
for (int i = 0; i < N; ++i)
{
for (int j = 0; j < N; ++j)
{
if ('.' == board[i][j])
{
for (char c = '1'; c <= '9'; ++c)
{
board[i][j] = c;
if (isValid(board, i, j) && doSudoku(board)) // recursive
return true;
board[i][j] = '.'; // back tracking
}
return false; // 0-9 are all illegal
}
}
}
return true;
}
// check (x, y)
static bool isValid(const vector<vector<char> > &board, int x, int y)
{
// check row
for (int i = 0; i < N; ++i)
if ((i != x) && (board[i][y] == board[x][y]))
return false;
// check col
for (int j = 0; j < N; ++j)
if ((j != y) && (board[x][j] == board[x][y]))
return false;
// check box
int xbox = (x / 3) * 3;
int ybox = (y / 3) * 3;
for (int i = xbox; i < xbox+3; ++i)
for (int j = ybox; j < ybox+3; ++j)
if ( ((i != x) || (j != y)) && (board[i][j] == board[x][y]) )
return false;
return true;
}
}; | true |
5417157368d47e399cba6377854801d6d41d4c2f | C++ | takasugi0406/GuessIt | /main.cpp | UTF-8 | 1,063 | 3.703125 | 4 | [] | no_license | #include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>
using namespace std;
int generateRandomNumber();
int getPlayerGuess();
void printAnswer(int guess, int secretNumber);
int main()
{
int secretNumber = generateRandomNumber();
int guess;
int score = 100;
int times = 0;
do
{
guess = getPlayerGuess();
printAnswer(guess, secretNumber);
score -= 1;
times ++;
} while(guess != secretNumber);
cout << endl << "YOUR SCORE:" << endl << score;
}
int generateRandomNumber()
{
srand(time(0));
int secretNumber = rand() % 99 + 1;
return secretNumber;
}
int getPlayerGuess()
{
int guess;
cout << endl << "Enter your guess (1..100): ";
cin >> guess;
return guess;
}
void printAnswer(int guess, int secretNumber)
{
if(guess > secretNumber)
{
cout << "YOUR NUMBER IS TOO BIG!";
}
else if (guess < secretNumber)
{
cout << "YOUR NUMBER IS TOO SMALL";
}
else
{
cout << "CONGRATULATION! YOU WIN.";
}
}
| true |
ec00ad33bd83b115630b7385e7d41f5c13e6943d | C++ | Outerskyb/baekjoon | /1934/main.cpp | UTF-8 | 253 | 2.921875 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
int t;
cin >> t;
while (t--)
{
int a, b;
cin >> a >> b;
int mul = a * b;
while (b != 0) {
int r = a % b;
a = b;
b = r;
}
cout << mul/a << '\n';
}
} | true |
ca739266f42a9ced027b597f8b6170c49deaef45 | C++ | gems-uff/oceano | /core/src/test/resources/CPP/neopz/Material/pzbiharmonic.h | UTF-8 | 4,335 | 2.578125 | 3 | [
"MIT"
] | permissive | /**
* \file
* @brief Contains the TPZBiharmonic class which implements a discontinuous Galerkin formulation for the bi-harmonic equation.
*/
// -*- c++ -*-
//$Id: pzbiharmonic.h,v 1.12 2009-11-16 18:41:59 diogo Exp $
#ifndef TPZBIHARMONICHPP
#define TPZBIHARMONICHPP
#include <iostream>
#include "pzdiscgal.h"
#include "pzfmatrix.h"
/**
* @ingroup material
* @brief Implements discontinuous Galerkin formulation for the bi-harmonic equation.
* @since Nov 27, 2003
* @author Igor Mozolevski e Paulo Bosing
*/
class TPZBiharmonic : public TPZDiscontinuousGalerkin {
protected:
REAL fXf;
public :
static REAL gLambda1, gLambda2, gSigmaA,gSigmaB, gL_alpha, gM_alpha, gL_betta, gM_betta;
/** @brief Inicialisation of biharmonic material */
TPZBiharmonic(int nummat, REAL f);
virtual ~TPZBiharmonic();
/** @brief Returns the number of norm errors. Default is 3: energy, L2, H1, semi-norm H2 and H2. */
virtual int NEvalErrors() {return 8;}
void SetMaterial(REAL &xfin) {
fXf = xfin;
}
int Dimension() { return 2;}
/** @brief Returns one because of scalar problem */
int NStateVariables(){
return 1;
};
virtual void Print(std::ostream & out);
virtual std::string Name() { return "TPZBiharmonic"; }
/** @brief Implements integral over element's volume */
virtual void Contribute(TPZMaterialData &data,
REAL weight,
TPZFMatrix<REAL> &ek,
TPZFMatrix<REAL> &ef);
/** @brief Implements integral over element's volume */
virtual void Contribute(TPZMaterialData &data,
REAL weight,
TPZFMatrix<REAL> &ef)
{
TPZDiscontinuousGalerkin::Contribute(data,weight,ef);
}
/** @brief Implements boundary conditions for continuous Galerkin */
virtual void ContributeBC(TPZMaterialData &data,
REAL weight,
TPZFMatrix<REAL> &ek,
TPZFMatrix<REAL> &ef,
TPZBndCond &bc);
/** @brief Implements boundary conditions for continuous Galerkin */
virtual void ContributeBC(TPZMaterialData &data,
REAL weight,
TPZFMatrix<REAL> &ef,
TPZBndCond &bc)
{
TPZDiscontinuousGalerkin::ContributeBC(data,weight,ef,bc);
}
virtual int VariableIndex(const std::string &name);
virtual int NSolutionVariables(int var);
virtual int NFluxes(){ return 0;}
protected:
virtual void Solution(TPZVec<REAL> &Sol,TPZFMatrix<REAL> &DSol,TPZFMatrix<REAL> &axes,int var,TPZVec<REAL> &Solout);
public:
/**
* @brief Returns the solution associated with the var index based on
* the finite element approximation
*/
virtual void SolutionDisc(TPZMaterialData &data, TPZMaterialData &dataleft, TPZMaterialData &dataright, int var, TPZVec<REAL> &Solout)
{
TPZDiscontinuousGalerkin::SolutionDisc(data,dataleft,dataright,var,Solout);
}
/** @brief Computes the value of the flux function to be used by ZZ error estimator */
virtual void Flux(TPZVec<REAL> &x, TPZVec<REAL> &Sol, TPZFMatrix<REAL> &DSol, TPZFMatrix<REAL> &axes, TPZVec<REAL> &flux);
/**
* @brief Compute the error due to the difference between the interpolated flux \n
* and the flux computed based on the derivative of the solution
*/
void Errors(TPZVec<REAL> &x,TPZVec<REAL> &u,
TPZFMatrix<REAL> &dudx, TPZFMatrix<REAL> &axes, TPZVec<REAL> &flux,
TPZVec<REAL> &u_exact,TPZFMatrix<REAL> &du_exact,TPZVec<REAL> &values);
virtual void ContributeInterface(TPZMaterialData &data, TPZMaterialData &dataleft, TPZMaterialData &dataright,
REAL weight,
TPZFMatrix<REAL> &ek,
TPZFMatrix<REAL> &ef);
virtual void ContributeBCInterface(TPZMaterialData &data, TPZMaterialData &dataleft,
REAL weight,
TPZFMatrix<REAL> &ek,
TPZFMatrix<REAL> &ef,
TPZBndCond &bc);
virtual void ContributeInterface(TPZMaterialData &data, TPZMaterialData &dataleft, TPZMaterialData &dataright,
REAL weight,
TPZFMatrix<REAL> &ef)
{
TPZDiscontinuousGalerkin::ContributeInterface(data,dataleft,dataright,weight,ef);
}
virtual void ContributeBCInterface(TPZMaterialData &data, TPZMaterialData &dataleft,
REAL weight,
TPZFMatrix<REAL> &ef,
TPZBndCond &bc)
{
TPZDiscontinuousGalerkin::ContributeBCInterface(data,dataleft,weight,ef,bc);
}
};
#endif
| true |
44d6ade473e303fd46edb6d66395f59de8aa2a5d | C++ | Tudor67/Competitive-Programming | /LeetCode/Explore/December-LeetCoding-Challenge-2021/#Day#26_KClosestPointsToOrigin_sol10_binary_search_O(N)_time_O(N)_extra_space_128ms_57.9MB.cpp | UTF-8 | 2,134 | 2.921875 | 3 | [
"MIT"
] | permissive | class Solution {
private:
int computeDistanceToOrigin(const vector<int>& P){
return (P[0] * P[0] + P[1] * P[1]);
}
int computeDistanceToOrigin(const pair<int, int>& P){
return (P.first * P.first + P.second * P.second);
}
public:
vector<vector<int>> kClosest(vector<vector<int>>& points, int k) {
int currentK = k;
vector<pair<int, int>> leftPoints;
vector<pair<int, int>> rightPoints;
vector<pair<int, int>> currentPoints;
for(const vector<int>& P: points){
currentPoints.emplace_back(P[0], P[1]);
}
int minDist = computeDistanceToOrigin(points[0]);
int maxDist = computeDistanceToOrigin(points[0]);
for(const vector<int>& P: points){
int dist = computeDistanceToOrigin(P);
minDist = min(minDist, dist);
maxDist = max(maxDist, dist);
}
int l = minDist;
int r = maxDist;
while(l != r){
int mid = (l + r) / 2;
leftPoints.clear();
rightPoints.clear();
for(const pair<int, int>& P: currentPoints){
if(computeDistanceToOrigin(P) < mid){
leftPoints.push_back(P);
}else{
rightPoints.push_back(P);
}
}
if((int)leftPoints.size() < currentK){
currentK -= (int)leftPoints.size();
currentPoints = rightPoints;
l = mid + 1;
}else{
currentPoints = leftPoints;
r = mid;
}
}
int distThreshold = r;
vector<vector<int>> closestPoints;
for(const vector<int>& P: points){
if(computeDistanceToOrigin(P) <= distThreshold){
closestPoints.push_back(P);
}
if((int)closestPoints.size() == k){
break;
}
}
return closestPoints;
}
}; | true |
7be421e39a27a2f31651bfa98ba4172f529cea66 | C++ | apiec/labirynth | /Maze.h | UTF-8 | 1,921 | 3.40625 | 3 | [] | no_license | #ifndef MAZE_H_INCLUDED
#define MAZE_H_INCLUDED
#include <iostream>
#include <vector>
#include "xy.h"
/** \brief Contains basic functionality of a maze.
*
* The maze is made up of square cells. Each cell can either be a wall or a passage.
* A maze can either randomly generated or read from a txt file.
**/
class Maze {
private:
int width, height;
bool** maze_grid;
//the layout of the maze
//0 - wall, 1 - passage
bool treelike; //true = maze is treelike (from any point
//there's only one way to any other point
//false = multiple possible ways
xy start;
xy finish;
//the start and the end of the maze
int initiate_maze_grid();
//creates a height x width boolean matrix
//filled with 0s (walls)
int add_wallstolist(xy cell, std::vector<xy>& wall_list);
//adds walls of a cell to a wall_list
bool can_bepassage(xy tocheck);
//checks if a point with those coordinates can be added as a passage
int generate_maze();
//create a maze out of maze_grid
int generate_maze(std::string filename);
//reads a maze layout from a txt file
int find_nearest_passage(xy& point);
int random_startfinish();
void initiate_startfinish();
public:
int print_maze_grid();
//prints out the maze_grid as it is (in binary)
int print_maze();
//prints out the maze_grid as a readable maze in console
int print_maze_totxt(std::string filename);
//prints the maze to txt
bool** get_maze_grid();
int get_height();
int get_width();
xy get_start();
xy get_finish();
Maze(bool is_treelike = true);
Maze(int h, int w, bool is_treelike = true);
Maze(std::string mazetxt);
~Maze();
};
#endif // MAZE_H_INCLUDED
| true |
153d70ad074002fb9cd03f46991ead0c424b8b2c | C++ | karapish/CPP | /BFS.cpp | UTF-8 | 1,458 | 3.515625 | 4 | [] | no_license | #include <iostream>
#include <queue>
using namespace std;
template <typename T=size_t>
struct Node {
T v;
Node* left;
Node* right;
static Node<T>* create(T v, Node<T>* l, Node<T>* r) {
auto n = new Node;
n->v = v;
n->left = l;
n->right = r;
return n;
}
};
int main()
{
Node<int>* t =
Node<int>::create(1,
Node<int>::create(2,
Node<int>::create(3,nullptr, nullptr),
Node<int>::create(4,nullptr, nullptr)
),
Node<int>::create(5,
Node<int>::create(3,nullptr, nullptr),
Node<int>::create(4,nullptr, nullptr)
)
);
struct NodeL {
Node<int>* node;
size_t level;
static NodeL* create(Node<int>* n, size_t l) {
auto node = new NodeL;
node->node = n;
node->level = l;
return node;
}
};
queue<NodeL*> q;
q.push(NodeL::create(t, 1));
auto level = 1;
while(!q.empty()) {
auto i = q.front();
if(i->level != level) {
cout << endl;
++level;
continue;
}
q.pop();
cout << i->node->v << " ";
if(i->node->left)
q.push(NodeL::create(i->node->left, level+1));
if(i->node->right)
q.push(NodeL::create(i->node->right, level+1));
}
return 0;
}
| true |
497b0140a3de81ab937b415992291a85819bbadf | C++ | Qux/CV-Shield | /examples/2CVs/2CVs.ino | UTF-8 | 371 | 2.65625 | 3 | [
"MIT"
] | permissive | #include <QuxCV.h>
int counter;
void setup() {
counter = 0;
/*
By using QuxCV::setup2CVs(), you can use digital 3 and 11 pins
as CV signal (fast PWM).
*/
Qux::CV::setup2CVs();
}
void loop() {
analogWrite(3, counter);
analogWrite(11, 255 - counter);
counter++;
if (counter == 256) {
counter = 0;
}
delay(25);
}
| true |
d2a998780f0bfbd0834c6d3346ab4616edb090e4 | C++ | AmirGD/AP-PROJECT | /HelperClass.cpp | UTF-8 | 4,035 | 2.9375 | 3 | [] | no_license | #include "HelperClass.h"
using namespace std;
void helper::create_by_template(string address)
{
outfile.open(address);
outfile << "#include <iostream>\n#include <vector>\n#include <string>\n\nusing namespace std;\n\ntypedef vector<int> ints\ntypedef vector<string> strings\n\nint main() {\n\treturn 0;\n}" << endl;
outfile.close();
}
void helper::replace(string address, map<string,string> repmap)
{
//Input
infile.open(address);
while (! infile.eof() )
{
getline(infile,templine);
lines.push_back(templine);
}
infile.close();
// Edit
outfile.open(address);
for (iter = repmap.begin(); iter != repmap.end(); iter++)
{
for (int i = 0; i < lines.size(); i++)
{
string oldstr = iter->first;
string newstr = iter->second;
int pos=lines[i].find(oldstr);
while (pos != string::npos)
{
lines[i].replace(pos, oldstr.length(), newstr);
pos = lines[i].find(oldstr);
}
}
}
//Output
for (int i = 0; i < lines.size(); i++)
{
outfile << lines[i] << endl;
}
lines.clear();
outfile.close();
}
void helper::format(string address)
{
infile.open(address);
int lines_count = 0, max_func_len=0;
//Input
while (!infile.eof())
{
getline(infile, templine);
lines.push_back(templine);
lines_count++;
}
infile.close();
outfile.open(address);
//cerr << "inja1" << endl;
//Edit
//8 Space To Tab
for (int i = 0; i < lines.size(); i++)
{
int pos = lines[i].find(" ");
while (pos != string::npos)
{
lines[i].replace(pos, 8, "\t");
pos = lines[i].find(" ");
}
}
//cerr << "inja2" << endl;
//Comment
for (int i = 0; i < lines.size(); i++)
{
if (lines[i].length() == 0)
continue;
if (lines[i][0] == '/' && lines[i][1] == '*')
{
//halati ke /* dar ye khat tanha bashad
if (lines[i].length() == 2)
{
lines.erase(lines.begin() + i);
while (true) {
lines[i] = "//" + lines[i];
if (lines[i + 1].length() == 0)
{
i++;
continue;
}
if (lines[i + 1][0] == '*' && lines[i + 1][1] == '/')
{
lines.erase(lines.begin() + i + 1);
break;
}
else if (lines[i + 1][lines[i + 1].length() - 1] == '/' && lines[i + 1][lines[i + 1].length() - 2] == '*')
{
lines[i + 1] = lines[i + 1].substr(0, lines[i + 1].length() - 2);
break;
}
i++;
}
break;
}
//halati ke bad az /* comment shoroo she
else
{
lines[i] = "//" + lines[i].substr(2, lines[i].length() - 2);
i++;
while (true)
{
lines[i] = "//" + lines[i];
if (lines[i + 1].length() == 0)
{
i++;
continue;
}
if (lines[i + 1][0] == '*' && lines[i + 1][1] == '/')
{
lines.erase(lines.begin() + i + 1);
break;
}
else if (lines[i + 1][lines[i + 1].length() - 1] == '/' && lines[i + 1][lines[i + 1].length() - 2] == '*')
{
lines[i + 1] = lines[i + 1].substr(0, lines[i + 1].length() - 2);
break;
}
i++;
}
break;
}
}
}
//cerr << "inja3" << endl;
//Max Function Length
int c=0, start, end,length;
for (int i = 0; i < lines.size(); i++)
{
if (lines[i].find('{') != string::npos)
{
if (c == 0)
{
int pos = lines[i].find('{');
if (lines[i].length() != 1)
if (pos + 1 == lines[i].length())
start = i + 1;
else
start = i;
else start = i + 1;
}
c++;
}
else if (lines[i].find('}') != string::npos)
{
if (c == 1)
{
if (lines[i].length() != 1)
end = i;
else end = i - 1;
length = end - start + 1;
if (length > max_func_len)
max_func_len = length;
}
c--;
}
}
//cerr << "inja4" << endl;
//Output
for (int i = 0; i < lines.size(); i++)
{
outfile << lines[i] << endl;
}
//Print
cout << "Lines: " << lines_count << endl;
cout << "Max Func Length: " << max_func_len;
lines.clear();
outfile.close();
}
| true |
1df27c1baef4fd92dcc4e6cbfa37928b1687c2c6 | C++ | smeredith/averagecolor | /AverageColorLib/AverageColor_StdThreadRecursive.cpp | UTF-8 | 2,528 | 3.203125 | 3 | [] | no_license | #include "stdafx.h"
#include <numeric>
#include <thread>
#include "EveryNIterator.h"
#include "AverageColor_StdThreadRecursive.h"
// An iterator to iterator over all bytes of one color.
typedef EveryNIterator<std::vector<BYTE>::const_iterator, 3> ColorIterator;
// Divide and conquer version of SumAverages() that uses threads. ChunkSize represents the
// number of iterations in a single work unit. If there is more work than this, it gets
// recursively divided into two more threads.
void AccumulateUsingThreads(
const ColorIterator& begin,
const ColorIterator& end,
ULONGLONG* pSum)
{
// Chunksize is the approximate size of one chunk of work for a thread, in the number of
// pixels to process.
const size_t chunkSize = 1000000;
if ((end - begin) < chunkSize)
{
*pSum = std::accumulate(begin, end, 0ULL);
}
else
{
ColorIterator middle = begin + ((end - begin) / 2);
ULONGLONG bottomHalfSum;
std::thread bottomHalfThread = std::thread(AccumulateUsingThreads, begin, middle, &bottomHalfSum);
ULONGLONG topHalfSum;
AccumulateUsingThreads(middle, end, &topHalfSum);
bottomHalfThread.join();
*pSum = bottomHalfSum + topHalfSum;
}
}
DWORD AverageColor_StdThreadRecursive(
const std::vector<BYTE>::const_iterator& begin,
const std::vector<BYTE>::const_iterator& end)
{
ULONGLONG greenSum;
auto greenThread = std::thread(AccumulateUsingThreads, ColorIterator(begin+1), ColorIterator(end-2), &greenSum);
ULONGLONG redSum;
auto redThread = std::thread(AccumulateUsingThreads, ColorIterator(begin+2), ColorIterator(end-1), &redSum);
ULONGLONG blueSum;
AccumulateUsingThreads(ColorIterator(begin), ColorIterator(end), &blueSum);
const size_t pixelCount = (end - begin) / 3;
redThread.join();
greenThread.join();
// We stopped short on the red and green accumulate so as to not initialize a
// ColorIterator past the end of the real iterator. Add in the last one now.
redSum += *(end-1);
greenSum += *(end-2);
#pragma warning(push)
#pragma warning(disable : 4244) // Guaranteed to fit into a byte because the sum accumulated bytes.
const BYTE blueAverage = blueSum / pixelCount;
const BYTE redAverage = redSum / pixelCount;
const BYTE greenAverage = greenSum / pixelCount;
#pragma warning(pop)
return RGB(redAverage, greenAverage, blueAverage);
}
| true |
7867b3f9566faefe499978b73876bfa70fb5487d | C++ | maromf/MaromAndNoaProject | /RoboticsProjMfNc/Utils.cpp | UTF-8 | 3,017 | 3.53125 | 4 | [] | no_license | /*
* Utils.cpp
*
* Created on: Jul 25, 2015
* Author: colman
*/
#include "Utils.h"
/**
* Calculates degrees to grid index
*/
int Utils::degreesToIndex(int degrees)
{
return degrees * (TOTAL_SCAN_SPAN / TOTAL_DEGREES);
}
/**
* Calculates grid index to degrees
*/
int Utils::indexToDegrees(int index)
{
return index * (TOTAL_DEGREES / TOTAL_SCAN_SPAN);
}
/**
* calculates degrees to radians
*/
double Utils::degreesToRadians(double degrees)
{
double yaw = degrees;
return (yaw * M_PI) / PAI_DEGREES;
}
/**
* calculates radians to degrees
*/
double Utils::radiansToDegrees(double radians)
{
double yaw = (radians * PAI_DEGREES) / M_PI;
return yaw;
}
/**
* calculates yaw between two locations
* @param curPos - first location
* @param goal - second location
* @return yaw
*/
double Utils::calcYaw(Location* curPos, Location* goal)
{
double angleInDegrees = calculateNeededYaw(curPos, goal);
return angleInDegrees;
}
/**
* calculates yaw according to quarter- yaw always positive
*/
double Utils::calculateNeededYaw(Location* curPos, Location* goal)
{
double yDeltaToPoint = abs(goal->getY() - curPos->getY());
double xDeltaToPoint = abs(goal->getX() - curPos->getX());
double neededYaw = atan2(yDeltaToPoint , xDeltaToPoint);
neededYaw = (neededYaw < 0) ? ( ((M_PI * 2) + neededYaw)) : neededYaw;
neededYaw = radiansToDegrees(neededYaw);
// check the quarter of the goal point
switch(getQuarter(curPos, goal)) {
case FIRST:
return neededYaw;
case SECOND:
return PAI_DEGREES - neededYaw;
case THIRD:
return PAI_DEGREES + neededYaw;
case FOURTH:
return (PAI_DEGREES * 2) - neededYaw;
default:
return neededYaw;
}
}
/**
* get quarter of the goal point
*/
int Utils::getQuarter(Location* pos, Location* goal) {
if (pos->getY() > goal->getY()) {
if (pos->getX() > goal->getX())
return SECOND;
else
return FIRST;
} else {
if (pos->getX() > goal->getX())
return THIRD;
else
return FOURTH;
}
}
/**
* turn yaw to positive
* @return positive yaw
*/
double Utils::NegativeYawToPositive(double negative)
{
return (negative < 0) ? ( ((PAI_DEGREES * 2) + negative)) : negative;
}
/**
* turn yaw to negative
* @return negative yaw
*/
double Utils::PositiveYawToNegative(double positive)
{
return (positive > PAI_DEGREES) ? ((-1) * ((PAI_DEGREES * 2) - positive)) : positive;
}
/**
* turn negative location to positive
* @return positive location
*/
Location* Utils::NegativeCoordinateLocationToPositive(Location* negative, int width, int height)
{
double posX = negative->getX() + floor(width / 2);
double posY = (-1) * (negative->getY() - floor(height / 2));
return new Location(posX, posY);
}
/**
* turn positive location to negative
* @return negative location
*/
Location* Utils::PositiveCoordinateLocationToNegative(Location* positive, int width, int height)
{
double posX = positive->getX() - (width / 2);
double posY = (-1) * (positive->getY() - (height / 2));
return new Location(posX, posY);
}
| true |
1f07002f882f7f58a7808775b0e65d799c51e410 | C++ | ganesh1729ganesh/dsa | /graphs/kruskals.cpp | UTF-8 | 1,482 | 2.828125 | 3 | [] | no_license | #include <iostream>
using namespace std;
int findpar(int node, vector<int> &parent){
if(node==parent[node]) return node;
return parent[node] = findpar(parent[node],parent);
}
void unionn(int u,int v,vector<int>&parent,vector<int>&rank){
u = findpar(u,parent);
v = findpar(v,parent);
if(rank[u]<rank[v]) parent[u]=v;
else if(rank[v]<rank[u]) parent[v]=u;
else{
parent[v]=u;
rank[u]++;
}
}
int spanningTree(int V, vector<vector<int>> adj[])
{
// code here
vector<vector<int>>edges;
for(int i=0;i<V;i++){
vector<int>temp;
for(auto j:adj[i]){
temp.push_back(j[1]);
temp.push_back(min(i,j[0]));
temp.push_back(max(i,j[0]));
edges.push_back(temp);
temp.clear();
}
}
sort(edges.begin(),edges.end());
vector<int> parent(V), rank(V);
for(int i=0;i<V;i++) parent[i]=i,rank[i]=0;
int cost =0;
for(auto it:edges){
if(findpar(it[1],parent)!=findpar(it[2],parent)){
cost+= it[0];
unionn(it[1],it[2],parent,rank);
}
}
return cost;
}
int main() {
// your code goes here
return 0;
} | true |